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 // Only bits set in Mask must be negated, other bits may be arbitrary.
4688 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4689   if (isBitwiseNot(V, AllowUndefs))
4690     return V.getOperand(0);
4691 
4692   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4693   // bits in the non-extended part.
4694   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4695   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4696     return SDValue();
4697   SDValue ExtArg = V.getOperand(0);
4698   if (ExtArg.getScalarValueSizeInBits() >=
4699           MaskC->getAPIntValue().getActiveBits() &&
4700       isBitwiseNot(ExtArg, AllowUndefs) &&
4701       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4702       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4703     return ExtArg.getOperand(0).getOperand(0);
4704   return SDValue();
4705 }
4706 
4707 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4708   // Match masked merge pattern (X & ~M) op (Y & M)
4709   // Including degenerate case (X & ~M) op M
4710   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4711                                       SDValue Other) {
4712     if (SDValue NotOperand =
4713             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4714       if (Other == NotOperand)
4715         return true;
4716       if (Other->getOpcode() == ISD::AND)
4717         return NotOperand == Other->getOperand(0) ||
4718                NotOperand == Other->getOperand(1);
4719     }
4720     return false;
4721   };
4722   if (A->getOpcode() == ISD::AND)
4723     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4724            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4725   return false;
4726 }
4727 
4728 // FIXME: unify with llvm::haveNoCommonBitsSet.
4729 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4730   assert(A.getValueType() == B.getValueType() &&
4731          "Values must have the same type");
4732   if (haveNoCommonBitsSetCommutative(A, B) ||
4733       haveNoCommonBitsSetCommutative(B, A))
4734     return true;
4735   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4736                                         computeKnownBits(B));
4737 }
4738 
4739 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4740                                SelectionDAG &DAG) {
4741   if (cast<ConstantSDNode>(Step)->isZero())
4742     return DAG.getConstant(0, DL, VT);
4743 
4744   return SDValue();
4745 }
4746 
4747 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4748                                 ArrayRef<SDValue> Ops,
4749                                 SelectionDAG &DAG) {
4750   int NumOps = Ops.size();
4751   assert(NumOps != 0 && "Can't build an empty vector!");
4752   assert(!VT.isScalableVector() &&
4753          "BUILD_VECTOR cannot be used with scalable types");
4754   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4755          "Incorrect element count in BUILD_VECTOR!");
4756 
4757   // BUILD_VECTOR of UNDEFs is UNDEF.
4758   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4759     return DAG.getUNDEF(VT);
4760 
4761   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4762   SDValue IdentitySrc;
4763   bool IsIdentity = true;
4764   for (int i = 0; i != NumOps; ++i) {
4765     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4766         Ops[i].getOperand(0).getValueType() != VT ||
4767         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4768         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4769         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4770       IsIdentity = false;
4771       break;
4772     }
4773     IdentitySrc = Ops[i].getOperand(0);
4774   }
4775   if (IsIdentity)
4776     return IdentitySrc;
4777 
4778   return SDValue();
4779 }
4780 
4781 /// Try to simplify vector concatenation to an input value, undef, or build
4782 /// vector.
4783 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4784                                   ArrayRef<SDValue> Ops,
4785                                   SelectionDAG &DAG) {
4786   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4787   assert(llvm::all_of(Ops,
4788                       [Ops](SDValue Op) {
4789                         return Ops[0].getValueType() == Op.getValueType();
4790                       }) &&
4791          "Concatenation of vectors with inconsistent value types!");
4792   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4793              VT.getVectorElementCount() &&
4794          "Incorrect element count in vector concatenation!");
4795 
4796   if (Ops.size() == 1)
4797     return Ops[0];
4798 
4799   // Concat of UNDEFs is UNDEF.
4800   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4801     return DAG.getUNDEF(VT);
4802 
4803   // Scan the operands and look for extract operations from a single source
4804   // that correspond to insertion at the same location via this concatenation:
4805   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4806   SDValue IdentitySrc;
4807   bool IsIdentity = true;
4808   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4809     SDValue Op = Ops[i];
4810     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4811     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4812         Op.getOperand(0).getValueType() != VT ||
4813         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4814         Op.getConstantOperandVal(1) != IdentityIndex) {
4815       IsIdentity = false;
4816       break;
4817     }
4818     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4819            "Unexpected identity source vector for concat of extracts");
4820     IdentitySrc = Op.getOperand(0);
4821   }
4822   if (IsIdentity) {
4823     assert(IdentitySrc && "Failed to set source vector of extracts");
4824     return IdentitySrc;
4825   }
4826 
4827   // The code below this point is only designed to work for fixed width
4828   // vectors, so we bail out for now.
4829   if (VT.isScalableVector())
4830     return SDValue();
4831 
4832   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4833   // simplified to one big BUILD_VECTOR.
4834   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4835   EVT SVT = VT.getScalarType();
4836   SmallVector<SDValue, 16> Elts;
4837   for (SDValue Op : Ops) {
4838     EVT OpVT = Op.getValueType();
4839     if (Op.isUndef())
4840       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4841     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4842       Elts.append(Op->op_begin(), Op->op_end());
4843     else
4844       return SDValue();
4845   }
4846 
4847   // BUILD_VECTOR requires all inputs to be of the same type, find the
4848   // maximum type and extend them all.
4849   for (SDValue Op : Elts)
4850     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4851 
4852   if (SVT.bitsGT(VT.getScalarType())) {
4853     for (SDValue &Op : Elts) {
4854       if (Op.isUndef())
4855         Op = DAG.getUNDEF(SVT);
4856       else
4857         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4858                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4859                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4860     }
4861   }
4862 
4863   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4864   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4865   return V;
4866 }
4867 
4868 /// Gets or creates the specified node.
4869 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4870   FoldingSetNodeID ID;
4871   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4872   void *IP = nullptr;
4873   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4874     return SDValue(E, 0);
4875 
4876   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4877                               getVTList(VT));
4878   CSEMap.InsertNode(N, IP);
4879 
4880   InsertNode(N);
4881   SDValue V = SDValue(N, 0);
4882   NewSDValueDbgMsg(V, "Creating new node: ", this);
4883   return V;
4884 }
4885 
4886 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4887                               SDValue Operand) {
4888   SDNodeFlags Flags;
4889   if (Inserter)
4890     Flags = Inserter->getFlags();
4891   return getNode(Opcode, DL, VT, Operand, Flags);
4892 }
4893 
4894 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4895                               SDValue Operand, const SDNodeFlags Flags) {
4896   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4897          "Operand is DELETED_NODE!");
4898   // Constant fold unary operations with an integer constant operand. Even
4899   // opaque constant will be folded, because the folding of unary operations
4900   // doesn't create new constants with different values. Nevertheless, the
4901   // opaque flag is preserved during folding to prevent future folding with
4902   // other constants.
4903   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4904     const APInt &Val = C->getAPIntValue();
4905     switch (Opcode) {
4906     default: break;
4907     case ISD::SIGN_EXTEND:
4908       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4909                          C->isTargetOpcode(), C->isOpaque());
4910     case ISD::TRUNCATE:
4911       if (C->isOpaque())
4912         break;
4913       LLVM_FALLTHROUGH;
4914     case ISD::ZERO_EXTEND:
4915       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4916                          C->isTargetOpcode(), C->isOpaque());
4917     case ISD::ANY_EXTEND:
4918       // Some targets like RISCV prefer to sign extend some types.
4919       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4920         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4921                            C->isTargetOpcode(), C->isOpaque());
4922       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4923                          C->isTargetOpcode(), C->isOpaque());
4924     case ISD::UINT_TO_FP:
4925     case ISD::SINT_TO_FP: {
4926       APFloat apf(EVTToAPFloatSemantics(VT),
4927                   APInt::getZero(VT.getSizeInBits()));
4928       (void)apf.convertFromAPInt(Val,
4929                                  Opcode==ISD::SINT_TO_FP,
4930                                  APFloat::rmNearestTiesToEven);
4931       return getConstantFP(apf, DL, VT);
4932     }
4933     case ISD::BITCAST:
4934       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4935         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4936       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4937         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4938       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4939         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4940       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4941         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4942       break;
4943     case ISD::ABS:
4944       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4945                          C->isOpaque());
4946     case ISD::BITREVERSE:
4947       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4948                          C->isOpaque());
4949     case ISD::BSWAP:
4950       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4951                          C->isOpaque());
4952     case ISD::CTPOP:
4953       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4954                          C->isOpaque());
4955     case ISD::CTLZ:
4956     case ISD::CTLZ_ZERO_UNDEF:
4957       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4958                          C->isOpaque());
4959     case ISD::CTTZ:
4960     case ISD::CTTZ_ZERO_UNDEF:
4961       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4962                          C->isOpaque());
4963     case ISD::FP16_TO_FP: {
4964       bool Ignored;
4965       APFloat FPV(APFloat::IEEEhalf(),
4966                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4967 
4968       // This can return overflow, underflow, or inexact; we don't care.
4969       // FIXME need to be more flexible about rounding mode.
4970       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4971                         APFloat::rmNearestTiesToEven, &Ignored);
4972       return getConstantFP(FPV, DL, VT);
4973     }
4974     case ISD::STEP_VECTOR: {
4975       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4976         return V;
4977       break;
4978     }
4979     }
4980   }
4981 
4982   // Constant fold unary operations with a floating point constant operand.
4983   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4984     APFloat V = C->getValueAPF();    // make copy
4985     switch (Opcode) {
4986     case ISD::FNEG:
4987       V.changeSign();
4988       return getConstantFP(V, DL, VT);
4989     case ISD::FABS:
4990       V.clearSign();
4991       return getConstantFP(V, DL, VT);
4992     case ISD::FCEIL: {
4993       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4994       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4995         return getConstantFP(V, DL, VT);
4996       break;
4997     }
4998     case ISD::FTRUNC: {
4999       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5000       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5001         return getConstantFP(V, DL, VT);
5002       break;
5003     }
5004     case ISD::FFLOOR: {
5005       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5006       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5007         return getConstantFP(V, DL, VT);
5008       break;
5009     }
5010     case ISD::FP_EXTEND: {
5011       bool ignored;
5012       // This can return overflow, underflow, or inexact; we don't care.
5013       // FIXME need to be more flexible about rounding mode.
5014       (void)V.convert(EVTToAPFloatSemantics(VT),
5015                       APFloat::rmNearestTiesToEven, &ignored);
5016       return getConstantFP(V, DL, VT);
5017     }
5018     case ISD::FP_TO_SINT:
5019     case ISD::FP_TO_UINT: {
5020       bool ignored;
5021       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5022       // FIXME need to be more flexible about rounding mode.
5023       APFloat::opStatus s =
5024           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5025       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5026         break;
5027       return getConstant(IntVal, DL, VT);
5028     }
5029     case ISD::BITCAST:
5030       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5031         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5032       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5033         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5034       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5035         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5036       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5037         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5038       break;
5039     case ISD::FP_TO_FP16: {
5040       bool Ignored;
5041       // This can return overflow, underflow, or inexact; we don't care.
5042       // FIXME need to be more flexible about rounding mode.
5043       (void)V.convert(APFloat::IEEEhalf(),
5044                       APFloat::rmNearestTiesToEven, &Ignored);
5045       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5046     }
5047     }
5048   }
5049 
5050   // Constant fold unary operations with a vector integer or float operand.
5051   switch (Opcode) {
5052   default:
5053     // FIXME: Entirely reasonable to perform folding of other unary
5054     // operations here as the need arises.
5055     break;
5056   case ISD::FNEG:
5057   case ISD::FABS:
5058   case ISD::FCEIL:
5059   case ISD::FTRUNC:
5060   case ISD::FFLOOR:
5061   case ISD::FP_EXTEND:
5062   case ISD::FP_TO_SINT:
5063   case ISD::FP_TO_UINT:
5064   case ISD::TRUNCATE:
5065   case ISD::ANY_EXTEND:
5066   case ISD::ZERO_EXTEND:
5067   case ISD::SIGN_EXTEND:
5068   case ISD::UINT_TO_FP:
5069   case ISD::SINT_TO_FP:
5070   case ISD::ABS:
5071   case ISD::BITREVERSE:
5072   case ISD::BSWAP:
5073   case ISD::CTLZ:
5074   case ISD::CTLZ_ZERO_UNDEF:
5075   case ISD::CTTZ:
5076   case ISD::CTTZ_ZERO_UNDEF:
5077   case ISD::CTPOP: {
5078     SDValue Ops = {Operand};
5079     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5080       return Fold;
5081   }
5082   }
5083 
5084   unsigned OpOpcode = Operand.getNode()->getOpcode();
5085   switch (Opcode) {
5086   case ISD::STEP_VECTOR:
5087     assert(VT.isScalableVector() &&
5088            "STEP_VECTOR can only be used with scalable types");
5089     assert(OpOpcode == ISD::TargetConstant &&
5090            VT.getVectorElementType() == Operand.getValueType() &&
5091            "Unexpected step operand");
5092     break;
5093   case ISD::FREEZE:
5094     assert(VT == Operand.getValueType() && "Unexpected VT!");
5095     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5096       return Operand;
5097     break;
5098   case ISD::TokenFactor:
5099   case ISD::MERGE_VALUES:
5100   case ISD::CONCAT_VECTORS:
5101     return Operand;         // Factor, merge or concat of one node?  No need.
5102   case ISD::BUILD_VECTOR: {
5103     // Attempt to simplify BUILD_VECTOR.
5104     SDValue Ops[] = {Operand};
5105     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5106       return V;
5107     break;
5108   }
5109   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5110   case ISD::FP_EXTEND:
5111     assert(VT.isFloatingPoint() &&
5112            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5113     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5114     assert((!VT.isVector() ||
5115             VT.getVectorElementCount() ==
5116             Operand.getValueType().getVectorElementCount()) &&
5117            "Vector element count mismatch!");
5118     assert(Operand.getValueType().bitsLT(VT) &&
5119            "Invalid fpext node, dst < src!");
5120     if (Operand.isUndef())
5121       return getUNDEF(VT);
5122     break;
5123   case ISD::FP_TO_SINT:
5124   case ISD::FP_TO_UINT:
5125     if (Operand.isUndef())
5126       return getUNDEF(VT);
5127     break;
5128   case ISD::SINT_TO_FP:
5129   case ISD::UINT_TO_FP:
5130     // [us]itofp(undef) = 0, because the result value is bounded.
5131     if (Operand.isUndef())
5132       return getConstantFP(0.0, DL, VT);
5133     break;
5134   case ISD::SIGN_EXTEND:
5135     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5136            "Invalid SIGN_EXTEND!");
5137     assert(VT.isVector() == Operand.getValueType().isVector() &&
5138            "SIGN_EXTEND result type type should be vector iff the operand "
5139            "type is vector!");
5140     if (Operand.getValueType() == VT) return Operand;   // noop extension
5141     assert((!VT.isVector() ||
5142             VT.getVectorElementCount() ==
5143                 Operand.getValueType().getVectorElementCount()) &&
5144            "Vector element count mismatch!");
5145     assert(Operand.getValueType().bitsLT(VT) &&
5146            "Invalid sext node, dst < src!");
5147     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5148       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5149     if (OpOpcode == ISD::UNDEF)
5150       // sext(undef) = 0, because the top bits will all be the same.
5151       return getConstant(0, DL, VT);
5152     break;
5153   case ISD::ZERO_EXTEND:
5154     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5155            "Invalid ZERO_EXTEND!");
5156     assert(VT.isVector() == Operand.getValueType().isVector() &&
5157            "ZERO_EXTEND result type type should be vector iff the operand "
5158            "type is vector!");
5159     if (Operand.getValueType() == VT) return Operand;   // noop extension
5160     assert((!VT.isVector() ||
5161             VT.getVectorElementCount() ==
5162                 Operand.getValueType().getVectorElementCount()) &&
5163            "Vector element count mismatch!");
5164     assert(Operand.getValueType().bitsLT(VT) &&
5165            "Invalid zext node, dst < src!");
5166     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5167       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5168     if (OpOpcode == ISD::UNDEF)
5169       // zext(undef) = 0, because the top bits will be zero.
5170       return getConstant(0, DL, VT);
5171     break;
5172   case ISD::ANY_EXTEND:
5173     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5174            "Invalid ANY_EXTEND!");
5175     assert(VT.isVector() == Operand.getValueType().isVector() &&
5176            "ANY_EXTEND result type type should be vector iff the operand "
5177            "type is vector!");
5178     if (Operand.getValueType() == VT) return Operand;   // noop extension
5179     assert((!VT.isVector() ||
5180             VT.getVectorElementCount() ==
5181                 Operand.getValueType().getVectorElementCount()) &&
5182            "Vector element count mismatch!");
5183     assert(Operand.getValueType().bitsLT(VT) &&
5184            "Invalid anyext node, dst < src!");
5185 
5186     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5187         OpOpcode == ISD::ANY_EXTEND)
5188       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5189       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5190     if (OpOpcode == ISD::UNDEF)
5191       return getUNDEF(VT);
5192 
5193     // (ext (trunc x)) -> x
5194     if (OpOpcode == ISD::TRUNCATE) {
5195       SDValue OpOp = Operand.getOperand(0);
5196       if (OpOp.getValueType() == VT) {
5197         transferDbgValues(Operand, OpOp);
5198         return OpOp;
5199       }
5200     }
5201     break;
5202   case ISD::TRUNCATE:
5203     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5204            "Invalid TRUNCATE!");
5205     assert(VT.isVector() == Operand.getValueType().isVector() &&
5206            "TRUNCATE result type type should be vector iff the operand "
5207            "type is vector!");
5208     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5209     assert((!VT.isVector() ||
5210             VT.getVectorElementCount() ==
5211                 Operand.getValueType().getVectorElementCount()) &&
5212            "Vector element count mismatch!");
5213     assert(Operand.getValueType().bitsGT(VT) &&
5214            "Invalid truncate node, src < dst!");
5215     if (OpOpcode == ISD::TRUNCATE)
5216       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5217     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5218         OpOpcode == ISD::ANY_EXTEND) {
5219       // If the source is smaller than the dest, we still need an extend.
5220       if (Operand.getOperand(0).getValueType().getScalarType()
5221             .bitsLT(VT.getScalarType()))
5222         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5223       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5224         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5225       return Operand.getOperand(0);
5226     }
5227     if (OpOpcode == ISD::UNDEF)
5228       return getUNDEF(VT);
5229     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5230       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5231     break;
5232   case ISD::ANY_EXTEND_VECTOR_INREG:
5233   case ISD::ZERO_EXTEND_VECTOR_INREG:
5234   case ISD::SIGN_EXTEND_VECTOR_INREG:
5235     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5236     assert(Operand.getValueType().bitsLE(VT) &&
5237            "The input must be the same size or smaller than the result.");
5238     assert(VT.getVectorMinNumElements() <
5239                Operand.getValueType().getVectorMinNumElements() &&
5240            "The destination vector type must have fewer lanes than the input.");
5241     break;
5242   case ISD::ABS:
5243     assert(VT.isInteger() && VT == Operand.getValueType() &&
5244            "Invalid ABS!");
5245     if (OpOpcode == ISD::UNDEF)
5246       return getUNDEF(VT);
5247     break;
5248   case ISD::BSWAP:
5249     assert(VT.isInteger() && VT == Operand.getValueType() &&
5250            "Invalid BSWAP!");
5251     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5252            "BSWAP types must be a multiple of 16 bits!");
5253     if (OpOpcode == ISD::UNDEF)
5254       return getUNDEF(VT);
5255     // bswap(bswap(X)) -> X.
5256     if (OpOpcode == ISD::BSWAP)
5257       return Operand.getOperand(0);
5258     break;
5259   case ISD::BITREVERSE:
5260     assert(VT.isInteger() && VT == Operand.getValueType() &&
5261            "Invalid BITREVERSE!");
5262     if (OpOpcode == ISD::UNDEF)
5263       return getUNDEF(VT);
5264     break;
5265   case ISD::BITCAST:
5266     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5267            "Cannot BITCAST between types of different sizes!");
5268     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5269     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5270       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5271     if (OpOpcode == ISD::UNDEF)
5272       return getUNDEF(VT);
5273     break;
5274   case ISD::SCALAR_TO_VECTOR:
5275     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5276            (VT.getVectorElementType() == Operand.getValueType() ||
5277             (VT.getVectorElementType().isInteger() &&
5278              Operand.getValueType().isInteger() &&
5279              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5280            "Illegal SCALAR_TO_VECTOR node!");
5281     if (OpOpcode == ISD::UNDEF)
5282       return getUNDEF(VT);
5283     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5284     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5285         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5286         Operand.getConstantOperandVal(1) == 0 &&
5287         Operand.getOperand(0).getValueType() == VT)
5288       return Operand.getOperand(0);
5289     break;
5290   case ISD::FNEG:
5291     // Negation of an unknown bag of bits is still completely undefined.
5292     if (OpOpcode == ISD::UNDEF)
5293       return getUNDEF(VT);
5294 
5295     if (OpOpcode == ISD::FNEG)  // --X -> X
5296       return Operand.getOperand(0);
5297     break;
5298   case ISD::FABS:
5299     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5300       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5301     break;
5302   case ISD::VSCALE:
5303     assert(VT == Operand.getValueType() && "Unexpected VT!");
5304     break;
5305   case ISD::CTPOP:
5306     if (Operand.getValueType().getScalarType() == MVT::i1)
5307       return Operand;
5308     break;
5309   case ISD::CTLZ:
5310   case ISD::CTTZ:
5311     if (Operand.getValueType().getScalarType() == MVT::i1)
5312       return getNOT(DL, Operand, Operand.getValueType());
5313     break;
5314   case ISD::VECREDUCE_SMIN:
5315   case ISD::VECREDUCE_UMAX:
5316     if (Operand.getValueType().getScalarType() == MVT::i1)
5317       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5318     break;
5319   case ISD::VECREDUCE_SMAX:
5320   case ISD::VECREDUCE_UMIN:
5321     if (Operand.getValueType().getScalarType() == MVT::i1)
5322       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5323     break;
5324   }
5325 
5326   SDNode *N;
5327   SDVTList VTs = getVTList(VT);
5328   SDValue Ops[] = {Operand};
5329   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5330     FoldingSetNodeID ID;
5331     AddNodeIDNode(ID, Opcode, VTs, Ops);
5332     void *IP = nullptr;
5333     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5334       E->intersectFlagsWith(Flags);
5335       return SDValue(E, 0);
5336     }
5337 
5338     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5339     N->setFlags(Flags);
5340     createOperands(N, Ops);
5341     CSEMap.InsertNode(N, IP);
5342   } else {
5343     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5344     createOperands(N, Ops);
5345   }
5346 
5347   InsertNode(N);
5348   SDValue V = SDValue(N, 0);
5349   NewSDValueDbgMsg(V, "Creating new node: ", this);
5350   return V;
5351 }
5352 
5353 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5354                                        const APInt &C2) {
5355   switch (Opcode) {
5356   case ISD::ADD:  return C1 + C2;
5357   case ISD::SUB:  return C1 - C2;
5358   case ISD::MUL:  return C1 * C2;
5359   case ISD::AND:  return C1 & C2;
5360   case ISD::OR:   return C1 | C2;
5361   case ISD::XOR:  return C1 ^ C2;
5362   case ISD::SHL:  return C1 << C2;
5363   case ISD::SRL:  return C1.lshr(C2);
5364   case ISD::SRA:  return C1.ashr(C2);
5365   case ISD::ROTL: return C1.rotl(C2);
5366   case ISD::ROTR: return C1.rotr(C2);
5367   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5368   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5369   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5370   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5371   case ISD::SADDSAT: return C1.sadd_sat(C2);
5372   case ISD::UADDSAT: return C1.uadd_sat(C2);
5373   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5374   case ISD::USUBSAT: return C1.usub_sat(C2);
5375   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5376   case ISD::USHLSAT: return C1.ushl_sat(C2);
5377   case ISD::UDIV:
5378     if (!C2.getBoolValue())
5379       break;
5380     return C1.udiv(C2);
5381   case ISD::UREM:
5382     if (!C2.getBoolValue())
5383       break;
5384     return C1.urem(C2);
5385   case ISD::SDIV:
5386     if (!C2.getBoolValue())
5387       break;
5388     return C1.sdiv(C2);
5389   case ISD::SREM:
5390     if (!C2.getBoolValue())
5391       break;
5392     return C1.srem(C2);
5393   case ISD::MULHS: {
5394     unsigned FullWidth = C1.getBitWidth() * 2;
5395     APInt C1Ext = C1.sext(FullWidth);
5396     APInt C2Ext = C2.sext(FullWidth);
5397     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5398   }
5399   case ISD::MULHU: {
5400     unsigned FullWidth = C1.getBitWidth() * 2;
5401     APInt C1Ext = C1.zext(FullWidth);
5402     APInt C2Ext = C2.zext(FullWidth);
5403     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5404   }
5405   case ISD::AVGFLOORS: {
5406     unsigned FullWidth = C1.getBitWidth() + 1;
5407     APInt C1Ext = C1.sext(FullWidth);
5408     APInt C2Ext = C2.sext(FullWidth);
5409     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5410   }
5411   case ISD::AVGFLOORU: {
5412     unsigned FullWidth = C1.getBitWidth() + 1;
5413     APInt C1Ext = C1.zext(FullWidth);
5414     APInt C2Ext = C2.zext(FullWidth);
5415     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5416   }
5417   case ISD::AVGCEILS: {
5418     unsigned FullWidth = C1.getBitWidth() + 1;
5419     APInt C1Ext = C1.sext(FullWidth);
5420     APInt C2Ext = C2.sext(FullWidth);
5421     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5422   }
5423   case ISD::AVGCEILU: {
5424     unsigned FullWidth = C1.getBitWidth() + 1;
5425     APInt C1Ext = C1.zext(FullWidth);
5426     APInt C2Ext = C2.zext(FullWidth);
5427     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5428   }
5429   }
5430   return llvm::None;
5431 }
5432 
5433 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5434                                        const GlobalAddressSDNode *GA,
5435                                        const SDNode *N2) {
5436   if (GA->getOpcode() != ISD::GlobalAddress)
5437     return SDValue();
5438   if (!TLI->isOffsetFoldingLegal(GA))
5439     return SDValue();
5440   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5441   if (!C2)
5442     return SDValue();
5443   int64_t Offset = C2->getSExtValue();
5444   switch (Opcode) {
5445   case ISD::ADD: break;
5446   case ISD::SUB: Offset = -uint64_t(Offset); break;
5447   default: return SDValue();
5448   }
5449   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5450                           GA->getOffset() + uint64_t(Offset));
5451 }
5452 
5453 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5454   switch (Opcode) {
5455   case ISD::SDIV:
5456   case ISD::UDIV:
5457   case ISD::SREM:
5458   case ISD::UREM: {
5459     // If a divisor is zero/undef or any element of a divisor vector is
5460     // zero/undef, the whole op is undef.
5461     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5462     SDValue Divisor = Ops[1];
5463     if (Divisor.isUndef() || isNullConstant(Divisor))
5464       return true;
5465 
5466     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5467            llvm::any_of(Divisor->op_values(),
5468                         [](SDValue V) { return V.isUndef() ||
5469                                         isNullConstant(V); });
5470     // TODO: Handle signed overflow.
5471   }
5472   // TODO: Handle oversized shifts.
5473   default:
5474     return false;
5475   }
5476 }
5477 
5478 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5479                                              EVT VT, ArrayRef<SDValue> Ops) {
5480   // If the opcode is a target-specific ISD node, there's nothing we can
5481   // do here and the operand rules may not line up with the below, so
5482   // bail early.
5483   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5484   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5485   // foldCONCAT_VECTORS in getNode before this is called.
5486   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5487     return SDValue();
5488 
5489   unsigned NumOps = Ops.size();
5490   if (NumOps == 0)
5491     return SDValue();
5492 
5493   if (isUndef(Opcode, Ops))
5494     return getUNDEF(VT);
5495 
5496   // Handle binops special cases.
5497   if (NumOps == 2) {
5498     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5499       return CFP;
5500 
5501     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5502       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5503         if (C1->isOpaque() || C2->isOpaque())
5504           return SDValue();
5505 
5506         Optional<APInt> FoldAttempt =
5507             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5508         if (!FoldAttempt)
5509           return SDValue();
5510 
5511         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5512         assert((!Folded || !VT.isVector()) &&
5513                "Can't fold vectors ops with scalar operands");
5514         return Folded;
5515       }
5516     }
5517 
5518     // fold (add Sym, c) -> Sym+c
5519     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5520       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5521     if (TLI->isCommutativeBinOp(Opcode))
5522       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5523         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5524   }
5525 
5526   // This is for vector folding only from here on.
5527   if (!VT.isVector())
5528     return SDValue();
5529 
5530   ElementCount NumElts = VT.getVectorElementCount();
5531 
5532   // See if we can fold through bitcasted integer ops.
5533   // TODO: Can we handle undef elements?
5534   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5535       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5536       Ops[0].getOpcode() == ISD::BITCAST &&
5537       Ops[1].getOpcode() == ISD::BITCAST) {
5538     SDValue N1 = peekThroughBitcasts(Ops[0]);
5539     SDValue N2 = peekThroughBitcasts(Ops[1]);
5540     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5541     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5542     EVT BVVT = N1.getValueType();
5543     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5544       bool IsLE = getDataLayout().isLittleEndian();
5545       unsigned EltBits = VT.getScalarSizeInBits();
5546       SmallVector<APInt> RawBits1, RawBits2;
5547       BitVector UndefElts1, UndefElts2;
5548       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5549           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5550           UndefElts1.none() && UndefElts2.none()) {
5551         SmallVector<APInt> RawBits;
5552         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5553           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5554           if (!Fold)
5555             break;
5556           RawBits.push_back(Fold.getValue());
5557         }
5558         if (RawBits.size() == NumElts.getFixedValue()) {
5559           // We have constant folded, but we need to cast this again back to
5560           // the original (possibly legalized) type.
5561           SmallVector<APInt> DstBits;
5562           BitVector DstUndefs;
5563           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5564                                            DstBits, RawBits, DstUndefs,
5565                                            BitVector(RawBits.size(), false));
5566           EVT BVEltVT = BV1->getOperand(0).getValueType();
5567           unsigned BVEltBits = BVEltVT.getSizeInBits();
5568           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5569           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5570             if (DstUndefs[I])
5571               continue;
5572             Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5573           }
5574           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5575         }
5576       }
5577     }
5578   }
5579 
5580   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5581   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5582   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5583       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5584     APInt RHSVal;
5585     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5586       APInt NewStep = Opcode == ISD::MUL
5587                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5588                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5589       return getStepVector(DL, VT, NewStep);
5590     }
5591   }
5592 
5593   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5594     return !Op.getValueType().isVector() ||
5595            Op.getValueType().getVectorElementCount() == NumElts;
5596   };
5597 
5598   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5599     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5600            Op.getOpcode() == ISD::BUILD_VECTOR ||
5601            Op.getOpcode() == ISD::SPLAT_VECTOR;
5602   };
5603 
5604   // All operands must be vector types with the same number of elements as
5605   // the result type and must be either UNDEF or a build/splat vector
5606   // or UNDEF scalars.
5607   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5608       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5609     return SDValue();
5610 
5611   // If we are comparing vectors, then the result needs to be a i1 boolean that
5612   // is then extended back to the legal result type depending on how booleans
5613   // are represented.
5614   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5615   ISD::NodeType ExtendCode =
5616       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5617           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5618           : ISD::SIGN_EXTEND;
5619 
5620   // Find legal integer scalar type for constant promotion and
5621   // ensure that its scalar size is at least as large as source.
5622   EVT LegalSVT = VT.getScalarType();
5623   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5624     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5625     if (LegalSVT.bitsLT(VT.getScalarType()))
5626       return SDValue();
5627   }
5628 
5629   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5630   // only have one operand to check. For fixed-length vector types we may have
5631   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5632   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5633 
5634   // Constant fold each scalar lane separately.
5635   SmallVector<SDValue, 4> ScalarResults;
5636   for (unsigned I = 0; I != NumVectorElts; I++) {
5637     SmallVector<SDValue, 4> ScalarOps;
5638     for (SDValue Op : Ops) {
5639       EVT InSVT = Op.getValueType().getScalarType();
5640       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5641           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5642         if (Op.isUndef())
5643           ScalarOps.push_back(getUNDEF(InSVT));
5644         else
5645           ScalarOps.push_back(Op);
5646         continue;
5647       }
5648 
5649       SDValue ScalarOp =
5650           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5651       EVT ScalarVT = ScalarOp.getValueType();
5652 
5653       // Build vector (integer) scalar operands may need implicit
5654       // truncation - do this before constant folding.
5655       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5656         // Don't create illegally-typed nodes unless they're constants or undef
5657         // - if we fail to constant fold we can't guarantee the (dead) nodes
5658         // we're creating will be cleaned up before being visited for
5659         // legalization.
5660         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5661             !isa<ConstantSDNode>(ScalarOp) &&
5662             TLI->getTypeAction(*getContext(), InSVT) !=
5663                 TargetLowering::TypeLegal)
5664           return SDValue();
5665         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5666       }
5667 
5668       ScalarOps.push_back(ScalarOp);
5669     }
5670 
5671     // Constant fold the scalar operands.
5672     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5673 
5674     // Legalize the (integer) scalar constant if necessary.
5675     if (LegalSVT != SVT)
5676       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5677 
5678     // Scalar folding only succeeded if the result is a constant or UNDEF.
5679     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5680         ScalarResult.getOpcode() != ISD::ConstantFP)
5681       return SDValue();
5682     ScalarResults.push_back(ScalarResult);
5683   }
5684 
5685   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5686                                    : getBuildVector(VT, DL, ScalarResults);
5687   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5688   return V;
5689 }
5690 
5691 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5692                                          EVT VT, SDValue N1, SDValue N2) {
5693   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5694   //       should. That will require dealing with a potentially non-default
5695   //       rounding mode, checking the "opStatus" return value from the APFloat
5696   //       math calculations, and possibly other variations.
5697   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5698   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5699   if (N1CFP && N2CFP) {
5700     APFloat C1 = N1CFP->getValueAPF(); // make copy
5701     const APFloat &C2 = N2CFP->getValueAPF();
5702     switch (Opcode) {
5703     case ISD::FADD:
5704       C1.add(C2, APFloat::rmNearestTiesToEven);
5705       return getConstantFP(C1, DL, VT);
5706     case ISD::FSUB:
5707       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5708       return getConstantFP(C1, DL, VT);
5709     case ISD::FMUL:
5710       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5711       return getConstantFP(C1, DL, VT);
5712     case ISD::FDIV:
5713       C1.divide(C2, APFloat::rmNearestTiesToEven);
5714       return getConstantFP(C1, DL, VT);
5715     case ISD::FREM:
5716       C1.mod(C2);
5717       return getConstantFP(C1, DL, VT);
5718     case ISD::FCOPYSIGN:
5719       C1.copySign(C2);
5720       return getConstantFP(C1, DL, VT);
5721     case ISD::FMINNUM:
5722       return getConstantFP(minnum(C1, C2), DL, VT);
5723     case ISD::FMAXNUM:
5724       return getConstantFP(maxnum(C1, C2), DL, VT);
5725     case ISD::FMINIMUM:
5726       return getConstantFP(minimum(C1, C2), DL, VT);
5727     case ISD::FMAXIMUM:
5728       return getConstantFP(maximum(C1, C2), DL, VT);
5729     default: break;
5730     }
5731   }
5732   if (N1CFP && Opcode == ISD::FP_ROUND) {
5733     APFloat C1 = N1CFP->getValueAPF();    // make copy
5734     bool Unused;
5735     // This can return overflow, underflow, or inexact; we don't care.
5736     // FIXME need to be more flexible about rounding mode.
5737     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5738                       &Unused);
5739     return getConstantFP(C1, DL, VT);
5740   }
5741 
5742   switch (Opcode) {
5743   case ISD::FSUB:
5744     // -0.0 - undef --> undef (consistent with "fneg undef")
5745     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5746       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5747         return getUNDEF(VT);
5748     LLVM_FALLTHROUGH;
5749 
5750   case ISD::FADD:
5751   case ISD::FMUL:
5752   case ISD::FDIV:
5753   case ISD::FREM:
5754     // If both operands are undef, the result is undef. If 1 operand is undef,
5755     // the result is NaN. This should match the behavior of the IR optimizer.
5756     if (N1.isUndef() && N2.isUndef())
5757       return getUNDEF(VT);
5758     if (N1.isUndef() || N2.isUndef())
5759       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5760   }
5761   return SDValue();
5762 }
5763 
5764 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5765   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5766 
5767   // There's no need to assert on a byte-aligned pointer. All pointers are at
5768   // least byte aligned.
5769   if (A == Align(1))
5770     return Val;
5771 
5772   FoldingSetNodeID ID;
5773   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5774   ID.AddInteger(A.value());
5775 
5776   void *IP = nullptr;
5777   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5778     return SDValue(E, 0);
5779 
5780   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5781                                          Val.getValueType(), A);
5782   createOperands(N, {Val});
5783 
5784   CSEMap.InsertNode(N, IP);
5785   InsertNode(N);
5786 
5787   SDValue V(N, 0);
5788   NewSDValueDbgMsg(V, "Creating new node: ", this);
5789   return V;
5790 }
5791 
5792 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5793                               SDValue N1, SDValue N2) {
5794   SDNodeFlags Flags;
5795   if (Inserter)
5796     Flags = Inserter->getFlags();
5797   return getNode(Opcode, DL, VT, N1, N2, Flags);
5798 }
5799 
5800 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5801                                                 SDValue &N2) const {
5802   if (!TLI->isCommutativeBinOp(Opcode))
5803     return;
5804 
5805   // Canonicalize:
5806   //   binop(const, nonconst) -> binop(nonconst, const)
5807   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5808   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5809   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5810   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5811   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5812     std::swap(N1, N2);
5813 
5814   // Canonicalize:
5815   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5816   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5817            N2.getOpcode() == ISD::STEP_VECTOR)
5818     std::swap(N1, N2);
5819 }
5820 
5821 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5822                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5823   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5824          N2.getOpcode() != ISD::DELETED_NODE &&
5825          "Operand is DELETED_NODE!");
5826 
5827   canonicalizeCommutativeBinop(Opcode, N1, N2);
5828 
5829   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5830   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5831 
5832   // Don't allow undefs in vector splats - we might be returning N2 when folding
5833   // to zero etc.
5834   ConstantSDNode *N2CV =
5835       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5836 
5837   switch (Opcode) {
5838   default: break;
5839   case ISD::TokenFactor:
5840     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5841            N2.getValueType() == MVT::Other && "Invalid token factor!");
5842     // Fold trivial token factors.
5843     if (N1.getOpcode() == ISD::EntryToken) return N2;
5844     if (N2.getOpcode() == ISD::EntryToken) return N1;
5845     if (N1 == N2) return N1;
5846     break;
5847   case ISD::BUILD_VECTOR: {
5848     // Attempt to simplify BUILD_VECTOR.
5849     SDValue Ops[] = {N1, N2};
5850     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5851       return V;
5852     break;
5853   }
5854   case ISD::CONCAT_VECTORS: {
5855     SDValue Ops[] = {N1, N2};
5856     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5857       return V;
5858     break;
5859   }
5860   case ISD::AND:
5861     assert(VT.isInteger() && "This operator does not apply to FP types!");
5862     assert(N1.getValueType() == N2.getValueType() &&
5863            N1.getValueType() == VT && "Binary operator types must match!");
5864     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5865     // worth handling here.
5866     if (N2CV && N2CV->isZero())
5867       return N2;
5868     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5869       return N1;
5870     break;
5871   case ISD::OR:
5872   case ISD::XOR:
5873   case ISD::ADD:
5874   case ISD::SUB:
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     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5879     // it's worth handling here.
5880     if (N2CV && N2CV->isZero())
5881       return N1;
5882     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5883         VT.getVectorElementType() == MVT::i1)
5884       return getNode(ISD::XOR, DL, VT, N1, N2);
5885     break;
5886   case ISD::MUL:
5887     assert(VT.isInteger() && "This operator does not apply to FP types!");
5888     assert(N1.getValueType() == N2.getValueType() &&
5889            N1.getValueType() == VT && "Binary operator types must match!");
5890     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5891       return getNode(ISD::AND, DL, VT, N1, N2);
5892     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5893       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5894       const APInt &N2CImm = N2C->getAPIntValue();
5895       return getVScale(DL, VT, MulImm * N2CImm);
5896     }
5897     break;
5898   case ISD::UDIV:
5899   case ISD::UREM:
5900   case ISD::MULHU:
5901   case ISD::MULHS:
5902   case ISD::SDIV:
5903   case ISD::SREM:
5904   case ISD::SADDSAT:
5905   case ISD::SSUBSAT:
5906   case ISD::UADDSAT:
5907   case ISD::USUBSAT:
5908     assert(VT.isInteger() && "This operator does not apply to FP types!");
5909     assert(N1.getValueType() == N2.getValueType() &&
5910            N1.getValueType() == VT && "Binary operator types must match!");
5911     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5912       // fold (add_sat x, y) -> (or x, y) for bool types.
5913       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5914         return getNode(ISD::OR, DL, VT, N1, N2);
5915       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5916       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5917         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5918     }
5919     break;
5920   case ISD::SMIN:
5921   case ISD::UMAX:
5922     assert(VT.isInteger() && "This operator does not apply to FP types!");
5923     assert(N1.getValueType() == N2.getValueType() &&
5924            N1.getValueType() == VT && "Binary operator types must match!");
5925     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5926       return getNode(ISD::OR, DL, VT, N1, N2);
5927     break;
5928   case ISD::SMAX:
5929   case ISD::UMIN:
5930     assert(VT.isInteger() && "This operator does not apply to FP types!");
5931     assert(N1.getValueType() == N2.getValueType() &&
5932            N1.getValueType() == VT && "Binary operator types must match!");
5933     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5934       return getNode(ISD::AND, DL, VT, N1, N2);
5935     break;
5936   case ISD::FADD:
5937   case ISD::FSUB:
5938   case ISD::FMUL:
5939   case ISD::FDIV:
5940   case ISD::FREM:
5941     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5942     assert(N1.getValueType() == N2.getValueType() &&
5943            N1.getValueType() == VT && "Binary operator types must match!");
5944     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5945       return V;
5946     break;
5947   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5948     assert(N1.getValueType() == VT &&
5949            N1.getValueType().isFloatingPoint() &&
5950            N2.getValueType().isFloatingPoint() &&
5951            "Invalid FCOPYSIGN!");
5952     break;
5953   case ISD::SHL:
5954     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5955       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5956       const APInt &ShiftImm = N2C->getAPIntValue();
5957       return getVScale(DL, VT, MulImm << ShiftImm);
5958     }
5959     LLVM_FALLTHROUGH;
5960   case ISD::SRA:
5961   case ISD::SRL:
5962     if (SDValue V = simplifyShift(N1, N2))
5963       return V;
5964     LLVM_FALLTHROUGH;
5965   case ISD::ROTL:
5966   case ISD::ROTR:
5967     assert(VT == N1.getValueType() &&
5968            "Shift operators return type must be the same as their first arg");
5969     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5970            "Shifts only work on integers");
5971     assert((!VT.isVector() || VT == N2.getValueType()) &&
5972            "Vector shift amounts must be in the same as their first arg");
5973     // Verify that the shift amount VT is big enough to hold valid shift
5974     // amounts.  This catches things like trying to shift an i1024 value by an
5975     // i8, which is easy to fall into in generic code that uses
5976     // TLI.getShiftAmount().
5977     assert(N2.getValueType().getScalarSizeInBits() >=
5978                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5979            "Invalid use of small shift amount with oversized value!");
5980 
5981     // Always fold shifts of i1 values so the code generator doesn't need to
5982     // handle them.  Since we know the size of the shift has to be less than the
5983     // size of the value, the shift/rotate count is guaranteed to be zero.
5984     if (VT == MVT::i1)
5985       return N1;
5986     if (N2CV && N2CV->isZero())
5987       return N1;
5988     break;
5989   case ISD::FP_ROUND:
5990     assert(VT.isFloatingPoint() &&
5991            N1.getValueType().isFloatingPoint() &&
5992            VT.bitsLE(N1.getValueType()) &&
5993            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5994            "Invalid FP_ROUND!");
5995     if (N1.getValueType() == VT) return N1;  // noop conversion.
5996     break;
5997   case ISD::AssertSext:
5998   case ISD::AssertZext: {
5999     EVT EVT = cast<VTSDNode>(N2)->getVT();
6000     assert(VT == N1.getValueType() && "Not an inreg extend!");
6001     assert(VT.isInteger() && EVT.isInteger() &&
6002            "Cannot *_EXTEND_INREG FP types");
6003     assert(!EVT.isVector() &&
6004            "AssertSExt/AssertZExt type should be the vector element type "
6005            "rather than the vector type!");
6006     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6007     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6008     break;
6009   }
6010   case ISD::SIGN_EXTEND_INREG: {
6011     EVT EVT = cast<VTSDNode>(N2)->getVT();
6012     assert(VT == N1.getValueType() && "Not an inreg extend!");
6013     assert(VT.isInteger() && EVT.isInteger() &&
6014            "Cannot *_EXTEND_INREG FP types");
6015     assert(EVT.isVector() == VT.isVector() &&
6016            "SIGN_EXTEND_INREG type should be vector iff the operand "
6017            "type is vector!");
6018     assert((!EVT.isVector() ||
6019             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6020            "Vector element counts must match in SIGN_EXTEND_INREG");
6021     assert(EVT.bitsLE(VT) && "Not extending!");
6022     if (EVT == VT) return N1;  // Not actually extending
6023 
6024     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6025       unsigned FromBits = EVT.getScalarSizeInBits();
6026       Val <<= Val.getBitWidth() - FromBits;
6027       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6028       return getConstant(Val, DL, ConstantVT);
6029     };
6030 
6031     if (N1C) {
6032       const APInt &Val = N1C->getAPIntValue();
6033       return SignExtendInReg(Val, VT);
6034     }
6035 
6036     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6037       SmallVector<SDValue, 8> Ops;
6038       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6039       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6040         SDValue Op = N1.getOperand(i);
6041         if (Op.isUndef()) {
6042           Ops.push_back(getUNDEF(OpVT));
6043           continue;
6044         }
6045         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6046         APInt Val = C->getAPIntValue();
6047         Ops.push_back(SignExtendInReg(Val, OpVT));
6048       }
6049       return getBuildVector(VT, DL, Ops);
6050     }
6051     break;
6052   }
6053   case ISD::FP_TO_SINT_SAT:
6054   case ISD::FP_TO_UINT_SAT: {
6055     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6056            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6057     assert(N1.getValueType().isVector() == VT.isVector() &&
6058            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6059            "vector!");
6060     assert((!VT.isVector() || VT.getVectorNumElements() ==
6061                                   N1.getValueType().getVectorNumElements()) &&
6062            "Vector element counts must match in FP_TO_*INT_SAT");
6063     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6064            "Type to saturate to must be a scalar.");
6065     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6066            "Not extending!");
6067     break;
6068   }
6069   case ISD::EXTRACT_VECTOR_ELT:
6070     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6071            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6072              element type of the vector.");
6073 
6074     // Extract from an undefined value or using an undefined index is undefined.
6075     if (N1.isUndef() || N2.isUndef())
6076       return getUNDEF(VT);
6077 
6078     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6079     // vectors. For scalable vectors we will provide appropriate support for
6080     // dealing with arbitrary indices.
6081     if (N2C && N1.getValueType().isFixedLengthVector() &&
6082         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6083       return getUNDEF(VT);
6084 
6085     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6086     // expanding copies of large vectors from registers. This only works for
6087     // fixed length vectors, since we need to know the exact number of
6088     // elements.
6089     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6090         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6091       unsigned Factor =
6092         N1.getOperand(0).getValueType().getVectorNumElements();
6093       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6094                      N1.getOperand(N2C->getZExtValue() / Factor),
6095                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6096     }
6097 
6098     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6099     // lowering is expanding large vector constants.
6100     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6101                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6102       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6103               N1.getValueType().isFixedLengthVector()) &&
6104              "BUILD_VECTOR used for scalable vectors");
6105       unsigned Index =
6106           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6107       SDValue Elt = N1.getOperand(Index);
6108 
6109       if (VT != Elt.getValueType())
6110         // If the vector element type is not legal, the BUILD_VECTOR operands
6111         // are promoted and implicitly truncated, and the result implicitly
6112         // extended. Make that explicit here.
6113         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6114 
6115       return Elt;
6116     }
6117 
6118     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6119     // operations are lowered to scalars.
6120     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6121       // If the indices are the same, return the inserted element else
6122       // if the indices are known different, extract the element from
6123       // the original vector.
6124       SDValue N1Op2 = N1.getOperand(2);
6125       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6126 
6127       if (N1Op2C && N2C) {
6128         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6129           if (VT == N1.getOperand(1).getValueType())
6130             return N1.getOperand(1);
6131           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6132         }
6133         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6134       }
6135     }
6136 
6137     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6138     // when vector types are scalarized and v1iX is legal.
6139     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6140     // Here we are completely ignoring the extract element index (N2),
6141     // which is fine for fixed width vectors, since any index other than 0
6142     // is undefined anyway. However, this cannot be ignored for scalable
6143     // vectors - in theory we could support this, but we don't want to do this
6144     // without a profitability check.
6145     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6146         N1.getValueType().isFixedLengthVector() &&
6147         N1.getValueType().getVectorNumElements() == 1) {
6148       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6149                      N1.getOperand(1));
6150     }
6151     break;
6152   case ISD::EXTRACT_ELEMENT:
6153     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6154     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6155            (N1.getValueType().isInteger() == VT.isInteger()) &&
6156            N1.getValueType() != VT &&
6157            "Wrong types for EXTRACT_ELEMENT!");
6158 
6159     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6160     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6161     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6162     if (N1.getOpcode() == ISD::BUILD_PAIR)
6163       return N1.getOperand(N2C->getZExtValue());
6164 
6165     // EXTRACT_ELEMENT of a constant int is also very common.
6166     if (N1C) {
6167       unsigned ElementSize = VT.getSizeInBits();
6168       unsigned Shift = ElementSize * N2C->getZExtValue();
6169       const APInt &Val = N1C->getAPIntValue();
6170       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6171     }
6172     break;
6173   case ISD::EXTRACT_SUBVECTOR: {
6174     EVT N1VT = N1.getValueType();
6175     assert(VT.isVector() && N1VT.isVector() &&
6176            "Extract subvector VTs must be vectors!");
6177     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6178            "Extract subvector VTs must have the same element type!");
6179     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6180            "Cannot extract a scalable vector from a fixed length vector!");
6181     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6182             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6183            "Extract subvector must be from larger vector to smaller vector!");
6184     assert(N2C && "Extract subvector index must be a constant");
6185     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6186             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6187                 N1VT.getVectorMinNumElements()) &&
6188            "Extract subvector overflow!");
6189     assert(N2C->getAPIntValue().getBitWidth() ==
6190                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6191            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6192 
6193     // Trivial extraction.
6194     if (VT == N1VT)
6195       return N1;
6196 
6197     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6198     if (N1.isUndef())
6199       return getUNDEF(VT);
6200 
6201     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6202     // the concat have the same type as the extract.
6203     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6204         VT == N1.getOperand(0).getValueType()) {
6205       unsigned Factor = VT.getVectorMinNumElements();
6206       return N1.getOperand(N2C->getZExtValue() / Factor);
6207     }
6208 
6209     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6210     // during shuffle legalization.
6211     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6212         VT == N1.getOperand(1).getValueType())
6213       return N1.getOperand(1);
6214     break;
6215   }
6216   }
6217 
6218   // Perform trivial constant folding.
6219   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6220     return SV;
6221 
6222   // Canonicalize an UNDEF to the RHS, even over a constant.
6223   if (N1.isUndef()) {
6224     if (TLI->isCommutativeBinOp(Opcode)) {
6225       std::swap(N1, N2);
6226     } else {
6227       switch (Opcode) {
6228       case ISD::SUB:
6229         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6230       case ISD::SIGN_EXTEND_INREG:
6231       case ISD::UDIV:
6232       case ISD::SDIV:
6233       case ISD::UREM:
6234       case ISD::SREM:
6235       case ISD::SSUBSAT:
6236       case ISD::USUBSAT:
6237         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6238       }
6239     }
6240   }
6241 
6242   // Fold a bunch of operators when the RHS is undef.
6243   if (N2.isUndef()) {
6244     switch (Opcode) {
6245     case ISD::XOR:
6246       if (N1.isUndef())
6247         // Handle undef ^ undef -> 0 special case. This is a common
6248         // idiom (misuse).
6249         return getConstant(0, DL, VT);
6250       LLVM_FALLTHROUGH;
6251     case ISD::ADD:
6252     case ISD::SUB:
6253     case ISD::UDIV:
6254     case ISD::SDIV:
6255     case ISD::UREM:
6256     case ISD::SREM:
6257       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6258     case ISD::MUL:
6259     case ISD::AND:
6260     case ISD::SSUBSAT:
6261     case ISD::USUBSAT:
6262       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6263     case ISD::OR:
6264     case ISD::SADDSAT:
6265     case ISD::UADDSAT:
6266       return getAllOnesConstant(DL, VT);
6267     }
6268   }
6269 
6270   // Memoize this node if possible.
6271   SDNode *N;
6272   SDVTList VTs = getVTList(VT);
6273   SDValue Ops[] = {N1, N2};
6274   if (VT != MVT::Glue) {
6275     FoldingSetNodeID ID;
6276     AddNodeIDNode(ID, Opcode, VTs, Ops);
6277     void *IP = nullptr;
6278     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6279       E->intersectFlagsWith(Flags);
6280       return SDValue(E, 0);
6281     }
6282 
6283     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6284     N->setFlags(Flags);
6285     createOperands(N, Ops);
6286     CSEMap.InsertNode(N, IP);
6287   } else {
6288     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6289     createOperands(N, Ops);
6290   }
6291 
6292   InsertNode(N);
6293   SDValue V = SDValue(N, 0);
6294   NewSDValueDbgMsg(V, "Creating new node: ", this);
6295   return V;
6296 }
6297 
6298 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6299                               SDValue N1, SDValue N2, SDValue N3) {
6300   SDNodeFlags Flags;
6301   if (Inserter)
6302     Flags = Inserter->getFlags();
6303   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6304 }
6305 
6306 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6307                               SDValue N1, SDValue N2, SDValue N3,
6308                               const SDNodeFlags Flags) {
6309   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6310          N2.getOpcode() != ISD::DELETED_NODE &&
6311          N3.getOpcode() != ISD::DELETED_NODE &&
6312          "Operand is DELETED_NODE!");
6313   // Perform various simplifications.
6314   switch (Opcode) {
6315   case ISD::FMA: {
6316     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6317     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6318            N3.getValueType() == VT && "FMA types must match!");
6319     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6320     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6321     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6322     if (N1CFP && N2CFP && N3CFP) {
6323       APFloat  V1 = N1CFP->getValueAPF();
6324       const APFloat &V2 = N2CFP->getValueAPF();
6325       const APFloat &V3 = N3CFP->getValueAPF();
6326       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6327       return getConstantFP(V1, DL, VT);
6328     }
6329     break;
6330   }
6331   case ISD::BUILD_VECTOR: {
6332     // Attempt to simplify BUILD_VECTOR.
6333     SDValue Ops[] = {N1, N2, N3};
6334     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6335       return V;
6336     break;
6337   }
6338   case ISD::CONCAT_VECTORS: {
6339     SDValue Ops[] = {N1, N2, N3};
6340     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6341       return V;
6342     break;
6343   }
6344   case ISD::SETCC: {
6345     assert(VT.isInteger() && "SETCC result type must be an integer!");
6346     assert(N1.getValueType() == N2.getValueType() &&
6347            "SETCC operands must have the same type!");
6348     assert(VT.isVector() == N1.getValueType().isVector() &&
6349            "SETCC type should be vector iff the operand type is vector!");
6350     assert((!VT.isVector() || VT.getVectorElementCount() ==
6351                                   N1.getValueType().getVectorElementCount()) &&
6352            "SETCC vector element counts must match!");
6353     // Use FoldSetCC to simplify SETCC's.
6354     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6355       return V;
6356     // Vector constant folding.
6357     SDValue Ops[] = {N1, N2, N3};
6358     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6359       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6360       return V;
6361     }
6362     break;
6363   }
6364   case ISD::SELECT:
6365   case ISD::VSELECT:
6366     if (SDValue V = simplifySelect(N1, N2, N3))
6367       return V;
6368     break;
6369   case ISD::VECTOR_SHUFFLE:
6370     llvm_unreachable("should use getVectorShuffle constructor!");
6371   case ISD::VECTOR_SPLICE: {
6372     if (cast<ConstantSDNode>(N3)->isNullValue())
6373       return N1;
6374     break;
6375   }
6376   case ISD::INSERT_VECTOR_ELT: {
6377     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6378     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6379     // for scalable vectors where we will generate appropriate code to
6380     // deal with out-of-bounds cases correctly.
6381     if (N3C && N1.getValueType().isFixedLengthVector() &&
6382         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6383       return getUNDEF(VT);
6384 
6385     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6386     if (N3.isUndef())
6387       return getUNDEF(VT);
6388 
6389     // If the inserted element is an UNDEF, just use the input vector.
6390     if (N2.isUndef())
6391       return N1;
6392 
6393     break;
6394   }
6395   case ISD::INSERT_SUBVECTOR: {
6396     // Inserting undef into undef is still undef.
6397     if (N1.isUndef() && N2.isUndef())
6398       return getUNDEF(VT);
6399 
6400     EVT N2VT = N2.getValueType();
6401     assert(VT == N1.getValueType() &&
6402            "Dest and insert subvector source types must match!");
6403     assert(VT.isVector() && N2VT.isVector() &&
6404            "Insert subvector VTs must be vectors!");
6405     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6406            "Cannot insert a scalable vector into a fixed length vector!");
6407     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6408             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6409            "Insert subvector must be from smaller vector to larger vector!");
6410     assert(isa<ConstantSDNode>(N3) &&
6411            "Insert subvector index must be constant");
6412     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6413             (N2VT.getVectorMinNumElements() +
6414              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6415                 VT.getVectorMinNumElements()) &&
6416            "Insert subvector overflow!");
6417     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6418                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6419            "Constant index for INSERT_SUBVECTOR has an invalid size");
6420 
6421     // Trivial insertion.
6422     if (VT == N2VT)
6423       return N2;
6424 
6425     // If this is an insert of an extracted vector into an undef vector, we
6426     // can just use the input to the extract.
6427     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6428         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6429       return N2.getOperand(0);
6430     break;
6431   }
6432   case ISD::BITCAST:
6433     // Fold bit_convert nodes from a type to themselves.
6434     if (N1.getValueType() == VT)
6435       return N1;
6436     break;
6437   }
6438 
6439   // Memoize node if it doesn't produce a flag.
6440   SDNode *N;
6441   SDVTList VTs = getVTList(VT);
6442   SDValue Ops[] = {N1, N2, N3};
6443   if (VT != MVT::Glue) {
6444     FoldingSetNodeID ID;
6445     AddNodeIDNode(ID, Opcode, VTs, Ops);
6446     void *IP = nullptr;
6447     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6448       E->intersectFlagsWith(Flags);
6449       return SDValue(E, 0);
6450     }
6451 
6452     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6453     N->setFlags(Flags);
6454     createOperands(N, Ops);
6455     CSEMap.InsertNode(N, IP);
6456   } else {
6457     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6458     createOperands(N, Ops);
6459   }
6460 
6461   InsertNode(N);
6462   SDValue V = SDValue(N, 0);
6463   NewSDValueDbgMsg(V, "Creating new node: ", this);
6464   return V;
6465 }
6466 
6467 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6468                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6469   SDValue Ops[] = { N1, N2, N3, N4 };
6470   return getNode(Opcode, DL, VT, Ops);
6471 }
6472 
6473 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6474                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6475                               SDValue N5) {
6476   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6477   return getNode(Opcode, DL, VT, Ops);
6478 }
6479 
6480 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6481 /// the incoming stack arguments to be loaded from the stack.
6482 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6483   SmallVector<SDValue, 8> ArgChains;
6484 
6485   // Include the original chain at the beginning of the list. When this is
6486   // used by target LowerCall hooks, this helps legalize find the
6487   // CALLSEQ_BEGIN node.
6488   ArgChains.push_back(Chain);
6489 
6490   // Add a chain value for each stack argument.
6491   for (SDNode *U : getEntryNode().getNode()->uses())
6492     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6493       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6494         if (FI->getIndex() < 0)
6495           ArgChains.push_back(SDValue(L, 1));
6496 
6497   // Build a tokenfactor for all the chains.
6498   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6499 }
6500 
6501 /// getMemsetValue - Vectorized representation of the memset value
6502 /// operand.
6503 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6504                               const SDLoc &dl) {
6505   assert(!Value.isUndef());
6506 
6507   unsigned NumBits = VT.getScalarSizeInBits();
6508   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6509     assert(C->getAPIntValue().getBitWidth() == 8);
6510     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6511     if (VT.isInteger()) {
6512       bool IsOpaque = VT.getSizeInBits() > 64 ||
6513           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6514       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6515     }
6516     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6517                              VT);
6518   }
6519 
6520   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6521   EVT IntVT = VT.getScalarType();
6522   if (!IntVT.isInteger())
6523     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6524 
6525   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6526   if (NumBits > 8) {
6527     // Use a multiplication with 0x010101... to extend the input to the
6528     // required length.
6529     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6530     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6531                         DAG.getConstant(Magic, dl, IntVT));
6532   }
6533 
6534   if (VT != Value.getValueType() && !VT.isInteger())
6535     Value = DAG.getBitcast(VT.getScalarType(), Value);
6536   if (VT != Value.getValueType())
6537     Value = DAG.getSplatBuildVector(VT, dl, Value);
6538 
6539   return Value;
6540 }
6541 
6542 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6543 /// used when a memcpy is turned into a memset when the source is a constant
6544 /// string ptr.
6545 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6546                                   const TargetLowering &TLI,
6547                                   const ConstantDataArraySlice &Slice) {
6548   // Handle vector with all elements zero.
6549   if (Slice.Array == nullptr) {
6550     if (VT.isInteger())
6551       return DAG.getConstant(0, dl, VT);
6552     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6553       return DAG.getConstantFP(0.0, dl, VT);
6554     if (VT.isVector()) {
6555       unsigned NumElts = VT.getVectorNumElements();
6556       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6557       return DAG.getNode(ISD::BITCAST, dl, VT,
6558                          DAG.getConstant(0, dl,
6559                                          EVT::getVectorVT(*DAG.getContext(),
6560                                                           EltVT, NumElts)));
6561     }
6562     llvm_unreachable("Expected type!");
6563   }
6564 
6565   assert(!VT.isVector() && "Can't handle vector type here!");
6566   unsigned NumVTBits = VT.getSizeInBits();
6567   unsigned NumVTBytes = NumVTBits / 8;
6568   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6569 
6570   APInt Val(NumVTBits, 0);
6571   if (DAG.getDataLayout().isLittleEndian()) {
6572     for (unsigned i = 0; i != NumBytes; ++i)
6573       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6574   } else {
6575     for (unsigned i = 0; i != NumBytes; ++i)
6576       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6577   }
6578 
6579   // If the "cost" of materializing the integer immediate is less than the cost
6580   // of a load, then it is cost effective to turn the load into the immediate.
6581   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6582   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6583     return DAG.getConstant(Val, dl, VT);
6584   return SDValue();
6585 }
6586 
6587 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6588                                            const SDLoc &DL,
6589                                            const SDNodeFlags Flags) {
6590   EVT VT = Base.getValueType();
6591   SDValue Index;
6592 
6593   if (Offset.isScalable())
6594     Index = getVScale(DL, Base.getValueType(),
6595                       APInt(Base.getValueSizeInBits().getFixedSize(),
6596                             Offset.getKnownMinSize()));
6597   else
6598     Index = getConstant(Offset.getFixedSize(), DL, VT);
6599 
6600   return getMemBasePlusOffset(Base, Index, DL, Flags);
6601 }
6602 
6603 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6604                                            const SDLoc &DL,
6605                                            const SDNodeFlags Flags) {
6606   assert(Offset.getValueType().isInteger());
6607   EVT BasePtrVT = Ptr.getValueType();
6608   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6609 }
6610 
6611 /// Returns true if memcpy source is constant data.
6612 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6613   uint64_t SrcDelta = 0;
6614   GlobalAddressSDNode *G = nullptr;
6615   if (Src.getOpcode() == ISD::GlobalAddress)
6616     G = cast<GlobalAddressSDNode>(Src);
6617   else if (Src.getOpcode() == ISD::ADD &&
6618            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6619            Src.getOperand(1).getOpcode() == ISD::Constant) {
6620     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6621     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6622   }
6623   if (!G)
6624     return false;
6625 
6626   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6627                                   SrcDelta + G->getOffset());
6628 }
6629 
6630 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6631                                       SelectionDAG &DAG) {
6632   // On Darwin, -Os means optimize for size without hurting performance, so
6633   // only really optimize for size when -Oz (MinSize) is used.
6634   if (MF.getTarget().getTargetTriple().isOSDarwin())
6635     return MF.getFunction().hasMinSize();
6636   return DAG.shouldOptForSize();
6637 }
6638 
6639 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6640                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6641                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6642                           SmallVector<SDValue, 16> &OutStoreChains) {
6643   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6644   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6645   SmallVector<SDValue, 16> GluedLoadChains;
6646   for (unsigned i = From; i < To; ++i) {
6647     OutChains.push_back(OutLoadChains[i]);
6648     GluedLoadChains.push_back(OutLoadChains[i]);
6649   }
6650 
6651   // Chain for all loads.
6652   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6653                                   GluedLoadChains);
6654 
6655   for (unsigned i = From; i < To; ++i) {
6656     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6657     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6658                                   ST->getBasePtr(), ST->getMemoryVT(),
6659                                   ST->getMemOperand());
6660     OutChains.push_back(NewStore);
6661   }
6662 }
6663 
6664 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6665                                        SDValue Chain, SDValue Dst, SDValue Src,
6666                                        uint64_t Size, Align Alignment,
6667                                        bool isVol, bool AlwaysInline,
6668                                        MachinePointerInfo DstPtrInfo,
6669                                        MachinePointerInfo SrcPtrInfo,
6670                                        const AAMDNodes &AAInfo) {
6671   // Turn a memcpy of undef to nop.
6672   // FIXME: We need to honor volatile even is Src is undef.
6673   if (Src.isUndef())
6674     return Chain;
6675 
6676   // Expand memcpy to a series of load and store ops if the size operand falls
6677   // below a certain threshold.
6678   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6679   // rather than maybe a humongous number of loads and stores.
6680   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6681   const DataLayout &DL = DAG.getDataLayout();
6682   LLVMContext &C = *DAG.getContext();
6683   std::vector<EVT> MemOps;
6684   bool DstAlignCanChange = false;
6685   MachineFunction &MF = DAG.getMachineFunction();
6686   MachineFrameInfo &MFI = MF.getFrameInfo();
6687   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6688   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6689   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6690     DstAlignCanChange = true;
6691   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6692   if (!SrcAlign || Alignment > *SrcAlign)
6693     SrcAlign = Alignment;
6694   assert(SrcAlign && "SrcAlign must be set");
6695   ConstantDataArraySlice Slice;
6696   // If marked as volatile, perform a copy even when marked as constant.
6697   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6698   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6699   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6700   const MemOp Op = isZeroConstant
6701                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6702                                     /*IsZeroMemset*/ true, isVol)
6703                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6704                                      *SrcAlign, isVol, CopyFromConstant);
6705   if (!TLI.findOptimalMemOpLowering(
6706           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6707           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6708     return SDValue();
6709 
6710   if (DstAlignCanChange) {
6711     Type *Ty = MemOps[0].getTypeForEVT(C);
6712     Align NewAlign = DL.getABITypeAlign(Ty);
6713 
6714     // Don't promote to an alignment that would require dynamic stack
6715     // realignment.
6716     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6717     if (!TRI->hasStackRealignment(MF))
6718       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6719         NewAlign = NewAlign / 2;
6720 
6721     if (NewAlign > Alignment) {
6722       // Give the stack frame object a larger alignment if needed.
6723       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6724         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6725       Alignment = NewAlign;
6726     }
6727   }
6728 
6729   // Prepare AAInfo for loads/stores after lowering this memcpy.
6730   AAMDNodes NewAAInfo = AAInfo;
6731   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6732 
6733   MachineMemOperand::Flags MMOFlags =
6734       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6735   SmallVector<SDValue, 16> OutLoadChains;
6736   SmallVector<SDValue, 16> OutStoreChains;
6737   SmallVector<SDValue, 32> OutChains;
6738   unsigned NumMemOps = MemOps.size();
6739   uint64_t SrcOff = 0, DstOff = 0;
6740   for (unsigned i = 0; i != NumMemOps; ++i) {
6741     EVT VT = MemOps[i];
6742     unsigned VTSize = VT.getSizeInBits() / 8;
6743     SDValue Value, Store;
6744 
6745     if (VTSize > Size) {
6746       // Issuing an unaligned load / store pair  that overlaps with the previous
6747       // pair. Adjust the offset accordingly.
6748       assert(i == NumMemOps-1 && i != 0);
6749       SrcOff -= VTSize - Size;
6750       DstOff -= VTSize - Size;
6751     }
6752 
6753     if (CopyFromConstant &&
6754         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6755       // It's unlikely a store of a vector immediate can be done in a single
6756       // instruction. It would require a load from a constantpool first.
6757       // We only handle zero vectors here.
6758       // FIXME: Handle other cases where store of vector immediate is done in
6759       // a single instruction.
6760       ConstantDataArraySlice SubSlice;
6761       if (SrcOff < Slice.Length) {
6762         SubSlice = Slice;
6763         SubSlice.move(SrcOff);
6764       } else {
6765         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6766         SubSlice.Array = nullptr;
6767         SubSlice.Offset = 0;
6768         SubSlice.Length = VTSize;
6769       }
6770       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6771       if (Value.getNode()) {
6772         Store = DAG.getStore(
6773             Chain, dl, Value,
6774             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6775             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6776         OutChains.push_back(Store);
6777       }
6778     }
6779 
6780     if (!Store.getNode()) {
6781       // The type might not be legal for the target.  This should only happen
6782       // if the type is smaller than a legal type, as on PPC, so the right
6783       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6784       // to Load/Store if NVT==VT.
6785       // FIXME does the case above also need this?
6786       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6787       assert(NVT.bitsGE(VT));
6788 
6789       bool isDereferenceable =
6790         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6791       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6792       if (isDereferenceable)
6793         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6794 
6795       Value = DAG.getExtLoad(
6796           ISD::EXTLOAD, dl, NVT, Chain,
6797           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6798           SrcPtrInfo.getWithOffset(SrcOff), VT,
6799           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6800       OutLoadChains.push_back(Value.getValue(1));
6801 
6802       Store = DAG.getTruncStore(
6803           Chain, dl, Value,
6804           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6805           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6806       OutStoreChains.push_back(Store);
6807     }
6808     SrcOff += VTSize;
6809     DstOff += VTSize;
6810     Size -= VTSize;
6811   }
6812 
6813   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6814                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6815   unsigned NumLdStInMemcpy = OutStoreChains.size();
6816 
6817   if (NumLdStInMemcpy) {
6818     // It may be that memcpy might be converted to memset if it's memcpy
6819     // of constants. In such a case, we won't have loads and stores, but
6820     // just stores. In the absence of loads, there is nothing to gang up.
6821     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6822       // If target does not care, just leave as it.
6823       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6824         OutChains.push_back(OutLoadChains[i]);
6825         OutChains.push_back(OutStoreChains[i]);
6826       }
6827     } else {
6828       // Ld/St less than/equal limit set by target.
6829       if (NumLdStInMemcpy <= GluedLdStLimit) {
6830           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6831                                         NumLdStInMemcpy, OutLoadChains,
6832                                         OutStoreChains);
6833       } else {
6834         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6835         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6836         unsigned GlueIter = 0;
6837 
6838         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6839           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6840           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6841 
6842           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6843                                        OutLoadChains, OutStoreChains);
6844           GlueIter += GluedLdStLimit;
6845         }
6846 
6847         // Residual ld/st.
6848         if (RemainingLdStInMemcpy) {
6849           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6850                                         RemainingLdStInMemcpy, OutLoadChains,
6851                                         OutStoreChains);
6852         }
6853       }
6854     }
6855   }
6856   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6857 }
6858 
6859 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6860                                         SDValue Chain, SDValue Dst, SDValue Src,
6861                                         uint64_t Size, Align Alignment,
6862                                         bool isVol, bool AlwaysInline,
6863                                         MachinePointerInfo DstPtrInfo,
6864                                         MachinePointerInfo SrcPtrInfo,
6865                                         const AAMDNodes &AAInfo) {
6866   // Turn a memmove of undef to nop.
6867   // FIXME: We need to honor volatile even is Src is undef.
6868   if (Src.isUndef())
6869     return Chain;
6870 
6871   // Expand memmove to a series of load and store ops if the size operand falls
6872   // below a certain threshold.
6873   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6874   const DataLayout &DL = DAG.getDataLayout();
6875   LLVMContext &C = *DAG.getContext();
6876   std::vector<EVT> MemOps;
6877   bool DstAlignCanChange = false;
6878   MachineFunction &MF = DAG.getMachineFunction();
6879   MachineFrameInfo &MFI = MF.getFrameInfo();
6880   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6881   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6882   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6883     DstAlignCanChange = true;
6884   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6885   if (!SrcAlign || Alignment > *SrcAlign)
6886     SrcAlign = Alignment;
6887   assert(SrcAlign && "SrcAlign must be set");
6888   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6889   if (!TLI.findOptimalMemOpLowering(
6890           MemOps, Limit,
6891           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6892                       /*IsVolatile*/ true),
6893           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6894           MF.getFunction().getAttributes()))
6895     return SDValue();
6896 
6897   if (DstAlignCanChange) {
6898     Type *Ty = MemOps[0].getTypeForEVT(C);
6899     Align NewAlign = DL.getABITypeAlign(Ty);
6900     if (NewAlign > Alignment) {
6901       // Give the stack frame object a larger alignment if needed.
6902       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6903         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6904       Alignment = NewAlign;
6905     }
6906   }
6907 
6908   // Prepare AAInfo for loads/stores after lowering this memmove.
6909   AAMDNodes NewAAInfo = AAInfo;
6910   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6911 
6912   MachineMemOperand::Flags MMOFlags =
6913       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6914   uint64_t SrcOff = 0, DstOff = 0;
6915   SmallVector<SDValue, 8> LoadValues;
6916   SmallVector<SDValue, 8> LoadChains;
6917   SmallVector<SDValue, 8> OutChains;
6918   unsigned NumMemOps = MemOps.size();
6919   for (unsigned i = 0; i < NumMemOps; i++) {
6920     EVT VT = MemOps[i];
6921     unsigned VTSize = VT.getSizeInBits() / 8;
6922     SDValue Value;
6923 
6924     bool isDereferenceable =
6925       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6926     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6927     if (isDereferenceable)
6928       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6929 
6930     Value = DAG.getLoad(
6931         VT, dl, Chain,
6932         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6933         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6934     LoadValues.push_back(Value);
6935     LoadChains.push_back(Value.getValue(1));
6936     SrcOff += VTSize;
6937   }
6938   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6939   OutChains.clear();
6940   for (unsigned i = 0; i < NumMemOps; i++) {
6941     EVT VT = MemOps[i];
6942     unsigned VTSize = VT.getSizeInBits() / 8;
6943     SDValue Store;
6944 
6945     Store = DAG.getStore(
6946         Chain, dl, LoadValues[i],
6947         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6948         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6949     OutChains.push_back(Store);
6950     DstOff += VTSize;
6951   }
6952 
6953   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6954 }
6955 
6956 /// Lower the call to 'memset' intrinsic function into a series of store
6957 /// operations.
6958 ///
6959 /// \param DAG Selection DAG where lowered code is placed.
6960 /// \param dl Link to corresponding IR location.
6961 /// \param Chain Control flow dependency.
6962 /// \param Dst Pointer to destination memory location.
6963 /// \param Src Value of byte to write into the memory.
6964 /// \param Size Number of bytes to write.
6965 /// \param Alignment Alignment of the destination in bytes.
6966 /// \param isVol True if destination is volatile.
6967 /// \param DstPtrInfo IR information on the memory pointer.
6968 /// \returns New head in the control flow, if lowering was successful, empty
6969 /// SDValue otherwise.
6970 ///
6971 /// The function tries to replace 'llvm.memset' intrinsic with several store
6972 /// operations and value calculation code. This is usually profitable for small
6973 /// memory size.
6974 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6975                                SDValue Chain, SDValue Dst, SDValue Src,
6976                                uint64_t Size, Align Alignment, bool isVol,
6977                                MachinePointerInfo DstPtrInfo,
6978                                const AAMDNodes &AAInfo) {
6979   // Turn a memset of undef to nop.
6980   // FIXME: We need to honor volatile even is Src is undef.
6981   if (Src.isUndef())
6982     return Chain;
6983 
6984   // Expand memset to a series of load/store ops if the size operand
6985   // falls below a certain threshold.
6986   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6987   std::vector<EVT> MemOps;
6988   bool DstAlignCanChange = false;
6989   MachineFunction &MF = DAG.getMachineFunction();
6990   MachineFrameInfo &MFI = MF.getFrameInfo();
6991   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6992   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6993   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6994     DstAlignCanChange = true;
6995   bool IsZeroVal =
6996       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6997   if (!TLI.findOptimalMemOpLowering(
6998           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6999           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7000           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7001     return SDValue();
7002 
7003   if (DstAlignCanChange) {
7004     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7005     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7006     if (NewAlign > Alignment) {
7007       // Give the stack frame object a larger alignment if needed.
7008       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7009         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7010       Alignment = NewAlign;
7011     }
7012   }
7013 
7014   SmallVector<SDValue, 8> OutChains;
7015   uint64_t DstOff = 0;
7016   unsigned NumMemOps = MemOps.size();
7017 
7018   // Find the largest store and generate the bit pattern for it.
7019   EVT LargestVT = MemOps[0];
7020   for (unsigned i = 1; i < NumMemOps; i++)
7021     if (MemOps[i].bitsGT(LargestVT))
7022       LargestVT = MemOps[i];
7023   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7024 
7025   // Prepare AAInfo for loads/stores after lowering this memset.
7026   AAMDNodes NewAAInfo = AAInfo;
7027   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7028 
7029   for (unsigned i = 0; i < NumMemOps; i++) {
7030     EVT VT = MemOps[i];
7031     unsigned VTSize = VT.getSizeInBits() / 8;
7032     if (VTSize > Size) {
7033       // Issuing an unaligned load / store pair  that overlaps with the previous
7034       // pair. Adjust the offset accordingly.
7035       assert(i == NumMemOps-1 && i != 0);
7036       DstOff -= VTSize - Size;
7037     }
7038 
7039     // If this store is smaller than the largest store see whether we can get
7040     // the smaller value for free with a truncate.
7041     SDValue Value = MemSetValue;
7042     if (VT.bitsLT(LargestVT)) {
7043       if (!LargestVT.isVector() && !VT.isVector() &&
7044           TLI.isTruncateFree(LargestVT, VT))
7045         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7046       else
7047         Value = getMemsetValue(Src, VT, DAG, dl);
7048     }
7049     assert(Value.getValueType() == VT && "Value with wrong type.");
7050     SDValue Store = DAG.getStore(
7051         Chain, dl, Value,
7052         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7053         DstPtrInfo.getWithOffset(DstOff), Alignment,
7054         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7055         NewAAInfo);
7056     OutChains.push_back(Store);
7057     DstOff += VT.getSizeInBits() / 8;
7058     Size -= VTSize;
7059   }
7060 
7061   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7062 }
7063 
7064 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7065                                             unsigned AS) {
7066   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7067   // pointer operands can be losslessly bitcasted to pointers of address space 0
7068   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7069     report_fatal_error("cannot lower memory intrinsic in address space " +
7070                        Twine(AS));
7071   }
7072 }
7073 
7074 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7075                                 SDValue Src, SDValue Size, Align Alignment,
7076                                 bool isVol, bool AlwaysInline, bool isTailCall,
7077                                 MachinePointerInfo DstPtrInfo,
7078                                 MachinePointerInfo SrcPtrInfo,
7079                                 const AAMDNodes &AAInfo) {
7080   // Check to see if we should lower the memcpy to loads and stores first.
7081   // For cases within the target-specified limits, this is the best choice.
7082   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7083   if (ConstantSize) {
7084     // Memcpy with size zero? Just return the original chain.
7085     if (ConstantSize->isZero())
7086       return Chain;
7087 
7088     SDValue Result = getMemcpyLoadsAndStores(
7089         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7090         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7091     if (Result.getNode())
7092       return Result;
7093   }
7094 
7095   // Then check to see if we should lower the memcpy with target-specific
7096   // code. If the target chooses to do this, this is the next best.
7097   if (TSI) {
7098     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7099         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7100         DstPtrInfo, SrcPtrInfo);
7101     if (Result.getNode())
7102       return Result;
7103   }
7104 
7105   // If we really need inline code and the target declined to provide it,
7106   // use a (potentially long) sequence of loads and stores.
7107   if (AlwaysInline) {
7108     assert(ConstantSize && "AlwaysInline requires a constant size!");
7109     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7110                                    ConstantSize->getZExtValue(), Alignment,
7111                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7112   }
7113 
7114   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7115   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7116 
7117   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7118   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7119   // respect volatile, so they may do things like read or write memory
7120   // beyond the given memory regions. But fixing this isn't easy, and most
7121   // people don't care.
7122 
7123   // Emit a library call.
7124   TargetLowering::ArgListTy Args;
7125   TargetLowering::ArgListEntry Entry;
7126   Entry.Ty = Type::getInt8PtrTy(*getContext());
7127   Entry.Node = Dst; Args.push_back(Entry);
7128   Entry.Node = Src; Args.push_back(Entry);
7129 
7130   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7131   Entry.Node = Size; Args.push_back(Entry);
7132   // FIXME: pass in SDLoc
7133   TargetLowering::CallLoweringInfo CLI(*this);
7134   CLI.setDebugLoc(dl)
7135       .setChain(Chain)
7136       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7137                     Dst.getValueType().getTypeForEVT(*getContext()),
7138                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7139                                       TLI->getPointerTy(getDataLayout())),
7140                     std::move(Args))
7141       .setDiscardResult()
7142       .setTailCall(isTailCall);
7143 
7144   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7145   return CallResult.second;
7146 }
7147 
7148 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7149                                       SDValue Dst, unsigned DstAlign,
7150                                       SDValue Src, unsigned SrcAlign,
7151                                       SDValue Size, Type *SizeTy,
7152                                       unsigned ElemSz, bool isTailCall,
7153                                       MachinePointerInfo DstPtrInfo,
7154                                       MachinePointerInfo SrcPtrInfo) {
7155   // Emit a library call.
7156   TargetLowering::ArgListTy Args;
7157   TargetLowering::ArgListEntry Entry;
7158   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7159   Entry.Node = Dst;
7160   Args.push_back(Entry);
7161 
7162   Entry.Node = Src;
7163   Args.push_back(Entry);
7164 
7165   Entry.Ty = SizeTy;
7166   Entry.Node = Size;
7167   Args.push_back(Entry);
7168 
7169   RTLIB::Libcall LibraryCall =
7170       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7171   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7172     report_fatal_error("Unsupported element size");
7173 
7174   TargetLowering::CallLoweringInfo CLI(*this);
7175   CLI.setDebugLoc(dl)
7176       .setChain(Chain)
7177       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7178                     Type::getVoidTy(*getContext()),
7179                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7180                                       TLI->getPointerTy(getDataLayout())),
7181                     std::move(Args))
7182       .setDiscardResult()
7183       .setTailCall(isTailCall);
7184 
7185   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7186   return CallResult.second;
7187 }
7188 
7189 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7190                                  SDValue Src, SDValue Size, Align Alignment,
7191                                  bool isVol, bool isTailCall,
7192                                  MachinePointerInfo DstPtrInfo,
7193                                  MachinePointerInfo SrcPtrInfo,
7194                                  const AAMDNodes &AAInfo) {
7195   // Check to see if we should lower the memmove to loads and stores first.
7196   // For cases within the target-specified limits, this is the best choice.
7197   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7198   if (ConstantSize) {
7199     // Memmove with size zero? Just return the original chain.
7200     if (ConstantSize->isZero())
7201       return Chain;
7202 
7203     SDValue Result = getMemmoveLoadsAndStores(
7204         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7205         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7206     if (Result.getNode())
7207       return Result;
7208   }
7209 
7210   // Then check to see if we should lower the memmove with target-specific
7211   // code. If the target chooses to do this, this is the next best.
7212   if (TSI) {
7213     SDValue Result =
7214         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7215                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7216     if (Result.getNode())
7217       return Result;
7218   }
7219 
7220   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7221   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7222 
7223   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7224   // not be safe.  See memcpy above for more details.
7225 
7226   // Emit a library call.
7227   TargetLowering::ArgListTy Args;
7228   TargetLowering::ArgListEntry Entry;
7229   Entry.Ty = Type::getInt8PtrTy(*getContext());
7230   Entry.Node = Dst; Args.push_back(Entry);
7231   Entry.Node = Src; Args.push_back(Entry);
7232 
7233   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7234   Entry.Node = Size; Args.push_back(Entry);
7235   // FIXME:  pass in SDLoc
7236   TargetLowering::CallLoweringInfo CLI(*this);
7237   CLI.setDebugLoc(dl)
7238       .setChain(Chain)
7239       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7240                     Dst.getValueType().getTypeForEVT(*getContext()),
7241                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7242                                       TLI->getPointerTy(getDataLayout())),
7243                     std::move(Args))
7244       .setDiscardResult()
7245       .setTailCall(isTailCall);
7246 
7247   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7248   return CallResult.second;
7249 }
7250 
7251 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7252                                        SDValue Dst, unsigned DstAlign,
7253                                        SDValue Src, unsigned SrcAlign,
7254                                        SDValue Size, Type *SizeTy,
7255                                        unsigned ElemSz, bool isTailCall,
7256                                        MachinePointerInfo DstPtrInfo,
7257                                        MachinePointerInfo SrcPtrInfo) {
7258   // Emit a library call.
7259   TargetLowering::ArgListTy Args;
7260   TargetLowering::ArgListEntry Entry;
7261   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7262   Entry.Node = Dst;
7263   Args.push_back(Entry);
7264 
7265   Entry.Node = Src;
7266   Args.push_back(Entry);
7267 
7268   Entry.Ty = SizeTy;
7269   Entry.Node = Size;
7270   Args.push_back(Entry);
7271 
7272   RTLIB::Libcall LibraryCall =
7273       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7274   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7275     report_fatal_error("Unsupported element size");
7276 
7277   TargetLowering::CallLoweringInfo CLI(*this);
7278   CLI.setDebugLoc(dl)
7279       .setChain(Chain)
7280       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7281                     Type::getVoidTy(*getContext()),
7282                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7283                                       TLI->getPointerTy(getDataLayout())),
7284                     std::move(Args))
7285       .setDiscardResult()
7286       .setTailCall(isTailCall);
7287 
7288   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7289   return CallResult.second;
7290 }
7291 
7292 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7293                                 SDValue Src, SDValue Size, Align Alignment,
7294                                 bool isVol, bool isTailCall,
7295                                 MachinePointerInfo DstPtrInfo,
7296                                 const AAMDNodes &AAInfo) {
7297   // Check to see if we should lower the memset to stores first.
7298   // For cases within the target-specified limits, this is the best choice.
7299   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7300   if (ConstantSize) {
7301     // Memset with size zero? Just return the original chain.
7302     if (ConstantSize->isZero())
7303       return Chain;
7304 
7305     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7306                                      ConstantSize->getZExtValue(), Alignment,
7307                                      isVol, DstPtrInfo, AAInfo);
7308 
7309     if (Result.getNode())
7310       return Result;
7311   }
7312 
7313   // Then check to see if we should lower the memset with target-specific
7314   // code. If the target chooses to do this, this is the next best.
7315   if (TSI) {
7316     SDValue Result = TSI->EmitTargetCodeForMemset(
7317         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7318     if (Result.getNode())
7319       return Result;
7320   }
7321 
7322   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7323 
7324   // Emit a library call.
7325   TargetLowering::ArgListTy Args;
7326   TargetLowering::ArgListEntry Entry;
7327   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7328   Args.push_back(Entry);
7329   Entry.Node = Src;
7330   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7331   Args.push_back(Entry);
7332   Entry.Node = Size;
7333   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7334   Args.push_back(Entry);
7335 
7336   // FIXME: pass in SDLoc
7337   TargetLowering::CallLoweringInfo CLI(*this);
7338   CLI.setDebugLoc(dl)
7339       .setChain(Chain)
7340       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7341                     Dst.getValueType().getTypeForEVT(*getContext()),
7342                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7343                                       TLI->getPointerTy(getDataLayout())),
7344                     std::move(Args))
7345       .setDiscardResult()
7346       .setTailCall(isTailCall);
7347 
7348   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7349   return CallResult.second;
7350 }
7351 
7352 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7353                                       SDValue Dst, unsigned DstAlign,
7354                                       SDValue Value, SDValue Size, Type *SizeTy,
7355                                       unsigned ElemSz, bool isTailCall,
7356                                       MachinePointerInfo DstPtrInfo) {
7357   // Emit a library call.
7358   TargetLowering::ArgListTy Args;
7359   TargetLowering::ArgListEntry Entry;
7360   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7361   Entry.Node = Dst;
7362   Args.push_back(Entry);
7363 
7364   Entry.Ty = Type::getInt8Ty(*getContext());
7365   Entry.Node = Value;
7366   Args.push_back(Entry);
7367 
7368   Entry.Ty = SizeTy;
7369   Entry.Node = Size;
7370   Args.push_back(Entry);
7371 
7372   RTLIB::Libcall LibraryCall =
7373       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7374   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7375     report_fatal_error("Unsupported element size");
7376 
7377   TargetLowering::CallLoweringInfo CLI(*this);
7378   CLI.setDebugLoc(dl)
7379       .setChain(Chain)
7380       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7381                     Type::getVoidTy(*getContext()),
7382                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7383                                       TLI->getPointerTy(getDataLayout())),
7384                     std::move(Args))
7385       .setDiscardResult()
7386       .setTailCall(isTailCall);
7387 
7388   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7389   return CallResult.second;
7390 }
7391 
7392 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7393                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7394                                 MachineMemOperand *MMO) {
7395   FoldingSetNodeID ID;
7396   ID.AddInteger(MemVT.getRawBits());
7397   AddNodeIDNode(ID, Opcode, VTList, Ops);
7398   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7399   ID.AddInteger(MMO->getFlags());
7400   void* IP = nullptr;
7401   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7402     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7403     return SDValue(E, 0);
7404   }
7405 
7406   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7407                                     VTList, MemVT, MMO);
7408   createOperands(N, Ops);
7409 
7410   CSEMap.InsertNode(N, IP);
7411   InsertNode(N);
7412   return SDValue(N, 0);
7413 }
7414 
7415 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7416                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7417                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7418                                        MachineMemOperand *MMO) {
7419   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7420          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7421   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7422 
7423   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7424   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7425 }
7426 
7427 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7428                                 SDValue Chain, SDValue Ptr, SDValue Val,
7429                                 MachineMemOperand *MMO) {
7430   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7431           Opcode == ISD::ATOMIC_LOAD_SUB ||
7432           Opcode == ISD::ATOMIC_LOAD_AND ||
7433           Opcode == ISD::ATOMIC_LOAD_CLR ||
7434           Opcode == ISD::ATOMIC_LOAD_OR ||
7435           Opcode == ISD::ATOMIC_LOAD_XOR ||
7436           Opcode == ISD::ATOMIC_LOAD_NAND ||
7437           Opcode == ISD::ATOMIC_LOAD_MIN ||
7438           Opcode == ISD::ATOMIC_LOAD_MAX ||
7439           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7440           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7441           Opcode == ISD::ATOMIC_LOAD_FADD ||
7442           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7443           Opcode == ISD::ATOMIC_SWAP ||
7444           Opcode == ISD::ATOMIC_STORE) &&
7445          "Invalid Atomic Op");
7446 
7447   EVT VT = Val.getValueType();
7448 
7449   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7450                                                getVTList(VT, MVT::Other);
7451   SDValue Ops[] = {Chain, Ptr, Val};
7452   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7453 }
7454 
7455 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7456                                 EVT VT, SDValue Chain, SDValue Ptr,
7457                                 MachineMemOperand *MMO) {
7458   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7459 
7460   SDVTList VTs = getVTList(VT, MVT::Other);
7461   SDValue Ops[] = {Chain, Ptr};
7462   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7463 }
7464 
7465 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7466 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7467   if (Ops.size() == 1)
7468     return Ops[0];
7469 
7470   SmallVector<EVT, 4> VTs;
7471   VTs.reserve(Ops.size());
7472   for (const SDValue &Op : Ops)
7473     VTs.push_back(Op.getValueType());
7474   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7475 }
7476 
7477 SDValue SelectionDAG::getMemIntrinsicNode(
7478     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7479     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7480     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7481   if (!Size && MemVT.isScalableVector())
7482     Size = MemoryLocation::UnknownSize;
7483   else if (!Size)
7484     Size = MemVT.getStoreSize();
7485 
7486   MachineFunction &MF = getMachineFunction();
7487   MachineMemOperand *MMO =
7488       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7489 
7490   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7491 }
7492 
7493 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7494                                           SDVTList VTList,
7495                                           ArrayRef<SDValue> Ops, EVT MemVT,
7496                                           MachineMemOperand *MMO) {
7497   assert((Opcode == ISD::INTRINSIC_VOID ||
7498           Opcode == ISD::INTRINSIC_W_CHAIN ||
7499           Opcode == ISD::PREFETCH ||
7500           ((int)Opcode <= std::numeric_limits<int>::max() &&
7501            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7502          "Opcode is not a memory-accessing opcode!");
7503 
7504   // Memoize the node unless it returns a flag.
7505   MemIntrinsicSDNode *N;
7506   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7507     FoldingSetNodeID ID;
7508     AddNodeIDNode(ID, Opcode, VTList, Ops);
7509     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7510         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7511     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7512     ID.AddInteger(MMO->getFlags());
7513     void *IP = nullptr;
7514     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7515       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7516       return SDValue(E, 0);
7517     }
7518 
7519     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7520                                       VTList, MemVT, MMO);
7521     createOperands(N, Ops);
7522 
7523   CSEMap.InsertNode(N, IP);
7524   } else {
7525     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7526                                       VTList, MemVT, MMO);
7527     createOperands(N, Ops);
7528   }
7529   InsertNode(N);
7530   SDValue V(N, 0);
7531   NewSDValueDbgMsg(V, "Creating new node: ", this);
7532   return V;
7533 }
7534 
7535 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7536                                       SDValue Chain, int FrameIndex,
7537                                       int64_t Size, int64_t Offset) {
7538   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7539   const auto VTs = getVTList(MVT::Other);
7540   SDValue Ops[2] = {
7541       Chain,
7542       getFrameIndex(FrameIndex,
7543                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7544                     true)};
7545 
7546   FoldingSetNodeID ID;
7547   AddNodeIDNode(ID, Opcode, VTs, Ops);
7548   ID.AddInteger(FrameIndex);
7549   ID.AddInteger(Size);
7550   ID.AddInteger(Offset);
7551   void *IP = nullptr;
7552   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7553     return SDValue(E, 0);
7554 
7555   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7556       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7557   createOperands(N, Ops);
7558   CSEMap.InsertNode(N, IP);
7559   InsertNode(N);
7560   SDValue V(N, 0);
7561   NewSDValueDbgMsg(V, "Creating new node: ", this);
7562   return V;
7563 }
7564 
7565 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7566                                          uint64_t Guid, uint64_t Index,
7567                                          uint32_t Attr) {
7568   const unsigned Opcode = ISD::PSEUDO_PROBE;
7569   const auto VTs = getVTList(MVT::Other);
7570   SDValue Ops[] = {Chain};
7571   FoldingSetNodeID ID;
7572   AddNodeIDNode(ID, Opcode, VTs, Ops);
7573   ID.AddInteger(Guid);
7574   ID.AddInteger(Index);
7575   void *IP = nullptr;
7576   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7577     return SDValue(E, 0);
7578 
7579   auto *N = newSDNode<PseudoProbeSDNode>(
7580       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7581   createOperands(N, Ops);
7582   CSEMap.InsertNode(N, IP);
7583   InsertNode(N);
7584   SDValue V(N, 0);
7585   NewSDValueDbgMsg(V, "Creating new node: ", this);
7586   return V;
7587 }
7588 
7589 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7590 /// MachinePointerInfo record from it.  This is particularly useful because the
7591 /// code generator has many cases where it doesn't bother passing in a
7592 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7593 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7594                                            SelectionDAG &DAG, SDValue Ptr,
7595                                            int64_t Offset = 0) {
7596   // If this is FI+Offset, we can model it.
7597   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7598     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7599                                              FI->getIndex(), Offset);
7600 
7601   // If this is (FI+Offset1)+Offset2, we can model it.
7602   if (Ptr.getOpcode() != ISD::ADD ||
7603       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7604       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7605     return Info;
7606 
7607   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7608   return MachinePointerInfo::getFixedStack(
7609       DAG.getMachineFunction(), FI,
7610       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7611 }
7612 
7613 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7614 /// MachinePointerInfo record from it.  This is particularly useful because the
7615 /// code generator has many cases where it doesn't bother passing in a
7616 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7617 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7618                                            SelectionDAG &DAG, SDValue Ptr,
7619                                            SDValue OffsetOp) {
7620   // If the 'Offset' value isn't a constant, we can't handle this.
7621   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7622     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7623   if (OffsetOp.isUndef())
7624     return InferPointerInfo(Info, DAG, Ptr);
7625   return Info;
7626 }
7627 
7628 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7629                               EVT VT, const SDLoc &dl, SDValue Chain,
7630                               SDValue Ptr, SDValue Offset,
7631                               MachinePointerInfo PtrInfo, EVT MemVT,
7632                               Align Alignment,
7633                               MachineMemOperand::Flags MMOFlags,
7634                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7635   assert(Chain.getValueType() == MVT::Other &&
7636         "Invalid chain type");
7637 
7638   MMOFlags |= MachineMemOperand::MOLoad;
7639   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7640   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7641   // clients.
7642   if (PtrInfo.V.isNull())
7643     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7644 
7645   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7646   MachineFunction &MF = getMachineFunction();
7647   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7648                                                    Alignment, AAInfo, Ranges);
7649   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7650 }
7651 
7652 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7653                               EVT VT, const SDLoc &dl, SDValue Chain,
7654                               SDValue Ptr, SDValue Offset, EVT MemVT,
7655                               MachineMemOperand *MMO) {
7656   if (VT == MemVT) {
7657     ExtType = ISD::NON_EXTLOAD;
7658   } else if (ExtType == ISD::NON_EXTLOAD) {
7659     assert(VT == MemVT && "Non-extending load from different memory type!");
7660   } else {
7661     // Extending load.
7662     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7663            "Should only be an extending load, not truncating!");
7664     assert(VT.isInteger() == MemVT.isInteger() &&
7665            "Cannot convert from FP to Int or Int -> FP!");
7666     assert(VT.isVector() == MemVT.isVector() &&
7667            "Cannot use an ext load to convert to or from a vector!");
7668     assert((!VT.isVector() ||
7669             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7670            "Cannot use an ext load to change the number of vector elements!");
7671   }
7672 
7673   bool Indexed = AM != ISD::UNINDEXED;
7674   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7675 
7676   SDVTList VTs = Indexed ?
7677     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7678   SDValue Ops[] = { Chain, Ptr, Offset };
7679   FoldingSetNodeID ID;
7680   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7681   ID.AddInteger(MemVT.getRawBits());
7682   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7683       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7684   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7685   ID.AddInteger(MMO->getFlags());
7686   void *IP = nullptr;
7687   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7688     cast<LoadSDNode>(E)->refineAlignment(MMO);
7689     return SDValue(E, 0);
7690   }
7691   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7692                                   ExtType, MemVT, MMO);
7693   createOperands(N, Ops);
7694 
7695   CSEMap.InsertNode(N, IP);
7696   InsertNode(N);
7697   SDValue V(N, 0);
7698   NewSDValueDbgMsg(V, "Creating new node: ", this);
7699   return V;
7700 }
7701 
7702 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7703                               SDValue Ptr, MachinePointerInfo PtrInfo,
7704                               MaybeAlign Alignment,
7705                               MachineMemOperand::Flags MMOFlags,
7706                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7707   SDValue Undef = getUNDEF(Ptr.getValueType());
7708   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7709                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7710 }
7711 
7712 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7713                               SDValue Ptr, MachineMemOperand *MMO) {
7714   SDValue Undef = getUNDEF(Ptr.getValueType());
7715   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7716                  VT, MMO);
7717 }
7718 
7719 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7720                                  EVT VT, SDValue Chain, SDValue Ptr,
7721                                  MachinePointerInfo PtrInfo, EVT MemVT,
7722                                  MaybeAlign Alignment,
7723                                  MachineMemOperand::Flags MMOFlags,
7724                                  const AAMDNodes &AAInfo) {
7725   SDValue Undef = getUNDEF(Ptr.getValueType());
7726   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7727                  MemVT, Alignment, MMOFlags, AAInfo);
7728 }
7729 
7730 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7731                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7732                                  MachineMemOperand *MMO) {
7733   SDValue Undef = getUNDEF(Ptr.getValueType());
7734   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7735                  MemVT, MMO);
7736 }
7737 
7738 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7739                                      SDValue Base, SDValue Offset,
7740                                      ISD::MemIndexedMode AM) {
7741   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7742   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7743   // Don't propagate the invariant or dereferenceable flags.
7744   auto MMOFlags =
7745       LD->getMemOperand()->getFlags() &
7746       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7747   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7748                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7749                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7750 }
7751 
7752 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7753                                SDValue Ptr, MachinePointerInfo PtrInfo,
7754                                Align Alignment,
7755                                MachineMemOperand::Flags MMOFlags,
7756                                const AAMDNodes &AAInfo) {
7757   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7758 
7759   MMOFlags |= MachineMemOperand::MOStore;
7760   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7761 
7762   if (PtrInfo.V.isNull())
7763     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7764 
7765   MachineFunction &MF = getMachineFunction();
7766   uint64_t Size =
7767       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7768   MachineMemOperand *MMO =
7769       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7770   return getStore(Chain, dl, Val, Ptr, MMO);
7771 }
7772 
7773 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7774                                SDValue Ptr, MachineMemOperand *MMO) {
7775   assert(Chain.getValueType() == MVT::Other &&
7776         "Invalid chain type");
7777   EVT VT = Val.getValueType();
7778   SDVTList VTs = getVTList(MVT::Other);
7779   SDValue Undef = getUNDEF(Ptr.getValueType());
7780   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7781   FoldingSetNodeID ID;
7782   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7783   ID.AddInteger(VT.getRawBits());
7784   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7785       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7786   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7787   ID.AddInteger(MMO->getFlags());
7788   void *IP = nullptr;
7789   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7790     cast<StoreSDNode>(E)->refineAlignment(MMO);
7791     return SDValue(E, 0);
7792   }
7793   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7794                                    ISD::UNINDEXED, false, VT, MMO);
7795   createOperands(N, Ops);
7796 
7797   CSEMap.InsertNode(N, IP);
7798   InsertNode(N);
7799   SDValue V(N, 0);
7800   NewSDValueDbgMsg(V, "Creating new node: ", this);
7801   return V;
7802 }
7803 
7804 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7805                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7806                                     EVT SVT, Align Alignment,
7807                                     MachineMemOperand::Flags MMOFlags,
7808                                     const AAMDNodes &AAInfo) {
7809   assert(Chain.getValueType() == MVT::Other &&
7810         "Invalid chain type");
7811 
7812   MMOFlags |= MachineMemOperand::MOStore;
7813   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7814 
7815   if (PtrInfo.V.isNull())
7816     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7817 
7818   MachineFunction &MF = getMachineFunction();
7819   MachineMemOperand *MMO = MF.getMachineMemOperand(
7820       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7821       Alignment, AAInfo);
7822   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7823 }
7824 
7825 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7826                                     SDValue Ptr, EVT SVT,
7827                                     MachineMemOperand *MMO) {
7828   EVT VT = Val.getValueType();
7829 
7830   assert(Chain.getValueType() == MVT::Other &&
7831         "Invalid chain type");
7832   if (VT == SVT)
7833     return getStore(Chain, dl, Val, Ptr, MMO);
7834 
7835   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7836          "Should only be a truncating store, not extending!");
7837   assert(VT.isInteger() == SVT.isInteger() &&
7838          "Can't do FP-INT conversion!");
7839   assert(VT.isVector() == SVT.isVector() &&
7840          "Cannot use trunc store to convert to or from a vector!");
7841   assert((!VT.isVector() ||
7842           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7843          "Cannot use trunc store to change the number of vector elements!");
7844 
7845   SDVTList VTs = getVTList(MVT::Other);
7846   SDValue Undef = getUNDEF(Ptr.getValueType());
7847   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7848   FoldingSetNodeID ID;
7849   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7850   ID.AddInteger(SVT.getRawBits());
7851   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7852       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7853   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7854   ID.AddInteger(MMO->getFlags());
7855   void *IP = nullptr;
7856   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7857     cast<StoreSDNode>(E)->refineAlignment(MMO);
7858     return SDValue(E, 0);
7859   }
7860   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7861                                    ISD::UNINDEXED, true, SVT, MMO);
7862   createOperands(N, Ops);
7863 
7864   CSEMap.InsertNode(N, IP);
7865   InsertNode(N);
7866   SDValue V(N, 0);
7867   NewSDValueDbgMsg(V, "Creating new node: ", this);
7868   return V;
7869 }
7870 
7871 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7872                                       SDValue Base, SDValue Offset,
7873                                       ISD::MemIndexedMode AM) {
7874   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7875   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7876   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7877   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7878   FoldingSetNodeID ID;
7879   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7880   ID.AddInteger(ST->getMemoryVT().getRawBits());
7881   ID.AddInteger(ST->getRawSubclassData());
7882   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7883   ID.AddInteger(ST->getMemOperand()->getFlags());
7884   void *IP = nullptr;
7885   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7886     return SDValue(E, 0);
7887 
7888   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7889                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7890                                    ST->getMemOperand());
7891   createOperands(N, Ops);
7892 
7893   CSEMap.InsertNode(N, IP);
7894   InsertNode(N);
7895   SDValue V(N, 0);
7896   NewSDValueDbgMsg(V, "Creating new node: ", this);
7897   return V;
7898 }
7899 
7900 SDValue SelectionDAG::getLoadVP(
7901     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7902     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7903     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7904     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7905     const MDNode *Ranges, bool IsExpanding) {
7906   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7907 
7908   MMOFlags |= MachineMemOperand::MOLoad;
7909   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7910   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7911   // clients.
7912   if (PtrInfo.V.isNull())
7913     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7914 
7915   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7916   MachineFunction &MF = getMachineFunction();
7917   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7918                                                    Alignment, AAInfo, Ranges);
7919   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7920                    MMO, IsExpanding);
7921 }
7922 
7923 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7924                                 ISD::LoadExtType ExtType, EVT VT,
7925                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7926                                 SDValue Offset, SDValue Mask, SDValue EVL,
7927                                 EVT MemVT, MachineMemOperand *MMO,
7928                                 bool IsExpanding) {
7929   bool Indexed = AM != ISD::UNINDEXED;
7930   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7931 
7932   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7933                          : getVTList(VT, MVT::Other);
7934   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7935   FoldingSetNodeID ID;
7936   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7937   ID.AddInteger(VT.getRawBits());
7938   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7939       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7940   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7941   ID.AddInteger(MMO->getFlags());
7942   void *IP = nullptr;
7943   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7944     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7945     return SDValue(E, 0);
7946   }
7947   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7948                                     ExtType, IsExpanding, MemVT, MMO);
7949   createOperands(N, Ops);
7950 
7951   CSEMap.InsertNode(N, IP);
7952   InsertNode(N);
7953   SDValue V(N, 0);
7954   NewSDValueDbgMsg(V, "Creating new node: ", this);
7955   return V;
7956 }
7957 
7958 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7959                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7960                                 MachinePointerInfo PtrInfo,
7961                                 MaybeAlign Alignment,
7962                                 MachineMemOperand::Flags MMOFlags,
7963                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7964                                 bool IsExpanding) {
7965   SDValue Undef = getUNDEF(Ptr.getValueType());
7966   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7967                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7968                    IsExpanding);
7969 }
7970 
7971 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7972                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7973                                 MachineMemOperand *MMO, bool IsExpanding) {
7974   SDValue Undef = getUNDEF(Ptr.getValueType());
7975   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7976                    Mask, EVL, VT, MMO, IsExpanding);
7977 }
7978 
7979 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7980                                    EVT VT, SDValue Chain, SDValue Ptr,
7981                                    SDValue Mask, SDValue EVL,
7982                                    MachinePointerInfo PtrInfo, EVT MemVT,
7983                                    MaybeAlign Alignment,
7984                                    MachineMemOperand::Flags MMOFlags,
7985                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7986   SDValue Undef = getUNDEF(Ptr.getValueType());
7987   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7988                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7989                    IsExpanding);
7990 }
7991 
7992 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7993                                    EVT VT, SDValue Chain, SDValue Ptr,
7994                                    SDValue Mask, SDValue EVL, EVT MemVT,
7995                                    MachineMemOperand *MMO, bool IsExpanding) {
7996   SDValue Undef = getUNDEF(Ptr.getValueType());
7997   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7998                    EVL, MemVT, MMO, IsExpanding);
7999 }
8000 
8001 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8002                                        SDValue Base, SDValue Offset,
8003                                        ISD::MemIndexedMode AM) {
8004   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8005   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8006   // Don't propagate the invariant or dereferenceable flags.
8007   auto MMOFlags =
8008       LD->getMemOperand()->getFlags() &
8009       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8010   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8011                    LD->getChain(), Base, Offset, LD->getMask(),
8012                    LD->getVectorLength(), LD->getPointerInfo(),
8013                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8014                    nullptr, LD->isExpandingLoad());
8015 }
8016 
8017 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8018                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8019                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8020                                  ISD::MemIndexedMode AM, bool IsTruncating,
8021                                  bool IsCompressing) {
8022   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8023   bool Indexed = AM != ISD::UNINDEXED;
8024   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8025   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8026                          : getVTList(MVT::Other);
8027   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8028   FoldingSetNodeID ID;
8029   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8030   ID.AddInteger(MemVT.getRawBits());
8031   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8032       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8033   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8034   ID.AddInteger(MMO->getFlags());
8035   void *IP = nullptr;
8036   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8037     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8038     return SDValue(E, 0);
8039   }
8040   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8041                                      IsTruncating, IsCompressing, MemVT, MMO);
8042   createOperands(N, Ops);
8043 
8044   CSEMap.InsertNode(N, IP);
8045   InsertNode(N);
8046   SDValue V(N, 0);
8047   NewSDValueDbgMsg(V, "Creating new node: ", this);
8048   return V;
8049 }
8050 
8051 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8052                                       SDValue Val, SDValue Ptr, SDValue Mask,
8053                                       SDValue EVL, MachinePointerInfo PtrInfo,
8054                                       EVT SVT, Align Alignment,
8055                                       MachineMemOperand::Flags MMOFlags,
8056                                       const AAMDNodes &AAInfo,
8057                                       bool IsCompressing) {
8058   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8059 
8060   MMOFlags |= MachineMemOperand::MOStore;
8061   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8062 
8063   if (PtrInfo.V.isNull())
8064     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8065 
8066   MachineFunction &MF = getMachineFunction();
8067   MachineMemOperand *MMO = MF.getMachineMemOperand(
8068       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8069       Alignment, AAInfo);
8070   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8071                          IsCompressing);
8072 }
8073 
8074 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8075                                       SDValue Val, SDValue Ptr, SDValue Mask,
8076                                       SDValue EVL, EVT SVT,
8077                                       MachineMemOperand *MMO,
8078                                       bool IsCompressing) {
8079   EVT VT = Val.getValueType();
8080 
8081   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8082   if (VT == SVT)
8083     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8084                       EVL, VT, MMO, ISD::UNINDEXED,
8085                       /*IsTruncating*/ false, IsCompressing);
8086 
8087   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8088          "Should only be a truncating store, not extending!");
8089   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8090   assert(VT.isVector() == SVT.isVector() &&
8091          "Cannot use trunc store to convert to or from a vector!");
8092   assert((!VT.isVector() ||
8093           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8094          "Cannot use trunc store to change the number of vector elements!");
8095 
8096   SDVTList VTs = getVTList(MVT::Other);
8097   SDValue Undef = getUNDEF(Ptr.getValueType());
8098   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8099   FoldingSetNodeID ID;
8100   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8101   ID.AddInteger(SVT.getRawBits());
8102   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8103       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8104   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8105   ID.AddInteger(MMO->getFlags());
8106   void *IP = nullptr;
8107   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8108     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8109     return SDValue(E, 0);
8110   }
8111   auto *N =
8112       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8113                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8114   createOperands(N, Ops);
8115 
8116   CSEMap.InsertNode(N, IP);
8117   InsertNode(N);
8118   SDValue V(N, 0);
8119   NewSDValueDbgMsg(V, "Creating new node: ", this);
8120   return V;
8121 }
8122 
8123 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8124                                         SDValue Base, SDValue Offset,
8125                                         ISD::MemIndexedMode AM) {
8126   auto *ST = cast<VPStoreSDNode>(OrigStore);
8127   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8128   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8129   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8130                    Offset,         ST->getMask(),  ST->getVectorLength()};
8131   FoldingSetNodeID ID;
8132   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8133   ID.AddInteger(ST->getMemoryVT().getRawBits());
8134   ID.AddInteger(ST->getRawSubclassData());
8135   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8136   ID.AddInteger(ST->getMemOperand()->getFlags());
8137   void *IP = nullptr;
8138   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8139     return SDValue(E, 0);
8140 
8141   auto *N = newSDNode<VPStoreSDNode>(
8142       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8143       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8144   createOperands(N, Ops);
8145 
8146   CSEMap.InsertNode(N, IP);
8147   InsertNode(N);
8148   SDValue V(N, 0);
8149   NewSDValueDbgMsg(V, "Creating new node: ", this);
8150   return V;
8151 }
8152 
8153 SDValue SelectionDAG::getStridedLoadVP(
8154     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8155     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8156     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8157     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8158     const MDNode *Ranges, bool IsExpanding) {
8159   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8160 
8161   MMOFlags |= MachineMemOperand::MOLoad;
8162   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8163   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8164   // clients.
8165   if (PtrInfo.V.isNull())
8166     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8167 
8168   uint64_t Size = MemoryLocation::UnknownSize;
8169   MachineFunction &MF = getMachineFunction();
8170   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8171                                                    Alignment, AAInfo, Ranges);
8172   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8173                           EVL, MemVT, MMO, IsExpanding);
8174 }
8175 
8176 SDValue SelectionDAG::getStridedLoadVP(
8177     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8178     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8179     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8180   bool Indexed = AM != ISD::UNINDEXED;
8181   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8182 
8183   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8184   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8185                          : getVTList(VT, MVT::Other);
8186   FoldingSetNodeID ID;
8187   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8188   ID.AddInteger(VT.getRawBits());
8189   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8190       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8191   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8192 
8193   void *IP = nullptr;
8194   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8195     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8196     return SDValue(E, 0);
8197   }
8198 
8199   auto *N =
8200       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8201                                      ExtType, IsExpanding, MemVT, MMO);
8202   createOperands(N, Ops);
8203   CSEMap.InsertNode(N, IP);
8204   InsertNode(N);
8205   SDValue V(N, 0);
8206   NewSDValueDbgMsg(V, "Creating new node: ", this);
8207   return V;
8208 }
8209 
8210 SDValue SelectionDAG::getStridedLoadVP(
8211     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8212     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8213     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8214     const MDNode *Ranges, bool IsExpanding) {
8215   SDValue Undef = getUNDEF(Ptr.getValueType());
8216   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8217                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8218                           MMOFlags, AAInfo, Ranges, IsExpanding);
8219 }
8220 
8221 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8222                                        SDValue Ptr, SDValue Stride,
8223                                        SDValue Mask, SDValue EVL,
8224                                        MachineMemOperand *MMO,
8225                                        bool IsExpanding) {
8226   SDValue Undef = getUNDEF(Ptr.getValueType());
8227   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8228                           Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8229 }
8230 
8231 SDValue SelectionDAG::getExtStridedLoadVP(
8232     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8233     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8234     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8235     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8236     bool IsExpanding) {
8237   SDValue Undef = getUNDEF(Ptr.getValueType());
8238   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8239                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8240                           MMOFlags, AAInfo, nullptr, IsExpanding);
8241 }
8242 
8243 SDValue SelectionDAG::getExtStridedLoadVP(
8244     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8245     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8246     MachineMemOperand *MMO, bool IsExpanding) {
8247   SDValue Undef = getUNDEF(Ptr.getValueType());
8248   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8249                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8250 }
8251 
8252 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8253                                               SDValue Base, SDValue Offset,
8254                                               ISD::MemIndexedMode AM) {
8255   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8256   assert(SLD->getOffset().isUndef() &&
8257          "Strided load is already a indexed load!");
8258   // Don't propagate the invariant or dereferenceable flags.
8259   auto MMOFlags =
8260       SLD->getMemOperand()->getFlags() &
8261       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8262   return getStridedLoadVP(
8263       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8264       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8265       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8266       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8267 }
8268 
8269 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8270                                         SDValue Val, SDValue Ptr,
8271                                         SDValue Offset, SDValue Stride,
8272                                         SDValue Mask, SDValue EVL, EVT MemVT,
8273                                         MachineMemOperand *MMO,
8274                                         ISD::MemIndexedMode AM,
8275                                         bool IsTruncating, bool IsCompressing) {
8276   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8277   bool Indexed = AM != ISD::UNINDEXED;
8278   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8279   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8280                          : getVTList(MVT::Other);
8281   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8282   FoldingSetNodeID ID;
8283   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8284   ID.AddInteger(MemVT.getRawBits());
8285   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8286       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8287   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8288   void *IP = nullptr;
8289   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8290     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8291     return SDValue(E, 0);
8292   }
8293   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8294                                             VTs, AM, IsTruncating,
8295                                             IsCompressing, MemVT, MMO);
8296   createOperands(N, Ops);
8297 
8298   CSEMap.InsertNode(N, IP);
8299   InsertNode(N);
8300   SDValue V(N, 0);
8301   NewSDValueDbgMsg(V, "Creating new node: ", this);
8302   return V;
8303 }
8304 
8305 SDValue SelectionDAG::getTruncStridedStoreVP(
8306     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8307     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8308     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8309     bool IsCompressing) {
8310   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8311 
8312   MMOFlags |= MachineMemOperand::MOStore;
8313   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8314 
8315   if (PtrInfo.V.isNull())
8316     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8317 
8318   MachineFunction &MF = getMachineFunction();
8319   MachineMemOperand *MMO = MF.getMachineMemOperand(
8320       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8321   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8322                                 MMO, IsCompressing);
8323 }
8324 
8325 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8326                                              SDValue Val, SDValue Ptr,
8327                                              SDValue Stride, SDValue Mask,
8328                                              SDValue EVL, EVT SVT,
8329                                              MachineMemOperand *MMO,
8330                                              bool IsCompressing) {
8331   EVT VT = Val.getValueType();
8332 
8333   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8334   if (VT == SVT)
8335     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8336                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8337                              /*IsTruncating*/ false, IsCompressing);
8338 
8339   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8340          "Should only be a truncating store, not extending!");
8341   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8342   assert(VT.isVector() == SVT.isVector() &&
8343          "Cannot use trunc store to convert to or from a vector!");
8344   assert((!VT.isVector() ||
8345           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8346          "Cannot use trunc store to change the number of vector elements!");
8347 
8348   SDVTList VTs = getVTList(MVT::Other);
8349   SDValue Undef = getUNDEF(Ptr.getValueType());
8350   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8351   FoldingSetNodeID ID;
8352   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8353   ID.AddInteger(SVT.getRawBits());
8354   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8355       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8356   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8357   void *IP = nullptr;
8358   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8359     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8360     return SDValue(E, 0);
8361   }
8362   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8363                                             VTs, ISD::UNINDEXED, true,
8364                                             IsCompressing, SVT, MMO);
8365   createOperands(N, Ops);
8366 
8367   CSEMap.InsertNode(N, IP);
8368   InsertNode(N);
8369   SDValue V(N, 0);
8370   NewSDValueDbgMsg(V, "Creating new node: ", this);
8371   return V;
8372 }
8373 
8374 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8375                                                const SDLoc &DL, SDValue Base,
8376                                                SDValue Offset,
8377                                                ISD::MemIndexedMode AM) {
8378   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8379   assert(SST->getOffset().isUndef() &&
8380          "Strided store is already an indexed store!");
8381   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8382   SDValue Ops[] = {
8383       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8384       SST->getMask(),  SST->getVectorLength()};
8385   FoldingSetNodeID ID;
8386   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8387   ID.AddInteger(SST->getMemoryVT().getRawBits());
8388   ID.AddInteger(SST->getRawSubclassData());
8389   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8390   void *IP = nullptr;
8391   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8392     return SDValue(E, 0);
8393 
8394   auto *N = newSDNode<VPStridedStoreSDNode>(
8395       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8396       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8397   createOperands(N, Ops);
8398 
8399   CSEMap.InsertNode(N, IP);
8400   InsertNode(N);
8401   SDValue V(N, 0);
8402   NewSDValueDbgMsg(V, "Creating new node: ", this);
8403   return V;
8404 }
8405 
8406 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8407                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8408                                   ISD::MemIndexType IndexType) {
8409   assert(Ops.size() == 6 && "Incompatible number of operands");
8410 
8411   FoldingSetNodeID ID;
8412   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8413   ID.AddInteger(VT.getRawBits());
8414   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8415       dl.getIROrder(), VTs, VT, MMO, IndexType));
8416   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8417   ID.AddInteger(MMO->getFlags());
8418   void *IP = nullptr;
8419   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8420     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8421     return SDValue(E, 0);
8422   }
8423 
8424   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8425                                       VT, MMO, IndexType);
8426   createOperands(N, Ops);
8427 
8428   assert(N->getMask().getValueType().getVectorElementCount() ==
8429              N->getValueType(0).getVectorElementCount() &&
8430          "Vector width mismatch between mask and data");
8431   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8432              N->getValueType(0).getVectorElementCount().isScalable() &&
8433          "Scalable flags of index and data do not match");
8434   assert(ElementCount::isKnownGE(
8435              N->getIndex().getValueType().getVectorElementCount(),
8436              N->getValueType(0).getVectorElementCount()) &&
8437          "Vector width mismatch between index and data");
8438   assert(isa<ConstantSDNode>(N->getScale()) &&
8439          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8440          "Scale should be a constant power of 2");
8441 
8442   CSEMap.InsertNode(N, IP);
8443   InsertNode(N);
8444   SDValue V(N, 0);
8445   NewSDValueDbgMsg(V, "Creating new node: ", this);
8446   return V;
8447 }
8448 
8449 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8450                                    ArrayRef<SDValue> Ops,
8451                                    MachineMemOperand *MMO,
8452                                    ISD::MemIndexType IndexType) {
8453   assert(Ops.size() == 7 && "Incompatible number of operands");
8454 
8455   FoldingSetNodeID ID;
8456   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8457   ID.AddInteger(VT.getRawBits());
8458   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8459       dl.getIROrder(), VTs, VT, MMO, IndexType));
8460   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8461   ID.AddInteger(MMO->getFlags());
8462   void *IP = nullptr;
8463   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8464     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8465     return SDValue(E, 0);
8466   }
8467   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8468                                        VT, MMO, IndexType);
8469   createOperands(N, Ops);
8470 
8471   assert(N->getMask().getValueType().getVectorElementCount() ==
8472              N->getValue().getValueType().getVectorElementCount() &&
8473          "Vector width mismatch between mask and data");
8474   assert(
8475       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8476           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8477       "Scalable flags of index and data do not match");
8478   assert(ElementCount::isKnownGE(
8479              N->getIndex().getValueType().getVectorElementCount(),
8480              N->getValue().getValueType().getVectorElementCount()) &&
8481          "Vector width mismatch between index and data");
8482   assert(isa<ConstantSDNode>(N->getScale()) &&
8483          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8484          "Scale should be a constant power of 2");
8485 
8486   CSEMap.InsertNode(N, IP);
8487   InsertNode(N);
8488   SDValue V(N, 0);
8489   NewSDValueDbgMsg(V, "Creating new node: ", this);
8490   return V;
8491 }
8492 
8493 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8494                                     SDValue Base, SDValue Offset, SDValue Mask,
8495                                     SDValue PassThru, EVT MemVT,
8496                                     MachineMemOperand *MMO,
8497                                     ISD::MemIndexedMode AM,
8498                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8499   bool Indexed = AM != ISD::UNINDEXED;
8500   assert((Indexed || Offset.isUndef()) &&
8501          "Unindexed masked load with an offset!");
8502   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8503                          : getVTList(VT, MVT::Other);
8504   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8505   FoldingSetNodeID ID;
8506   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8507   ID.AddInteger(MemVT.getRawBits());
8508   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8509       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8510   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8511   ID.AddInteger(MMO->getFlags());
8512   void *IP = nullptr;
8513   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8514     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8515     return SDValue(E, 0);
8516   }
8517   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8518                                         AM, ExtTy, isExpanding, MemVT, MMO);
8519   createOperands(N, Ops);
8520 
8521   CSEMap.InsertNode(N, IP);
8522   InsertNode(N);
8523   SDValue V(N, 0);
8524   NewSDValueDbgMsg(V, "Creating new node: ", this);
8525   return V;
8526 }
8527 
8528 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8529                                            SDValue Base, SDValue Offset,
8530                                            ISD::MemIndexedMode AM) {
8531   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8532   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8533   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8534                        Offset, LD->getMask(), LD->getPassThru(),
8535                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8536                        LD->getExtensionType(), LD->isExpandingLoad());
8537 }
8538 
8539 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8540                                      SDValue Val, SDValue Base, SDValue Offset,
8541                                      SDValue Mask, EVT MemVT,
8542                                      MachineMemOperand *MMO,
8543                                      ISD::MemIndexedMode AM, bool IsTruncating,
8544                                      bool IsCompressing) {
8545   assert(Chain.getValueType() == MVT::Other &&
8546         "Invalid chain type");
8547   bool Indexed = AM != ISD::UNINDEXED;
8548   assert((Indexed || Offset.isUndef()) &&
8549          "Unindexed masked store with an offset!");
8550   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8551                          : getVTList(MVT::Other);
8552   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8553   FoldingSetNodeID ID;
8554   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8555   ID.AddInteger(MemVT.getRawBits());
8556   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8557       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8558   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8559   ID.AddInteger(MMO->getFlags());
8560   void *IP = nullptr;
8561   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8562     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8563     return SDValue(E, 0);
8564   }
8565   auto *N =
8566       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8567                                    IsTruncating, IsCompressing, MemVT, MMO);
8568   createOperands(N, Ops);
8569 
8570   CSEMap.InsertNode(N, IP);
8571   InsertNode(N);
8572   SDValue V(N, 0);
8573   NewSDValueDbgMsg(V, "Creating new node: ", this);
8574   return V;
8575 }
8576 
8577 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8578                                             SDValue Base, SDValue Offset,
8579                                             ISD::MemIndexedMode AM) {
8580   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8581   assert(ST->getOffset().isUndef() &&
8582          "Masked store is already a indexed store!");
8583   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8584                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8585                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8586 }
8587 
8588 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8589                                       ArrayRef<SDValue> Ops,
8590                                       MachineMemOperand *MMO,
8591                                       ISD::MemIndexType IndexType,
8592                                       ISD::LoadExtType ExtTy) {
8593   assert(Ops.size() == 6 && "Incompatible number of operands");
8594 
8595   FoldingSetNodeID ID;
8596   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8597   ID.AddInteger(MemVT.getRawBits());
8598   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8599       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8600   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8601   ID.AddInteger(MMO->getFlags());
8602   void *IP = nullptr;
8603   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8604     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8605     return SDValue(E, 0);
8606   }
8607 
8608   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8609                                           VTs, MemVT, MMO, IndexType, ExtTy);
8610   createOperands(N, Ops);
8611 
8612   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8613          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8614   assert(N->getMask().getValueType().getVectorElementCount() ==
8615              N->getValueType(0).getVectorElementCount() &&
8616          "Vector width mismatch between mask and data");
8617   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8618              N->getValueType(0).getVectorElementCount().isScalable() &&
8619          "Scalable flags of index and data do not match");
8620   assert(ElementCount::isKnownGE(
8621              N->getIndex().getValueType().getVectorElementCount(),
8622              N->getValueType(0).getVectorElementCount()) &&
8623          "Vector width mismatch between index and data");
8624   assert(isa<ConstantSDNode>(N->getScale()) &&
8625          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8626          "Scale should be a constant power of 2");
8627 
8628   CSEMap.InsertNode(N, IP);
8629   InsertNode(N);
8630   SDValue V(N, 0);
8631   NewSDValueDbgMsg(V, "Creating new node: ", this);
8632   return V;
8633 }
8634 
8635 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8636                                        ArrayRef<SDValue> Ops,
8637                                        MachineMemOperand *MMO,
8638                                        ISD::MemIndexType IndexType,
8639                                        bool IsTrunc) {
8640   assert(Ops.size() == 6 && "Incompatible number of operands");
8641 
8642   FoldingSetNodeID ID;
8643   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8644   ID.AddInteger(MemVT.getRawBits());
8645   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8646       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8647   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8648   ID.AddInteger(MMO->getFlags());
8649   void *IP = nullptr;
8650   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8651     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8652     return SDValue(E, 0);
8653   }
8654 
8655   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8656                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8657   createOperands(N, Ops);
8658 
8659   assert(N->getMask().getValueType().getVectorElementCount() ==
8660              N->getValue().getValueType().getVectorElementCount() &&
8661          "Vector width mismatch between mask and data");
8662   assert(
8663       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8664           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8665       "Scalable flags of index and data do not match");
8666   assert(ElementCount::isKnownGE(
8667              N->getIndex().getValueType().getVectorElementCount(),
8668              N->getValue().getValueType().getVectorElementCount()) &&
8669          "Vector width mismatch between index and data");
8670   assert(isa<ConstantSDNode>(N->getScale()) &&
8671          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8672          "Scale should be a constant power of 2");
8673 
8674   CSEMap.InsertNode(N, IP);
8675   InsertNode(N);
8676   SDValue V(N, 0);
8677   NewSDValueDbgMsg(V, "Creating new node: ", this);
8678   return V;
8679 }
8680 
8681 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8682   // select undef, T, F --> T (if T is a constant), otherwise F
8683   // select, ?, undef, F --> F
8684   // select, ?, T, undef --> T
8685   if (Cond.isUndef())
8686     return isConstantValueOfAnyType(T) ? T : F;
8687   if (T.isUndef())
8688     return F;
8689   if (F.isUndef())
8690     return T;
8691 
8692   // select true, T, F --> T
8693   // select false, T, F --> F
8694   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8695     return CondC->isZero() ? F : T;
8696 
8697   // TODO: This should simplify VSELECT with constant condition using something
8698   // like this (but check boolean contents to be complete?):
8699   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8700   //    return T;
8701   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8702   //    return F;
8703 
8704   // select ?, T, T --> T
8705   if (T == F)
8706     return T;
8707 
8708   return SDValue();
8709 }
8710 
8711 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8712   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8713   if (X.isUndef())
8714     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8715   // shift X, undef --> undef (because it may shift by the bitwidth)
8716   if (Y.isUndef())
8717     return getUNDEF(X.getValueType());
8718 
8719   // shift 0, Y --> 0
8720   // shift X, 0 --> X
8721   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8722     return X;
8723 
8724   // shift X, C >= bitwidth(X) --> undef
8725   // All vector elements must be too big (or undef) to avoid partial undefs.
8726   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8727     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8728   };
8729   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8730     return getUNDEF(X.getValueType());
8731 
8732   return SDValue();
8733 }
8734 
8735 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8736                                       SDNodeFlags Flags) {
8737   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8738   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8739   // operation is poison. That result can be relaxed to undef.
8740   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8741   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8742   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8743                 (YC && YC->getValueAPF().isNaN());
8744   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8745                 (YC && YC->getValueAPF().isInfinity());
8746 
8747   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8748     return getUNDEF(X.getValueType());
8749 
8750   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8751     return getUNDEF(X.getValueType());
8752 
8753   if (!YC)
8754     return SDValue();
8755 
8756   // X + -0.0 --> X
8757   if (Opcode == ISD::FADD)
8758     if (YC->getValueAPF().isNegZero())
8759       return X;
8760 
8761   // X - +0.0 --> X
8762   if (Opcode == ISD::FSUB)
8763     if (YC->getValueAPF().isPosZero())
8764       return X;
8765 
8766   // X * 1.0 --> X
8767   // X / 1.0 --> X
8768   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8769     if (YC->getValueAPF().isExactlyValue(1.0))
8770       return X;
8771 
8772   // X * 0.0 --> 0.0
8773   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8774     if (YC->getValueAPF().isZero())
8775       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8776 
8777   return SDValue();
8778 }
8779 
8780 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8781                                SDValue Ptr, SDValue SV, unsigned Align) {
8782   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8783   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8784 }
8785 
8786 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8787                               ArrayRef<SDUse> Ops) {
8788   switch (Ops.size()) {
8789   case 0: return getNode(Opcode, DL, VT);
8790   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8791   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8792   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8793   default: break;
8794   }
8795 
8796   // Copy from an SDUse array into an SDValue array for use with
8797   // the regular getNode logic.
8798   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8799   return getNode(Opcode, DL, VT, NewOps);
8800 }
8801 
8802 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8803                               ArrayRef<SDValue> Ops) {
8804   SDNodeFlags Flags;
8805   if (Inserter)
8806     Flags = Inserter->getFlags();
8807   return getNode(Opcode, DL, VT, Ops, Flags);
8808 }
8809 
8810 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8811                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8812   unsigned NumOps = Ops.size();
8813   switch (NumOps) {
8814   case 0: return getNode(Opcode, DL, VT);
8815   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8816   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8817   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8818   default: break;
8819   }
8820 
8821 #ifndef NDEBUG
8822   for (auto &Op : Ops)
8823     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8824            "Operand is DELETED_NODE!");
8825 #endif
8826 
8827   switch (Opcode) {
8828   default: break;
8829   case ISD::BUILD_VECTOR:
8830     // Attempt to simplify BUILD_VECTOR.
8831     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8832       return V;
8833     break;
8834   case ISD::CONCAT_VECTORS:
8835     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8836       return V;
8837     break;
8838   case ISD::SELECT_CC:
8839     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8840     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8841            "LHS and RHS of condition must have same type!");
8842     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8843            "True and False arms of SelectCC must have same type!");
8844     assert(Ops[2].getValueType() == VT &&
8845            "select_cc node must be of same type as true and false value!");
8846     break;
8847   case ISD::BR_CC:
8848     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8849     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8850            "LHS/RHS of comparison should match types!");
8851     break;
8852   case ISD::VP_ADD:
8853   case ISD::VP_SUB:
8854     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8855     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8856       Opcode = ISD::VP_XOR;
8857     break;
8858   case ISD::VP_MUL:
8859     // If it is VP_MUL mask operation then turn it to VP_AND
8860     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8861       Opcode = ISD::VP_AND;
8862     break;
8863   case ISD::VP_REDUCE_ADD:
8864     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8865     if (VT == MVT::i1)
8866       Opcode = ISD::VP_REDUCE_XOR;
8867     break;
8868   case ISD::VP_REDUCE_SMAX:
8869   case ISD::VP_REDUCE_UMIN:
8870     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
8871     // VP_REDUCE_AND.
8872     if (VT == MVT::i1)
8873       Opcode = ISD::VP_REDUCE_AND;
8874     break;
8875   case ISD::VP_REDUCE_SMIN:
8876   case ISD::VP_REDUCE_UMAX:
8877     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
8878     // VP_REDUCE_OR.
8879     if (VT == MVT::i1)
8880       Opcode = ISD::VP_REDUCE_OR;
8881     break;
8882   }
8883 
8884   // Memoize nodes.
8885   SDNode *N;
8886   SDVTList VTs = getVTList(VT);
8887 
8888   if (VT != MVT::Glue) {
8889     FoldingSetNodeID ID;
8890     AddNodeIDNode(ID, Opcode, VTs, Ops);
8891     void *IP = nullptr;
8892 
8893     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8894       return SDValue(E, 0);
8895 
8896     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8897     createOperands(N, Ops);
8898 
8899     CSEMap.InsertNode(N, IP);
8900   } else {
8901     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8902     createOperands(N, Ops);
8903   }
8904 
8905   N->setFlags(Flags);
8906   InsertNode(N);
8907   SDValue V(N, 0);
8908   NewSDValueDbgMsg(V, "Creating new node: ", this);
8909   return V;
8910 }
8911 
8912 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8913                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8914   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8915 }
8916 
8917 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8918                               ArrayRef<SDValue> Ops) {
8919   SDNodeFlags Flags;
8920   if (Inserter)
8921     Flags = Inserter->getFlags();
8922   return getNode(Opcode, DL, VTList, Ops, Flags);
8923 }
8924 
8925 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8926                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8927   if (VTList.NumVTs == 1)
8928     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
8929 
8930 #ifndef NDEBUG
8931   for (auto &Op : Ops)
8932     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8933            "Operand is DELETED_NODE!");
8934 #endif
8935 
8936   switch (Opcode) {
8937   case ISD::STRICT_FP_EXTEND:
8938     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8939            "Invalid STRICT_FP_EXTEND!");
8940     assert(VTList.VTs[0].isFloatingPoint() &&
8941            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8942     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8943            "STRICT_FP_EXTEND result type should be vector iff the operand "
8944            "type is vector!");
8945     assert((!VTList.VTs[0].isVector() ||
8946             VTList.VTs[0].getVectorNumElements() ==
8947             Ops[1].getValueType().getVectorNumElements()) &&
8948            "Vector element count mismatch!");
8949     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8950            "Invalid fpext node, dst <= src!");
8951     break;
8952   case ISD::STRICT_FP_ROUND:
8953     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8954     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8955            "STRICT_FP_ROUND result type should be vector iff the operand "
8956            "type is vector!");
8957     assert((!VTList.VTs[0].isVector() ||
8958             VTList.VTs[0].getVectorNumElements() ==
8959             Ops[1].getValueType().getVectorNumElements()) &&
8960            "Vector element count mismatch!");
8961     assert(VTList.VTs[0].isFloatingPoint() &&
8962            Ops[1].getValueType().isFloatingPoint() &&
8963            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8964            isa<ConstantSDNode>(Ops[2]) &&
8965            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8966             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8967            "Invalid STRICT_FP_ROUND!");
8968     break;
8969 #if 0
8970   // FIXME: figure out how to safely handle things like
8971   // int foo(int x) { return 1 << (x & 255); }
8972   // int bar() { return foo(256); }
8973   case ISD::SRA_PARTS:
8974   case ISD::SRL_PARTS:
8975   case ISD::SHL_PARTS:
8976     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8977         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8978       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8979     else if (N3.getOpcode() == ISD::AND)
8980       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8981         // If the and is only masking out bits that cannot effect the shift,
8982         // eliminate the and.
8983         unsigned NumBits = VT.getScalarSizeInBits()*2;
8984         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8985           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8986       }
8987     break;
8988 #endif
8989   }
8990 
8991   // Memoize the node unless it returns a flag.
8992   SDNode *N;
8993   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8994     FoldingSetNodeID ID;
8995     AddNodeIDNode(ID, Opcode, VTList, Ops);
8996     void *IP = nullptr;
8997     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8998       return SDValue(E, 0);
8999 
9000     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9001     createOperands(N, Ops);
9002     CSEMap.InsertNode(N, IP);
9003   } else {
9004     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9005     createOperands(N, Ops);
9006   }
9007 
9008   N->setFlags(Flags);
9009   InsertNode(N);
9010   SDValue V(N, 0);
9011   NewSDValueDbgMsg(V, "Creating new node: ", this);
9012   return V;
9013 }
9014 
9015 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9016                               SDVTList VTList) {
9017   return getNode(Opcode, DL, VTList, None);
9018 }
9019 
9020 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9021                               SDValue N1) {
9022   SDValue Ops[] = { N1 };
9023   return getNode(Opcode, DL, VTList, Ops);
9024 }
9025 
9026 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9027                               SDValue N1, SDValue N2) {
9028   SDValue Ops[] = { N1, N2 };
9029   return getNode(Opcode, DL, VTList, Ops);
9030 }
9031 
9032 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9033                               SDValue N1, SDValue N2, SDValue N3) {
9034   SDValue Ops[] = { N1, N2, N3 };
9035   return getNode(Opcode, DL, VTList, Ops);
9036 }
9037 
9038 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9039                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9040   SDValue Ops[] = { N1, N2, N3, N4 };
9041   return getNode(Opcode, DL, VTList, Ops);
9042 }
9043 
9044 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9045                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9046                               SDValue N5) {
9047   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9048   return getNode(Opcode, DL, VTList, Ops);
9049 }
9050 
9051 SDVTList SelectionDAG::getVTList(EVT VT) {
9052   return makeVTList(SDNode::getValueTypeList(VT), 1);
9053 }
9054 
9055 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9056   FoldingSetNodeID ID;
9057   ID.AddInteger(2U);
9058   ID.AddInteger(VT1.getRawBits());
9059   ID.AddInteger(VT2.getRawBits());
9060 
9061   void *IP = nullptr;
9062   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9063   if (!Result) {
9064     EVT *Array = Allocator.Allocate<EVT>(2);
9065     Array[0] = VT1;
9066     Array[1] = VT2;
9067     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9068     VTListMap.InsertNode(Result, IP);
9069   }
9070   return Result->getSDVTList();
9071 }
9072 
9073 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9074   FoldingSetNodeID ID;
9075   ID.AddInteger(3U);
9076   ID.AddInteger(VT1.getRawBits());
9077   ID.AddInteger(VT2.getRawBits());
9078   ID.AddInteger(VT3.getRawBits());
9079 
9080   void *IP = nullptr;
9081   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9082   if (!Result) {
9083     EVT *Array = Allocator.Allocate<EVT>(3);
9084     Array[0] = VT1;
9085     Array[1] = VT2;
9086     Array[2] = VT3;
9087     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9088     VTListMap.InsertNode(Result, IP);
9089   }
9090   return Result->getSDVTList();
9091 }
9092 
9093 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9094   FoldingSetNodeID ID;
9095   ID.AddInteger(4U);
9096   ID.AddInteger(VT1.getRawBits());
9097   ID.AddInteger(VT2.getRawBits());
9098   ID.AddInteger(VT3.getRawBits());
9099   ID.AddInteger(VT4.getRawBits());
9100 
9101   void *IP = nullptr;
9102   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9103   if (!Result) {
9104     EVT *Array = Allocator.Allocate<EVT>(4);
9105     Array[0] = VT1;
9106     Array[1] = VT2;
9107     Array[2] = VT3;
9108     Array[3] = VT4;
9109     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9110     VTListMap.InsertNode(Result, IP);
9111   }
9112   return Result->getSDVTList();
9113 }
9114 
9115 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9116   unsigned NumVTs = VTs.size();
9117   FoldingSetNodeID ID;
9118   ID.AddInteger(NumVTs);
9119   for (unsigned index = 0; index < NumVTs; index++) {
9120     ID.AddInteger(VTs[index].getRawBits());
9121   }
9122 
9123   void *IP = nullptr;
9124   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9125   if (!Result) {
9126     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9127     llvm::copy(VTs, Array);
9128     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9129     VTListMap.InsertNode(Result, IP);
9130   }
9131   return Result->getSDVTList();
9132 }
9133 
9134 
9135 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9136 /// specified operands.  If the resultant node already exists in the DAG,
9137 /// this does not modify the specified node, instead it returns the node that
9138 /// already exists.  If the resultant node does not exist in the DAG, the
9139 /// input node is returned.  As a degenerate case, if you specify the same
9140 /// input operands as the node already has, the input node is returned.
9141 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9142   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9143 
9144   // Check to see if there is no change.
9145   if (Op == N->getOperand(0)) return N;
9146 
9147   // See if the modified node already exists.
9148   void *InsertPos = nullptr;
9149   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9150     return Existing;
9151 
9152   // Nope it doesn't.  Remove the node from its current place in the maps.
9153   if (InsertPos)
9154     if (!RemoveNodeFromCSEMaps(N))
9155       InsertPos = nullptr;
9156 
9157   // Now we update the operands.
9158   N->OperandList[0].set(Op);
9159 
9160   updateDivergence(N);
9161   // If this gets put into a CSE map, add it.
9162   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9163   return N;
9164 }
9165 
9166 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9167   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9168 
9169   // Check to see if there is no change.
9170   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9171     return N;   // No operands changed, just return the input node.
9172 
9173   // See if the modified node already exists.
9174   void *InsertPos = nullptr;
9175   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9176     return Existing;
9177 
9178   // Nope it doesn't.  Remove the node from its current place in the maps.
9179   if (InsertPos)
9180     if (!RemoveNodeFromCSEMaps(N))
9181       InsertPos = nullptr;
9182 
9183   // Now we update the operands.
9184   if (N->OperandList[0] != Op1)
9185     N->OperandList[0].set(Op1);
9186   if (N->OperandList[1] != Op2)
9187     N->OperandList[1].set(Op2);
9188 
9189   updateDivergence(N);
9190   // If this gets put into a CSE map, add it.
9191   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9192   return N;
9193 }
9194 
9195 SDNode *SelectionDAG::
9196 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9197   SDValue Ops[] = { Op1, Op2, Op3 };
9198   return UpdateNodeOperands(N, Ops);
9199 }
9200 
9201 SDNode *SelectionDAG::
9202 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9203                    SDValue Op3, SDValue Op4) {
9204   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9205   return UpdateNodeOperands(N, Ops);
9206 }
9207 
9208 SDNode *SelectionDAG::
9209 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9210                    SDValue Op3, SDValue Op4, SDValue Op5) {
9211   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9212   return UpdateNodeOperands(N, Ops);
9213 }
9214 
9215 SDNode *SelectionDAG::
9216 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9217   unsigned NumOps = Ops.size();
9218   assert(N->getNumOperands() == NumOps &&
9219          "Update with wrong number of operands");
9220 
9221   // If no operands changed just return the input node.
9222   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9223     return N;
9224 
9225   // See if the modified node already exists.
9226   void *InsertPos = nullptr;
9227   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9228     return Existing;
9229 
9230   // Nope it doesn't.  Remove the node from its current place in the maps.
9231   if (InsertPos)
9232     if (!RemoveNodeFromCSEMaps(N))
9233       InsertPos = nullptr;
9234 
9235   // Now we update the operands.
9236   for (unsigned i = 0; i != NumOps; ++i)
9237     if (N->OperandList[i] != Ops[i])
9238       N->OperandList[i].set(Ops[i]);
9239 
9240   updateDivergence(N);
9241   // If this gets put into a CSE map, add it.
9242   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9243   return N;
9244 }
9245 
9246 /// DropOperands - Release the operands and set this node to have
9247 /// zero operands.
9248 void SDNode::DropOperands() {
9249   // Unlike the code in MorphNodeTo that does this, we don't need to
9250   // watch for dead nodes here.
9251   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9252     SDUse &Use = *I++;
9253     Use.set(SDValue());
9254   }
9255 }
9256 
9257 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9258                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9259   if (NewMemRefs.empty()) {
9260     N->clearMemRefs();
9261     return;
9262   }
9263 
9264   // Check if we can avoid allocating by storing a single reference directly.
9265   if (NewMemRefs.size() == 1) {
9266     N->MemRefs = NewMemRefs[0];
9267     N->NumMemRefs = 1;
9268     return;
9269   }
9270 
9271   MachineMemOperand **MemRefsBuffer =
9272       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9273   llvm::copy(NewMemRefs, MemRefsBuffer);
9274   N->MemRefs = MemRefsBuffer;
9275   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9276 }
9277 
9278 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9279 /// machine opcode.
9280 ///
9281 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9282                                    EVT VT) {
9283   SDVTList VTs = getVTList(VT);
9284   return SelectNodeTo(N, MachineOpc, VTs, None);
9285 }
9286 
9287 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9288                                    EVT VT, SDValue Op1) {
9289   SDVTList VTs = getVTList(VT);
9290   SDValue Ops[] = { Op1 };
9291   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9292 }
9293 
9294 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9295                                    EVT VT, SDValue Op1,
9296                                    SDValue Op2) {
9297   SDVTList VTs = getVTList(VT);
9298   SDValue Ops[] = { Op1, Op2 };
9299   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9300 }
9301 
9302 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9303                                    EVT VT, SDValue Op1,
9304                                    SDValue Op2, SDValue Op3) {
9305   SDVTList VTs = getVTList(VT);
9306   SDValue Ops[] = { Op1, Op2, Op3 };
9307   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9308 }
9309 
9310 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9311                                    EVT VT, ArrayRef<SDValue> Ops) {
9312   SDVTList VTs = getVTList(VT);
9313   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9314 }
9315 
9316 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9317                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9318   SDVTList VTs = getVTList(VT1, VT2);
9319   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9320 }
9321 
9322 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9323                                    EVT VT1, EVT VT2) {
9324   SDVTList VTs = getVTList(VT1, VT2);
9325   return SelectNodeTo(N, MachineOpc, VTs, None);
9326 }
9327 
9328 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9329                                    EVT VT1, EVT VT2, EVT VT3,
9330                                    ArrayRef<SDValue> Ops) {
9331   SDVTList VTs = getVTList(VT1, VT2, VT3);
9332   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9333 }
9334 
9335 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9336                                    EVT VT1, EVT VT2,
9337                                    SDValue Op1, SDValue Op2) {
9338   SDVTList VTs = getVTList(VT1, VT2);
9339   SDValue Ops[] = { Op1, Op2 };
9340   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9341 }
9342 
9343 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9344                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9345   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9346   // Reset the NodeID to -1.
9347   New->setNodeId(-1);
9348   if (New != N) {
9349     ReplaceAllUsesWith(N, New);
9350     RemoveDeadNode(N);
9351   }
9352   return New;
9353 }
9354 
9355 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9356 /// the line number information on the merged node since it is not possible to
9357 /// preserve the information that operation is associated with multiple lines.
9358 /// This will make the debugger working better at -O0, were there is a higher
9359 /// probability having other instructions associated with that line.
9360 ///
9361 /// For IROrder, we keep the smaller of the two
9362 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9363   DebugLoc NLoc = N->getDebugLoc();
9364   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9365     N->setDebugLoc(DebugLoc());
9366   }
9367   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9368   N->setIROrder(Order);
9369   return N;
9370 }
9371 
9372 /// MorphNodeTo - This *mutates* the specified node to have the specified
9373 /// return type, opcode, and operands.
9374 ///
9375 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9376 /// node of the specified opcode and operands, it returns that node instead of
9377 /// the current one.  Note that the SDLoc need not be the same.
9378 ///
9379 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9380 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9381 /// node, and because it doesn't require CSE recalculation for any of
9382 /// the node's users.
9383 ///
9384 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9385 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9386 /// the legalizer which maintain worklists that would need to be updated when
9387 /// deleting things.
9388 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9389                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9390   // If an identical node already exists, use it.
9391   void *IP = nullptr;
9392   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9393     FoldingSetNodeID ID;
9394     AddNodeIDNode(ID, Opc, VTs, Ops);
9395     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9396       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9397   }
9398 
9399   if (!RemoveNodeFromCSEMaps(N))
9400     IP = nullptr;
9401 
9402   // Start the morphing.
9403   N->NodeType = Opc;
9404   N->ValueList = VTs.VTs;
9405   N->NumValues = VTs.NumVTs;
9406 
9407   // Clear the operands list, updating used nodes to remove this from their
9408   // use list.  Keep track of any operands that become dead as a result.
9409   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9410   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9411     SDUse &Use = *I++;
9412     SDNode *Used = Use.getNode();
9413     Use.set(SDValue());
9414     if (Used->use_empty())
9415       DeadNodeSet.insert(Used);
9416   }
9417 
9418   // For MachineNode, initialize the memory references information.
9419   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9420     MN->clearMemRefs();
9421 
9422   // Swap for an appropriately sized array from the recycler.
9423   removeOperands(N);
9424   createOperands(N, Ops);
9425 
9426   // Delete any nodes that are still dead after adding the uses for the
9427   // new operands.
9428   if (!DeadNodeSet.empty()) {
9429     SmallVector<SDNode *, 16> DeadNodes;
9430     for (SDNode *N : DeadNodeSet)
9431       if (N->use_empty())
9432         DeadNodes.push_back(N);
9433     RemoveDeadNodes(DeadNodes);
9434   }
9435 
9436   if (IP)
9437     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9438   return N;
9439 }
9440 
9441 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9442   unsigned OrigOpc = Node->getOpcode();
9443   unsigned NewOpc;
9444   switch (OrigOpc) {
9445   default:
9446     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9447 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9448   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9449 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9450   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9451 #include "llvm/IR/ConstrainedOps.def"
9452   }
9453 
9454   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9455 
9456   // We're taking this node out of the chain, so we need to re-link things.
9457   SDValue InputChain = Node->getOperand(0);
9458   SDValue OutputChain = SDValue(Node, 1);
9459   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9460 
9461   SmallVector<SDValue, 3> Ops;
9462   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9463     Ops.push_back(Node->getOperand(i));
9464 
9465   SDVTList VTs = getVTList(Node->getValueType(0));
9466   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9467 
9468   // MorphNodeTo can operate in two ways: if an existing node with the
9469   // specified operands exists, it can just return it.  Otherwise, it
9470   // updates the node in place to have the requested operands.
9471   if (Res == Node) {
9472     // If we updated the node in place, reset the node ID.  To the isel,
9473     // this should be just like a newly allocated machine node.
9474     Res->setNodeId(-1);
9475   } else {
9476     ReplaceAllUsesWith(Node, Res);
9477     RemoveDeadNode(Node);
9478   }
9479 
9480   return Res;
9481 }
9482 
9483 /// getMachineNode - These are used for target selectors to create a new node
9484 /// with specified return type(s), MachineInstr opcode, and operands.
9485 ///
9486 /// Note that getMachineNode returns the resultant node.  If there is already a
9487 /// node of the specified opcode and operands, it returns that node instead of
9488 /// the current one.
9489 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9490                                             EVT VT) {
9491   SDVTList VTs = getVTList(VT);
9492   return getMachineNode(Opcode, dl, VTs, None);
9493 }
9494 
9495 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9496                                             EVT VT, SDValue Op1) {
9497   SDVTList VTs = getVTList(VT);
9498   SDValue Ops[] = { Op1 };
9499   return getMachineNode(Opcode, dl, VTs, Ops);
9500 }
9501 
9502 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9503                                             EVT VT, SDValue Op1, SDValue Op2) {
9504   SDVTList VTs = getVTList(VT);
9505   SDValue Ops[] = { Op1, Op2 };
9506   return getMachineNode(Opcode, dl, VTs, Ops);
9507 }
9508 
9509 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9510                                             EVT VT, SDValue Op1, SDValue Op2,
9511                                             SDValue Op3) {
9512   SDVTList VTs = getVTList(VT);
9513   SDValue Ops[] = { Op1, Op2, Op3 };
9514   return getMachineNode(Opcode, dl, VTs, Ops);
9515 }
9516 
9517 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9518                                             EVT VT, ArrayRef<SDValue> Ops) {
9519   SDVTList VTs = getVTList(VT);
9520   return getMachineNode(Opcode, dl, VTs, Ops);
9521 }
9522 
9523 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9524                                             EVT VT1, EVT VT2, SDValue Op1,
9525                                             SDValue Op2) {
9526   SDVTList VTs = getVTList(VT1, VT2);
9527   SDValue Ops[] = { Op1, Op2 };
9528   return getMachineNode(Opcode, dl, VTs, Ops);
9529 }
9530 
9531 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9532                                             EVT VT1, EVT VT2, SDValue Op1,
9533                                             SDValue Op2, SDValue Op3) {
9534   SDVTList VTs = getVTList(VT1, VT2);
9535   SDValue Ops[] = { Op1, Op2, Op3 };
9536   return getMachineNode(Opcode, dl, VTs, Ops);
9537 }
9538 
9539 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9540                                             EVT VT1, EVT VT2,
9541                                             ArrayRef<SDValue> Ops) {
9542   SDVTList VTs = getVTList(VT1, VT2);
9543   return getMachineNode(Opcode, dl, VTs, Ops);
9544 }
9545 
9546 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9547                                             EVT VT1, EVT VT2, EVT VT3,
9548                                             SDValue Op1, SDValue Op2) {
9549   SDVTList VTs = getVTList(VT1, VT2, VT3);
9550   SDValue Ops[] = { Op1, Op2 };
9551   return getMachineNode(Opcode, dl, VTs, Ops);
9552 }
9553 
9554 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9555                                             EVT VT1, EVT VT2, EVT VT3,
9556                                             SDValue Op1, SDValue Op2,
9557                                             SDValue Op3) {
9558   SDVTList VTs = getVTList(VT1, VT2, VT3);
9559   SDValue Ops[] = { Op1, Op2, Op3 };
9560   return getMachineNode(Opcode, dl, VTs, Ops);
9561 }
9562 
9563 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9564                                             EVT VT1, EVT VT2, EVT VT3,
9565                                             ArrayRef<SDValue> Ops) {
9566   SDVTList VTs = getVTList(VT1, VT2, VT3);
9567   return getMachineNode(Opcode, dl, VTs, Ops);
9568 }
9569 
9570 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9571                                             ArrayRef<EVT> ResultTys,
9572                                             ArrayRef<SDValue> Ops) {
9573   SDVTList VTs = getVTList(ResultTys);
9574   return getMachineNode(Opcode, dl, VTs, Ops);
9575 }
9576 
9577 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9578                                             SDVTList VTs,
9579                                             ArrayRef<SDValue> Ops) {
9580   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9581   MachineSDNode *N;
9582   void *IP = nullptr;
9583 
9584   if (DoCSE) {
9585     FoldingSetNodeID ID;
9586     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9587     IP = nullptr;
9588     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9589       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9590     }
9591   }
9592 
9593   // Allocate a new MachineSDNode.
9594   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9595   createOperands(N, Ops);
9596 
9597   if (DoCSE)
9598     CSEMap.InsertNode(N, IP);
9599 
9600   InsertNode(N);
9601   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9602   return N;
9603 }
9604 
9605 /// getTargetExtractSubreg - A convenience function for creating
9606 /// TargetOpcode::EXTRACT_SUBREG nodes.
9607 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9608                                              SDValue Operand) {
9609   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9610   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9611                                   VT, Operand, SRIdxVal);
9612   return SDValue(Subreg, 0);
9613 }
9614 
9615 /// getTargetInsertSubreg - A convenience function for creating
9616 /// TargetOpcode::INSERT_SUBREG nodes.
9617 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9618                                             SDValue Operand, SDValue Subreg) {
9619   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9620   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9621                                   VT, Operand, Subreg, SRIdxVal);
9622   return SDValue(Result, 0);
9623 }
9624 
9625 /// getNodeIfExists - Get the specified node if it's already available, or
9626 /// else return NULL.
9627 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9628                                       ArrayRef<SDValue> Ops) {
9629   SDNodeFlags Flags;
9630   if (Inserter)
9631     Flags = Inserter->getFlags();
9632   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9633 }
9634 
9635 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9636                                       ArrayRef<SDValue> Ops,
9637                                       const SDNodeFlags Flags) {
9638   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9639     FoldingSetNodeID ID;
9640     AddNodeIDNode(ID, Opcode, VTList, Ops);
9641     void *IP = nullptr;
9642     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9643       E->intersectFlagsWith(Flags);
9644       return E;
9645     }
9646   }
9647   return nullptr;
9648 }
9649 
9650 /// doesNodeExist - Check if a node exists without modifying its flags.
9651 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9652                                  ArrayRef<SDValue> Ops) {
9653   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9654     FoldingSetNodeID ID;
9655     AddNodeIDNode(ID, Opcode, VTList, Ops);
9656     void *IP = nullptr;
9657     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9658       return true;
9659   }
9660   return false;
9661 }
9662 
9663 /// getDbgValue - Creates a SDDbgValue node.
9664 ///
9665 /// SDNode
9666 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9667                                       SDNode *N, unsigned R, bool IsIndirect,
9668                                       const DebugLoc &DL, unsigned O) {
9669   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9670          "Expected inlined-at fields to agree");
9671   return new (DbgInfo->getAlloc())
9672       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9673                  {}, IsIndirect, DL, O,
9674                  /*IsVariadic=*/false);
9675 }
9676 
9677 /// Constant
9678 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9679                                               DIExpression *Expr,
9680                                               const Value *C,
9681                                               const DebugLoc &DL, unsigned O) {
9682   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9683          "Expected inlined-at fields to agree");
9684   return new (DbgInfo->getAlloc())
9685       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9686                  /*IsIndirect=*/false, DL, O,
9687                  /*IsVariadic=*/false);
9688 }
9689 
9690 /// FrameIndex
9691 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9692                                                 DIExpression *Expr, unsigned FI,
9693                                                 bool IsIndirect,
9694                                                 const DebugLoc &DL,
9695                                                 unsigned O) {
9696   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9697          "Expected inlined-at fields to agree");
9698   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9699 }
9700 
9701 /// FrameIndex with dependencies
9702 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9703                                                 DIExpression *Expr, unsigned FI,
9704                                                 ArrayRef<SDNode *> Dependencies,
9705                                                 bool IsIndirect,
9706                                                 const DebugLoc &DL,
9707                                                 unsigned O) {
9708   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9709          "Expected inlined-at fields to agree");
9710   return new (DbgInfo->getAlloc())
9711       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9712                  Dependencies, IsIndirect, DL, O,
9713                  /*IsVariadic=*/false);
9714 }
9715 
9716 /// VReg
9717 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9718                                           unsigned VReg, bool IsIndirect,
9719                                           const DebugLoc &DL, unsigned O) {
9720   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9721          "Expected inlined-at fields to agree");
9722   return new (DbgInfo->getAlloc())
9723       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9724                  {}, IsIndirect, DL, O,
9725                  /*IsVariadic=*/false);
9726 }
9727 
9728 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9729                                           ArrayRef<SDDbgOperand> Locs,
9730                                           ArrayRef<SDNode *> Dependencies,
9731                                           bool IsIndirect, const DebugLoc &DL,
9732                                           unsigned O, bool IsVariadic) {
9733   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9734          "Expected inlined-at fields to agree");
9735   return new (DbgInfo->getAlloc())
9736       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9737                  DL, O, IsVariadic);
9738 }
9739 
9740 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9741                                      unsigned OffsetInBits, unsigned SizeInBits,
9742                                      bool InvalidateDbg) {
9743   SDNode *FromNode = From.getNode();
9744   SDNode *ToNode = To.getNode();
9745   assert(FromNode && ToNode && "Can't modify dbg values");
9746 
9747   // PR35338
9748   // TODO: assert(From != To && "Redundant dbg value transfer");
9749   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9750   if (From == To || FromNode == ToNode)
9751     return;
9752 
9753   if (!FromNode->getHasDebugValue())
9754     return;
9755 
9756   SDDbgOperand FromLocOp =
9757       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9758   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9759 
9760   SmallVector<SDDbgValue *, 2> ClonedDVs;
9761   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9762     if (Dbg->isInvalidated())
9763       continue;
9764 
9765     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9766 
9767     // Create a new location ops vector that is equal to the old vector, but
9768     // with each instance of FromLocOp replaced with ToLocOp.
9769     bool Changed = false;
9770     auto NewLocOps = Dbg->copyLocationOps();
9771     std::replace_if(
9772         NewLocOps.begin(), NewLocOps.end(),
9773         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9774           bool Match = Op == FromLocOp;
9775           Changed |= Match;
9776           return Match;
9777         },
9778         ToLocOp);
9779     // Ignore this SDDbgValue if we didn't find a matching location.
9780     if (!Changed)
9781       continue;
9782 
9783     DIVariable *Var = Dbg->getVariable();
9784     auto *Expr = Dbg->getExpression();
9785     // If a fragment is requested, update the expression.
9786     if (SizeInBits) {
9787       // When splitting a larger (e.g., sign-extended) value whose
9788       // lower bits are described with an SDDbgValue, do not attempt
9789       // to transfer the SDDbgValue to the upper bits.
9790       if (auto FI = Expr->getFragmentInfo())
9791         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9792           continue;
9793       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9794                                                              SizeInBits);
9795       if (!Fragment)
9796         continue;
9797       Expr = *Fragment;
9798     }
9799 
9800     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9801     // Clone the SDDbgValue and move it to To.
9802     SDDbgValue *Clone = getDbgValueList(
9803         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9804         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9805         Dbg->isVariadic());
9806     ClonedDVs.push_back(Clone);
9807 
9808     if (InvalidateDbg) {
9809       // Invalidate value and indicate the SDDbgValue should not be emitted.
9810       Dbg->setIsInvalidated();
9811       Dbg->setIsEmitted();
9812     }
9813   }
9814 
9815   for (SDDbgValue *Dbg : ClonedDVs) {
9816     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9817            "Transferred DbgValues should depend on the new SDNode");
9818     AddDbgValue(Dbg, false);
9819   }
9820 }
9821 
9822 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9823   if (!N.getHasDebugValue())
9824     return;
9825 
9826   SmallVector<SDDbgValue *, 2> ClonedDVs;
9827   for (auto DV : GetDbgValues(&N)) {
9828     if (DV->isInvalidated())
9829       continue;
9830     switch (N.getOpcode()) {
9831     default:
9832       break;
9833     case ISD::ADD:
9834       SDValue N0 = N.getOperand(0);
9835       SDValue N1 = N.getOperand(1);
9836       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9837           isConstantIntBuildVectorOrConstantInt(N1)) {
9838         uint64_t Offset = N.getConstantOperandVal(1);
9839 
9840         // Rewrite an ADD constant node into a DIExpression. Since we are
9841         // performing arithmetic to compute the variable's *value* in the
9842         // DIExpression, we need to mark the expression with a
9843         // DW_OP_stack_value.
9844         auto *DIExpr = DV->getExpression();
9845         auto NewLocOps = DV->copyLocationOps();
9846         bool Changed = false;
9847         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9848           // We're not given a ResNo to compare against because the whole
9849           // node is going away. We know that any ISD::ADD only has one
9850           // result, so we can assume any node match is using the result.
9851           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9852               NewLocOps[i].getSDNode() != &N)
9853             continue;
9854           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9855           SmallVector<uint64_t, 3> ExprOps;
9856           DIExpression::appendOffset(ExprOps, Offset);
9857           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9858           Changed = true;
9859         }
9860         (void)Changed;
9861         assert(Changed && "Salvage target doesn't use N");
9862 
9863         auto AdditionalDependencies = DV->getAdditionalDependencies();
9864         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9865                                             NewLocOps, AdditionalDependencies,
9866                                             DV->isIndirect(), DV->getDebugLoc(),
9867                                             DV->getOrder(), DV->isVariadic());
9868         ClonedDVs.push_back(Clone);
9869         DV->setIsInvalidated();
9870         DV->setIsEmitted();
9871         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9872                    N0.getNode()->dumprFull(this);
9873                    dbgs() << " into " << *DIExpr << '\n');
9874       }
9875     }
9876   }
9877 
9878   for (SDDbgValue *Dbg : ClonedDVs) {
9879     assert(!Dbg->getSDNodes().empty() &&
9880            "Salvaged DbgValue should depend on a new SDNode");
9881     AddDbgValue(Dbg, false);
9882   }
9883 }
9884 
9885 /// Creates a SDDbgLabel node.
9886 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9887                                       const DebugLoc &DL, unsigned O) {
9888   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9889          "Expected inlined-at fields to agree");
9890   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9891 }
9892 
9893 namespace {
9894 
9895 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9896 /// pointed to by a use iterator is deleted, increment the use iterator
9897 /// so that it doesn't dangle.
9898 ///
9899 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9900   SDNode::use_iterator &UI;
9901   SDNode::use_iterator &UE;
9902 
9903   void NodeDeleted(SDNode *N, SDNode *E) override {
9904     // Increment the iterator as needed.
9905     while (UI != UE && N == *UI)
9906       ++UI;
9907   }
9908 
9909 public:
9910   RAUWUpdateListener(SelectionDAG &d,
9911                      SDNode::use_iterator &ui,
9912                      SDNode::use_iterator &ue)
9913     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9914 };
9915 
9916 } // end anonymous namespace
9917 
9918 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9919 /// This can cause recursive merging of nodes in the DAG.
9920 ///
9921 /// This version assumes From has a single result value.
9922 ///
9923 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9924   SDNode *From = FromN.getNode();
9925   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9926          "Cannot replace with this method!");
9927   assert(From != To.getNode() && "Cannot replace uses of with self");
9928 
9929   // Preserve Debug Values
9930   transferDbgValues(FromN, To);
9931 
9932   // Iterate over all the existing uses of From. New uses will be added
9933   // to the beginning of the use list, which we avoid visiting.
9934   // This specifically avoids visiting uses of From that arise while the
9935   // replacement is happening, because any such uses would be the result
9936   // of CSE: If an existing node looks like From after one of its operands
9937   // is replaced by To, we don't want to replace of all its users with To
9938   // too. See PR3018 for more info.
9939   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9940   RAUWUpdateListener Listener(*this, UI, UE);
9941   while (UI != UE) {
9942     SDNode *User = *UI;
9943 
9944     // This node is about to morph, remove its old self from the CSE maps.
9945     RemoveNodeFromCSEMaps(User);
9946 
9947     // A user can appear in a use list multiple times, and when this
9948     // happens the uses are usually next to each other in the list.
9949     // To help reduce the number of CSE recomputations, process all
9950     // the uses of this user that we can find this way.
9951     do {
9952       SDUse &Use = UI.getUse();
9953       ++UI;
9954       Use.set(To);
9955       if (To->isDivergent() != From->isDivergent())
9956         updateDivergence(User);
9957     } while (UI != UE && *UI == User);
9958     // Now that we have modified User, add it back to the CSE maps.  If it
9959     // already exists there, recursively merge the results together.
9960     AddModifiedNodeToCSEMaps(User);
9961   }
9962 
9963   // If we just RAUW'd the root, take note.
9964   if (FromN == getRoot())
9965     setRoot(To);
9966 }
9967 
9968 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9969 /// This can cause recursive merging of nodes in the DAG.
9970 ///
9971 /// This version assumes that for each value of From, there is a
9972 /// corresponding value in To in the same position with the same type.
9973 ///
9974 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9975 #ifndef NDEBUG
9976   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9977     assert((!From->hasAnyUseOfValue(i) ||
9978             From->getValueType(i) == To->getValueType(i)) &&
9979            "Cannot use this version of ReplaceAllUsesWith!");
9980 #endif
9981 
9982   // Handle the trivial case.
9983   if (From == To)
9984     return;
9985 
9986   // Preserve Debug Info. Only do this if there's a use.
9987   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9988     if (From->hasAnyUseOfValue(i)) {
9989       assert((i < To->getNumValues()) && "Invalid To location");
9990       transferDbgValues(SDValue(From, i), SDValue(To, i));
9991     }
9992 
9993   // Iterate over just the existing users of From. See the comments in
9994   // the ReplaceAllUsesWith above.
9995   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9996   RAUWUpdateListener Listener(*this, UI, UE);
9997   while (UI != UE) {
9998     SDNode *User = *UI;
9999 
10000     // This node is about to morph, remove its old self from the CSE maps.
10001     RemoveNodeFromCSEMaps(User);
10002 
10003     // A user can appear in a use list multiple times, and when this
10004     // happens the uses are usually next to each other in the list.
10005     // To help reduce the number of CSE recomputations, process all
10006     // the uses of this user that we can find this way.
10007     do {
10008       SDUse &Use = UI.getUse();
10009       ++UI;
10010       Use.setNode(To);
10011       if (To->isDivergent() != From->isDivergent())
10012         updateDivergence(User);
10013     } while (UI != UE && *UI == User);
10014 
10015     // Now that we have modified User, add it back to the CSE maps.  If it
10016     // already exists there, recursively merge the results together.
10017     AddModifiedNodeToCSEMaps(User);
10018   }
10019 
10020   // If we just RAUW'd the root, take note.
10021   if (From == getRoot().getNode())
10022     setRoot(SDValue(To, getRoot().getResNo()));
10023 }
10024 
10025 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10026 /// This can cause recursive merging of nodes in the DAG.
10027 ///
10028 /// This version can replace From with any result values.  To must match the
10029 /// number and types of values returned by From.
10030 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10031   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10032     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10033 
10034   // Preserve Debug Info.
10035   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10036     transferDbgValues(SDValue(From, i), To[i]);
10037 
10038   // Iterate over just the existing users of From. See the comments in
10039   // the ReplaceAllUsesWith above.
10040   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10041   RAUWUpdateListener Listener(*this, UI, UE);
10042   while (UI != UE) {
10043     SDNode *User = *UI;
10044 
10045     // This node is about to morph, remove its old self from the CSE maps.
10046     RemoveNodeFromCSEMaps(User);
10047 
10048     // A user can appear in a use list multiple times, and when this happens the
10049     // uses are usually next to each other in the list.  To help reduce the
10050     // number of CSE and divergence recomputations, process all the uses of this
10051     // user that we can find this way.
10052     bool To_IsDivergent = false;
10053     do {
10054       SDUse &Use = UI.getUse();
10055       const SDValue &ToOp = To[Use.getResNo()];
10056       ++UI;
10057       Use.set(ToOp);
10058       To_IsDivergent |= ToOp->isDivergent();
10059     } while (UI != UE && *UI == User);
10060 
10061     if (To_IsDivergent != From->isDivergent())
10062       updateDivergence(User);
10063 
10064     // Now that we have modified User, add it back to the CSE maps.  If it
10065     // already exists there, recursively merge the results together.
10066     AddModifiedNodeToCSEMaps(User);
10067   }
10068 
10069   // If we just RAUW'd the root, take note.
10070   if (From == getRoot().getNode())
10071     setRoot(SDValue(To[getRoot().getResNo()]));
10072 }
10073 
10074 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10075 /// uses of other values produced by From.getNode() alone.  The Deleted
10076 /// vector is handled the same way as for ReplaceAllUsesWith.
10077 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10078   // Handle the really simple, really trivial case efficiently.
10079   if (From == To) return;
10080 
10081   // Handle the simple, trivial, case efficiently.
10082   if (From.getNode()->getNumValues() == 1) {
10083     ReplaceAllUsesWith(From, To);
10084     return;
10085   }
10086 
10087   // Preserve Debug Info.
10088   transferDbgValues(From, To);
10089 
10090   // Iterate over just the existing users of From. See the comments in
10091   // the ReplaceAllUsesWith above.
10092   SDNode::use_iterator UI = From.getNode()->use_begin(),
10093                        UE = From.getNode()->use_end();
10094   RAUWUpdateListener Listener(*this, UI, UE);
10095   while (UI != UE) {
10096     SDNode *User = *UI;
10097     bool UserRemovedFromCSEMaps = false;
10098 
10099     // A user can appear in a use list multiple times, and when this
10100     // happens the uses are usually next to each other in the list.
10101     // To help reduce the number of CSE recomputations, process all
10102     // the uses of this user that we can find this way.
10103     do {
10104       SDUse &Use = UI.getUse();
10105 
10106       // Skip uses of different values from the same node.
10107       if (Use.getResNo() != From.getResNo()) {
10108         ++UI;
10109         continue;
10110       }
10111 
10112       // If this node hasn't been modified yet, it's still in the CSE maps,
10113       // so remove its old self from the CSE maps.
10114       if (!UserRemovedFromCSEMaps) {
10115         RemoveNodeFromCSEMaps(User);
10116         UserRemovedFromCSEMaps = true;
10117       }
10118 
10119       ++UI;
10120       Use.set(To);
10121       if (To->isDivergent() != From->isDivergent())
10122         updateDivergence(User);
10123     } while (UI != UE && *UI == User);
10124     // We are iterating over all uses of the From node, so if a use
10125     // doesn't use the specific value, no changes are made.
10126     if (!UserRemovedFromCSEMaps)
10127       continue;
10128 
10129     // Now that we have modified User, add it back to the CSE maps.  If it
10130     // already exists there, recursively merge the results together.
10131     AddModifiedNodeToCSEMaps(User);
10132   }
10133 
10134   // If we just RAUW'd the root, take note.
10135   if (From == getRoot())
10136     setRoot(To);
10137 }
10138 
10139 namespace {
10140 
10141 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10142 /// to record information about a use.
10143 struct UseMemo {
10144   SDNode *User;
10145   unsigned Index;
10146   SDUse *Use;
10147 };
10148 
10149 /// operator< - Sort Memos by User.
10150 bool operator<(const UseMemo &L, const UseMemo &R) {
10151   return (intptr_t)L.User < (intptr_t)R.User;
10152 }
10153 
10154 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10155 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10156 /// the node already has been taken care of recursively.
10157 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10158   SmallVector<UseMemo, 4> &Uses;
10159 
10160   void NodeDeleted(SDNode *N, SDNode *E) override {
10161     for (UseMemo &Memo : Uses)
10162       if (Memo.User == N)
10163         Memo.User = nullptr;
10164   }
10165 
10166 public:
10167   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10168       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10169 };
10170 
10171 } // end anonymous namespace
10172 
10173 bool SelectionDAG::calculateDivergence(SDNode *N) {
10174   if (TLI->isSDNodeAlwaysUniform(N)) {
10175     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10176            "Conflicting divergence information!");
10177     return false;
10178   }
10179   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10180     return true;
10181   for (auto &Op : N->ops()) {
10182     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10183       return true;
10184   }
10185   return false;
10186 }
10187 
10188 void SelectionDAG::updateDivergence(SDNode *N) {
10189   SmallVector<SDNode *, 16> Worklist(1, N);
10190   do {
10191     N = Worklist.pop_back_val();
10192     bool IsDivergent = calculateDivergence(N);
10193     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10194       N->SDNodeBits.IsDivergent = IsDivergent;
10195       llvm::append_range(Worklist, N->uses());
10196     }
10197   } while (!Worklist.empty());
10198 }
10199 
10200 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10201   DenseMap<SDNode *, unsigned> Degree;
10202   Order.reserve(AllNodes.size());
10203   for (auto &N : allnodes()) {
10204     unsigned NOps = N.getNumOperands();
10205     Degree[&N] = NOps;
10206     if (0 == NOps)
10207       Order.push_back(&N);
10208   }
10209   for (size_t I = 0; I != Order.size(); ++I) {
10210     SDNode *N = Order[I];
10211     for (auto U : N->uses()) {
10212       unsigned &UnsortedOps = Degree[U];
10213       if (0 == --UnsortedOps)
10214         Order.push_back(U);
10215     }
10216   }
10217 }
10218 
10219 #ifndef NDEBUG
10220 void SelectionDAG::VerifyDAGDivergence() {
10221   std::vector<SDNode *> TopoOrder;
10222   CreateTopologicalOrder(TopoOrder);
10223   for (auto *N : TopoOrder) {
10224     assert(calculateDivergence(N) == N->isDivergent() &&
10225            "Divergence bit inconsistency detected");
10226   }
10227 }
10228 #endif
10229 
10230 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10231 /// uses of other values produced by From.getNode() alone.  The same value
10232 /// may appear in both the From and To list.  The Deleted vector is
10233 /// handled the same way as for ReplaceAllUsesWith.
10234 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10235                                               const SDValue *To,
10236                                               unsigned Num){
10237   // Handle the simple, trivial case efficiently.
10238   if (Num == 1)
10239     return ReplaceAllUsesOfValueWith(*From, *To);
10240 
10241   transferDbgValues(*From, *To);
10242 
10243   // Read up all the uses and make records of them. This helps
10244   // processing new uses that are introduced during the
10245   // replacement process.
10246   SmallVector<UseMemo, 4> Uses;
10247   for (unsigned i = 0; i != Num; ++i) {
10248     unsigned FromResNo = From[i].getResNo();
10249     SDNode *FromNode = From[i].getNode();
10250     for (SDNode::use_iterator UI = FromNode->use_begin(),
10251          E = FromNode->use_end(); UI != E; ++UI) {
10252       SDUse &Use = UI.getUse();
10253       if (Use.getResNo() == FromResNo) {
10254         UseMemo Memo = { *UI, i, &Use };
10255         Uses.push_back(Memo);
10256       }
10257     }
10258   }
10259 
10260   // Sort the uses, so that all the uses from a given User are together.
10261   llvm::sort(Uses);
10262   RAUOVWUpdateListener Listener(*this, Uses);
10263 
10264   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10265        UseIndex != UseIndexEnd; ) {
10266     // We know that this user uses some value of From.  If it is the right
10267     // value, update it.
10268     SDNode *User = Uses[UseIndex].User;
10269     // If the node has been deleted by recursive CSE updates when updating
10270     // another node, then just skip this entry.
10271     if (User == nullptr) {
10272       ++UseIndex;
10273       continue;
10274     }
10275 
10276     // This node is about to morph, remove its old self from the CSE maps.
10277     RemoveNodeFromCSEMaps(User);
10278 
10279     // The Uses array is sorted, so all the uses for a given User
10280     // are next to each other in the list.
10281     // To help reduce the number of CSE recomputations, process all
10282     // the uses of this user that we can find this way.
10283     do {
10284       unsigned i = Uses[UseIndex].Index;
10285       SDUse &Use = *Uses[UseIndex].Use;
10286       ++UseIndex;
10287 
10288       Use.set(To[i]);
10289     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10290 
10291     // Now that we have modified User, add it back to the CSE maps.  If it
10292     // already exists there, recursively merge the results together.
10293     AddModifiedNodeToCSEMaps(User);
10294   }
10295 }
10296 
10297 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10298 /// based on their topological order. It returns the maximum id and a vector
10299 /// of the SDNodes* in assigned order by reference.
10300 unsigned SelectionDAG::AssignTopologicalOrder() {
10301   unsigned DAGSize = 0;
10302 
10303   // SortedPos tracks the progress of the algorithm. Nodes before it are
10304   // sorted, nodes after it are unsorted. When the algorithm completes
10305   // it is at the end of the list.
10306   allnodes_iterator SortedPos = allnodes_begin();
10307 
10308   // Visit all the nodes. Move nodes with no operands to the front of
10309   // the list immediately. Annotate nodes that do have operands with their
10310   // operand count. Before we do this, the Node Id fields of the nodes
10311   // may contain arbitrary values. After, the Node Id fields for nodes
10312   // before SortedPos will contain the topological sort index, and the
10313   // Node Id fields for nodes At SortedPos and after will contain the
10314   // count of outstanding operands.
10315   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10316     checkForCycles(&N, this);
10317     unsigned Degree = N.getNumOperands();
10318     if (Degree == 0) {
10319       // A node with no uses, add it to the result array immediately.
10320       N.setNodeId(DAGSize++);
10321       allnodes_iterator Q(&N);
10322       if (Q != SortedPos)
10323         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10324       assert(SortedPos != AllNodes.end() && "Overran node list");
10325       ++SortedPos;
10326     } else {
10327       // Temporarily use the Node Id as scratch space for the degree count.
10328       N.setNodeId(Degree);
10329     }
10330   }
10331 
10332   // Visit all the nodes. As we iterate, move nodes into sorted order,
10333   // such that by the time the end is reached all nodes will be sorted.
10334   for (SDNode &Node : allnodes()) {
10335     SDNode *N = &Node;
10336     checkForCycles(N, this);
10337     // N is in sorted position, so all its uses have one less operand
10338     // that needs to be sorted.
10339     for (SDNode *P : N->uses()) {
10340       unsigned Degree = P->getNodeId();
10341       assert(Degree != 0 && "Invalid node degree");
10342       --Degree;
10343       if (Degree == 0) {
10344         // All of P's operands are sorted, so P may sorted now.
10345         P->setNodeId(DAGSize++);
10346         if (P->getIterator() != SortedPos)
10347           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10348         assert(SortedPos != AllNodes.end() && "Overran node list");
10349         ++SortedPos;
10350       } else {
10351         // Update P's outstanding operand count.
10352         P->setNodeId(Degree);
10353       }
10354     }
10355     if (Node.getIterator() == SortedPos) {
10356 #ifndef NDEBUG
10357       allnodes_iterator I(N);
10358       SDNode *S = &*++I;
10359       dbgs() << "Overran sorted position:\n";
10360       S->dumprFull(this); dbgs() << "\n";
10361       dbgs() << "Checking if this is due to cycles\n";
10362       checkForCycles(this, true);
10363 #endif
10364       llvm_unreachable(nullptr);
10365     }
10366   }
10367 
10368   assert(SortedPos == AllNodes.end() &&
10369          "Topological sort incomplete!");
10370   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10371          "First node in topological sort is not the entry token!");
10372   assert(AllNodes.front().getNodeId() == 0 &&
10373          "First node in topological sort has non-zero id!");
10374   assert(AllNodes.front().getNumOperands() == 0 &&
10375          "First node in topological sort has operands!");
10376   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10377          "Last node in topologic sort has unexpected id!");
10378   assert(AllNodes.back().use_empty() &&
10379          "Last node in topologic sort has users!");
10380   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10381   return DAGSize;
10382 }
10383 
10384 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10385 /// value is produced by SD.
10386 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10387   for (SDNode *SD : DB->getSDNodes()) {
10388     if (!SD)
10389       continue;
10390     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10391     SD->setHasDebugValue(true);
10392   }
10393   DbgInfo->add(DB, isParameter);
10394 }
10395 
10396 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10397 
10398 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10399                                                    SDValue NewMemOpChain) {
10400   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10401   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10402   // The new memory operation must have the same position as the old load in
10403   // terms of memory dependency. Create a TokenFactor for the old load and new
10404   // memory operation and update uses of the old load's output chain to use that
10405   // TokenFactor.
10406   if (OldChain == NewMemOpChain || OldChain.use_empty())
10407     return NewMemOpChain;
10408 
10409   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10410                                 OldChain, NewMemOpChain);
10411   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10412   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10413   return TokenFactor;
10414 }
10415 
10416 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10417                                                    SDValue NewMemOp) {
10418   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10419   SDValue OldChain = SDValue(OldLoad, 1);
10420   SDValue NewMemOpChain = NewMemOp.getValue(1);
10421   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10422 }
10423 
10424 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10425                                                      Function **OutFunction) {
10426   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10427 
10428   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10429   auto *Module = MF->getFunction().getParent();
10430   auto *Function = Module->getFunction(Symbol);
10431 
10432   if (OutFunction != nullptr)
10433       *OutFunction = Function;
10434 
10435   if (Function != nullptr) {
10436     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10437     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10438   }
10439 
10440   std::string ErrorStr;
10441   raw_string_ostream ErrorFormatter(ErrorStr);
10442   ErrorFormatter << "Undefined external symbol ";
10443   ErrorFormatter << '"' << Symbol << '"';
10444   report_fatal_error(Twine(ErrorFormatter.str()));
10445 }
10446 
10447 //===----------------------------------------------------------------------===//
10448 //                              SDNode Class
10449 //===----------------------------------------------------------------------===//
10450 
10451 bool llvm::isNullConstant(SDValue V) {
10452   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10453   return Const != nullptr && Const->isZero();
10454 }
10455 
10456 bool llvm::isNullFPConstant(SDValue V) {
10457   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10458   return Const != nullptr && Const->isZero() && !Const->isNegative();
10459 }
10460 
10461 bool llvm::isAllOnesConstant(SDValue V) {
10462   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10463   return Const != nullptr && Const->isAllOnes();
10464 }
10465 
10466 bool llvm::isOneConstant(SDValue V) {
10467   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10468   return Const != nullptr && Const->isOne();
10469 }
10470 
10471 bool llvm::isMinSignedConstant(SDValue V) {
10472   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10473   return Const != nullptr && Const->isMinSignedValue();
10474 }
10475 
10476 SDValue llvm::peekThroughBitcasts(SDValue V) {
10477   while (V.getOpcode() == ISD::BITCAST)
10478     V = V.getOperand(0);
10479   return V;
10480 }
10481 
10482 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10483   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10484     V = V.getOperand(0);
10485   return V;
10486 }
10487 
10488 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10489   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10490     V = V.getOperand(0);
10491   return V;
10492 }
10493 
10494 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10495   if (V.getOpcode() != ISD::XOR)
10496     return false;
10497   V = peekThroughBitcasts(V.getOperand(1));
10498   unsigned NumBits = V.getScalarValueSizeInBits();
10499   ConstantSDNode *C =
10500       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10501   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10502 }
10503 
10504 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10505                                           bool AllowTruncation) {
10506   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10507     return CN;
10508 
10509   // SplatVectors can truncate their operands. Ignore that case here unless
10510   // AllowTruncation is set.
10511   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10512     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10513     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10514       EVT CVT = CN->getValueType(0);
10515       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10516       if (AllowTruncation || CVT == VecEltVT)
10517         return CN;
10518     }
10519   }
10520 
10521   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10522     BitVector UndefElements;
10523     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10524 
10525     // BuildVectors can truncate their operands. Ignore that case here unless
10526     // AllowTruncation is set.
10527     if (CN && (UndefElements.none() || AllowUndefs)) {
10528       EVT CVT = CN->getValueType(0);
10529       EVT NSVT = N.getValueType().getScalarType();
10530       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10531       if (AllowTruncation || (CVT == NSVT))
10532         return CN;
10533     }
10534   }
10535 
10536   return nullptr;
10537 }
10538 
10539 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10540                                           bool AllowUndefs,
10541                                           bool AllowTruncation) {
10542   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10543     return CN;
10544 
10545   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10546     BitVector UndefElements;
10547     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10548 
10549     // BuildVectors can truncate their operands. Ignore that case here unless
10550     // AllowTruncation is set.
10551     if (CN && (UndefElements.none() || AllowUndefs)) {
10552       EVT CVT = CN->getValueType(0);
10553       EVT NSVT = N.getValueType().getScalarType();
10554       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10555       if (AllowTruncation || (CVT == NSVT))
10556         return CN;
10557     }
10558   }
10559 
10560   return nullptr;
10561 }
10562 
10563 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10564   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10565     return CN;
10566 
10567   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10568     BitVector UndefElements;
10569     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10570     if (CN && (UndefElements.none() || AllowUndefs))
10571       return CN;
10572   }
10573 
10574   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10575     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10576       return CN;
10577 
10578   return nullptr;
10579 }
10580 
10581 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10582                                               const APInt &DemandedElts,
10583                                               bool AllowUndefs) {
10584   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10585     return CN;
10586 
10587   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10588     BitVector UndefElements;
10589     ConstantFPSDNode *CN =
10590         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10591     if (CN && (UndefElements.none() || AllowUndefs))
10592       return CN;
10593   }
10594 
10595   return nullptr;
10596 }
10597 
10598 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10599   // TODO: may want to use peekThroughBitcast() here.
10600   ConstantSDNode *C =
10601       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10602   return C && C->isZero();
10603 }
10604 
10605 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10606   // TODO: may want to use peekThroughBitcast() here.
10607   unsigned BitWidth = N.getScalarValueSizeInBits();
10608   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10609   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10610 }
10611 
10612 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10613   N = peekThroughBitcasts(N);
10614   unsigned BitWidth = N.getScalarValueSizeInBits();
10615   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10616   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10617 }
10618 
10619 HandleSDNode::~HandleSDNode() {
10620   DropOperands();
10621 }
10622 
10623 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10624                                          const DebugLoc &DL,
10625                                          const GlobalValue *GA, EVT VT,
10626                                          int64_t o, unsigned TF)
10627     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10628   TheGlobal = GA;
10629 }
10630 
10631 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10632                                          EVT VT, unsigned SrcAS,
10633                                          unsigned DestAS)
10634     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10635       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10636 
10637 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10638                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10639     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10640   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10641   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10642   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10643   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10644 
10645   // We check here that the size of the memory operand fits within the size of
10646   // the MMO. This is because the MMO might indicate only a possible address
10647   // range instead of specifying the affected memory addresses precisely.
10648   // TODO: Make MachineMemOperands aware of scalable vectors.
10649   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10650          "Size mismatch!");
10651 }
10652 
10653 /// Profile - Gather unique data for the node.
10654 ///
10655 void SDNode::Profile(FoldingSetNodeID &ID) const {
10656   AddNodeIDNode(ID, this);
10657 }
10658 
10659 namespace {
10660 
10661   struct EVTArray {
10662     std::vector<EVT> VTs;
10663 
10664     EVTArray() {
10665       VTs.reserve(MVT::VALUETYPE_SIZE);
10666       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10667         VTs.push_back(MVT((MVT::SimpleValueType)i));
10668     }
10669   };
10670 
10671 } // end anonymous namespace
10672 
10673 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10674 static ManagedStatic<EVTArray> SimpleVTArray;
10675 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10676 
10677 /// getValueTypeList - Return a pointer to the specified value type.
10678 ///
10679 const EVT *SDNode::getValueTypeList(EVT VT) {
10680   if (VT.isExtended()) {
10681     sys::SmartScopedLock<true> Lock(*VTMutex);
10682     return &(*EVTs->insert(VT).first);
10683   }
10684   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10685   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10686 }
10687 
10688 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10689 /// indicated value.  This method ignores uses of other values defined by this
10690 /// operation.
10691 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10692   assert(Value < getNumValues() && "Bad value!");
10693 
10694   // TODO: Only iterate over uses of a given value of the node
10695   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10696     if (UI.getUse().getResNo() == Value) {
10697       if (NUses == 0)
10698         return false;
10699       --NUses;
10700     }
10701   }
10702 
10703   // Found exactly the right number of uses?
10704   return NUses == 0;
10705 }
10706 
10707 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10708 /// value. This method ignores uses of other values defined by this operation.
10709 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10710   assert(Value < getNumValues() && "Bad value!");
10711 
10712   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10713     if (UI.getUse().getResNo() == Value)
10714       return true;
10715 
10716   return false;
10717 }
10718 
10719 /// isOnlyUserOf - Return true if this node is the only use of N.
10720 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10721   bool Seen = false;
10722   for (const SDNode *User : N->uses()) {
10723     if (User == this)
10724       Seen = true;
10725     else
10726       return false;
10727   }
10728 
10729   return Seen;
10730 }
10731 
10732 /// Return true if the only users of N are contained in Nodes.
10733 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10734   bool Seen = false;
10735   for (const SDNode *User : N->uses()) {
10736     if (llvm::is_contained(Nodes, User))
10737       Seen = true;
10738     else
10739       return false;
10740   }
10741 
10742   return Seen;
10743 }
10744 
10745 /// isOperand - Return true if this node is an operand of N.
10746 bool SDValue::isOperandOf(const SDNode *N) const {
10747   return is_contained(N->op_values(), *this);
10748 }
10749 
10750 bool SDNode::isOperandOf(const SDNode *N) const {
10751   return any_of(N->op_values(),
10752                 [this](SDValue Op) { return this == Op.getNode(); });
10753 }
10754 
10755 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10756 /// be a chain) reaches the specified operand without crossing any
10757 /// side-effecting instructions on any chain path.  In practice, this looks
10758 /// through token factors and non-volatile loads.  In order to remain efficient,
10759 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10760 ///
10761 /// Note that we only need to examine chains when we're searching for
10762 /// side-effects; SelectionDAG requires that all side-effects are represented
10763 /// by chains, even if another operand would force a specific ordering. This
10764 /// constraint is necessary to allow transformations like splitting loads.
10765 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10766                                              unsigned Depth) const {
10767   if (*this == Dest) return true;
10768 
10769   // Don't search too deeply, we just want to be able to see through
10770   // TokenFactor's etc.
10771   if (Depth == 0) return false;
10772 
10773   // If this is a token factor, all inputs to the TF happen in parallel.
10774   if (getOpcode() == ISD::TokenFactor) {
10775     // First, try a shallow search.
10776     if (is_contained((*this)->ops(), Dest)) {
10777       // We found the chain we want as an operand of this TokenFactor.
10778       // Essentially, we reach the chain without side-effects if we could
10779       // serialize the TokenFactor into a simple chain of operations with
10780       // Dest as the last operation. This is automatically true if the
10781       // chain has one use: there are no other ordering constraints.
10782       // If the chain has more than one use, we give up: some other
10783       // use of Dest might force a side-effect between Dest and the current
10784       // node.
10785       if (Dest.hasOneUse())
10786         return true;
10787     }
10788     // Next, try a deep search: check whether every operand of the TokenFactor
10789     // reaches Dest.
10790     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10791       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10792     });
10793   }
10794 
10795   // Loads don't have side effects, look through them.
10796   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10797     if (Ld->isUnordered())
10798       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10799   }
10800   return false;
10801 }
10802 
10803 bool SDNode::hasPredecessor(const SDNode *N) const {
10804   SmallPtrSet<const SDNode *, 32> Visited;
10805   SmallVector<const SDNode *, 16> Worklist;
10806   Worklist.push_back(this);
10807   return hasPredecessorHelper(N, Visited, Worklist);
10808 }
10809 
10810 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10811   this->Flags.intersectWith(Flags);
10812 }
10813 
10814 SDValue
10815 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10816                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10817                                   bool AllowPartials) {
10818   // The pattern must end in an extract from index 0.
10819   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10820       !isNullConstant(Extract->getOperand(1)))
10821     return SDValue();
10822 
10823   // Match against one of the candidate binary ops.
10824   SDValue Op = Extract->getOperand(0);
10825   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10826         return Op.getOpcode() == unsigned(BinOp);
10827       }))
10828     return SDValue();
10829 
10830   // Floating-point reductions may require relaxed constraints on the final step
10831   // of the reduction because they may reorder intermediate operations.
10832   unsigned CandidateBinOp = Op.getOpcode();
10833   if (Op.getValueType().isFloatingPoint()) {
10834     SDNodeFlags Flags = Op->getFlags();
10835     switch (CandidateBinOp) {
10836     case ISD::FADD:
10837       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10838         return SDValue();
10839       break;
10840     default:
10841       llvm_unreachable("Unhandled FP opcode for binop reduction");
10842     }
10843   }
10844 
10845   // Matching failed - attempt to see if we did enough stages that a partial
10846   // reduction from a subvector is possible.
10847   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10848     if (!AllowPartials || !Op)
10849       return SDValue();
10850     EVT OpVT = Op.getValueType();
10851     EVT OpSVT = OpVT.getScalarType();
10852     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10853     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10854       return SDValue();
10855     BinOp = (ISD::NodeType)CandidateBinOp;
10856     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10857                    getVectorIdxConstant(0, SDLoc(Op)));
10858   };
10859 
10860   // At each stage, we're looking for something that looks like:
10861   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10862   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10863   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10864   // %a = binop <8 x i32> %op, %s
10865   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10866   // we expect something like:
10867   // <4,5,6,7,u,u,u,u>
10868   // <2,3,u,u,u,u,u,u>
10869   // <1,u,u,u,u,u,u,u>
10870   // While a partial reduction match would be:
10871   // <2,3,u,u,u,u,u,u>
10872   // <1,u,u,u,u,u,u,u>
10873   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10874   SDValue PrevOp;
10875   for (unsigned i = 0; i < Stages; ++i) {
10876     unsigned MaskEnd = (1 << i);
10877 
10878     if (Op.getOpcode() != CandidateBinOp)
10879       return PartialReduction(PrevOp, MaskEnd);
10880 
10881     SDValue Op0 = Op.getOperand(0);
10882     SDValue Op1 = Op.getOperand(1);
10883 
10884     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10885     if (Shuffle) {
10886       Op = Op1;
10887     } else {
10888       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10889       Op = Op0;
10890     }
10891 
10892     // The first operand of the shuffle should be the same as the other operand
10893     // of the binop.
10894     if (!Shuffle || Shuffle->getOperand(0) != Op)
10895       return PartialReduction(PrevOp, MaskEnd);
10896 
10897     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10898     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10899       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10900         return PartialReduction(PrevOp, MaskEnd);
10901 
10902     PrevOp = Op;
10903   }
10904 
10905   // Handle subvector reductions, which tend to appear after the shuffle
10906   // reduction stages.
10907   while (Op.getOpcode() == CandidateBinOp) {
10908     unsigned NumElts = Op.getValueType().getVectorNumElements();
10909     SDValue Op0 = Op.getOperand(0);
10910     SDValue Op1 = Op.getOperand(1);
10911     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10912         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10913         Op0.getOperand(0) != Op1.getOperand(0))
10914       break;
10915     SDValue Src = Op0.getOperand(0);
10916     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10917     if (NumSrcElts != (2 * NumElts))
10918       break;
10919     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10920           Op1.getConstantOperandAPInt(1) == NumElts) &&
10921         !(Op1.getConstantOperandAPInt(1) == 0 &&
10922           Op0.getConstantOperandAPInt(1) == NumElts))
10923       break;
10924     Op = Src;
10925   }
10926 
10927   BinOp = (ISD::NodeType)CandidateBinOp;
10928   return Op;
10929 }
10930 
10931 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10932   assert(N->getNumValues() == 1 &&
10933          "Can't unroll a vector with multiple results!");
10934 
10935   EVT VT = N->getValueType(0);
10936   unsigned NE = VT.getVectorNumElements();
10937   EVT EltVT = VT.getVectorElementType();
10938   SDLoc dl(N);
10939 
10940   SmallVector<SDValue, 8> Scalars;
10941   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10942 
10943   // If ResNE is 0, fully unroll the vector op.
10944   if (ResNE == 0)
10945     ResNE = NE;
10946   else if (NE > ResNE)
10947     NE = ResNE;
10948 
10949   unsigned i;
10950   for (i= 0; i != NE; ++i) {
10951     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10952       SDValue Operand = N->getOperand(j);
10953       EVT OperandVT = Operand.getValueType();
10954       if (OperandVT.isVector()) {
10955         // A vector operand; extract a single element.
10956         EVT OperandEltVT = OperandVT.getVectorElementType();
10957         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10958                               Operand, getVectorIdxConstant(i, dl));
10959       } else {
10960         // A scalar operand; just use it as is.
10961         Operands[j] = Operand;
10962       }
10963     }
10964 
10965     switch (N->getOpcode()) {
10966     default: {
10967       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10968                                 N->getFlags()));
10969       break;
10970     }
10971     case ISD::VSELECT:
10972       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10973       break;
10974     case ISD::SHL:
10975     case ISD::SRA:
10976     case ISD::SRL:
10977     case ISD::ROTL:
10978     case ISD::ROTR:
10979       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10980                                getShiftAmountOperand(Operands[0].getValueType(),
10981                                                      Operands[1])));
10982       break;
10983     case ISD::SIGN_EXTEND_INREG: {
10984       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10985       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10986                                 Operands[0],
10987                                 getValueType(ExtVT)));
10988     }
10989     }
10990   }
10991 
10992   for (; i < ResNE; ++i)
10993     Scalars.push_back(getUNDEF(EltVT));
10994 
10995   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10996   return getBuildVector(VecVT, dl, Scalars);
10997 }
10998 
10999 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11000     SDNode *N, unsigned ResNE) {
11001   unsigned Opcode = N->getOpcode();
11002   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11003           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11004           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11005          "Expected an overflow opcode");
11006 
11007   EVT ResVT = N->getValueType(0);
11008   EVT OvVT = N->getValueType(1);
11009   EVT ResEltVT = ResVT.getVectorElementType();
11010   EVT OvEltVT = OvVT.getVectorElementType();
11011   SDLoc dl(N);
11012 
11013   // If ResNE is 0, fully unroll the vector op.
11014   unsigned NE = ResVT.getVectorNumElements();
11015   if (ResNE == 0)
11016     ResNE = NE;
11017   else if (NE > ResNE)
11018     NE = ResNE;
11019 
11020   SmallVector<SDValue, 8> LHSScalars;
11021   SmallVector<SDValue, 8> RHSScalars;
11022   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11023   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11024 
11025   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11026   SDVTList VTs = getVTList(ResEltVT, SVT);
11027   SmallVector<SDValue, 8> ResScalars;
11028   SmallVector<SDValue, 8> OvScalars;
11029   for (unsigned i = 0; i < NE; ++i) {
11030     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11031     SDValue Ov =
11032         getSelect(dl, OvEltVT, Res.getValue(1),
11033                   getBoolConstant(true, dl, OvEltVT, ResVT),
11034                   getConstant(0, dl, OvEltVT));
11035 
11036     ResScalars.push_back(Res);
11037     OvScalars.push_back(Ov);
11038   }
11039 
11040   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11041   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11042 
11043   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11044   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11045   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11046                         getBuildVector(NewOvVT, dl, OvScalars));
11047 }
11048 
11049 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11050                                                   LoadSDNode *Base,
11051                                                   unsigned Bytes,
11052                                                   int Dist) const {
11053   if (LD->isVolatile() || Base->isVolatile())
11054     return false;
11055   // TODO: probably too restrictive for atomics, revisit
11056   if (!LD->isSimple())
11057     return false;
11058   if (LD->isIndexed() || Base->isIndexed())
11059     return false;
11060   if (LD->getChain() != Base->getChain())
11061     return false;
11062   EVT VT = LD->getValueType(0);
11063   if (VT.getSizeInBits() / 8 != Bytes)
11064     return false;
11065 
11066   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11067   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11068 
11069   int64_t Offset = 0;
11070   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11071     return (Dist * Bytes == Offset);
11072   return false;
11073 }
11074 
11075 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11076 /// if it cannot be inferred.
11077 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11078   // If this is a GlobalAddress + cst, return the alignment.
11079   const GlobalValue *GV = nullptr;
11080   int64_t GVOffset = 0;
11081   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11082     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11083     KnownBits Known(PtrWidth);
11084     llvm::computeKnownBits(GV, Known, getDataLayout());
11085     unsigned AlignBits = Known.countMinTrailingZeros();
11086     if (AlignBits)
11087       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11088   }
11089 
11090   // If this is a direct reference to a stack slot, use information about the
11091   // stack slot's alignment.
11092   int FrameIdx = INT_MIN;
11093   int64_t FrameOffset = 0;
11094   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11095     FrameIdx = FI->getIndex();
11096   } else if (isBaseWithConstantOffset(Ptr) &&
11097              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11098     // Handle FI+Cst
11099     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11100     FrameOffset = Ptr.getConstantOperandVal(1);
11101   }
11102 
11103   if (FrameIdx != INT_MIN) {
11104     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11105     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11106   }
11107 
11108   return None;
11109 }
11110 
11111 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11112 /// which is split (or expanded) into two not necessarily identical pieces.
11113 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11114   // Currently all types are split in half.
11115   EVT LoVT, HiVT;
11116   if (!VT.isVector())
11117     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11118   else
11119     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11120 
11121   return std::make_pair(LoVT, HiVT);
11122 }
11123 
11124 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11125 /// type, dependent on an enveloping VT that has been split into two identical
11126 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11127 std::pair<EVT, EVT>
11128 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11129                                        bool *HiIsEmpty) const {
11130   EVT EltTp = VT.getVectorElementType();
11131   // Examples:
11132   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11133   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11134   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11135   //   etc.
11136   ElementCount VTNumElts = VT.getVectorElementCount();
11137   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11138   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11139          "Mixing fixed width and scalable vectors when enveloping a type");
11140   EVT LoVT, HiVT;
11141   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11142     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11143     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11144     *HiIsEmpty = false;
11145   } else {
11146     // Flag that hi type has zero storage size, but return split envelop type
11147     // (this would be easier if vector types with zero elements were allowed).
11148     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11149     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11150     *HiIsEmpty = true;
11151   }
11152   return std::make_pair(LoVT, HiVT);
11153 }
11154 
11155 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11156 /// low/high part.
11157 std::pair<SDValue, SDValue>
11158 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11159                           const EVT &HiVT) {
11160   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11161          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11162          "Splitting vector with an invalid mixture of fixed and scalable "
11163          "vector types");
11164   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11165              N.getValueType().getVectorMinNumElements() &&
11166          "More vector elements requested than available!");
11167   SDValue Lo, Hi;
11168   Lo =
11169       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11170   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11171   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11172   // IDX with the runtime scaling factor of the result vector type. For
11173   // fixed-width result vectors, that runtime scaling factor is 1.
11174   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11175                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11176   return std::make_pair(Lo, Hi);
11177 }
11178 
11179 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11180                                                    const SDLoc &DL) {
11181   // Split the vector length parameter.
11182   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11183   EVT VT = N.getValueType();
11184   assert(VecVT.getVectorElementCount().isKnownEven() &&
11185          "Expecting the mask to be an evenly-sized vector");
11186   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11187   SDValue HalfNumElts =
11188       VecVT.isFixedLengthVector()
11189           ? getConstant(HalfMinNumElts, DL, VT)
11190           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11191   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11192   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11193   return std::make_pair(Lo, Hi);
11194 }
11195 
11196 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11197 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11198   EVT VT = N.getValueType();
11199   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11200                                 NextPowerOf2(VT.getVectorNumElements()));
11201   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11202                  getVectorIdxConstant(0, DL));
11203 }
11204 
11205 void SelectionDAG::ExtractVectorElements(SDValue Op,
11206                                          SmallVectorImpl<SDValue> &Args,
11207                                          unsigned Start, unsigned Count,
11208                                          EVT EltVT) {
11209   EVT VT = Op.getValueType();
11210   if (Count == 0)
11211     Count = VT.getVectorNumElements();
11212   if (EltVT == EVT())
11213     EltVT = VT.getVectorElementType();
11214   SDLoc SL(Op);
11215   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11216     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11217                            getVectorIdxConstant(i, SL)));
11218   }
11219 }
11220 
11221 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11222 unsigned GlobalAddressSDNode::getAddressSpace() const {
11223   return getGlobal()->getType()->getAddressSpace();
11224 }
11225 
11226 Type *ConstantPoolSDNode::getType() const {
11227   if (isMachineConstantPoolEntry())
11228     return Val.MachineCPVal->getType();
11229   return Val.ConstVal->getType();
11230 }
11231 
11232 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11233                                         unsigned &SplatBitSize,
11234                                         bool &HasAnyUndefs,
11235                                         unsigned MinSplatBits,
11236                                         bool IsBigEndian) const {
11237   EVT VT = getValueType(0);
11238   assert(VT.isVector() && "Expected a vector type");
11239   unsigned VecWidth = VT.getSizeInBits();
11240   if (MinSplatBits > VecWidth)
11241     return false;
11242 
11243   // FIXME: The widths are based on this node's type, but build vectors can
11244   // truncate their operands.
11245   SplatValue = APInt(VecWidth, 0);
11246   SplatUndef = APInt(VecWidth, 0);
11247 
11248   // Get the bits. Bits with undefined values (when the corresponding element
11249   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11250   // in SplatValue. If any of the values are not constant, give up and return
11251   // false.
11252   unsigned int NumOps = getNumOperands();
11253   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11254   unsigned EltWidth = VT.getScalarSizeInBits();
11255 
11256   for (unsigned j = 0; j < NumOps; ++j) {
11257     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11258     SDValue OpVal = getOperand(i);
11259     unsigned BitPos = j * EltWidth;
11260 
11261     if (OpVal.isUndef())
11262       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11263     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11264       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11265     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11266       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11267     else
11268       return false;
11269   }
11270 
11271   // The build_vector is all constants or undefs. Find the smallest element
11272   // size that splats the vector.
11273   HasAnyUndefs = (SplatUndef != 0);
11274 
11275   // FIXME: This does not work for vectors with elements less than 8 bits.
11276   while (VecWidth > 8) {
11277     unsigned HalfSize = VecWidth / 2;
11278     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11279     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11280     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11281     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11282 
11283     // If the two halves do not match (ignoring undef bits), stop here.
11284     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11285         MinSplatBits > HalfSize)
11286       break;
11287 
11288     SplatValue = HighValue | LowValue;
11289     SplatUndef = HighUndef & LowUndef;
11290 
11291     VecWidth = HalfSize;
11292   }
11293 
11294   SplatBitSize = VecWidth;
11295   return true;
11296 }
11297 
11298 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11299                                          BitVector *UndefElements) const {
11300   unsigned NumOps = getNumOperands();
11301   if (UndefElements) {
11302     UndefElements->clear();
11303     UndefElements->resize(NumOps);
11304   }
11305   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11306   if (!DemandedElts)
11307     return SDValue();
11308   SDValue Splatted;
11309   for (unsigned i = 0; i != NumOps; ++i) {
11310     if (!DemandedElts[i])
11311       continue;
11312     SDValue Op = getOperand(i);
11313     if (Op.isUndef()) {
11314       if (UndefElements)
11315         (*UndefElements)[i] = true;
11316     } else if (!Splatted) {
11317       Splatted = Op;
11318     } else if (Splatted != Op) {
11319       return SDValue();
11320     }
11321   }
11322 
11323   if (!Splatted) {
11324     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11325     assert(getOperand(FirstDemandedIdx).isUndef() &&
11326            "Can only have a splat without a constant for all undefs.");
11327     return getOperand(FirstDemandedIdx);
11328   }
11329 
11330   return Splatted;
11331 }
11332 
11333 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11334   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11335   return getSplatValue(DemandedElts, UndefElements);
11336 }
11337 
11338 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11339                                             SmallVectorImpl<SDValue> &Sequence,
11340                                             BitVector *UndefElements) const {
11341   unsigned NumOps = getNumOperands();
11342   Sequence.clear();
11343   if (UndefElements) {
11344     UndefElements->clear();
11345     UndefElements->resize(NumOps);
11346   }
11347   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11348   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11349     return false;
11350 
11351   // Set the undefs even if we don't find a sequence (like getSplatValue).
11352   if (UndefElements)
11353     for (unsigned I = 0; I != NumOps; ++I)
11354       if (DemandedElts[I] && getOperand(I).isUndef())
11355         (*UndefElements)[I] = true;
11356 
11357   // Iteratively widen the sequence length looking for repetitions.
11358   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11359     Sequence.append(SeqLen, SDValue());
11360     for (unsigned I = 0; I != NumOps; ++I) {
11361       if (!DemandedElts[I])
11362         continue;
11363       SDValue &SeqOp = Sequence[I % SeqLen];
11364       SDValue Op = getOperand(I);
11365       if (Op.isUndef()) {
11366         if (!SeqOp)
11367           SeqOp = Op;
11368         continue;
11369       }
11370       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11371         Sequence.clear();
11372         break;
11373       }
11374       SeqOp = Op;
11375     }
11376     if (!Sequence.empty())
11377       return true;
11378   }
11379 
11380   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11381   return false;
11382 }
11383 
11384 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11385                                             BitVector *UndefElements) const {
11386   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11387   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11388 }
11389 
11390 ConstantSDNode *
11391 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11392                                         BitVector *UndefElements) const {
11393   return dyn_cast_or_null<ConstantSDNode>(
11394       getSplatValue(DemandedElts, UndefElements));
11395 }
11396 
11397 ConstantSDNode *
11398 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11399   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11400 }
11401 
11402 ConstantFPSDNode *
11403 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11404                                           BitVector *UndefElements) const {
11405   return dyn_cast_or_null<ConstantFPSDNode>(
11406       getSplatValue(DemandedElts, UndefElements));
11407 }
11408 
11409 ConstantFPSDNode *
11410 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11411   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11412 }
11413 
11414 int32_t
11415 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11416                                                    uint32_t BitWidth) const {
11417   if (ConstantFPSDNode *CN =
11418           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11419     bool IsExact;
11420     APSInt IntVal(BitWidth);
11421     const APFloat &APF = CN->getValueAPF();
11422     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11423             APFloat::opOK ||
11424         !IsExact)
11425       return -1;
11426 
11427     return IntVal.exactLogBase2();
11428   }
11429   return -1;
11430 }
11431 
11432 bool BuildVectorSDNode::getConstantRawBits(
11433     bool IsLittleEndian, unsigned DstEltSizeInBits,
11434     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11435   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11436   if (!isConstant())
11437     return false;
11438 
11439   unsigned NumSrcOps = getNumOperands();
11440   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11441   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11442          "Invalid bitcast scale");
11443 
11444   // Extract raw src bits.
11445   SmallVector<APInt> SrcBitElements(NumSrcOps,
11446                                     APInt::getNullValue(SrcEltSizeInBits));
11447   BitVector SrcUndeElements(NumSrcOps, false);
11448 
11449   for (unsigned I = 0; I != NumSrcOps; ++I) {
11450     SDValue Op = getOperand(I);
11451     if (Op.isUndef()) {
11452       SrcUndeElements.set(I);
11453       continue;
11454     }
11455     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11456     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11457     assert((CInt || CFP) && "Unknown constant");
11458     SrcBitElements[I] =
11459         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
11460              : CFP->getValueAPF().bitcastToAPInt();
11461   }
11462 
11463   // Recast to dst width.
11464   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11465                 SrcBitElements, UndefElements, SrcUndeElements);
11466   return true;
11467 }
11468 
11469 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11470                                       unsigned DstEltSizeInBits,
11471                                       SmallVectorImpl<APInt> &DstBitElements,
11472                                       ArrayRef<APInt> SrcBitElements,
11473                                       BitVector &DstUndefElements,
11474                                       const BitVector &SrcUndefElements) {
11475   unsigned NumSrcOps = SrcBitElements.size();
11476   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11477   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11478          "Invalid bitcast scale");
11479   assert(NumSrcOps == SrcUndefElements.size() &&
11480          "Vector size mismatch");
11481 
11482   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11483   DstUndefElements.clear();
11484   DstUndefElements.resize(NumDstOps, false);
11485   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11486 
11487   // Concatenate src elements constant bits together into dst element.
11488   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11489     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11490     for (unsigned I = 0; I != NumDstOps; ++I) {
11491       DstUndefElements.set(I);
11492       APInt &DstBits = DstBitElements[I];
11493       for (unsigned J = 0; J != Scale; ++J) {
11494         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11495         if (SrcUndefElements[Idx])
11496           continue;
11497         DstUndefElements.reset(I);
11498         const APInt &SrcBits = SrcBitElements[Idx];
11499         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11500                "Illegal constant bitwidths");
11501         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11502       }
11503     }
11504     return;
11505   }
11506 
11507   // Split src element constant bits into dst elements.
11508   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11509   for (unsigned I = 0; I != NumSrcOps; ++I) {
11510     if (SrcUndefElements[I]) {
11511       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11512       continue;
11513     }
11514     const APInt &SrcBits = SrcBitElements[I];
11515     for (unsigned J = 0; J != Scale; ++J) {
11516       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11517       APInt &DstBits = DstBitElements[Idx];
11518       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11519     }
11520   }
11521 }
11522 
11523 bool BuildVectorSDNode::isConstant() const {
11524   for (const SDValue &Op : op_values()) {
11525     unsigned Opc = Op.getOpcode();
11526     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11527       return false;
11528   }
11529   return true;
11530 }
11531 
11532 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11533   // Find the first non-undef value in the shuffle mask.
11534   unsigned i, e;
11535   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11536     /* search */;
11537 
11538   // If all elements are undefined, this shuffle can be considered a splat
11539   // (although it should eventually get simplified away completely).
11540   if (i == e)
11541     return true;
11542 
11543   // Make sure all remaining elements are either undef or the same as the first
11544   // non-undef value.
11545   for (int Idx = Mask[i]; i != e; ++i)
11546     if (Mask[i] >= 0 && Mask[i] != Idx)
11547       return false;
11548   return true;
11549 }
11550 
11551 // Returns the SDNode if it is a constant integer BuildVector
11552 // or constant integer.
11553 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11554   if (isa<ConstantSDNode>(N))
11555     return N.getNode();
11556   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11557     return N.getNode();
11558   // Treat a GlobalAddress supporting constant offset folding as a
11559   // constant integer.
11560   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11561     if (GA->getOpcode() == ISD::GlobalAddress &&
11562         TLI->isOffsetFoldingLegal(GA))
11563       return GA;
11564   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11565       isa<ConstantSDNode>(N.getOperand(0)))
11566     return N.getNode();
11567   return nullptr;
11568 }
11569 
11570 // Returns the SDNode if it is a constant float BuildVector
11571 // or constant float.
11572 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11573   if (isa<ConstantFPSDNode>(N))
11574     return N.getNode();
11575 
11576   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11577     return N.getNode();
11578 
11579   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11580       isa<ConstantFPSDNode>(N.getOperand(0)))
11581     return N.getNode();
11582 
11583   return nullptr;
11584 }
11585 
11586 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11587   assert(!Node->OperandList && "Node already has operands");
11588   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11589          "too many operands to fit into SDNode");
11590   SDUse *Ops = OperandRecycler.allocate(
11591       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11592 
11593   bool IsDivergent = false;
11594   for (unsigned I = 0; I != Vals.size(); ++I) {
11595     Ops[I].setUser(Node);
11596     Ops[I].setInitial(Vals[I]);
11597     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11598       IsDivergent |= Ops[I].getNode()->isDivergent();
11599   }
11600   Node->NumOperands = Vals.size();
11601   Node->OperandList = Ops;
11602   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11603     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11604     Node->SDNodeBits.IsDivergent = IsDivergent;
11605   }
11606   checkForCycles(Node);
11607 }
11608 
11609 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11610                                      SmallVectorImpl<SDValue> &Vals) {
11611   size_t Limit = SDNode::getMaxNumOperands();
11612   while (Vals.size() > Limit) {
11613     unsigned SliceIdx = Vals.size() - Limit;
11614     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11615     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11616     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11617     Vals.emplace_back(NewTF);
11618   }
11619   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11620 }
11621 
11622 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11623                                         EVT VT, SDNodeFlags Flags) {
11624   switch (Opcode) {
11625   default:
11626     return SDValue();
11627   case ISD::ADD:
11628   case ISD::OR:
11629   case ISD::XOR:
11630   case ISD::UMAX:
11631     return getConstant(0, DL, VT);
11632   case ISD::MUL:
11633     return getConstant(1, DL, VT);
11634   case ISD::AND:
11635   case ISD::UMIN:
11636     return getAllOnesConstant(DL, VT);
11637   case ISD::SMAX:
11638     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11639   case ISD::SMIN:
11640     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11641   case ISD::FADD:
11642     return getConstantFP(-0.0, DL, VT);
11643   case ISD::FMUL:
11644     return getConstantFP(1.0, DL, VT);
11645   case ISD::FMINNUM:
11646   case ISD::FMAXNUM: {
11647     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11648     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11649     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11650                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11651                         APFloat::getLargest(Semantics);
11652     if (Opcode == ISD::FMAXNUM)
11653       NeutralAF.changeSign();
11654 
11655     return getConstantFP(NeutralAF, DL, VT);
11656   }
11657   }
11658 }
11659 
11660 #ifndef NDEBUG
11661 static void checkForCyclesHelper(const SDNode *N,
11662                                  SmallPtrSetImpl<const SDNode*> &Visited,
11663                                  SmallPtrSetImpl<const SDNode*> &Checked,
11664                                  const llvm::SelectionDAG *DAG) {
11665   // If this node has already been checked, don't check it again.
11666   if (Checked.count(N))
11667     return;
11668 
11669   // If a node has already been visited on this depth-first walk, reject it as
11670   // a cycle.
11671   if (!Visited.insert(N).second) {
11672     errs() << "Detected cycle in SelectionDAG\n";
11673     dbgs() << "Offending node:\n";
11674     N->dumprFull(DAG); dbgs() << "\n";
11675     abort();
11676   }
11677 
11678   for (const SDValue &Op : N->op_values())
11679     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11680 
11681   Checked.insert(N);
11682   Visited.erase(N);
11683 }
11684 #endif
11685 
11686 void llvm::checkForCycles(const llvm::SDNode *N,
11687                           const llvm::SelectionDAG *DAG,
11688                           bool force) {
11689 #ifndef NDEBUG
11690   bool check = force;
11691 #ifdef EXPENSIVE_CHECKS
11692   check = true;
11693 #endif  // EXPENSIVE_CHECKS
11694   if (check) {
11695     assert(N && "Checking nonexistent SDNode");
11696     SmallPtrSet<const SDNode*, 32> visited;
11697     SmallPtrSet<const SDNode*, 32> checked;
11698     checkForCyclesHelper(N, visited, checked, DAG);
11699   }
11700 #endif  // !NDEBUG
11701 }
11702 
11703 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11704   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11705 }
11706