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/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/CodeGen/FunctionLoweringInfo.h"
33 #include "llvm/CodeGen/ISDOpcodes.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineConstantPool.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/RuntimeLibcalls.h"
40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
41 #include "llvm/CodeGen/SelectionDAGNodes.h"
42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
43 #include "llvm/CodeGen/TargetFrameLowering.h"
44 #include "llvm/CodeGen/TargetLowering.h"
45 #include "llvm/CodeGen/TargetRegisterInfo.h"
46 #include "llvm/CodeGen/TargetSubtargetInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugInfoMetadata.h"
52 #include "llvm/IR/DebugLoc.h"
53 #include "llvm/IR/DerivedTypes.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CodeGen.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/KnownBits.h"
65 #include "llvm/Support/MachineValueType.h"
66 #include "llvm/Support/ManagedStatic.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Support/Mutex.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Target/TargetMachine.h"
71 #include "llvm/Target/TargetOptions.h"
72 #include "llvm/Transforms/Utils/SizeOpts.h"
73 #include <algorithm>
74 #include <cassert>
75 #include <cstdint>
76 #include <cstdlib>
77 #include <limits>
78 #include <set>
79 #include <string>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 /// makeVTList - Return an instance of the SDVTList struct initialized with the
86 /// specified members.
87 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
88   SDVTList Res = {VTs, NumVTs};
89   return Res;
90 }
91 
92 // Default null implementations of the callbacks.
93 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
94 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
95 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
96 
97 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
98 
99 #define DEBUG_TYPE "selectiondag"
100 
101 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
102        cl::Hidden, cl::init(true),
103        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
104 
105 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
106        cl::desc("Number limit for gluing ld/st of memcpy."),
107        cl::Hidden, cl::init(0));
108 
109 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
110   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
111 }
112 
113 //===----------------------------------------------------------------------===//
114 //                              ConstantFPSDNode Class
115 //===----------------------------------------------------------------------===//
116 
117 /// isExactlyValue - We don't rely on operator== working on double values, as
118 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
119 /// As such, this method can be used to do an exact bit-for-bit comparison of
120 /// two floating point values.
121 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
122   return getValueAPF().bitwiseIsEqual(V);
123 }
124 
125 bool ConstantFPSDNode::isValueValidForType(EVT VT,
126                                            const APFloat& Val) {
127   assert(VT.isFloatingPoint() && "Can only convert between FP types");
128 
129   // convert modifies in place, so make a copy.
130   APFloat Val2 = APFloat(Val);
131   bool losesInfo;
132   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
133                       APFloat::rmNearestTiesToEven,
134                       &losesInfo);
135   return !losesInfo;
136 }
137 
138 //===----------------------------------------------------------------------===//
139 //                              ISD Namespace
140 //===----------------------------------------------------------------------===//
141 
142 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
143   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
144     unsigned EltSize =
145         N->getValueType(0).getVectorElementType().getSizeInBits();
146     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
147       SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
148       return true;
149     }
150     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
151       SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
152       return true;
153     }
154   }
155 
156   auto *BV = dyn_cast<BuildVectorSDNode>(N);
157   if (!BV)
158     return false;
159 
160   APInt SplatUndef;
161   unsigned SplatBitSize;
162   bool HasUndefs;
163   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
164   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
165                              EltSize) &&
166          EltSize == SplatBitSize;
167 }
168 
169 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
170 // specializations of the more general isConstantSplatVector()?
171 
172 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
173   // Look through a bit convert.
174   while (N->getOpcode() == ISD::BITCAST)
175     N = N->getOperand(0).getNode();
176 
177   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
178     APInt SplatVal;
179     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
180   }
181 
182   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
183 
184   unsigned i = 0, e = N->getNumOperands();
185 
186   // Skip over all of the undef values.
187   while (i != e && N->getOperand(i).isUndef())
188     ++i;
189 
190   // Do not accept an all-undef vector.
191   if (i == e) return false;
192 
193   // Do not accept build_vectors that aren't all constants or which have non-~0
194   // elements. We have to be a bit careful here, as the type of the constant
195   // may not be the same as the type of the vector elements due to type
196   // legalization (the elements are promoted to a legal type for the target and
197   // a vector of a type may be legal when the base element type is not).
198   // We only want to check enough bits to cover the vector elements, because
199   // we care if the resultant vector is all ones, not whether the individual
200   // constants are.
201   SDValue NotZero = N->getOperand(i);
202   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
203   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
204     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
205       return false;
206   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
207     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
208       return false;
209   } else
210     return false;
211 
212   // Okay, we have at least one ~0 value, check to see if the rest match or are
213   // undefs. Even with the above element type twiddling, this should be OK, as
214   // the same type legalization should have applied to all the elements.
215   for (++i; i != e; ++i)
216     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
217       return false;
218   return true;
219 }
220 
221 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
222   // Look through a bit convert.
223   while (N->getOpcode() == ISD::BITCAST)
224     N = N->getOperand(0).getNode();
225 
226   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
227     APInt SplatVal;
228     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
229   }
230 
231   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
232 
233   bool IsAllUndef = true;
234   for (const SDValue &Op : N->op_values()) {
235     if (Op.isUndef())
236       continue;
237     IsAllUndef = false;
238     // Do not accept build_vectors that aren't all constants or which have non-0
239     // elements. We have to be a bit careful here, as the type of the constant
240     // may not be the same as the type of the vector elements due to type
241     // legalization (the elements are promoted to a legal type for the target
242     // and a vector of a type may be legal when the base element type is not).
243     // We only want to check enough bits to cover the vector elements, because
244     // we care if the resultant vector is all zeros, not whether the individual
245     // constants are.
246     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
247     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
248       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
249         return false;
250     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
251       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
252         return false;
253     } else
254       return false;
255   }
256 
257   // Do not accept an all-undef vector.
258   if (IsAllUndef)
259     return false;
260   return true;
261 }
262 
263 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
264   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
265 }
266 
267 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
268   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
269 }
270 
271 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
272   if (N->getOpcode() != ISD::BUILD_VECTOR)
273     return false;
274 
275   for (const SDValue &Op : N->op_values()) {
276     if (Op.isUndef())
277       continue;
278     if (!isa<ConstantSDNode>(Op))
279       return false;
280   }
281   return true;
282 }
283 
284 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
285   if (N->getOpcode() != ISD::BUILD_VECTOR)
286     return false;
287 
288   for (const SDValue &Op : N->op_values()) {
289     if (Op.isUndef())
290       continue;
291     if (!isa<ConstantFPSDNode>(Op))
292       return false;
293   }
294   return true;
295 }
296 
297 bool ISD::allOperandsUndef(const SDNode *N) {
298   // Return false if the node has no operands.
299   // This is "logically inconsistent" with the definition of "all" but
300   // is probably the desired behavior.
301   if (N->getNumOperands() == 0)
302     return false;
303   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
304 }
305 
306 bool ISD::matchUnaryPredicate(SDValue Op,
307                               std::function<bool(ConstantSDNode *)> Match,
308                               bool AllowUndefs) {
309   // FIXME: Add support for scalar UNDEF cases?
310   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
311     return Match(Cst);
312 
313   // FIXME: Add support for vector UNDEF cases?
314   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
315       ISD::SPLAT_VECTOR != Op.getOpcode())
316     return false;
317 
318   EVT SVT = Op.getValueType().getScalarType();
319   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
320     if (AllowUndefs && Op.getOperand(i).isUndef()) {
321       if (!Match(nullptr))
322         return false;
323       continue;
324     }
325 
326     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
327     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
328       return false;
329   }
330   return true;
331 }
332 
333 bool ISD::matchBinaryPredicate(
334     SDValue LHS, SDValue RHS,
335     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
336     bool AllowUndefs, bool AllowTypeMismatch) {
337   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
338     return false;
339 
340   // TODO: Add support for scalar UNDEF cases?
341   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
342     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
343       return Match(LHSCst, RHSCst);
344 
345   // TODO: Add support for vector UNDEF cases?
346   if (LHS.getOpcode() != RHS.getOpcode() ||
347       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
348        LHS.getOpcode() != ISD::SPLAT_VECTOR))
349     return false;
350 
351   EVT SVT = LHS.getValueType().getScalarType();
352   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
353     SDValue LHSOp = LHS.getOperand(i);
354     SDValue RHSOp = RHS.getOperand(i);
355     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
356     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
357     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
358     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
359     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
360       return false;
361     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
362                                LHSOp.getValueType() != RHSOp.getValueType()))
363       return false;
364     if (!Match(LHSCst, RHSCst))
365       return false;
366   }
367   return true;
368 }
369 
370 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
371   switch (VecReduceOpcode) {
372   default:
373     llvm_unreachable("Expected VECREDUCE opcode");
374   case ISD::VECREDUCE_FADD:
375   case ISD::VECREDUCE_SEQ_FADD:
376     return ISD::FADD;
377   case ISD::VECREDUCE_FMUL:
378   case ISD::VECREDUCE_SEQ_FMUL:
379     return ISD::FMUL;
380   case ISD::VECREDUCE_ADD:
381     return ISD::ADD;
382   case ISD::VECREDUCE_MUL:
383     return ISD::MUL;
384   case ISD::VECREDUCE_AND:
385     return ISD::AND;
386   case ISD::VECREDUCE_OR:
387     return ISD::OR;
388   case ISD::VECREDUCE_XOR:
389     return ISD::XOR;
390   case ISD::VECREDUCE_SMAX:
391     return ISD::SMAX;
392   case ISD::VECREDUCE_SMIN:
393     return ISD::SMIN;
394   case ISD::VECREDUCE_UMAX:
395     return ISD::UMAX;
396   case ISD::VECREDUCE_UMIN:
397     return ISD::UMIN;
398   case ISD::VECREDUCE_FMAX:
399     return ISD::FMAXNUM;
400   case ISD::VECREDUCE_FMIN:
401     return ISD::FMINNUM;
402   }
403 }
404 
405 bool ISD::isVPOpcode(unsigned Opcode) {
406   switch (Opcode) {
407   default:
408     return false;
409 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
410   case ISD::SDOPC:                                                             \
411     return true;
412 #include "llvm/IR/VPIntrinsics.def"
413   }
414 }
415 
416 bool ISD::isVPBinaryOp(unsigned Opcode) {
417   switch (Opcode) {
418   default:
419     return false;
420 #define PROPERTY_VP_BINARYOP_SDNODE(SDOPC)                                     \
421   case ISD::SDOPC:                                                             \
422     return true;
423 #include "llvm/IR/VPIntrinsics.def"
424   }
425 }
426 
427 bool ISD::isVPReduction(unsigned Opcode) {
428   switch (Opcode) {
429   default:
430     return false;
431 #define PROPERTY_VP_REDUCTION_SDNODE(SDOPC)                                    \
432   case ISD::SDOPC:                                                             \
433     return true;
434 #include "llvm/IR/VPIntrinsics.def"
435   }
436 }
437 
438 /// The operand position of the vector mask.
439 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
440   switch (Opcode) {
441   default:
442     return None;
443 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...)        \
444   case ISD::SDOPC:                                                             \
445     return MASKPOS;
446 #include "llvm/IR/VPIntrinsics.def"
447   }
448 }
449 
450 /// The operand position of the explicit vector length parameter.
451 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
452   switch (Opcode) {
453   default:
454     return None;
455 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS)     \
456   case ISD::SDOPC:                                                             \
457     return EVLPOS;
458 #include "llvm/IR/VPIntrinsics.def"
459   }
460 }
461 
462 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
463   switch (ExtType) {
464   case ISD::EXTLOAD:
465     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
466   case ISD::SEXTLOAD:
467     return ISD::SIGN_EXTEND;
468   case ISD::ZEXTLOAD:
469     return ISD::ZERO_EXTEND;
470   default:
471     break;
472   }
473 
474   llvm_unreachable("Invalid LoadExtType");
475 }
476 
477 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
478   // To perform this operation, we just need to swap the L and G bits of the
479   // operation.
480   unsigned OldL = (Operation >> 2) & 1;
481   unsigned OldG = (Operation >> 1) & 1;
482   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
483                        (OldL << 1) |       // New G bit
484                        (OldG << 2));       // New L bit.
485 }
486 
487 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
488   unsigned Operation = Op;
489   if (isIntegerLike)
490     Operation ^= 7;   // Flip L, G, E bits, but not U.
491   else
492     Operation ^= 15;  // Flip all of the condition bits.
493 
494   if (Operation > ISD::SETTRUE2)
495     Operation &= ~8;  // Don't let N and U bits get set.
496 
497   return ISD::CondCode(Operation);
498 }
499 
500 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
501   return getSetCCInverseImpl(Op, Type.isInteger());
502 }
503 
504 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
505                                                bool isIntegerLike) {
506   return getSetCCInverseImpl(Op, isIntegerLike);
507 }
508 
509 /// For an integer comparison, return 1 if the comparison is a signed operation
510 /// and 2 if the result is an unsigned comparison. Return zero if the operation
511 /// does not depend on the sign of the input (setne and seteq).
512 static int isSignedOp(ISD::CondCode Opcode) {
513   switch (Opcode) {
514   default: llvm_unreachable("Illegal integer setcc operation!");
515   case ISD::SETEQ:
516   case ISD::SETNE: return 0;
517   case ISD::SETLT:
518   case ISD::SETLE:
519   case ISD::SETGT:
520   case ISD::SETGE: return 1;
521   case ISD::SETULT:
522   case ISD::SETULE:
523   case ISD::SETUGT:
524   case ISD::SETUGE: return 2;
525   }
526 }
527 
528 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
529                                        EVT Type) {
530   bool IsInteger = Type.isInteger();
531   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
532     // Cannot fold a signed integer setcc with an unsigned integer setcc.
533     return ISD::SETCC_INVALID;
534 
535   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
536 
537   // If the N and U bits get set, then the resultant comparison DOES suddenly
538   // care about orderedness, and it is true when ordered.
539   if (Op > ISD::SETTRUE2)
540     Op &= ~16;     // Clear the U bit if the N bit is set.
541 
542   // Canonicalize illegal integer setcc's.
543   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
544     Op = ISD::SETNE;
545 
546   return ISD::CondCode(Op);
547 }
548 
549 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
550                                         EVT Type) {
551   bool IsInteger = Type.isInteger();
552   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
553     // Cannot fold a signed setcc with an unsigned setcc.
554     return ISD::SETCC_INVALID;
555 
556   // Combine all of the condition bits.
557   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
558 
559   // Canonicalize illegal integer setcc's.
560   if (IsInteger) {
561     switch (Result) {
562     default: break;
563     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
564     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
565     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
566     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
567     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
568     }
569   }
570 
571   return Result;
572 }
573 
574 //===----------------------------------------------------------------------===//
575 //                           SDNode Profile Support
576 //===----------------------------------------------------------------------===//
577 
578 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
579 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
580   ID.AddInteger(OpC);
581 }
582 
583 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
584 /// solely with their pointer.
585 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
586   ID.AddPointer(VTList.VTs);
587 }
588 
589 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
590 static void AddNodeIDOperands(FoldingSetNodeID &ID,
591                               ArrayRef<SDValue> Ops) {
592   for (auto& Op : Ops) {
593     ID.AddPointer(Op.getNode());
594     ID.AddInteger(Op.getResNo());
595   }
596 }
597 
598 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
599 static void AddNodeIDOperands(FoldingSetNodeID &ID,
600                               ArrayRef<SDUse> Ops) {
601   for (auto& Op : Ops) {
602     ID.AddPointer(Op.getNode());
603     ID.AddInteger(Op.getResNo());
604   }
605 }
606 
607 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
608                           SDVTList VTList, ArrayRef<SDValue> OpList) {
609   AddNodeIDOpcode(ID, OpC);
610   AddNodeIDValueTypes(ID, VTList);
611   AddNodeIDOperands(ID, OpList);
612 }
613 
614 /// If this is an SDNode with special info, add this info to the NodeID data.
615 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
616   switch (N->getOpcode()) {
617   case ISD::TargetExternalSymbol:
618   case ISD::ExternalSymbol:
619   case ISD::MCSymbol:
620     llvm_unreachable("Should only be used on nodes with operands");
621   default: break;  // Normal nodes don't need extra info.
622   case ISD::TargetConstant:
623   case ISD::Constant: {
624     const ConstantSDNode *C = cast<ConstantSDNode>(N);
625     ID.AddPointer(C->getConstantIntValue());
626     ID.AddBoolean(C->isOpaque());
627     break;
628   }
629   case ISD::TargetConstantFP:
630   case ISD::ConstantFP:
631     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
632     break;
633   case ISD::TargetGlobalAddress:
634   case ISD::GlobalAddress:
635   case ISD::TargetGlobalTLSAddress:
636   case ISD::GlobalTLSAddress: {
637     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
638     ID.AddPointer(GA->getGlobal());
639     ID.AddInteger(GA->getOffset());
640     ID.AddInteger(GA->getTargetFlags());
641     break;
642   }
643   case ISD::BasicBlock:
644     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
645     break;
646   case ISD::Register:
647     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
648     break;
649   case ISD::RegisterMask:
650     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
651     break;
652   case ISD::SRCVALUE:
653     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
654     break;
655   case ISD::FrameIndex:
656   case ISD::TargetFrameIndex:
657     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
658     break;
659   case ISD::LIFETIME_START:
660   case ISD::LIFETIME_END:
661     if (cast<LifetimeSDNode>(N)->hasOffset()) {
662       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
663       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
664     }
665     break;
666   case ISD::PSEUDO_PROBE:
667     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
668     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
669     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
670     break;
671   case ISD::JumpTable:
672   case ISD::TargetJumpTable:
673     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
674     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
675     break;
676   case ISD::ConstantPool:
677   case ISD::TargetConstantPool: {
678     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
679     ID.AddInteger(CP->getAlign().value());
680     ID.AddInteger(CP->getOffset());
681     if (CP->isMachineConstantPoolEntry())
682       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
683     else
684       ID.AddPointer(CP->getConstVal());
685     ID.AddInteger(CP->getTargetFlags());
686     break;
687   }
688   case ISD::TargetIndex: {
689     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
690     ID.AddInteger(TI->getIndex());
691     ID.AddInteger(TI->getOffset());
692     ID.AddInteger(TI->getTargetFlags());
693     break;
694   }
695   case ISD::LOAD: {
696     const LoadSDNode *LD = cast<LoadSDNode>(N);
697     ID.AddInteger(LD->getMemoryVT().getRawBits());
698     ID.AddInteger(LD->getRawSubclassData());
699     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
700     break;
701   }
702   case ISD::STORE: {
703     const StoreSDNode *ST = cast<StoreSDNode>(N);
704     ID.AddInteger(ST->getMemoryVT().getRawBits());
705     ID.AddInteger(ST->getRawSubclassData());
706     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
707     break;
708   }
709   case ISD::VP_LOAD: {
710     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
711     ID.AddInteger(ELD->getMemoryVT().getRawBits());
712     ID.AddInteger(ELD->getRawSubclassData());
713     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
714     break;
715   }
716   case ISD::VP_STORE: {
717     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
718     ID.AddInteger(EST->getMemoryVT().getRawBits());
719     ID.AddInteger(EST->getRawSubclassData());
720     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
721     break;
722   }
723   case ISD::VP_GATHER: {
724     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
725     ID.AddInteger(EG->getMemoryVT().getRawBits());
726     ID.AddInteger(EG->getRawSubclassData());
727     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
728     break;
729   }
730   case ISD::VP_SCATTER: {
731     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
732     ID.AddInteger(ES->getMemoryVT().getRawBits());
733     ID.AddInteger(ES->getRawSubclassData());
734     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
735     break;
736   }
737   case ISD::MLOAD: {
738     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
739     ID.AddInteger(MLD->getMemoryVT().getRawBits());
740     ID.AddInteger(MLD->getRawSubclassData());
741     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
742     break;
743   }
744   case ISD::MSTORE: {
745     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
746     ID.AddInteger(MST->getMemoryVT().getRawBits());
747     ID.AddInteger(MST->getRawSubclassData());
748     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
749     break;
750   }
751   case ISD::MGATHER: {
752     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
753     ID.AddInteger(MG->getMemoryVT().getRawBits());
754     ID.AddInteger(MG->getRawSubclassData());
755     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
756     break;
757   }
758   case ISD::MSCATTER: {
759     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
760     ID.AddInteger(MS->getMemoryVT().getRawBits());
761     ID.AddInteger(MS->getRawSubclassData());
762     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
763     break;
764   }
765   case ISD::ATOMIC_CMP_SWAP:
766   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
767   case ISD::ATOMIC_SWAP:
768   case ISD::ATOMIC_LOAD_ADD:
769   case ISD::ATOMIC_LOAD_SUB:
770   case ISD::ATOMIC_LOAD_AND:
771   case ISD::ATOMIC_LOAD_CLR:
772   case ISD::ATOMIC_LOAD_OR:
773   case ISD::ATOMIC_LOAD_XOR:
774   case ISD::ATOMIC_LOAD_NAND:
775   case ISD::ATOMIC_LOAD_MIN:
776   case ISD::ATOMIC_LOAD_MAX:
777   case ISD::ATOMIC_LOAD_UMIN:
778   case ISD::ATOMIC_LOAD_UMAX:
779   case ISD::ATOMIC_LOAD:
780   case ISD::ATOMIC_STORE: {
781     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
782     ID.AddInteger(AT->getMemoryVT().getRawBits());
783     ID.AddInteger(AT->getRawSubclassData());
784     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
785     break;
786   }
787   case ISD::PREFETCH: {
788     const MemSDNode *PF = cast<MemSDNode>(N);
789     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
790     break;
791   }
792   case ISD::VECTOR_SHUFFLE: {
793     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
794     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
795          i != e; ++i)
796       ID.AddInteger(SVN->getMaskElt(i));
797     break;
798   }
799   case ISD::TargetBlockAddress:
800   case ISD::BlockAddress: {
801     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
802     ID.AddPointer(BA->getBlockAddress());
803     ID.AddInteger(BA->getOffset());
804     ID.AddInteger(BA->getTargetFlags());
805     break;
806   }
807   } // end switch (N->getOpcode())
808 
809   // Target specific memory nodes could also have address spaces to check.
810   if (N->isTargetMemoryOpcode())
811     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
812 }
813 
814 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
815 /// data.
816 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
817   AddNodeIDOpcode(ID, N->getOpcode());
818   // Add the return value info.
819   AddNodeIDValueTypes(ID, N->getVTList());
820   // Add the operand info.
821   AddNodeIDOperands(ID, N->ops());
822 
823   // Handle SDNode leafs with special info.
824   AddNodeIDCustom(ID, N);
825 }
826 
827 //===----------------------------------------------------------------------===//
828 //                              SelectionDAG Class
829 //===----------------------------------------------------------------------===//
830 
831 /// doNotCSE - Return true if CSE should not be performed for this node.
832 static bool doNotCSE(SDNode *N) {
833   if (N->getValueType(0) == MVT::Glue)
834     return true; // Never CSE anything that produces a flag.
835 
836   switch (N->getOpcode()) {
837   default: break;
838   case ISD::HANDLENODE:
839   case ISD::EH_LABEL:
840     return true;   // Never CSE these nodes.
841   }
842 
843   // Check that remaining values produced are not flags.
844   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
845     if (N->getValueType(i) == MVT::Glue)
846       return true; // Never CSE anything that produces a flag.
847 
848   return false;
849 }
850 
851 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
852 /// SelectionDAG.
853 void SelectionDAG::RemoveDeadNodes() {
854   // Create a dummy node (which is not added to allnodes), that adds a reference
855   // to the root node, preventing it from being deleted.
856   HandleSDNode Dummy(getRoot());
857 
858   SmallVector<SDNode*, 128> DeadNodes;
859 
860   // Add all obviously-dead nodes to the DeadNodes worklist.
861   for (SDNode &Node : allnodes())
862     if (Node.use_empty())
863       DeadNodes.push_back(&Node);
864 
865   RemoveDeadNodes(DeadNodes);
866 
867   // If the root changed (e.g. it was a dead load, update the root).
868   setRoot(Dummy.getValue());
869 }
870 
871 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
872 /// given list, and any nodes that become unreachable as a result.
873 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
874 
875   // Process the worklist, deleting the nodes and adding their uses to the
876   // worklist.
877   while (!DeadNodes.empty()) {
878     SDNode *N = DeadNodes.pop_back_val();
879     // Skip to next node if we've already managed to delete the node. This could
880     // happen if replacing a node causes a node previously added to the node to
881     // be deleted.
882     if (N->getOpcode() == ISD::DELETED_NODE)
883       continue;
884 
885     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
886       DUL->NodeDeleted(N, nullptr);
887 
888     // Take the node out of the appropriate CSE map.
889     RemoveNodeFromCSEMaps(N);
890 
891     // Next, brutally remove the operand list.  This is safe to do, as there are
892     // no cycles in the graph.
893     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
894       SDUse &Use = *I++;
895       SDNode *Operand = Use.getNode();
896       Use.set(SDValue());
897 
898       // Now that we removed this operand, see if there are no uses of it left.
899       if (Operand->use_empty())
900         DeadNodes.push_back(Operand);
901     }
902 
903     DeallocateNode(N);
904   }
905 }
906 
907 void SelectionDAG::RemoveDeadNode(SDNode *N){
908   SmallVector<SDNode*, 16> DeadNodes(1, N);
909 
910   // Create a dummy node that adds a reference to the root node, preventing
911   // it from being deleted.  (This matters if the root is an operand of the
912   // dead node.)
913   HandleSDNode Dummy(getRoot());
914 
915   RemoveDeadNodes(DeadNodes);
916 }
917 
918 void SelectionDAG::DeleteNode(SDNode *N) {
919   // First take this out of the appropriate CSE map.
920   RemoveNodeFromCSEMaps(N);
921 
922   // Finally, remove uses due to operands of this node, remove from the
923   // AllNodes list, and delete the node.
924   DeleteNodeNotInCSEMaps(N);
925 }
926 
927 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
928   assert(N->getIterator() != AllNodes.begin() &&
929          "Cannot delete the entry node!");
930   assert(N->use_empty() && "Cannot delete a node that is not dead!");
931 
932   // Drop all of the operands and decrement used node's use counts.
933   N->DropOperands();
934 
935   DeallocateNode(N);
936 }
937 
938 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
939   assert(!(V->isVariadic() && isParameter));
940   if (isParameter)
941     ByvalParmDbgValues.push_back(V);
942   else
943     DbgValues.push_back(V);
944   for (const SDNode *Node : V->getSDNodes())
945     if (Node)
946       DbgValMap[Node].push_back(V);
947 }
948 
949 void SDDbgInfo::erase(const SDNode *Node) {
950   DbgValMapType::iterator I = DbgValMap.find(Node);
951   if (I == DbgValMap.end())
952     return;
953   for (auto &Val: I->second)
954     Val->setIsInvalidated();
955   DbgValMap.erase(I);
956 }
957 
958 void SelectionDAG::DeallocateNode(SDNode *N) {
959   // If we have operands, deallocate them.
960   removeOperands(N);
961 
962   NodeAllocator.Deallocate(AllNodes.remove(N));
963 
964   // Set the opcode to DELETED_NODE to help catch bugs when node
965   // memory is reallocated.
966   // FIXME: There are places in SDag that have grown a dependency on the opcode
967   // value in the released node.
968   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
969   N->NodeType = ISD::DELETED_NODE;
970 
971   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
972   // them and forget about that node.
973   DbgInfo->erase(N);
974 }
975 
976 #ifndef NDEBUG
977 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
978 static void VerifySDNode(SDNode *N) {
979   switch (N->getOpcode()) {
980   default:
981     break;
982   case ISD::BUILD_PAIR: {
983     EVT VT = N->getValueType(0);
984     assert(N->getNumValues() == 1 && "Too many results!");
985     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
986            "Wrong return type!");
987     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
988     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
989            "Mismatched operand types!");
990     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
991            "Wrong operand type!");
992     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
993            "Wrong return type size");
994     break;
995   }
996   case ISD::BUILD_VECTOR: {
997     assert(N->getNumValues() == 1 && "Too many results!");
998     assert(N->getValueType(0).isVector() && "Wrong return type!");
999     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1000            "Wrong number of operands!");
1001     EVT EltVT = N->getValueType(0).getVectorElementType();
1002     for (const SDUse &Op : N->ops()) {
1003       assert((Op.getValueType() == EltVT ||
1004               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1005                EltVT.bitsLE(Op.getValueType()))) &&
1006              "Wrong operand type!");
1007       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1008              "Operands must all have the same type");
1009     }
1010     break;
1011   }
1012   }
1013 }
1014 #endif // NDEBUG
1015 
1016 /// Insert a newly allocated node into the DAG.
1017 ///
1018 /// Handles insertion into the all nodes list and CSE map, as well as
1019 /// verification and other common operations when a new node is allocated.
1020 void SelectionDAG::InsertNode(SDNode *N) {
1021   AllNodes.push_back(N);
1022 #ifndef NDEBUG
1023   N->PersistentId = NextPersistentId++;
1024   VerifySDNode(N);
1025 #endif
1026   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1027     DUL->NodeInserted(N);
1028 }
1029 
1030 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1031 /// correspond to it.  This is useful when we're about to delete or repurpose
1032 /// the node.  We don't want future request for structurally identical nodes
1033 /// to return N anymore.
1034 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1035   bool Erased = false;
1036   switch (N->getOpcode()) {
1037   case ISD::HANDLENODE: return false;  // noop.
1038   case ISD::CONDCODE:
1039     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1040            "Cond code doesn't exist!");
1041     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1042     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1043     break;
1044   case ISD::ExternalSymbol:
1045     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1046     break;
1047   case ISD::TargetExternalSymbol: {
1048     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1049     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1050         ESN->getSymbol(), ESN->getTargetFlags()));
1051     break;
1052   }
1053   case ISD::MCSymbol: {
1054     auto *MCSN = cast<MCSymbolSDNode>(N);
1055     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1056     break;
1057   }
1058   case ISD::VALUETYPE: {
1059     EVT VT = cast<VTSDNode>(N)->getVT();
1060     if (VT.isExtended()) {
1061       Erased = ExtendedValueTypeNodes.erase(VT);
1062     } else {
1063       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1064       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1065     }
1066     break;
1067   }
1068   default:
1069     // Remove it from the CSE Map.
1070     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1071     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1072     Erased = CSEMap.RemoveNode(N);
1073     break;
1074   }
1075 #ifndef NDEBUG
1076   // Verify that the node was actually in one of the CSE maps, unless it has a
1077   // flag result (which cannot be CSE'd) or is one of the special cases that are
1078   // not subject to CSE.
1079   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1080       !N->isMachineOpcode() && !doNotCSE(N)) {
1081     N->dump(this);
1082     dbgs() << "\n";
1083     llvm_unreachable("Node is not in map!");
1084   }
1085 #endif
1086   return Erased;
1087 }
1088 
1089 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1090 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1091 /// node already exists, in which case transfer all its users to the existing
1092 /// node. This transfer can potentially trigger recursive merging.
1093 void
1094 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1095   // For node types that aren't CSE'd, just act as if no identical node
1096   // already exists.
1097   if (!doNotCSE(N)) {
1098     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1099     if (Existing != N) {
1100       // If there was already an existing matching node, use ReplaceAllUsesWith
1101       // to replace the dead one with the existing one.  This can cause
1102       // recursive merging of other unrelated nodes down the line.
1103       ReplaceAllUsesWith(N, Existing);
1104 
1105       // N is now dead. Inform the listeners and delete it.
1106       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1107         DUL->NodeDeleted(N, Existing);
1108       DeleteNodeNotInCSEMaps(N);
1109       return;
1110     }
1111   }
1112 
1113   // If the node doesn't already exist, we updated it.  Inform listeners.
1114   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1115     DUL->NodeUpdated(N);
1116 }
1117 
1118 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1119 /// were replaced with those specified.  If this node is never memoized,
1120 /// return null, otherwise return a pointer to the slot it would take.  If a
1121 /// node already exists with these operands, the slot will be non-null.
1122 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1123                                            void *&InsertPos) {
1124   if (doNotCSE(N))
1125     return nullptr;
1126 
1127   SDValue Ops[] = { Op };
1128   FoldingSetNodeID ID;
1129   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1130   AddNodeIDCustom(ID, N);
1131   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1132   if (Node)
1133     Node->intersectFlagsWith(N->getFlags());
1134   return Node;
1135 }
1136 
1137 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1138 /// were replaced with those specified.  If this node is never memoized,
1139 /// return null, otherwise return a pointer to the slot it would take.  If a
1140 /// node already exists with these operands, the slot will be non-null.
1141 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1142                                            SDValue Op1, SDValue Op2,
1143                                            void *&InsertPos) {
1144   if (doNotCSE(N))
1145     return nullptr;
1146 
1147   SDValue Ops[] = { Op1, Op2 };
1148   FoldingSetNodeID ID;
1149   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1150   AddNodeIDCustom(ID, N);
1151   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1152   if (Node)
1153     Node->intersectFlagsWith(N->getFlags());
1154   return Node;
1155 }
1156 
1157 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1158 /// were replaced with those specified.  If this node is never memoized,
1159 /// return null, otherwise return a pointer to the slot it would take.  If a
1160 /// node already exists with these operands, the slot will be non-null.
1161 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1162                                            void *&InsertPos) {
1163   if (doNotCSE(N))
1164     return nullptr;
1165 
1166   FoldingSetNodeID ID;
1167   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1168   AddNodeIDCustom(ID, N);
1169   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1170   if (Node)
1171     Node->intersectFlagsWith(N->getFlags());
1172   return Node;
1173 }
1174 
1175 Align SelectionDAG::getEVTAlign(EVT VT) const {
1176   Type *Ty = VT == MVT::iPTR ?
1177                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1178                    VT.getTypeForEVT(*getContext());
1179 
1180   return getDataLayout().getABITypeAlign(Ty);
1181 }
1182 
1183 // EntryNode could meaningfully have debug info if we can find it...
1184 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1185     : TM(tm), OptLevel(OL),
1186       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1187       Root(getEntryNode()) {
1188   InsertNode(&EntryNode);
1189   DbgInfo = new SDDbgInfo();
1190 }
1191 
1192 void SelectionDAG::init(MachineFunction &NewMF,
1193                         OptimizationRemarkEmitter &NewORE,
1194                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1195                         LegacyDivergenceAnalysis * Divergence,
1196                         ProfileSummaryInfo *PSIin,
1197                         BlockFrequencyInfo *BFIin) {
1198   MF = &NewMF;
1199   SDAGISelPass = PassPtr;
1200   ORE = &NewORE;
1201   TLI = getSubtarget().getTargetLowering();
1202   TSI = getSubtarget().getSelectionDAGInfo();
1203   LibInfo = LibraryInfo;
1204   Context = &MF->getFunction().getContext();
1205   DA = Divergence;
1206   PSI = PSIin;
1207   BFI = BFIin;
1208 }
1209 
1210 SelectionDAG::~SelectionDAG() {
1211   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1212   allnodes_clear();
1213   OperandRecycler.clear(OperandAllocator);
1214   delete DbgInfo;
1215 }
1216 
1217 bool SelectionDAG::shouldOptForSize() const {
1218   return MF->getFunction().hasOptSize() ||
1219       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1220 }
1221 
1222 void SelectionDAG::allnodes_clear() {
1223   assert(&*AllNodes.begin() == &EntryNode);
1224   AllNodes.remove(AllNodes.begin());
1225   while (!AllNodes.empty())
1226     DeallocateNode(&AllNodes.front());
1227 #ifndef NDEBUG
1228   NextPersistentId = 0;
1229 #endif
1230 }
1231 
1232 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1233                                           void *&InsertPos) {
1234   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1235   if (N) {
1236     switch (N->getOpcode()) {
1237     default: break;
1238     case ISD::Constant:
1239     case ISD::ConstantFP:
1240       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1241                        "debug location.  Use another overload.");
1242     }
1243   }
1244   return N;
1245 }
1246 
1247 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1248                                           const SDLoc &DL, void *&InsertPos) {
1249   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1250   if (N) {
1251     switch (N->getOpcode()) {
1252     case ISD::Constant:
1253     case ISD::ConstantFP:
1254       // Erase debug location from the node if the node is used at several
1255       // different places. Do not propagate one location to all uses as it
1256       // will cause a worse single stepping debugging experience.
1257       if (N->getDebugLoc() != DL.getDebugLoc())
1258         N->setDebugLoc(DebugLoc());
1259       break;
1260     default:
1261       // When the node's point of use is located earlier in the instruction
1262       // sequence than its prior point of use, update its debug info to the
1263       // earlier location.
1264       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1265         N->setDebugLoc(DL.getDebugLoc());
1266       break;
1267     }
1268   }
1269   return N;
1270 }
1271 
1272 void SelectionDAG::clear() {
1273   allnodes_clear();
1274   OperandRecycler.clear(OperandAllocator);
1275   OperandAllocator.Reset();
1276   CSEMap.clear();
1277 
1278   ExtendedValueTypeNodes.clear();
1279   ExternalSymbols.clear();
1280   TargetExternalSymbols.clear();
1281   MCSymbols.clear();
1282   SDCallSiteDbgInfo.clear();
1283   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1284             static_cast<CondCodeSDNode*>(nullptr));
1285   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1286             static_cast<SDNode*>(nullptr));
1287 
1288   EntryNode.UseList = nullptr;
1289   InsertNode(&EntryNode);
1290   Root = getEntryNode();
1291   DbgInfo->clear();
1292 }
1293 
1294 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1295   return VT.bitsGT(Op.getValueType())
1296              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1297              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1298 }
1299 
1300 std::pair<SDValue, SDValue>
1301 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1302                                        const SDLoc &DL, EVT VT) {
1303   assert(!VT.bitsEq(Op.getValueType()) &&
1304          "Strict no-op FP extend/round not allowed.");
1305   SDValue Res =
1306       VT.bitsGT(Op.getValueType())
1307           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1308           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1309                     {Chain, Op, getIntPtrConstant(0, DL)});
1310 
1311   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1312 }
1313 
1314 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1315   return VT.bitsGT(Op.getValueType()) ?
1316     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1317     getNode(ISD::TRUNCATE, DL, VT, Op);
1318 }
1319 
1320 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1321   return VT.bitsGT(Op.getValueType()) ?
1322     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1323     getNode(ISD::TRUNCATE, DL, VT, Op);
1324 }
1325 
1326 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1327   return VT.bitsGT(Op.getValueType()) ?
1328     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1329     getNode(ISD::TRUNCATE, DL, VT, Op);
1330 }
1331 
1332 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1333                                         EVT OpVT) {
1334   if (VT.bitsLE(Op.getValueType()))
1335     return getNode(ISD::TRUNCATE, SL, VT, Op);
1336 
1337   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1338   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1339 }
1340 
1341 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1342   EVT OpVT = Op.getValueType();
1343   assert(VT.isInteger() && OpVT.isInteger() &&
1344          "Cannot getZeroExtendInReg FP types");
1345   assert(VT.isVector() == OpVT.isVector() &&
1346          "getZeroExtendInReg type should be vector iff the operand "
1347          "type is vector!");
1348   assert((!VT.isVector() ||
1349           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1350          "Vector element counts must match in getZeroExtendInReg");
1351   assert(VT.bitsLE(OpVT) && "Not extending!");
1352   if (OpVT == VT)
1353     return Op;
1354   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1355                                    VT.getScalarSizeInBits());
1356   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1357 }
1358 
1359 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1360   // Only unsigned pointer semantics are supported right now. In the future this
1361   // might delegate to TLI to check pointer signedness.
1362   return getZExtOrTrunc(Op, DL, VT);
1363 }
1364 
1365 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1366   // Only unsigned pointer semantics are supported right now. In the future this
1367   // might delegate to TLI to check pointer signedness.
1368   return getZeroExtendInReg(Op, DL, VT);
1369 }
1370 
1371 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1372 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1373   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1374 }
1375 
1376 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1377   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1378   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1379 }
1380 
1381 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1382                                       EVT OpVT) {
1383   if (!V)
1384     return getConstant(0, DL, VT);
1385 
1386   switch (TLI->getBooleanContents(OpVT)) {
1387   case TargetLowering::ZeroOrOneBooleanContent:
1388   case TargetLowering::UndefinedBooleanContent:
1389     return getConstant(1, DL, VT);
1390   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1391     return getAllOnesConstant(DL, VT);
1392   }
1393   llvm_unreachable("Unexpected boolean content enum!");
1394 }
1395 
1396 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1397                                   bool isT, bool isO) {
1398   EVT EltVT = VT.getScalarType();
1399   assert((EltVT.getSizeInBits() >= 64 ||
1400           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1401          "getConstant with a uint64_t value that doesn't fit in the type!");
1402   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1403 }
1404 
1405 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1406                                   bool isT, bool isO) {
1407   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1408 }
1409 
1410 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1411                                   EVT VT, bool isT, bool isO) {
1412   assert(VT.isInteger() && "Cannot create FP integer constant!");
1413 
1414   EVT EltVT = VT.getScalarType();
1415   const ConstantInt *Elt = &Val;
1416 
1417   // In some cases the vector type is legal but the element type is illegal and
1418   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1419   // inserted value (the type does not need to match the vector element type).
1420   // Any extra bits introduced will be truncated away.
1421   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1422                            TargetLowering::TypePromoteInteger) {
1423     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1424     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1425     Elt = ConstantInt::get(*getContext(), NewVal);
1426   }
1427   // In other cases the element type is illegal and needs to be expanded, for
1428   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1429   // the value into n parts and use a vector type with n-times the elements.
1430   // Then bitcast to the type requested.
1431   // Legalizing constants too early makes the DAGCombiner's job harder so we
1432   // only legalize if the DAG tells us we must produce legal types.
1433   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1434            TLI->getTypeAction(*getContext(), EltVT) ==
1435                TargetLowering::TypeExpandInteger) {
1436     const APInt &NewVal = Elt->getValue();
1437     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1438     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1439 
1440     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1441     if (VT.isScalableVector()) {
1442       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1443              "Can only handle an even split!");
1444       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1445 
1446       SmallVector<SDValue, 2> ScalarParts;
1447       for (unsigned i = 0; i != Parts; ++i)
1448         ScalarParts.push_back(getConstant(
1449             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1450             ViaEltVT, isT, isO));
1451 
1452       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1453     }
1454 
1455     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1456     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1457 
1458     // Check the temporary vector is the correct size. If this fails then
1459     // getTypeToTransformTo() probably returned a type whose size (in bits)
1460     // isn't a power-of-2 factor of the requested type size.
1461     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1462 
1463     SmallVector<SDValue, 2> EltParts;
1464     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1465       EltParts.push_back(getConstant(
1466           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1467           ViaEltVT, isT, isO));
1468 
1469     // EltParts is currently in little endian order. If we actually want
1470     // big-endian order then reverse it now.
1471     if (getDataLayout().isBigEndian())
1472       std::reverse(EltParts.begin(), EltParts.end());
1473 
1474     // The elements must be reversed when the element order is different
1475     // to the endianness of the elements (because the BITCAST is itself a
1476     // vector shuffle in this situation). However, we do not need any code to
1477     // perform this reversal because getConstant() is producing a vector
1478     // splat.
1479     // This situation occurs in MIPS MSA.
1480 
1481     SmallVector<SDValue, 8> Ops;
1482     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1483       llvm::append_range(Ops, EltParts);
1484 
1485     SDValue V =
1486         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1487     return V;
1488   }
1489 
1490   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1491          "APInt size does not match type size!");
1492   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1493   FoldingSetNodeID ID;
1494   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1495   ID.AddPointer(Elt);
1496   ID.AddBoolean(isO);
1497   void *IP = nullptr;
1498   SDNode *N = nullptr;
1499   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1500     if (!VT.isVector())
1501       return SDValue(N, 0);
1502 
1503   if (!N) {
1504     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1505     CSEMap.InsertNode(N, IP);
1506     InsertNode(N);
1507     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1508   }
1509 
1510   SDValue Result(N, 0);
1511   if (VT.isScalableVector())
1512     Result = getSplatVector(VT, DL, Result);
1513   else if (VT.isVector())
1514     Result = getSplatBuildVector(VT, DL, Result);
1515 
1516   return Result;
1517 }
1518 
1519 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1520                                         bool isTarget) {
1521   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1522 }
1523 
1524 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1525                                              const SDLoc &DL, bool LegalTypes) {
1526   assert(VT.isInteger() && "Shift amount is not an integer type!");
1527   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1528   return getConstant(Val, DL, ShiftVT);
1529 }
1530 
1531 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1532                                            bool isTarget) {
1533   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1534 }
1535 
1536 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1537                                     bool isTarget) {
1538   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1539 }
1540 
1541 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1542                                     EVT VT, bool isTarget) {
1543   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1544 
1545   EVT EltVT = VT.getScalarType();
1546 
1547   // Do the map lookup using the actual bit pattern for the floating point
1548   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1549   // we don't have issues with SNANs.
1550   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1551   FoldingSetNodeID ID;
1552   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1553   ID.AddPointer(&V);
1554   void *IP = nullptr;
1555   SDNode *N = nullptr;
1556   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1557     if (!VT.isVector())
1558       return SDValue(N, 0);
1559 
1560   if (!N) {
1561     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1562     CSEMap.InsertNode(N, IP);
1563     InsertNode(N);
1564   }
1565 
1566   SDValue Result(N, 0);
1567   if (VT.isScalableVector())
1568     Result = getSplatVector(VT, DL, Result);
1569   else if (VT.isVector())
1570     Result = getSplatBuildVector(VT, DL, Result);
1571   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1572   return Result;
1573 }
1574 
1575 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1576                                     bool isTarget) {
1577   EVT EltVT = VT.getScalarType();
1578   if (EltVT == MVT::f32)
1579     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1580   if (EltVT == MVT::f64)
1581     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1582   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1583       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1584     bool Ignored;
1585     APFloat APF = APFloat(Val);
1586     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1587                 &Ignored);
1588     return getConstantFP(APF, DL, VT, isTarget);
1589   }
1590   llvm_unreachable("Unsupported type in getConstantFP");
1591 }
1592 
1593 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1594                                        EVT VT, int64_t Offset, bool isTargetGA,
1595                                        unsigned TargetFlags) {
1596   assert((TargetFlags == 0 || isTargetGA) &&
1597          "Cannot set target flags on target-independent globals");
1598 
1599   // Truncate (with sign-extension) the offset value to the pointer size.
1600   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1601   if (BitWidth < 64)
1602     Offset = SignExtend64(Offset, BitWidth);
1603 
1604   unsigned Opc;
1605   if (GV->isThreadLocal())
1606     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1607   else
1608     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1609 
1610   FoldingSetNodeID ID;
1611   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1612   ID.AddPointer(GV);
1613   ID.AddInteger(Offset);
1614   ID.AddInteger(TargetFlags);
1615   void *IP = nullptr;
1616   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1617     return SDValue(E, 0);
1618 
1619   auto *N = newSDNode<GlobalAddressSDNode>(
1620       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1621   CSEMap.InsertNode(N, IP);
1622     InsertNode(N);
1623   return SDValue(N, 0);
1624 }
1625 
1626 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1627   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1628   FoldingSetNodeID ID;
1629   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1630   ID.AddInteger(FI);
1631   void *IP = nullptr;
1632   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1633     return SDValue(E, 0);
1634 
1635   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1636   CSEMap.InsertNode(N, IP);
1637   InsertNode(N);
1638   return SDValue(N, 0);
1639 }
1640 
1641 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1642                                    unsigned TargetFlags) {
1643   assert((TargetFlags == 0 || isTarget) &&
1644          "Cannot set target flags on target-independent jump tables");
1645   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1646   FoldingSetNodeID ID;
1647   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1648   ID.AddInteger(JTI);
1649   ID.AddInteger(TargetFlags);
1650   void *IP = nullptr;
1651   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1652     return SDValue(E, 0);
1653 
1654   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1655   CSEMap.InsertNode(N, IP);
1656   InsertNode(N);
1657   return SDValue(N, 0);
1658 }
1659 
1660 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1661                                       MaybeAlign Alignment, int Offset,
1662                                       bool isTarget, unsigned TargetFlags) {
1663   assert((TargetFlags == 0 || isTarget) &&
1664          "Cannot set target flags on target-independent globals");
1665   if (!Alignment)
1666     Alignment = shouldOptForSize()
1667                     ? getDataLayout().getABITypeAlign(C->getType())
1668                     : getDataLayout().getPrefTypeAlign(C->getType());
1669   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1670   FoldingSetNodeID ID;
1671   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1672   ID.AddInteger(Alignment->value());
1673   ID.AddInteger(Offset);
1674   ID.AddPointer(C);
1675   ID.AddInteger(TargetFlags);
1676   void *IP = nullptr;
1677   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1678     return SDValue(E, 0);
1679 
1680   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1681                                           TargetFlags);
1682   CSEMap.InsertNode(N, IP);
1683   InsertNode(N);
1684   SDValue V = SDValue(N, 0);
1685   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1686   return V;
1687 }
1688 
1689 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1690                                       MaybeAlign Alignment, int Offset,
1691                                       bool isTarget, unsigned TargetFlags) {
1692   assert((TargetFlags == 0 || isTarget) &&
1693          "Cannot set target flags on target-independent globals");
1694   if (!Alignment)
1695     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1696   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1697   FoldingSetNodeID ID;
1698   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1699   ID.AddInteger(Alignment->value());
1700   ID.AddInteger(Offset);
1701   C->addSelectionDAGCSEId(ID);
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<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1708                                           TargetFlags);
1709   CSEMap.InsertNode(N, IP);
1710   InsertNode(N);
1711   return SDValue(N, 0);
1712 }
1713 
1714 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1715                                      unsigned TargetFlags) {
1716   FoldingSetNodeID ID;
1717   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1718   ID.AddInteger(Index);
1719   ID.AddInteger(Offset);
1720   ID.AddInteger(TargetFlags);
1721   void *IP = nullptr;
1722   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1723     return SDValue(E, 0);
1724 
1725   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1726   CSEMap.InsertNode(N, IP);
1727   InsertNode(N);
1728   return SDValue(N, 0);
1729 }
1730 
1731 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1732   FoldingSetNodeID ID;
1733   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1734   ID.AddPointer(MBB);
1735   void *IP = nullptr;
1736   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1737     return SDValue(E, 0);
1738 
1739   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1740   CSEMap.InsertNode(N, IP);
1741   InsertNode(N);
1742   return SDValue(N, 0);
1743 }
1744 
1745 SDValue SelectionDAG::getValueType(EVT VT) {
1746   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1747       ValueTypeNodes.size())
1748     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1749 
1750   SDNode *&N = VT.isExtended() ?
1751     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1752 
1753   if (N) return SDValue(N, 0);
1754   N = newSDNode<VTSDNode>(VT);
1755   InsertNode(N);
1756   return SDValue(N, 0);
1757 }
1758 
1759 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1760   SDNode *&N = ExternalSymbols[Sym];
1761   if (N) return SDValue(N, 0);
1762   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1763   InsertNode(N);
1764   return SDValue(N, 0);
1765 }
1766 
1767 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1768   SDNode *&N = MCSymbols[Sym];
1769   if (N)
1770     return SDValue(N, 0);
1771   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1772   InsertNode(N);
1773   return SDValue(N, 0);
1774 }
1775 
1776 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1777                                               unsigned TargetFlags) {
1778   SDNode *&N =
1779       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1780   if (N) return SDValue(N, 0);
1781   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1782   InsertNode(N);
1783   return SDValue(N, 0);
1784 }
1785 
1786 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1787   if ((unsigned)Cond >= CondCodeNodes.size())
1788     CondCodeNodes.resize(Cond+1);
1789 
1790   if (!CondCodeNodes[Cond]) {
1791     auto *N = newSDNode<CondCodeSDNode>(Cond);
1792     CondCodeNodes[Cond] = N;
1793     InsertNode(N);
1794   }
1795 
1796   return SDValue(CondCodeNodes[Cond], 0);
1797 }
1798 
1799 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1800   APInt One(ResVT.getScalarSizeInBits(), 1);
1801   return getStepVector(DL, ResVT, One);
1802 }
1803 
1804 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1805   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1806   if (ResVT.isScalableVector())
1807     return getNode(
1808         ISD::STEP_VECTOR, DL, ResVT,
1809         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1810 
1811   SmallVector<SDValue, 16> OpsStepConstants;
1812   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1813     OpsStepConstants.push_back(
1814         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1815   return getBuildVector(ResVT, DL, OpsStepConstants);
1816 }
1817 
1818 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1819 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1820 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1821   std::swap(N1, N2);
1822   ShuffleVectorSDNode::commuteMask(M);
1823 }
1824 
1825 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1826                                        SDValue N2, ArrayRef<int> Mask) {
1827   assert(VT.getVectorNumElements() == Mask.size() &&
1828          "Must have the same number of vector elements as mask elements!");
1829   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1830          "Invalid VECTOR_SHUFFLE");
1831 
1832   // Canonicalize shuffle undef, undef -> undef
1833   if (N1.isUndef() && N2.isUndef())
1834     return getUNDEF(VT);
1835 
1836   // Validate that all indices in Mask are within the range of the elements
1837   // input to the shuffle.
1838   int NElts = Mask.size();
1839   assert(llvm::all_of(Mask,
1840                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1841          "Index out of range");
1842 
1843   // Copy the mask so we can do any needed cleanup.
1844   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1845 
1846   // Canonicalize shuffle v, v -> v, undef
1847   if (N1 == N2) {
1848     N2 = getUNDEF(VT);
1849     for (int i = 0; i != NElts; ++i)
1850       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1851   }
1852 
1853   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1854   if (N1.isUndef())
1855     commuteShuffle(N1, N2, MaskVec);
1856 
1857   if (TLI->hasVectorBlend()) {
1858     // If shuffling a splat, try to blend the splat instead. We do this here so
1859     // that even when this arises during lowering we don't have to re-handle it.
1860     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1861       BitVector UndefElements;
1862       SDValue Splat = BV->getSplatValue(&UndefElements);
1863       if (!Splat)
1864         return;
1865 
1866       for (int i = 0; i < NElts; ++i) {
1867         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1868           continue;
1869 
1870         // If this input comes from undef, mark it as such.
1871         if (UndefElements[MaskVec[i] - Offset]) {
1872           MaskVec[i] = -1;
1873           continue;
1874         }
1875 
1876         // If we can blend a non-undef lane, use that instead.
1877         if (!UndefElements[i])
1878           MaskVec[i] = i + Offset;
1879       }
1880     };
1881     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1882       BlendSplat(N1BV, 0);
1883     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1884       BlendSplat(N2BV, NElts);
1885   }
1886 
1887   // Canonicalize all index into lhs, -> shuffle lhs, undef
1888   // Canonicalize all index into rhs, -> shuffle rhs, undef
1889   bool AllLHS = true, AllRHS = true;
1890   bool N2Undef = N2.isUndef();
1891   for (int i = 0; i != NElts; ++i) {
1892     if (MaskVec[i] >= NElts) {
1893       if (N2Undef)
1894         MaskVec[i] = -1;
1895       else
1896         AllLHS = false;
1897     } else if (MaskVec[i] >= 0) {
1898       AllRHS = false;
1899     }
1900   }
1901   if (AllLHS && AllRHS)
1902     return getUNDEF(VT);
1903   if (AllLHS && !N2Undef)
1904     N2 = getUNDEF(VT);
1905   if (AllRHS) {
1906     N1 = getUNDEF(VT);
1907     commuteShuffle(N1, N2, MaskVec);
1908   }
1909   // Reset our undef status after accounting for the mask.
1910   N2Undef = N2.isUndef();
1911   // Re-check whether both sides ended up undef.
1912   if (N1.isUndef() && N2Undef)
1913     return getUNDEF(VT);
1914 
1915   // If Identity shuffle return that node.
1916   bool Identity = true, AllSame = true;
1917   for (int i = 0; i != NElts; ++i) {
1918     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1919     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1920   }
1921   if (Identity && NElts)
1922     return N1;
1923 
1924   // Shuffling a constant splat doesn't change the result.
1925   if (N2Undef) {
1926     SDValue V = N1;
1927 
1928     // Look through any bitcasts. We check that these don't change the number
1929     // (and size) of elements and just changes their types.
1930     while (V.getOpcode() == ISD::BITCAST)
1931       V = V->getOperand(0);
1932 
1933     // A splat should always show up as a build vector node.
1934     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1935       BitVector UndefElements;
1936       SDValue Splat = BV->getSplatValue(&UndefElements);
1937       // If this is a splat of an undef, shuffling it is also undef.
1938       if (Splat && Splat.isUndef())
1939         return getUNDEF(VT);
1940 
1941       bool SameNumElts =
1942           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1943 
1944       // We only have a splat which can skip shuffles if there is a splatted
1945       // value and no undef lanes rearranged by the shuffle.
1946       if (Splat && UndefElements.none()) {
1947         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1948         // number of elements match or the value splatted is a zero constant.
1949         if (SameNumElts)
1950           return N1;
1951         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1952           if (C->isZero())
1953             return N1;
1954       }
1955 
1956       // If the shuffle itself creates a splat, build the vector directly.
1957       if (AllSame && SameNumElts) {
1958         EVT BuildVT = BV->getValueType(0);
1959         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1960         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1961 
1962         // We may have jumped through bitcasts, so the type of the
1963         // BUILD_VECTOR may not match the type of the shuffle.
1964         if (BuildVT != VT)
1965           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1966         return NewBV;
1967       }
1968     }
1969   }
1970 
1971   FoldingSetNodeID ID;
1972   SDValue Ops[2] = { N1, N2 };
1973   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1974   for (int i = 0; i != NElts; ++i)
1975     ID.AddInteger(MaskVec[i]);
1976 
1977   void* IP = nullptr;
1978   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1979     return SDValue(E, 0);
1980 
1981   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1982   // SDNode doesn't have access to it.  This memory will be "leaked" when
1983   // the node is deallocated, but recovered when the NodeAllocator is released.
1984   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1985   llvm::copy(MaskVec, MaskAlloc);
1986 
1987   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1988                                            dl.getDebugLoc(), MaskAlloc);
1989   createOperands(N, Ops);
1990 
1991   CSEMap.InsertNode(N, IP);
1992   InsertNode(N);
1993   SDValue V = SDValue(N, 0);
1994   NewSDValueDbgMsg(V, "Creating new node: ", this);
1995   return V;
1996 }
1997 
1998 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1999   EVT VT = SV.getValueType(0);
2000   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2001   ShuffleVectorSDNode::commuteMask(MaskVec);
2002 
2003   SDValue Op0 = SV.getOperand(0);
2004   SDValue Op1 = SV.getOperand(1);
2005   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2006 }
2007 
2008 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2009   FoldingSetNodeID ID;
2010   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2011   ID.AddInteger(RegNo);
2012   void *IP = nullptr;
2013   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2014     return SDValue(E, 0);
2015 
2016   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2017   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2018   CSEMap.InsertNode(N, IP);
2019   InsertNode(N);
2020   return SDValue(N, 0);
2021 }
2022 
2023 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2024   FoldingSetNodeID ID;
2025   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2026   ID.AddPointer(RegMask);
2027   void *IP = nullptr;
2028   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2029     return SDValue(E, 0);
2030 
2031   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2032   CSEMap.InsertNode(N, IP);
2033   InsertNode(N);
2034   return SDValue(N, 0);
2035 }
2036 
2037 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2038                                  MCSymbol *Label) {
2039   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2040 }
2041 
2042 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2043                                    SDValue Root, MCSymbol *Label) {
2044   FoldingSetNodeID ID;
2045   SDValue Ops[] = { Root };
2046   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2047   ID.AddPointer(Label);
2048   void *IP = nullptr;
2049   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2050     return SDValue(E, 0);
2051 
2052   auto *N =
2053       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2054   createOperands(N, Ops);
2055 
2056   CSEMap.InsertNode(N, IP);
2057   InsertNode(N);
2058   return SDValue(N, 0);
2059 }
2060 
2061 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2062                                       int64_t Offset, bool isTarget,
2063                                       unsigned TargetFlags) {
2064   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2065 
2066   FoldingSetNodeID ID;
2067   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2068   ID.AddPointer(BA);
2069   ID.AddInteger(Offset);
2070   ID.AddInteger(TargetFlags);
2071   void *IP = nullptr;
2072   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2073     return SDValue(E, 0);
2074 
2075   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2076   CSEMap.InsertNode(N, IP);
2077   InsertNode(N);
2078   return SDValue(N, 0);
2079 }
2080 
2081 SDValue SelectionDAG::getSrcValue(const Value *V) {
2082   FoldingSetNodeID ID;
2083   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2084   ID.AddPointer(V);
2085 
2086   void *IP = nullptr;
2087   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2088     return SDValue(E, 0);
2089 
2090   auto *N = newSDNode<SrcValueSDNode>(V);
2091   CSEMap.InsertNode(N, IP);
2092   InsertNode(N);
2093   return SDValue(N, 0);
2094 }
2095 
2096 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2097   FoldingSetNodeID ID;
2098   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2099   ID.AddPointer(MD);
2100 
2101   void *IP = nullptr;
2102   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2103     return SDValue(E, 0);
2104 
2105   auto *N = newSDNode<MDNodeSDNode>(MD);
2106   CSEMap.InsertNode(N, IP);
2107   InsertNode(N);
2108   return SDValue(N, 0);
2109 }
2110 
2111 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2112   if (VT == V.getValueType())
2113     return V;
2114 
2115   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2116 }
2117 
2118 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2119                                        unsigned SrcAS, unsigned DestAS) {
2120   SDValue Ops[] = {Ptr};
2121   FoldingSetNodeID ID;
2122   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2123   ID.AddInteger(SrcAS);
2124   ID.AddInteger(DestAS);
2125 
2126   void *IP = nullptr;
2127   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2128     return SDValue(E, 0);
2129 
2130   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2131                                            VT, SrcAS, DestAS);
2132   createOperands(N, Ops);
2133 
2134   CSEMap.InsertNode(N, IP);
2135   InsertNode(N);
2136   return SDValue(N, 0);
2137 }
2138 
2139 SDValue SelectionDAG::getFreeze(SDValue V) {
2140   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2141 }
2142 
2143 /// getShiftAmountOperand - Return the specified value casted to
2144 /// the target's desired shift amount type.
2145 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2146   EVT OpTy = Op.getValueType();
2147   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2148   if (OpTy == ShTy || OpTy.isVector()) return Op;
2149 
2150   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2151 }
2152 
2153 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2154   SDLoc dl(Node);
2155   const TargetLowering &TLI = getTargetLoweringInfo();
2156   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2157   EVT VT = Node->getValueType(0);
2158   SDValue Tmp1 = Node->getOperand(0);
2159   SDValue Tmp2 = Node->getOperand(1);
2160   const MaybeAlign MA(Node->getConstantOperandVal(3));
2161 
2162   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2163                                Tmp2, MachinePointerInfo(V));
2164   SDValue VAList = VAListLoad;
2165 
2166   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2167     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2168                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2169 
2170     VAList =
2171         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2172                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2173   }
2174 
2175   // Increment the pointer, VAList, to the next vaarg
2176   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2177                  getConstant(getDataLayout().getTypeAllocSize(
2178                                                VT.getTypeForEVT(*getContext())),
2179                              dl, VAList.getValueType()));
2180   // Store the incremented VAList to the legalized pointer
2181   Tmp1 =
2182       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2183   // Load the actual argument out of the pointer VAList
2184   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2185 }
2186 
2187 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2188   SDLoc dl(Node);
2189   const TargetLowering &TLI = getTargetLoweringInfo();
2190   // This defaults to loading a pointer from the input and storing it to the
2191   // output, returning the chain.
2192   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2193   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2194   SDValue Tmp1 =
2195       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2196               Node->getOperand(2), MachinePointerInfo(VS));
2197   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2198                   MachinePointerInfo(VD));
2199 }
2200 
2201 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2202   const DataLayout &DL = getDataLayout();
2203   Type *Ty = VT.getTypeForEVT(*getContext());
2204   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2205 
2206   if (TLI->isTypeLegal(VT) || !VT.isVector())
2207     return RedAlign;
2208 
2209   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2210   const Align StackAlign = TFI->getStackAlign();
2211 
2212   // See if we can choose a smaller ABI alignment in cases where it's an
2213   // illegal vector type that will get broken down.
2214   if (RedAlign > StackAlign) {
2215     EVT IntermediateVT;
2216     MVT RegisterVT;
2217     unsigned NumIntermediates;
2218     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2219                                 NumIntermediates, RegisterVT);
2220     Ty = IntermediateVT.getTypeForEVT(*getContext());
2221     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2222     if (RedAlign2 < RedAlign)
2223       RedAlign = RedAlign2;
2224   }
2225 
2226   return RedAlign;
2227 }
2228 
2229 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2230   MachineFrameInfo &MFI = MF->getFrameInfo();
2231   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2232   int StackID = 0;
2233   if (Bytes.isScalable())
2234     StackID = TFI->getStackIDForScalableVectors();
2235   // The stack id gives an indication of whether the object is scalable or
2236   // not, so it's safe to pass in the minimum size here.
2237   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2238                                        false, nullptr, StackID);
2239   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2240 }
2241 
2242 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2243   Type *Ty = VT.getTypeForEVT(*getContext());
2244   Align StackAlign =
2245       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2246   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2247 }
2248 
2249 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2250   TypeSize VT1Size = VT1.getStoreSize();
2251   TypeSize VT2Size = VT2.getStoreSize();
2252   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2253          "Don't know how to choose the maximum size when creating a stack "
2254          "temporary");
2255   TypeSize Bytes =
2256       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2257 
2258   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2259   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2260   const DataLayout &DL = getDataLayout();
2261   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2262   return CreateStackTemporary(Bytes, Align);
2263 }
2264 
2265 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2266                                 ISD::CondCode Cond, const SDLoc &dl) {
2267   EVT OpVT = N1.getValueType();
2268 
2269   // These setcc operations always fold.
2270   switch (Cond) {
2271   default: break;
2272   case ISD::SETFALSE:
2273   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2274   case ISD::SETTRUE:
2275   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2276 
2277   case ISD::SETOEQ:
2278   case ISD::SETOGT:
2279   case ISD::SETOGE:
2280   case ISD::SETOLT:
2281   case ISD::SETOLE:
2282   case ISD::SETONE:
2283   case ISD::SETO:
2284   case ISD::SETUO:
2285   case ISD::SETUEQ:
2286   case ISD::SETUNE:
2287     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2288     break;
2289   }
2290 
2291   if (OpVT.isInteger()) {
2292     // For EQ and NE, we can always pick a value for the undef to make the
2293     // predicate pass or fail, so we can return undef.
2294     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2295     // icmp eq/ne X, undef -> undef.
2296     if ((N1.isUndef() || N2.isUndef()) &&
2297         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2298       return getUNDEF(VT);
2299 
2300     // If both operands are undef, we can return undef for int comparison.
2301     // icmp undef, undef -> undef.
2302     if (N1.isUndef() && N2.isUndef())
2303       return getUNDEF(VT);
2304 
2305     // icmp X, X -> true/false
2306     // icmp X, undef -> true/false because undef could be X.
2307     if (N1 == N2)
2308       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2309   }
2310 
2311   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2312     const APInt &C2 = N2C->getAPIntValue();
2313     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2314       const APInt &C1 = N1C->getAPIntValue();
2315 
2316       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2317                              dl, VT, OpVT);
2318     }
2319   }
2320 
2321   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2322   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2323 
2324   if (N1CFP && N2CFP) {
2325     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2326     switch (Cond) {
2327     default: break;
2328     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2329                         return getUNDEF(VT);
2330                       LLVM_FALLTHROUGH;
2331     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2332                                              OpVT);
2333     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2334                         return getUNDEF(VT);
2335                       LLVM_FALLTHROUGH;
2336     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2337                                              R==APFloat::cmpLessThan, dl, VT,
2338                                              OpVT);
2339     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2340                         return getUNDEF(VT);
2341                       LLVM_FALLTHROUGH;
2342     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2343                                              OpVT);
2344     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2345                         return getUNDEF(VT);
2346                       LLVM_FALLTHROUGH;
2347     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2348                                              VT, OpVT);
2349     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2350                         return getUNDEF(VT);
2351                       LLVM_FALLTHROUGH;
2352     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2353                                              R==APFloat::cmpEqual, dl, VT,
2354                                              OpVT);
2355     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2356                         return getUNDEF(VT);
2357                       LLVM_FALLTHROUGH;
2358     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2359                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2360     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2361                                              OpVT);
2362     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2363                                              OpVT);
2364     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2365                                              R==APFloat::cmpEqual, dl, VT,
2366                                              OpVT);
2367     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2368                                              OpVT);
2369     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2370                                              R==APFloat::cmpLessThan, dl, VT,
2371                                              OpVT);
2372     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2373                                              R==APFloat::cmpUnordered, dl, VT,
2374                                              OpVT);
2375     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2376                                              VT, OpVT);
2377     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2378                                              OpVT);
2379     }
2380   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2381     // Ensure that the constant occurs on the RHS.
2382     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2383     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2384       return SDValue();
2385     return getSetCC(dl, VT, N2, N1, SwappedCond);
2386   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2387              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2388     // If an operand is known to be a nan (or undef that could be a nan), we can
2389     // fold it.
2390     // Choosing NaN for the undef will always make unordered comparison succeed
2391     // and ordered comparison fails.
2392     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2393     switch (ISD::getUnorderedFlavor(Cond)) {
2394     default:
2395       llvm_unreachable("Unknown flavor!");
2396     case 0: // Known false.
2397       return getBoolConstant(false, dl, VT, OpVT);
2398     case 1: // Known true.
2399       return getBoolConstant(true, dl, VT, OpVT);
2400     case 2: // Undefined.
2401       return getUNDEF(VT);
2402     }
2403   }
2404 
2405   // Could not fold it.
2406   return SDValue();
2407 }
2408 
2409 /// See if the specified operand can be simplified with the knowledge that only
2410 /// the bits specified by DemandedBits are used.
2411 /// TODO: really we should be making this into the DAG equivalent of
2412 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2413 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2414   EVT VT = V.getValueType();
2415 
2416   if (VT.isScalableVector())
2417     return SDValue();
2418 
2419   APInt DemandedElts = VT.isVector()
2420                            ? APInt::getAllOnes(VT.getVectorNumElements())
2421                            : APInt(1, 1);
2422   return GetDemandedBits(V, DemandedBits, DemandedElts);
2423 }
2424 
2425 /// See if the specified operand can be simplified with the knowledge that only
2426 /// the bits specified by DemandedBits are used in the elements specified by
2427 /// DemandedElts.
2428 /// TODO: really we should be making this into the DAG equivalent of
2429 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2430 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2431                                       const APInt &DemandedElts) {
2432   switch (V.getOpcode()) {
2433   default:
2434     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2435                                                 *this, 0);
2436   case ISD::Constant: {
2437     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2438     APInt NewVal = CVal & DemandedBits;
2439     if (NewVal != CVal)
2440       return getConstant(NewVal, SDLoc(V), V.getValueType());
2441     break;
2442   }
2443   case ISD::SRL:
2444     // Only look at single-use SRLs.
2445     if (!V.getNode()->hasOneUse())
2446       break;
2447     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2448       // See if we can recursively simplify the LHS.
2449       unsigned Amt = RHSC->getZExtValue();
2450 
2451       // Watch out for shift count overflow though.
2452       if (Amt >= DemandedBits.getBitWidth())
2453         break;
2454       APInt SrcDemandedBits = DemandedBits << Amt;
2455       if (SDValue SimplifyLHS =
2456               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2457         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2458                        V.getOperand(1));
2459     }
2460     break;
2461   }
2462   return SDValue();
2463 }
2464 
2465 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2466 /// use this predicate to simplify operations downstream.
2467 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2468   unsigned BitWidth = Op.getScalarValueSizeInBits();
2469   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2470 }
2471 
2472 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2473 /// this predicate to simplify operations downstream.  Mask is known to be zero
2474 /// for bits that V cannot have.
2475 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2476                                      unsigned Depth) const {
2477   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2478 }
2479 
2480 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2481 /// DemandedElts.  We use this predicate to simplify operations downstream.
2482 /// Mask is known to be zero for bits that V cannot have.
2483 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2484                                      const APInt &DemandedElts,
2485                                      unsigned Depth) const {
2486   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2487 }
2488 
2489 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2490 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2491                                         unsigned Depth) const {
2492   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2493 }
2494 
2495 /// isSplatValue - Return true if the vector V has the same value
2496 /// across all DemandedElts. For scalable vectors it does not make
2497 /// sense to specify which elements are demanded or undefined, therefore
2498 /// they are simply ignored.
2499 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2500                                 APInt &UndefElts, unsigned Depth) {
2501   EVT VT = V.getValueType();
2502   assert(VT.isVector() && "Vector type expected");
2503 
2504   if (!VT.isScalableVector() && !DemandedElts)
2505     return false; // No demanded elts, better to assume we don't know anything.
2506 
2507   if (Depth >= MaxRecursionDepth)
2508     return false; // Limit search depth.
2509 
2510   // Deal with some common cases here that work for both fixed and scalable
2511   // vector types.
2512   switch (V.getOpcode()) {
2513   case ISD::SPLAT_VECTOR:
2514     UndefElts = V.getOperand(0).isUndef()
2515                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2516                     : APInt(DemandedElts.getBitWidth(), 0);
2517     return true;
2518   case ISD::ADD:
2519   case ISD::SUB:
2520   case ISD::AND:
2521   case ISD::XOR:
2522   case ISD::OR: {
2523     APInt UndefLHS, UndefRHS;
2524     SDValue LHS = V.getOperand(0);
2525     SDValue RHS = V.getOperand(1);
2526     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2527         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2528       UndefElts = UndefLHS | UndefRHS;
2529       return true;
2530     }
2531     return false;
2532   }
2533   case ISD::ABS:
2534   case ISD::TRUNCATE:
2535   case ISD::SIGN_EXTEND:
2536   case ISD::ZERO_EXTEND:
2537     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2538   }
2539 
2540   // We don't support other cases than those above for scalable vectors at
2541   // the moment.
2542   if (VT.isScalableVector())
2543     return false;
2544 
2545   unsigned NumElts = VT.getVectorNumElements();
2546   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2547   UndefElts = APInt::getZero(NumElts);
2548 
2549   switch (V.getOpcode()) {
2550   case ISD::BUILD_VECTOR: {
2551     SDValue Scl;
2552     for (unsigned i = 0; i != NumElts; ++i) {
2553       SDValue Op = V.getOperand(i);
2554       if (Op.isUndef()) {
2555         UndefElts.setBit(i);
2556         continue;
2557       }
2558       if (!DemandedElts[i])
2559         continue;
2560       if (Scl && Scl != Op)
2561         return false;
2562       Scl = Op;
2563     }
2564     return true;
2565   }
2566   case ISD::VECTOR_SHUFFLE: {
2567     // Check if this is a shuffle node doing a splat.
2568     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2569     int SplatIndex = -1;
2570     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2571     for (int i = 0; i != (int)NumElts; ++i) {
2572       int M = Mask[i];
2573       if (M < 0) {
2574         UndefElts.setBit(i);
2575         continue;
2576       }
2577       if (!DemandedElts[i])
2578         continue;
2579       if (0 <= SplatIndex && SplatIndex != M)
2580         return false;
2581       SplatIndex = M;
2582     }
2583     return true;
2584   }
2585   case ISD::EXTRACT_SUBVECTOR: {
2586     // Offset the demanded elts by the subvector index.
2587     SDValue Src = V.getOperand(0);
2588     // We don't support scalable vectors at the moment.
2589     if (Src.getValueType().isScalableVector())
2590       return false;
2591     uint64_t Idx = V.getConstantOperandVal(1);
2592     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2593     APInt UndefSrcElts;
2594     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2595     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2596       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2597       return true;
2598     }
2599     break;
2600   }
2601   }
2602 
2603   return false;
2604 }
2605 
2606 /// Helper wrapper to main isSplatValue function.
2607 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2608   EVT VT = V.getValueType();
2609   assert(VT.isVector() && "Vector type expected");
2610 
2611   APInt UndefElts;
2612   APInt DemandedElts;
2613 
2614   // For now we don't support this with scalable vectors.
2615   if (!VT.isScalableVector())
2616     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2617   return isSplatValue(V, DemandedElts, UndefElts) &&
2618          (AllowUndefs || !UndefElts);
2619 }
2620 
2621 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2622   V = peekThroughExtractSubvectors(V);
2623 
2624   EVT VT = V.getValueType();
2625   unsigned Opcode = V.getOpcode();
2626   switch (Opcode) {
2627   default: {
2628     APInt UndefElts;
2629     APInt DemandedElts;
2630 
2631     if (!VT.isScalableVector())
2632       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2633 
2634     if (isSplatValue(V, DemandedElts, UndefElts)) {
2635       if (VT.isScalableVector()) {
2636         // DemandedElts and UndefElts are ignored for scalable vectors, since
2637         // the only supported cases are SPLAT_VECTOR nodes.
2638         SplatIdx = 0;
2639       } else {
2640         // Handle case where all demanded elements are UNDEF.
2641         if (DemandedElts.isSubsetOf(UndefElts)) {
2642           SplatIdx = 0;
2643           return getUNDEF(VT);
2644         }
2645         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2646       }
2647       return V;
2648     }
2649     break;
2650   }
2651   case ISD::SPLAT_VECTOR:
2652     SplatIdx = 0;
2653     return V;
2654   case ISD::VECTOR_SHUFFLE: {
2655     if (VT.isScalableVector())
2656       return SDValue();
2657 
2658     // Check if this is a shuffle node doing a splat.
2659     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2660     // getTargetVShiftNode currently struggles without the splat source.
2661     auto *SVN = cast<ShuffleVectorSDNode>(V);
2662     if (!SVN->isSplat())
2663       break;
2664     int Idx = SVN->getSplatIndex();
2665     int NumElts = V.getValueType().getVectorNumElements();
2666     SplatIdx = Idx % NumElts;
2667     return V.getOperand(Idx / NumElts);
2668   }
2669   }
2670 
2671   return SDValue();
2672 }
2673 
2674 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2675   int SplatIdx;
2676   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2677     EVT SVT = SrcVector.getValueType().getScalarType();
2678     EVT LegalSVT = SVT;
2679     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2680       if (!SVT.isInteger())
2681         return SDValue();
2682       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2683       if (LegalSVT.bitsLT(SVT))
2684         return SDValue();
2685     }
2686     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2687                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2688   }
2689   return SDValue();
2690 }
2691 
2692 const APInt *
2693 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2694                                           const APInt &DemandedElts) const {
2695   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2696           V.getOpcode() == ISD::SRA) &&
2697          "Unknown shift node");
2698   unsigned BitWidth = V.getScalarValueSizeInBits();
2699   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2700     // Shifting more than the bitwidth is not valid.
2701     const APInt &ShAmt = SA->getAPIntValue();
2702     if (ShAmt.ult(BitWidth))
2703       return &ShAmt;
2704   }
2705   return nullptr;
2706 }
2707 
2708 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2709     SDValue V, const APInt &DemandedElts) const {
2710   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2711           V.getOpcode() == ISD::SRA) &&
2712          "Unknown shift node");
2713   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2714     return ValidAmt;
2715   unsigned BitWidth = V.getScalarValueSizeInBits();
2716   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2717   if (!BV)
2718     return nullptr;
2719   const APInt *MinShAmt = nullptr;
2720   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2721     if (!DemandedElts[i])
2722       continue;
2723     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2724     if (!SA)
2725       return nullptr;
2726     // Shifting more than the bitwidth is not valid.
2727     const APInt &ShAmt = SA->getAPIntValue();
2728     if (ShAmt.uge(BitWidth))
2729       return nullptr;
2730     if (MinShAmt && MinShAmt->ule(ShAmt))
2731       continue;
2732     MinShAmt = &ShAmt;
2733   }
2734   return MinShAmt;
2735 }
2736 
2737 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2738     SDValue V, const APInt &DemandedElts) const {
2739   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2740           V.getOpcode() == ISD::SRA) &&
2741          "Unknown shift node");
2742   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2743     return ValidAmt;
2744   unsigned BitWidth = V.getScalarValueSizeInBits();
2745   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2746   if (!BV)
2747     return nullptr;
2748   const APInt *MaxShAmt = nullptr;
2749   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2750     if (!DemandedElts[i])
2751       continue;
2752     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2753     if (!SA)
2754       return nullptr;
2755     // Shifting more than the bitwidth is not valid.
2756     const APInt &ShAmt = SA->getAPIntValue();
2757     if (ShAmt.uge(BitWidth))
2758       return nullptr;
2759     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2760       continue;
2761     MaxShAmt = &ShAmt;
2762   }
2763   return MaxShAmt;
2764 }
2765 
2766 /// Determine which bits of Op are known to be either zero or one and return
2767 /// them in Known. For vectors, the known bits are those that are shared by
2768 /// every vector element.
2769 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2770   EVT VT = Op.getValueType();
2771 
2772   // TOOD: Until we have a plan for how to represent demanded elements for
2773   // scalable vectors, we can just bail out for now.
2774   if (Op.getValueType().isScalableVector()) {
2775     unsigned BitWidth = Op.getScalarValueSizeInBits();
2776     return KnownBits(BitWidth);
2777   }
2778 
2779   APInt DemandedElts = VT.isVector()
2780                            ? APInt::getAllOnes(VT.getVectorNumElements())
2781                            : APInt(1, 1);
2782   return computeKnownBits(Op, DemandedElts, Depth);
2783 }
2784 
2785 /// Determine which bits of Op are known to be either zero or one and return
2786 /// them in Known. The DemandedElts argument allows us to only collect the known
2787 /// bits that are shared by the requested vector elements.
2788 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2789                                          unsigned Depth) const {
2790   unsigned BitWidth = Op.getScalarValueSizeInBits();
2791 
2792   KnownBits Known(BitWidth);   // Don't know anything.
2793 
2794   // TOOD: Until we have a plan for how to represent demanded elements for
2795   // scalable vectors, we can just bail out for now.
2796   if (Op.getValueType().isScalableVector())
2797     return Known;
2798 
2799   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2800     // We know all of the bits for a constant!
2801     return KnownBits::makeConstant(C->getAPIntValue());
2802   }
2803   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2804     // We know all of the bits for a constant fp!
2805     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2806   }
2807 
2808   if (Depth >= MaxRecursionDepth)
2809     return Known;  // Limit search depth.
2810 
2811   KnownBits Known2;
2812   unsigned NumElts = DemandedElts.getBitWidth();
2813   assert((!Op.getValueType().isVector() ||
2814           NumElts == Op.getValueType().getVectorNumElements()) &&
2815          "Unexpected vector size");
2816 
2817   if (!DemandedElts)
2818     return Known;  // No demanded elts, better to assume we don't know anything.
2819 
2820   unsigned Opcode = Op.getOpcode();
2821   switch (Opcode) {
2822   case ISD::BUILD_VECTOR:
2823     // Collect the known bits that are shared by every demanded vector element.
2824     Known.Zero.setAllBits(); Known.One.setAllBits();
2825     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2826       if (!DemandedElts[i])
2827         continue;
2828 
2829       SDValue SrcOp = Op.getOperand(i);
2830       Known2 = computeKnownBits(SrcOp, Depth + 1);
2831 
2832       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2833       if (SrcOp.getValueSizeInBits() != BitWidth) {
2834         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2835                "Expected BUILD_VECTOR implicit truncation");
2836         Known2 = Known2.trunc(BitWidth);
2837       }
2838 
2839       // Known bits are the values that are shared by every demanded element.
2840       Known = KnownBits::commonBits(Known, Known2);
2841 
2842       // If we don't know any bits, early out.
2843       if (Known.isUnknown())
2844         break;
2845     }
2846     break;
2847   case ISD::VECTOR_SHUFFLE: {
2848     // Collect the known bits that are shared by every vector element referenced
2849     // by the shuffle.
2850     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2851     Known.Zero.setAllBits(); Known.One.setAllBits();
2852     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2853     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2854     for (unsigned i = 0; i != NumElts; ++i) {
2855       if (!DemandedElts[i])
2856         continue;
2857 
2858       int M = SVN->getMaskElt(i);
2859       if (M < 0) {
2860         // For UNDEF elements, we don't know anything about the common state of
2861         // the shuffle result.
2862         Known.resetAll();
2863         DemandedLHS.clearAllBits();
2864         DemandedRHS.clearAllBits();
2865         break;
2866       }
2867 
2868       if ((unsigned)M < NumElts)
2869         DemandedLHS.setBit((unsigned)M % NumElts);
2870       else
2871         DemandedRHS.setBit((unsigned)M % NumElts);
2872     }
2873     // Known bits are the values that are shared by every demanded element.
2874     if (!!DemandedLHS) {
2875       SDValue LHS = Op.getOperand(0);
2876       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2877       Known = KnownBits::commonBits(Known, Known2);
2878     }
2879     // If we don't know any bits, early out.
2880     if (Known.isUnknown())
2881       break;
2882     if (!!DemandedRHS) {
2883       SDValue RHS = Op.getOperand(1);
2884       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2885       Known = KnownBits::commonBits(Known, Known2);
2886     }
2887     break;
2888   }
2889   case ISD::CONCAT_VECTORS: {
2890     // Split DemandedElts and test each of the demanded subvectors.
2891     Known.Zero.setAllBits(); Known.One.setAllBits();
2892     EVT SubVectorVT = Op.getOperand(0).getValueType();
2893     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2894     unsigned NumSubVectors = Op.getNumOperands();
2895     for (unsigned i = 0; i != NumSubVectors; ++i) {
2896       APInt DemandedSub =
2897           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2898       if (!!DemandedSub) {
2899         SDValue Sub = Op.getOperand(i);
2900         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2901         Known = KnownBits::commonBits(Known, Known2);
2902       }
2903       // If we don't know any bits, early out.
2904       if (Known.isUnknown())
2905         break;
2906     }
2907     break;
2908   }
2909   case ISD::INSERT_SUBVECTOR: {
2910     // Demand any elements from the subvector and the remainder from the src its
2911     // inserted into.
2912     SDValue Src = Op.getOperand(0);
2913     SDValue Sub = Op.getOperand(1);
2914     uint64_t Idx = Op.getConstantOperandVal(2);
2915     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2916     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2917     APInt DemandedSrcElts = DemandedElts;
2918     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2919 
2920     Known.One.setAllBits();
2921     Known.Zero.setAllBits();
2922     if (!!DemandedSubElts) {
2923       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2924       if (Known.isUnknown())
2925         break; // early-out.
2926     }
2927     if (!!DemandedSrcElts) {
2928       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2929       Known = KnownBits::commonBits(Known, Known2);
2930     }
2931     break;
2932   }
2933   case ISD::EXTRACT_SUBVECTOR: {
2934     // Offset the demanded elts by the subvector index.
2935     SDValue Src = Op.getOperand(0);
2936     // Bail until we can represent demanded elements for scalable vectors.
2937     if (Src.getValueType().isScalableVector())
2938       break;
2939     uint64_t Idx = Op.getConstantOperandVal(1);
2940     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2941     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2942     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2943     break;
2944   }
2945   case ISD::SCALAR_TO_VECTOR: {
2946     // We know about scalar_to_vector as much as we know about it source,
2947     // which becomes the first element of otherwise unknown vector.
2948     if (DemandedElts != 1)
2949       break;
2950 
2951     SDValue N0 = Op.getOperand(0);
2952     Known = computeKnownBits(N0, Depth + 1);
2953     if (N0.getValueSizeInBits() != BitWidth)
2954       Known = Known.trunc(BitWidth);
2955 
2956     break;
2957   }
2958   case ISD::BITCAST: {
2959     SDValue N0 = Op.getOperand(0);
2960     EVT SubVT = N0.getValueType();
2961     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2962 
2963     // Ignore bitcasts from unsupported types.
2964     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2965       break;
2966 
2967     // Fast handling of 'identity' bitcasts.
2968     if (BitWidth == SubBitWidth) {
2969       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2970       break;
2971     }
2972 
2973     bool IsLE = getDataLayout().isLittleEndian();
2974 
2975     // Bitcast 'small element' vector to 'large element' scalar/vector.
2976     if ((BitWidth % SubBitWidth) == 0) {
2977       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2978 
2979       // Collect known bits for the (larger) output by collecting the known
2980       // bits from each set of sub elements and shift these into place.
2981       // We need to separately call computeKnownBits for each set of
2982       // sub elements as the knownbits for each is likely to be different.
2983       unsigned SubScale = BitWidth / SubBitWidth;
2984       APInt SubDemandedElts(NumElts * SubScale, 0);
2985       for (unsigned i = 0; i != NumElts; ++i)
2986         if (DemandedElts[i])
2987           SubDemandedElts.setBit(i * SubScale);
2988 
2989       for (unsigned i = 0; i != SubScale; ++i) {
2990         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2991                          Depth + 1);
2992         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2993         Known.insertBits(Known2, SubBitWidth * Shifts);
2994       }
2995     }
2996 
2997     // Bitcast 'large element' scalar/vector to 'small element' vector.
2998     if ((SubBitWidth % BitWidth) == 0) {
2999       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3000 
3001       // Collect known bits for the (smaller) output by collecting the known
3002       // bits from the overlapping larger input elements and extracting the
3003       // sub sections we actually care about.
3004       unsigned SubScale = SubBitWidth / BitWidth;
3005       APInt SubDemandedElts =
3006           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3007       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3008 
3009       Known.Zero.setAllBits(); Known.One.setAllBits();
3010       for (unsigned i = 0; i != NumElts; ++i)
3011         if (DemandedElts[i]) {
3012           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3013           unsigned Offset = (Shifts % SubScale) * BitWidth;
3014           Known = KnownBits::commonBits(Known,
3015                                         Known2.extractBits(BitWidth, Offset));
3016           // If we don't know any bits, early out.
3017           if (Known.isUnknown())
3018             break;
3019         }
3020     }
3021     break;
3022   }
3023   case ISD::AND:
3024     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3025     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3026 
3027     Known &= Known2;
3028     break;
3029   case ISD::OR:
3030     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3031     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3032 
3033     Known |= Known2;
3034     break;
3035   case ISD::XOR:
3036     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3037     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3038 
3039     Known ^= Known2;
3040     break;
3041   case ISD::MUL: {
3042     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3043     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3044     Known = KnownBits::mul(Known, Known2);
3045     break;
3046   }
3047   case ISD::MULHU: {
3048     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3049     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3050     Known = KnownBits::mulhu(Known, Known2);
3051     break;
3052   }
3053   case ISD::MULHS: {
3054     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3055     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3056     Known = KnownBits::mulhs(Known, Known2);
3057     break;
3058   }
3059   case ISD::UMUL_LOHI: {
3060     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3061     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3062     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3063     if (Op.getResNo() == 0)
3064       Known = KnownBits::mul(Known, Known2);
3065     else
3066       Known = KnownBits::mulhu(Known, Known2);
3067     break;
3068   }
3069   case ISD::SMUL_LOHI: {
3070     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3071     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3072     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3073     if (Op.getResNo() == 0)
3074       Known = KnownBits::mul(Known, Known2);
3075     else
3076       Known = KnownBits::mulhs(Known, Known2);
3077     break;
3078   }
3079   case ISD::UDIV: {
3080     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3081     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3082     Known = KnownBits::udiv(Known, Known2);
3083     break;
3084   }
3085   case ISD::SELECT:
3086   case ISD::VSELECT:
3087     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3088     // If we don't know any bits, early out.
3089     if (Known.isUnknown())
3090       break;
3091     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3092 
3093     // Only known if known in both the LHS and RHS.
3094     Known = KnownBits::commonBits(Known, Known2);
3095     break;
3096   case ISD::SELECT_CC:
3097     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3098     // If we don't know any bits, early out.
3099     if (Known.isUnknown())
3100       break;
3101     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3102 
3103     // Only known if known in both the LHS and RHS.
3104     Known = KnownBits::commonBits(Known, Known2);
3105     break;
3106   case ISD::SMULO:
3107   case ISD::UMULO:
3108     if (Op.getResNo() != 1)
3109       break;
3110     // The boolean result conforms to getBooleanContents.
3111     // If we know the result of a setcc has the top bits zero, use this info.
3112     // We know that we have an integer-based boolean since these operations
3113     // are only available for integer.
3114     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3115             TargetLowering::ZeroOrOneBooleanContent &&
3116         BitWidth > 1)
3117       Known.Zero.setBitsFrom(1);
3118     break;
3119   case ISD::SETCC:
3120   case ISD::STRICT_FSETCC:
3121   case ISD::STRICT_FSETCCS: {
3122     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3123     // If we know the result of a setcc has the top bits zero, use this info.
3124     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3125             TargetLowering::ZeroOrOneBooleanContent &&
3126         BitWidth > 1)
3127       Known.Zero.setBitsFrom(1);
3128     break;
3129   }
3130   case ISD::SHL:
3131     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3132     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3133     Known = KnownBits::shl(Known, Known2);
3134 
3135     // Minimum shift low bits are known zero.
3136     if (const APInt *ShMinAmt =
3137             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3138       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3139     break;
3140   case ISD::SRL:
3141     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3142     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3143     Known = KnownBits::lshr(Known, Known2);
3144 
3145     // Minimum shift high bits are known zero.
3146     if (const APInt *ShMinAmt =
3147             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3148       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3149     break;
3150   case ISD::SRA:
3151     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3152     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3153     Known = KnownBits::ashr(Known, Known2);
3154     // TODO: Add minimum shift high known sign bits.
3155     break;
3156   case ISD::FSHL:
3157   case ISD::FSHR:
3158     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3159       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3160 
3161       // For fshl, 0-shift returns the 1st arg.
3162       // For fshr, 0-shift returns the 2nd arg.
3163       if (Amt == 0) {
3164         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3165                                  DemandedElts, Depth + 1);
3166         break;
3167       }
3168 
3169       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3170       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3171       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3172       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3173       if (Opcode == ISD::FSHL) {
3174         Known.One <<= Amt;
3175         Known.Zero <<= Amt;
3176         Known2.One.lshrInPlace(BitWidth - Amt);
3177         Known2.Zero.lshrInPlace(BitWidth - Amt);
3178       } else {
3179         Known.One <<= BitWidth - Amt;
3180         Known.Zero <<= BitWidth - Amt;
3181         Known2.One.lshrInPlace(Amt);
3182         Known2.Zero.lshrInPlace(Amt);
3183       }
3184       Known.One |= Known2.One;
3185       Known.Zero |= Known2.Zero;
3186     }
3187     break;
3188   case ISD::SIGN_EXTEND_INREG: {
3189     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3190     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3191     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3192     break;
3193   }
3194   case ISD::CTTZ:
3195   case ISD::CTTZ_ZERO_UNDEF: {
3196     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3197     // If we have a known 1, its position is our upper bound.
3198     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3199     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3200     Known.Zero.setBitsFrom(LowBits);
3201     break;
3202   }
3203   case ISD::CTLZ:
3204   case ISD::CTLZ_ZERO_UNDEF: {
3205     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3206     // If we have a known 1, its position is our upper bound.
3207     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3208     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3209     Known.Zero.setBitsFrom(LowBits);
3210     break;
3211   }
3212   case ISD::CTPOP: {
3213     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3214     // If we know some of the bits are zero, they can't be one.
3215     unsigned PossibleOnes = Known2.countMaxPopulation();
3216     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3217     break;
3218   }
3219   case ISD::PARITY: {
3220     // Parity returns 0 everywhere but the LSB.
3221     Known.Zero.setBitsFrom(1);
3222     break;
3223   }
3224   case ISD::LOAD: {
3225     LoadSDNode *LD = cast<LoadSDNode>(Op);
3226     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3227     if (ISD::isNON_EXTLoad(LD) && Cst) {
3228       // Determine any common known bits from the loaded constant pool value.
3229       Type *CstTy = Cst->getType();
3230       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3231         // If its a vector splat, then we can (quickly) reuse the scalar path.
3232         // NOTE: We assume all elements match and none are UNDEF.
3233         if (CstTy->isVectorTy()) {
3234           if (const Constant *Splat = Cst->getSplatValue()) {
3235             Cst = Splat;
3236             CstTy = Cst->getType();
3237           }
3238         }
3239         // TODO - do we need to handle different bitwidths?
3240         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3241           // Iterate across all vector elements finding common known bits.
3242           Known.One.setAllBits();
3243           Known.Zero.setAllBits();
3244           for (unsigned i = 0; i != NumElts; ++i) {
3245             if (!DemandedElts[i])
3246               continue;
3247             if (Constant *Elt = Cst->getAggregateElement(i)) {
3248               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3249                 const APInt &Value = CInt->getValue();
3250                 Known.One &= Value;
3251                 Known.Zero &= ~Value;
3252                 continue;
3253               }
3254               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3255                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3256                 Known.One &= Value;
3257                 Known.Zero &= ~Value;
3258                 continue;
3259               }
3260             }
3261             Known.One.clearAllBits();
3262             Known.Zero.clearAllBits();
3263             break;
3264           }
3265         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3266           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3267             Known = KnownBits::makeConstant(CInt->getValue());
3268           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3269             Known =
3270                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3271           }
3272         }
3273       }
3274     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3275       // If this is a ZEXTLoad and we are looking at the loaded value.
3276       EVT VT = LD->getMemoryVT();
3277       unsigned MemBits = VT.getScalarSizeInBits();
3278       Known.Zero.setBitsFrom(MemBits);
3279     } else if (const MDNode *Ranges = LD->getRanges()) {
3280       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3281         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3282     }
3283     break;
3284   }
3285   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3286     EVT InVT = Op.getOperand(0).getValueType();
3287     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3288     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3289     Known = Known.zext(BitWidth);
3290     break;
3291   }
3292   case ISD::ZERO_EXTEND: {
3293     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3294     Known = Known.zext(BitWidth);
3295     break;
3296   }
3297   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3298     EVT InVT = Op.getOperand(0).getValueType();
3299     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3300     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3301     // If the sign bit is known to be zero or one, then sext will extend
3302     // it to the top bits, else it will just zext.
3303     Known = Known.sext(BitWidth);
3304     break;
3305   }
3306   case ISD::SIGN_EXTEND: {
3307     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3308     // If the sign bit is known to be zero or one, then sext will extend
3309     // it to the top bits, else it will just zext.
3310     Known = Known.sext(BitWidth);
3311     break;
3312   }
3313   case ISD::ANY_EXTEND_VECTOR_INREG: {
3314     EVT InVT = Op.getOperand(0).getValueType();
3315     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3316     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3317     Known = Known.anyext(BitWidth);
3318     break;
3319   }
3320   case ISD::ANY_EXTEND: {
3321     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3322     Known = Known.anyext(BitWidth);
3323     break;
3324   }
3325   case ISD::TRUNCATE: {
3326     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3327     Known = Known.trunc(BitWidth);
3328     break;
3329   }
3330   case ISD::AssertZext: {
3331     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3332     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3333     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3334     Known.Zero |= (~InMask);
3335     Known.One  &= (~Known.Zero);
3336     break;
3337   }
3338   case ISD::AssertAlign: {
3339     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3340     assert(LogOfAlign != 0);
3341     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3342     // well as clearing one bits.
3343     Known.Zero.setLowBits(LogOfAlign);
3344     Known.One.clearLowBits(LogOfAlign);
3345     break;
3346   }
3347   case ISD::FGETSIGN:
3348     // All bits are zero except the low bit.
3349     Known.Zero.setBitsFrom(1);
3350     break;
3351   case ISD::USUBO:
3352   case ISD::SSUBO:
3353     if (Op.getResNo() == 1) {
3354       // If we know the result of a setcc has the top bits zero, use this info.
3355       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3356               TargetLowering::ZeroOrOneBooleanContent &&
3357           BitWidth > 1)
3358         Known.Zero.setBitsFrom(1);
3359       break;
3360     }
3361     LLVM_FALLTHROUGH;
3362   case ISD::SUB:
3363   case ISD::SUBC: {
3364     assert(Op.getResNo() == 0 &&
3365            "We only compute knownbits for the difference here.");
3366 
3367     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3368     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3369     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3370                                         Known, Known2);
3371     break;
3372   }
3373   case ISD::UADDO:
3374   case ISD::SADDO:
3375   case ISD::ADDCARRY:
3376     if (Op.getResNo() == 1) {
3377       // If we know the result of a setcc has the top bits zero, use this info.
3378       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3379               TargetLowering::ZeroOrOneBooleanContent &&
3380           BitWidth > 1)
3381         Known.Zero.setBitsFrom(1);
3382       break;
3383     }
3384     LLVM_FALLTHROUGH;
3385   case ISD::ADD:
3386   case ISD::ADDC:
3387   case ISD::ADDE: {
3388     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3389 
3390     // With ADDE and ADDCARRY, a carry bit may be added in.
3391     KnownBits Carry(1);
3392     if (Opcode == ISD::ADDE)
3393       // Can't track carry from glue, set carry to unknown.
3394       Carry.resetAll();
3395     else if (Opcode == ISD::ADDCARRY)
3396       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3397       // the trouble (how often will we find a known carry bit). And I haven't
3398       // tested this very much yet, but something like this might work:
3399       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3400       //   Carry = Carry.zextOrTrunc(1, false);
3401       Carry.resetAll();
3402     else
3403       Carry.setAllZero();
3404 
3405     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3406     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3407     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3408     break;
3409   }
3410   case ISD::SREM: {
3411     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3412     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3413     Known = KnownBits::srem(Known, Known2);
3414     break;
3415   }
3416   case ISD::UREM: {
3417     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3418     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3419     Known = KnownBits::urem(Known, Known2);
3420     break;
3421   }
3422   case ISD::EXTRACT_ELEMENT: {
3423     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3424     const unsigned Index = Op.getConstantOperandVal(1);
3425     const unsigned EltBitWidth = Op.getValueSizeInBits();
3426 
3427     // Remove low part of known bits mask
3428     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3429     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3430 
3431     // Remove high part of known bit mask
3432     Known = Known.trunc(EltBitWidth);
3433     break;
3434   }
3435   case ISD::EXTRACT_VECTOR_ELT: {
3436     SDValue InVec = Op.getOperand(0);
3437     SDValue EltNo = Op.getOperand(1);
3438     EVT VecVT = InVec.getValueType();
3439     // computeKnownBits not yet implemented for scalable vectors.
3440     if (VecVT.isScalableVector())
3441       break;
3442     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3443     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3444 
3445     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3446     // anything about the extended bits.
3447     if (BitWidth > EltBitWidth)
3448       Known = Known.trunc(EltBitWidth);
3449 
3450     // If we know the element index, just demand that vector element, else for
3451     // an unknown element index, ignore DemandedElts and demand them all.
3452     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3453     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3454     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3455       DemandedSrcElts =
3456           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3457 
3458     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3459     if (BitWidth > EltBitWidth)
3460       Known = Known.anyext(BitWidth);
3461     break;
3462   }
3463   case ISD::INSERT_VECTOR_ELT: {
3464     // If we know the element index, split the demand between the
3465     // source vector and the inserted element, otherwise assume we need
3466     // the original demanded vector elements and the value.
3467     SDValue InVec = Op.getOperand(0);
3468     SDValue InVal = Op.getOperand(1);
3469     SDValue EltNo = Op.getOperand(2);
3470     bool DemandedVal = true;
3471     APInt DemandedVecElts = DemandedElts;
3472     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3473     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3474       unsigned EltIdx = CEltNo->getZExtValue();
3475       DemandedVal = !!DemandedElts[EltIdx];
3476       DemandedVecElts.clearBit(EltIdx);
3477     }
3478     Known.One.setAllBits();
3479     Known.Zero.setAllBits();
3480     if (DemandedVal) {
3481       Known2 = computeKnownBits(InVal, Depth + 1);
3482       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3483     }
3484     if (!!DemandedVecElts) {
3485       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3486       Known = KnownBits::commonBits(Known, Known2);
3487     }
3488     break;
3489   }
3490   case ISD::BITREVERSE: {
3491     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3492     Known = Known2.reverseBits();
3493     break;
3494   }
3495   case ISD::BSWAP: {
3496     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3497     Known = Known2.byteSwap();
3498     break;
3499   }
3500   case ISD::ABS: {
3501     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3502     Known = Known2.abs();
3503     break;
3504   }
3505   case ISD::USUBSAT: {
3506     // The result of usubsat will never be larger than the LHS.
3507     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3508     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3509     break;
3510   }
3511   case ISD::UMIN: {
3512     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3513     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3514     Known = KnownBits::umin(Known, Known2);
3515     break;
3516   }
3517   case ISD::UMAX: {
3518     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3519     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3520     Known = KnownBits::umax(Known, Known2);
3521     break;
3522   }
3523   case ISD::SMIN:
3524   case ISD::SMAX: {
3525     // If we have a clamp pattern, we know that the number of sign bits will be
3526     // the minimum of the clamp min/max range.
3527     bool IsMax = (Opcode == ISD::SMAX);
3528     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3529     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3530       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3531         CstHigh =
3532             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3533     if (CstLow && CstHigh) {
3534       if (!IsMax)
3535         std::swap(CstLow, CstHigh);
3536 
3537       const APInt &ValueLow = CstLow->getAPIntValue();
3538       const APInt &ValueHigh = CstHigh->getAPIntValue();
3539       if (ValueLow.sle(ValueHigh)) {
3540         unsigned LowSignBits = ValueLow.getNumSignBits();
3541         unsigned HighSignBits = ValueHigh.getNumSignBits();
3542         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3543         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3544           Known.One.setHighBits(MinSignBits);
3545           break;
3546         }
3547         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3548           Known.Zero.setHighBits(MinSignBits);
3549           break;
3550         }
3551       }
3552     }
3553 
3554     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3555     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3556     if (IsMax)
3557       Known = KnownBits::smax(Known, Known2);
3558     else
3559       Known = KnownBits::smin(Known, Known2);
3560     break;
3561   }
3562   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3563     if (Op.getResNo() == 1) {
3564       // The boolean result conforms to getBooleanContents.
3565       // If we know the result of a setcc has the top bits zero, use this info.
3566       // We know that we have an integer-based boolean since these operations
3567       // are only available for integer.
3568       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3569               TargetLowering::ZeroOrOneBooleanContent &&
3570           BitWidth > 1)
3571         Known.Zero.setBitsFrom(1);
3572       break;
3573     }
3574     LLVM_FALLTHROUGH;
3575   case ISD::ATOMIC_CMP_SWAP:
3576   case ISD::ATOMIC_SWAP:
3577   case ISD::ATOMIC_LOAD_ADD:
3578   case ISD::ATOMIC_LOAD_SUB:
3579   case ISD::ATOMIC_LOAD_AND:
3580   case ISD::ATOMIC_LOAD_CLR:
3581   case ISD::ATOMIC_LOAD_OR:
3582   case ISD::ATOMIC_LOAD_XOR:
3583   case ISD::ATOMIC_LOAD_NAND:
3584   case ISD::ATOMIC_LOAD_MIN:
3585   case ISD::ATOMIC_LOAD_MAX:
3586   case ISD::ATOMIC_LOAD_UMIN:
3587   case ISD::ATOMIC_LOAD_UMAX:
3588   case ISD::ATOMIC_LOAD: {
3589     unsigned MemBits =
3590         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3591     // If we are looking at the loaded value.
3592     if (Op.getResNo() == 0) {
3593       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3594         Known.Zero.setBitsFrom(MemBits);
3595     }
3596     break;
3597   }
3598   case ISD::FrameIndex:
3599   case ISD::TargetFrameIndex:
3600     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3601                                        Known, getMachineFunction());
3602     break;
3603 
3604   default:
3605     if (Opcode < ISD::BUILTIN_OP_END)
3606       break;
3607     LLVM_FALLTHROUGH;
3608   case ISD::INTRINSIC_WO_CHAIN:
3609   case ISD::INTRINSIC_W_CHAIN:
3610   case ISD::INTRINSIC_VOID:
3611     // Allow the target to implement this method for its nodes.
3612     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3613     break;
3614   }
3615 
3616   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3617   return Known;
3618 }
3619 
3620 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3621                                                              SDValue N1) const {
3622   // X + 0 never overflow
3623   if (isNullConstant(N1))
3624     return OFK_Never;
3625 
3626   KnownBits N1Known = computeKnownBits(N1);
3627   if (N1Known.Zero.getBoolValue()) {
3628     KnownBits N0Known = computeKnownBits(N0);
3629 
3630     bool overflow;
3631     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3632     if (!overflow)
3633       return OFK_Never;
3634   }
3635 
3636   // mulhi + 1 never overflow
3637   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3638       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3639     return OFK_Never;
3640 
3641   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3642     KnownBits N0Known = computeKnownBits(N0);
3643 
3644     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3645       return OFK_Never;
3646   }
3647 
3648   return OFK_Sometime;
3649 }
3650 
3651 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3652   EVT OpVT = Val.getValueType();
3653   unsigned BitWidth = OpVT.getScalarSizeInBits();
3654 
3655   // Is the constant a known power of 2?
3656   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3657     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3658 
3659   // A left-shift of a constant one will have exactly one bit set because
3660   // shifting the bit off the end is undefined.
3661   if (Val.getOpcode() == ISD::SHL) {
3662     auto *C = isConstOrConstSplat(Val.getOperand(0));
3663     if (C && C->getAPIntValue() == 1)
3664       return true;
3665   }
3666 
3667   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3668   // one bit set.
3669   if (Val.getOpcode() == ISD::SRL) {
3670     auto *C = isConstOrConstSplat(Val.getOperand(0));
3671     if (C && C->getAPIntValue().isSignMask())
3672       return true;
3673   }
3674 
3675   // Are all operands of a build vector constant powers of two?
3676   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3677     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3678           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3679             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3680           return false;
3681         }))
3682       return true;
3683 
3684   // Is the operand of a splat vector a constant power of two?
3685   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3686     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3687       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3688         return true;
3689 
3690   // More could be done here, though the above checks are enough
3691   // to handle some common cases.
3692 
3693   // Fall back to computeKnownBits to catch other known cases.
3694   KnownBits Known = computeKnownBits(Val);
3695   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3696 }
3697 
3698 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3699   EVT VT = Op.getValueType();
3700 
3701   // TODO: Assume we don't know anything for now.
3702   if (VT.isScalableVector())
3703     return 1;
3704 
3705   APInt DemandedElts = VT.isVector()
3706                            ? APInt::getAllOnes(VT.getVectorNumElements())
3707                            : APInt(1, 1);
3708   return ComputeNumSignBits(Op, DemandedElts, Depth);
3709 }
3710 
3711 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3712                                           unsigned Depth) const {
3713   EVT VT = Op.getValueType();
3714   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3715   unsigned VTBits = VT.getScalarSizeInBits();
3716   unsigned NumElts = DemandedElts.getBitWidth();
3717   unsigned Tmp, Tmp2;
3718   unsigned FirstAnswer = 1;
3719 
3720   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3721     const APInt &Val = C->getAPIntValue();
3722     return Val.getNumSignBits();
3723   }
3724 
3725   if (Depth >= MaxRecursionDepth)
3726     return 1;  // Limit search depth.
3727 
3728   if (!DemandedElts || VT.isScalableVector())
3729     return 1;  // No demanded elts, better to assume we don't know anything.
3730 
3731   unsigned Opcode = Op.getOpcode();
3732   switch (Opcode) {
3733   default: break;
3734   case ISD::AssertSext:
3735     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3736     return VTBits-Tmp+1;
3737   case ISD::AssertZext:
3738     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3739     return VTBits-Tmp;
3740 
3741   case ISD::BUILD_VECTOR:
3742     Tmp = VTBits;
3743     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3744       if (!DemandedElts[i])
3745         continue;
3746 
3747       SDValue SrcOp = Op.getOperand(i);
3748       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3749 
3750       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3751       if (SrcOp.getValueSizeInBits() != VTBits) {
3752         assert(SrcOp.getValueSizeInBits() > VTBits &&
3753                "Expected BUILD_VECTOR implicit truncation");
3754         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3755         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3756       }
3757       Tmp = std::min(Tmp, Tmp2);
3758     }
3759     return Tmp;
3760 
3761   case ISD::VECTOR_SHUFFLE: {
3762     // Collect the minimum number of sign bits that are shared by every vector
3763     // element referenced by the shuffle.
3764     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3765     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3766     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3767     for (unsigned i = 0; i != NumElts; ++i) {
3768       int M = SVN->getMaskElt(i);
3769       if (!DemandedElts[i])
3770         continue;
3771       // For UNDEF elements, we don't know anything about the common state of
3772       // the shuffle result.
3773       if (M < 0)
3774         return 1;
3775       if ((unsigned)M < NumElts)
3776         DemandedLHS.setBit((unsigned)M % NumElts);
3777       else
3778         DemandedRHS.setBit((unsigned)M % NumElts);
3779     }
3780     Tmp = std::numeric_limits<unsigned>::max();
3781     if (!!DemandedLHS)
3782       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3783     if (!!DemandedRHS) {
3784       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3785       Tmp = std::min(Tmp, Tmp2);
3786     }
3787     // If we don't know anything, early out and try computeKnownBits fall-back.
3788     if (Tmp == 1)
3789       break;
3790     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3791     return Tmp;
3792   }
3793 
3794   case ISD::BITCAST: {
3795     SDValue N0 = Op.getOperand(0);
3796     EVT SrcVT = N0.getValueType();
3797     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3798 
3799     // Ignore bitcasts from unsupported types..
3800     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3801       break;
3802 
3803     // Fast handling of 'identity' bitcasts.
3804     if (VTBits == SrcBits)
3805       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3806 
3807     bool IsLE = getDataLayout().isLittleEndian();
3808 
3809     // Bitcast 'large element' scalar/vector to 'small element' vector.
3810     if ((SrcBits % VTBits) == 0) {
3811       assert(VT.isVector() && "Expected bitcast to vector");
3812 
3813       unsigned Scale = SrcBits / VTBits;
3814       APInt SrcDemandedElts =
3815           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3816 
3817       // Fast case - sign splat can be simply split across the small elements.
3818       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3819       if (Tmp == SrcBits)
3820         return VTBits;
3821 
3822       // Slow case - determine how far the sign extends into each sub-element.
3823       Tmp2 = VTBits;
3824       for (unsigned i = 0; i != NumElts; ++i)
3825         if (DemandedElts[i]) {
3826           unsigned SubOffset = i % Scale;
3827           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3828           SubOffset = SubOffset * VTBits;
3829           if (Tmp <= SubOffset)
3830             return 1;
3831           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3832         }
3833       return Tmp2;
3834     }
3835     break;
3836   }
3837 
3838   case ISD::SIGN_EXTEND:
3839     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3840     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3841   case ISD::SIGN_EXTEND_INREG:
3842     // Max of the input and what this extends.
3843     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3844     Tmp = VTBits-Tmp+1;
3845     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3846     return std::max(Tmp, Tmp2);
3847   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3848     SDValue Src = Op.getOperand(0);
3849     EVT SrcVT = Src.getValueType();
3850     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3851     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3852     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3853   }
3854   case ISD::SRA:
3855     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3856     // SRA X, C -> adds C sign bits.
3857     if (const APInt *ShAmt =
3858             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3859       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3860     return Tmp;
3861   case ISD::SHL:
3862     if (const APInt *ShAmt =
3863             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3864       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3865       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3866       if (ShAmt->ult(Tmp))
3867         return Tmp - ShAmt->getZExtValue();
3868     }
3869     break;
3870   case ISD::AND:
3871   case ISD::OR:
3872   case ISD::XOR:    // NOT is handled here.
3873     // Logical binary ops preserve the number of sign bits at the worst.
3874     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3875     if (Tmp != 1) {
3876       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3877       FirstAnswer = std::min(Tmp, Tmp2);
3878       // We computed what we know about the sign bits as our first
3879       // answer. Now proceed to the generic code that uses
3880       // computeKnownBits, and pick whichever answer is better.
3881     }
3882     break;
3883 
3884   case ISD::SELECT:
3885   case ISD::VSELECT:
3886     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3887     if (Tmp == 1) return 1;  // Early out.
3888     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3889     return std::min(Tmp, Tmp2);
3890   case ISD::SELECT_CC:
3891     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3892     if (Tmp == 1) return 1;  // Early out.
3893     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3894     return std::min(Tmp, Tmp2);
3895 
3896   case ISD::SMIN:
3897   case ISD::SMAX: {
3898     // If we have a clamp pattern, we know that the number of sign bits will be
3899     // the minimum of the clamp min/max range.
3900     bool IsMax = (Opcode == ISD::SMAX);
3901     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3902     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3903       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3904         CstHigh =
3905             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3906     if (CstLow && CstHigh) {
3907       if (!IsMax)
3908         std::swap(CstLow, CstHigh);
3909       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3910         Tmp = CstLow->getAPIntValue().getNumSignBits();
3911         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3912         return std::min(Tmp, Tmp2);
3913       }
3914     }
3915 
3916     // Fallback - just get the minimum number of sign bits of the operands.
3917     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3918     if (Tmp == 1)
3919       return 1;  // Early out.
3920     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3921     return std::min(Tmp, Tmp2);
3922   }
3923   case ISD::UMIN:
3924   case ISD::UMAX:
3925     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3926     if (Tmp == 1)
3927       return 1;  // Early out.
3928     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3929     return std::min(Tmp, Tmp2);
3930   case ISD::SADDO:
3931   case ISD::UADDO:
3932   case ISD::SSUBO:
3933   case ISD::USUBO:
3934   case ISD::SMULO:
3935   case ISD::UMULO:
3936     if (Op.getResNo() != 1)
3937       break;
3938     // The boolean result conforms to getBooleanContents.  Fall through.
3939     // If setcc returns 0/-1, all bits are sign bits.
3940     // We know that we have an integer-based boolean since these operations
3941     // are only available for integer.
3942     if (TLI->getBooleanContents(VT.isVector(), false) ==
3943         TargetLowering::ZeroOrNegativeOneBooleanContent)
3944       return VTBits;
3945     break;
3946   case ISD::SETCC:
3947   case ISD::STRICT_FSETCC:
3948   case ISD::STRICT_FSETCCS: {
3949     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3950     // If setcc returns 0/-1, all bits are sign bits.
3951     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3952         TargetLowering::ZeroOrNegativeOneBooleanContent)
3953       return VTBits;
3954     break;
3955   }
3956   case ISD::ROTL:
3957   case ISD::ROTR:
3958     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3959 
3960     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3961     if (Tmp == VTBits)
3962       return VTBits;
3963 
3964     if (ConstantSDNode *C =
3965             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3966       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3967 
3968       // Handle rotate right by N like a rotate left by 32-N.
3969       if (Opcode == ISD::ROTR)
3970         RotAmt = (VTBits - RotAmt) % VTBits;
3971 
3972       // If we aren't rotating out all of the known-in sign bits, return the
3973       // number that are left.  This handles rotl(sext(x), 1) for example.
3974       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3975     }
3976     break;
3977   case ISD::ADD:
3978   case ISD::ADDC:
3979     // Add can have at most one carry bit.  Thus we know that the output
3980     // is, at worst, one more bit than the inputs.
3981     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3982     if (Tmp == 1) return 1; // Early out.
3983 
3984     // Special case decrementing a value (ADD X, -1):
3985     if (ConstantSDNode *CRHS =
3986             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3987       if (CRHS->isAllOnes()) {
3988         KnownBits Known =
3989             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3990 
3991         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3992         // sign bits set.
3993         if ((Known.Zero | 1).isAllOnes())
3994           return VTBits;
3995 
3996         // If we are subtracting one from a positive number, there is no carry
3997         // out of the result.
3998         if (Known.isNonNegative())
3999           return Tmp;
4000       }
4001 
4002     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4003     if (Tmp2 == 1) return 1; // Early out.
4004     return std::min(Tmp, Tmp2) - 1;
4005   case ISD::SUB:
4006     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4007     if (Tmp2 == 1) return 1; // Early out.
4008 
4009     // Handle NEG.
4010     if (ConstantSDNode *CLHS =
4011             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4012       if (CLHS->isZero()) {
4013         KnownBits Known =
4014             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4015         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4016         // sign bits set.
4017         if ((Known.Zero | 1).isAllOnes())
4018           return VTBits;
4019 
4020         // If the input is known to be positive (the sign bit is known clear),
4021         // the output of the NEG has the same number of sign bits as the input.
4022         if (Known.isNonNegative())
4023           return Tmp2;
4024 
4025         // Otherwise, we treat this like a SUB.
4026       }
4027 
4028     // Sub can have at most one carry bit.  Thus we know that the output
4029     // is, at worst, one more bit than the inputs.
4030     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4031     if (Tmp == 1) return 1; // Early out.
4032     return std::min(Tmp, Tmp2) - 1;
4033   case ISD::MUL: {
4034     // The output of the Mul can be at most twice the valid bits in the inputs.
4035     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4036     if (SignBitsOp0 == 1)
4037       break;
4038     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4039     if (SignBitsOp1 == 1)
4040       break;
4041     unsigned OutValidBits =
4042         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4043     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4044   }
4045   case ISD::SREM:
4046     // The sign bit is the LHS's sign bit, except when the result of the
4047     // remainder is zero. The magnitude of the result should be less than or
4048     // equal to the magnitude of the LHS. Therefore, the result should have
4049     // at least as many sign bits as the left hand side.
4050     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4051   case ISD::TRUNCATE: {
4052     // Check if the sign bits of source go down as far as the truncated value.
4053     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4054     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4055     if (NumSrcSignBits > (NumSrcBits - VTBits))
4056       return NumSrcSignBits - (NumSrcBits - VTBits);
4057     break;
4058   }
4059   case ISD::EXTRACT_ELEMENT: {
4060     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4061     const int BitWidth = Op.getValueSizeInBits();
4062     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4063 
4064     // Get reverse index (starting from 1), Op1 value indexes elements from
4065     // little end. Sign starts at big end.
4066     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4067 
4068     // If the sign portion ends in our element the subtraction gives correct
4069     // result. Otherwise it gives either negative or > bitwidth result
4070     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4071   }
4072   case ISD::INSERT_VECTOR_ELT: {
4073     // If we know the element index, split the demand between the
4074     // source vector and the inserted element, otherwise assume we need
4075     // the original demanded vector elements and the value.
4076     SDValue InVec = Op.getOperand(0);
4077     SDValue InVal = Op.getOperand(1);
4078     SDValue EltNo = Op.getOperand(2);
4079     bool DemandedVal = true;
4080     APInt DemandedVecElts = DemandedElts;
4081     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4082     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4083       unsigned EltIdx = CEltNo->getZExtValue();
4084       DemandedVal = !!DemandedElts[EltIdx];
4085       DemandedVecElts.clearBit(EltIdx);
4086     }
4087     Tmp = std::numeric_limits<unsigned>::max();
4088     if (DemandedVal) {
4089       // TODO - handle implicit truncation of inserted elements.
4090       if (InVal.getScalarValueSizeInBits() != VTBits)
4091         break;
4092       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4093       Tmp = std::min(Tmp, Tmp2);
4094     }
4095     if (!!DemandedVecElts) {
4096       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4097       Tmp = std::min(Tmp, Tmp2);
4098     }
4099     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4100     return Tmp;
4101   }
4102   case ISD::EXTRACT_VECTOR_ELT: {
4103     SDValue InVec = Op.getOperand(0);
4104     SDValue EltNo = Op.getOperand(1);
4105     EVT VecVT = InVec.getValueType();
4106     // ComputeNumSignBits not yet implemented for scalable vectors.
4107     if (VecVT.isScalableVector())
4108       break;
4109     const unsigned BitWidth = Op.getValueSizeInBits();
4110     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4111     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4112 
4113     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4114     // anything about sign bits. But if the sizes match we can derive knowledge
4115     // about sign bits from the vector operand.
4116     if (BitWidth != EltBitWidth)
4117       break;
4118 
4119     // If we know the element index, just demand that vector element, else for
4120     // an unknown element index, ignore DemandedElts and demand them all.
4121     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4122     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4123     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4124       DemandedSrcElts =
4125           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4126 
4127     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4128   }
4129   case ISD::EXTRACT_SUBVECTOR: {
4130     // Offset the demanded elts by the subvector index.
4131     SDValue Src = Op.getOperand(0);
4132     // Bail until we can represent demanded elements for scalable vectors.
4133     if (Src.getValueType().isScalableVector())
4134       break;
4135     uint64_t Idx = Op.getConstantOperandVal(1);
4136     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4137     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4138     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4139   }
4140   case ISD::CONCAT_VECTORS: {
4141     // Determine the minimum number of sign bits across all demanded
4142     // elts of the input vectors. Early out if the result is already 1.
4143     Tmp = std::numeric_limits<unsigned>::max();
4144     EVT SubVectorVT = Op.getOperand(0).getValueType();
4145     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4146     unsigned NumSubVectors = Op.getNumOperands();
4147     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4148       APInt DemandedSub =
4149           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4150       if (!DemandedSub)
4151         continue;
4152       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4153       Tmp = std::min(Tmp, Tmp2);
4154     }
4155     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4156     return Tmp;
4157   }
4158   case ISD::INSERT_SUBVECTOR: {
4159     // Demand any elements from the subvector and the remainder from the src its
4160     // inserted into.
4161     SDValue Src = Op.getOperand(0);
4162     SDValue Sub = Op.getOperand(1);
4163     uint64_t Idx = Op.getConstantOperandVal(2);
4164     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4165     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4166     APInt DemandedSrcElts = DemandedElts;
4167     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4168 
4169     Tmp = std::numeric_limits<unsigned>::max();
4170     if (!!DemandedSubElts) {
4171       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4172       if (Tmp == 1)
4173         return 1; // early-out
4174     }
4175     if (!!DemandedSrcElts) {
4176       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4177       Tmp = std::min(Tmp, Tmp2);
4178     }
4179     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4180     return Tmp;
4181   }
4182   case ISD::ATOMIC_CMP_SWAP:
4183   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4184   case ISD::ATOMIC_SWAP:
4185   case ISD::ATOMIC_LOAD_ADD:
4186   case ISD::ATOMIC_LOAD_SUB:
4187   case ISD::ATOMIC_LOAD_AND:
4188   case ISD::ATOMIC_LOAD_CLR:
4189   case ISD::ATOMIC_LOAD_OR:
4190   case ISD::ATOMIC_LOAD_XOR:
4191   case ISD::ATOMIC_LOAD_NAND:
4192   case ISD::ATOMIC_LOAD_MIN:
4193   case ISD::ATOMIC_LOAD_MAX:
4194   case ISD::ATOMIC_LOAD_UMIN:
4195   case ISD::ATOMIC_LOAD_UMAX:
4196   case ISD::ATOMIC_LOAD: {
4197     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4198     // If we are looking at the loaded value.
4199     if (Op.getResNo() == 0) {
4200       if (Tmp == VTBits)
4201         return 1; // early-out
4202       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4203         return VTBits - Tmp + 1;
4204       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4205         return VTBits - Tmp;
4206     }
4207     break;
4208   }
4209   }
4210 
4211   // If we are looking at the loaded value of the SDNode.
4212   if (Op.getResNo() == 0) {
4213     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4214     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4215       unsigned ExtType = LD->getExtensionType();
4216       switch (ExtType) {
4217       default: break;
4218       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4219         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4220         return VTBits - Tmp + 1;
4221       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4222         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4223         return VTBits - Tmp;
4224       case ISD::NON_EXTLOAD:
4225         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4226           // We only need to handle vectors - computeKnownBits should handle
4227           // scalar cases.
4228           Type *CstTy = Cst->getType();
4229           if (CstTy->isVectorTy() &&
4230               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4231             Tmp = VTBits;
4232             for (unsigned i = 0; i != NumElts; ++i) {
4233               if (!DemandedElts[i])
4234                 continue;
4235               if (Constant *Elt = Cst->getAggregateElement(i)) {
4236                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4237                   const APInt &Value = CInt->getValue();
4238                   Tmp = std::min(Tmp, Value.getNumSignBits());
4239                   continue;
4240                 }
4241                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4242                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4243                   Tmp = std::min(Tmp, Value.getNumSignBits());
4244                   continue;
4245                 }
4246               }
4247               // Unknown type. Conservatively assume no bits match sign bit.
4248               return 1;
4249             }
4250             return Tmp;
4251           }
4252         }
4253         break;
4254       }
4255     }
4256   }
4257 
4258   // Allow the target to implement this method for its nodes.
4259   if (Opcode >= ISD::BUILTIN_OP_END ||
4260       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4261       Opcode == ISD::INTRINSIC_W_CHAIN ||
4262       Opcode == ISD::INTRINSIC_VOID) {
4263     unsigned NumBits =
4264         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4265     if (NumBits > 1)
4266       FirstAnswer = std::max(FirstAnswer, NumBits);
4267   }
4268 
4269   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4270   // use this information.
4271   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4272 
4273   APInt Mask;
4274   if (Known.isNonNegative()) {        // sign bit is 0
4275     Mask = Known.Zero;
4276   } else if (Known.isNegative()) {  // sign bit is 1;
4277     Mask = Known.One;
4278   } else {
4279     // Nothing known.
4280     return FirstAnswer;
4281   }
4282 
4283   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4284   // the number of identical bits in the top of the input value.
4285   Mask <<= Mask.getBitWidth()-VTBits;
4286   return std::max(FirstAnswer, Mask.countLeadingOnes());
4287 }
4288 
4289 unsigned SelectionDAG::ComputeMinSignedBits(SDValue Op, unsigned Depth) const {
4290   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4291   return Op.getScalarValueSizeInBits() - SignBits + 1;
4292 }
4293 
4294 unsigned SelectionDAG::ComputeMinSignedBits(SDValue Op,
4295                                             const APInt &DemandedElts,
4296                                             unsigned Depth) const {
4297   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4298   return Op.getScalarValueSizeInBits() - SignBits + 1;
4299 }
4300 
4301 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4302                                                     unsigned Depth) const {
4303   // Early out for FREEZE.
4304   if (Op.getOpcode() == ISD::FREEZE)
4305     return true;
4306 
4307   // TODO: Assume we don't know anything for now.
4308   EVT VT = Op.getValueType();
4309   if (VT.isScalableVector())
4310     return false;
4311 
4312   APInt DemandedElts = VT.isVector()
4313                            ? APInt::getAllOnes(VT.getVectorNumElements())
4314                            : APInt(1, 1);
4315   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4316 }
4317 
4318 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4319                                                     const APInt &DemandedElts,
4320                                                     bool PoisonOnly,
4321                                                     unsigned Depth) const {
4322   unsigned Opcode = Op.getOpcode();
4323 
4324   // Early out for FREEZE.
4325   if (Opcode == ISD::FREEZE)
4326     return true;
4327 
4328   if (Depth >= MaxRecursionDepth)
4329     return false; // Limit search depth.
4330 
4331   if (isIntOrFPConstant(Op))
4332     return true;
4333 
4334   switch (Opcode) {
4335   case ISD::UNDEF:
4336     return PoisonOnly;
4337 
4338   case ISD::BUILD_VECTOR:
4339     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4340     // this shouldn't affect the result.
4341     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4342       if (!DemandedElts[i])
4343         continue;
4344       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4345                                             Depth + 1))
4346         return false;
4347     }
4348     return true;
4349 
4350   // TODO: Search for noundef attributes from library functions.
4351 
4352   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4353 
4354   default:
4355     // Allow the target to implement this method for its nodes.
4356     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4357         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4358       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4359           Op, DemandedElts, *this, PoisonOnly, Depth);
4360     break;
4361   }
4362 
4363   return false;
4364 }
4365 
4366 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4367   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4368       !isa<ConstantSDNode>(Op.getOperand(1)))
4369     return false;
4370 
4371   if (Op.getOpcode() == ISD::OR &&
4372       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4373     return false;
4374 
4375   return true;
4376 }
4377 
4378 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4379   // If we're told that NaNs won't happen, assume they won't.
4380   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4381     return true;
4382 
4383   if (Depth >= MaxRecursionDepth)
4384     return false; // Limit search depth.
4385 
4386   // TODO: Handle vectors.
4387   // If the value is a constant, we can obviously see if it is a NaN or not.
4388   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4389     return !C->getValueAPF().isNaN() ||
4390            (SNaN && !C->getValueAPF().isSignaling());
4391   }
4392 
4393   unsigned Opcode = Op.getOpcode();
4394   switch (Opcode) {
4395   case ISD::FADD:
4396   case ISD::FSUB:
4397   case ISD::FMUL:
4398   case ISD::FDIV:
4399   case ISD::FREM:
4400   case ISD::FSIN:
4401   case ISD::FCOS: {
4402     if (SNaN)
4403       return true;
4404     // TODO: Need isKnownNeverInfinity
4405     return false;
4406   }
4407   case ISD::FCANONICALIZE:
4408   case ISD::FEXP:
4409   case ISD::FEXP2:
4410   case ISD::FTRUNC:
4411   case ISD::FFLOOR:
4412   case ISD::FCEIL:
4413   case ISD::FROUND:
4414   case ISD::FROUNDEVEN:
4415   case ISD::FRINT:
4416   case ISD::FNEARBYINT: {
4417     if (SNaN)
4418       return true;
4419     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4420   }
4421   case ISD::FABS:
4422   case ISD::FNEG:
4423   case ISD::FCOPYSIGN: {
4424     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4425   }
4426   case ISD::SELECT:
4427     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4428            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4429   case ISD::FP_EXTEND:
4430   case ISD::FP_ROUND: {
4431     if (SNaN)
4432       return true;
4433     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4434   }
4435   case ISD::SINT_TO_FP:
4436   case ISD::UINT_TO_FP:
4437     return true;
4438   case ISD::FMA:
4439   case ISD::FMAD: {
4440     if (SNaN)
4441       return true;
4442     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4443            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4444            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4445   }
4446   case ISD::FSQRT: // Need is known positive
4447   case ISD::FLOG:
4448   case ISD::FLOG2:
4449   case ISD::FLOG10:
4450   case ISD::FPOWI:
4451   case ISD::FPOW: {
4452     if (SNaN)
4453       return true;
4454     // TODO: Refine on operand
4455     return false;
4456   }
4457   case ISD::FMINNUM:
4458   case ISD::FMAXNUM: {
4459     // Only one needs to be known not-nan, since it will be returned if the
4460     // other ends up being one.
4461     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4462            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4463   }
4464   case ISD::FMINNUM_IEEE:
4465   case ISD::FMAXNUM_IEEE: {
4466     if (SNaN)
4467       return true;
4468     // This can return a NaN if either operand is an sNaN, or if both operands
4469     // are NaN.
4470     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4471             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4472            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4473             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4474   }
4475   case ISD::FMINIMUM:
4476   case ISD::FMAXIMUM: {
4477     // TODO: Does this quiet or return the origina NaN as-is?
4478     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4479            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4480   }
4481   case ISD::EXTRACT_VECTOR_ELT: {
4482     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4483   }
4484   default:
4485     if (Opcode >= ISD::BUILTIN_OP_END ||
4486         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4487         Opcode == ISD::INTRINSIC_W_CHAIN ||
4488         Opcode == ISD::INTRINSIC_VOID) {
4489       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4490     }
4491 
4492     return false;
4493   }
4494 }
4495 
4496 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4497   assert(Op.getValueType().isFloatingPoint() &&
4498          "Floating point type expected");
4499 
4500   // If the value is a constant, we can obviously see if it is a zero or not.
4501   // TODO: Add BuildVector support.
4502   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4503     return !C->isZero();
4504   return false;
4505 }
4506 
4507 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4508   assert(!Op.getValueType().isFloatingPoint() &&
4509          "Floating point types unsupported - use isKnownNeverZeroFloat");
4510 
4511   // If the value is a constant, we can obviously see if it is a zero or not.
4512   if (ISD::matchUnaryPredicate(Op,
4513                                [](ConstantSDNode *C) { return !C->isZero(); }))
4514     return true;
4515 
4516   // TODO: Recognize more cases here.
4517   switch (Op.getOpcode()) {
4518   default: break;
4519   case ISD::OR:
4520     if (isKnownNeverZero(Op.getOperand(1)) ||
4521         isKnownNeverZero(Op.getOperand(0)))
4522       return true;
4523     break;
4524   }
4525 
4526   return false;
4527 }
4528 
4529 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4530   // Check the obvious case.
4531   if (A == B) return true;
4532 
4533   // For for negative and positive zero.
4534   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4535     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4536       if (CA->isZero() && CB->isZero()) return true;
4537 
4538   // Otherwise they may not be equal.
4539   return false;
4540 }
4541 
4542 // FIXME: unify with llvm::haveNoCommonBitsSet.
4543 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4544 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4545   assert(A.getValueType() == B.getValueType() &&
4546          "Values must have the same type");
4547   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4548                                         computeKnownBits(B));
4549 }
4550 
4551 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4552                                SelectionDAG &DAG) {
4553   if (cast<ConstantSDNode>(Step)->isZero())
4554     return DAG.getConstant(0, DL, VT);
4555 
4556   return SDValue();
4557 }
4558 
4559 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4560                                 ArrayRef<SDValue> Ops,
4561                                 SelectionDAG &DAG) {
4562   int NumOps = Ops.size();
4563   assert(NumOps != 0 && "Can't build an empty vector!");
4564   assert(!VT.isScalableVector() &&
4565          "BUILD_VECTOR cannot be used with scalable types");
4566   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4567          "Incorrect element count in BUILD_VECTOR!");
4568 
4569   // BUILD_VECTOR of UNDEFs is UNDEF.
4570   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4571     return DAG.getUNDEF(VT);
4572 
4573   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4574   SDValue IdentitySrc;
4575   bool IsIdentity = true;
4576   for (int i = 0; i != NumOps; ++i) {
4577     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4578         Ops[i].getOperand(0).getValueType() != VT ||
4579         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4580         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4581         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4582       IsIdentity = false;
4583       break;
4584     }
4585     IdentitySrc = Ops[i].getOperand(0);
4586   }
4587   if (IsIdentity)
4588     return IdentitySrc;
4589 
4590   return SDValue();
4591 }
4592 
4593 /// Try to simplify vector concatenation to an input value, undef, or build
4594 /// vector.
4595 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4596                                   ArrayRef<SDValue> Ops,
4597                                   SelectionDAG &DAG) {
4598   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4599   assert(llvm::all_of(Ops,
4600                       [Ops](SDValue Op) {
4601                         return Ops[0].getValueType() == Op.getValueType();
4602                       }) &&
4603          "Concatenation of vectors with inconsistent value types!");
4604   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4605              VT.getVectorElementCount() &&
4606          "Incorrect element count in vector concatenation!");
4607 
4608   if (Ops.size() == 1)
4609     return Ops[0];
4610 
4611   // Concat of UNDEFs is UNDEF.
4612   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4613     return DAG.getUNDEF(VT);
4614 
4615   // Scan the operands and look for extract operations from a single source
4616   // that correspond to insertion at the same location via this concatenation:
4617   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4618   SDValue IdentitySrc;
4619   bool IsIdentity = true;
4620   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4621     SDValue Op = Ops[i];
4622     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4623     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4624         Op.getOperand(0).getValueType() != VT ||
4625         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4626         Op.getConstantOperandVal(1) != IdentityIndex) {
4627       IsIdentity = false;
4628       break;
4629     }
4630     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4631            "Unexpected identity source vector for concat of extracts");
4632     IdentitySrc = Op.getOperand(0);
4633   }
4634   if (IsIdentity) {
4635     assert(IdentitySrc && "Failed to set source vector of extracts");
4636     return IdentitySrc;
4637   }
4638 
4639   // The code below this point is only designed to work for fixed width
4640   // vectors, so we bail out for now.
4641   if (VT.isScalableVector())
4642     return SDValue();
4643 
4644   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4645   // simplified to one big BUILD_VECTOR.
4646   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4647   EVT SVT = VT.getScalarType();
4648   SmallVector<SDValue, 16> Elts;
4649   for (SDValue Op : Ops) {
4650     EVT OpVT = Op.getValueType();
4651     if (Op.isUndef())
4652       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4653     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4654       Elts.append(Op->op_begin(), Op->op_end());
4655     else
4656       return SDValue();
4657   }
4658 
4659   // BUILD_VECTOR requires all inputs to be of the same type, find the
4660   // maximum type and extend them all.
4661   for (SDValue Op : Elts)
4662     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4663 
4664   if (SVT.bitsGT(VT.getScalarType())) {
4665     for (SDValue &Op : Elts) {
4666       if (Op.isUndef())
4667         Op = DAG.getUNDEF(SVT);
4668       else
4669         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4670                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4671                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4672     }
4673   }
4674 
4675   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4676   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4677   return V;
4678 }
4679 
4680 /// Gets or creates the specified node.
4681 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4682   FoldingSetNodeID ID;
4683   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4684   void *IP = nullptr;
4685   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4686     return SDValue(E, 0);
4687 
4688   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4689                               getVTList(VT));
4690   CSEMap.InsertNode(N, IP);
4691 
4692   InsertNode(N);
4693   SDValue V = SDValue(N, 0);
4694   NewSDValueDbgMsg(V, "Creating new node: ", this);
4695   return V;
4696 }
4697 
4698 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4699                               SDValue Operand) {
4700   SDNodeFlags Flags;
4701   if (Inserter)
4702     Flags = Inserter->getFlags();
4703   return getNode(Opcode, DL, VT, Operand, Flags);
4704 }
4705 
4706 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4707                               SDValue Operand, const SDNodeFlags Flags) {
4708   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4709          "Operand is DELETED_NODE!");
4710   // Constant fold unary operations with an integer constant operand. Even
4711   // opaque constant will be folded, because the folding of unary operations
4712   // doesn't create new constants with different values. Nevertheless, the
4713   // opaque flag is preserved during folding to prevent future folding with
4714   // other constants.
4715   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4716     const APInt &Val = C->getAPIntValue();
4717     switch (Opcode) {
4718     default: break;
4719     case ISD::SIGN_EXTEND:
4720       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4721                          C->isTargetOpcode(), C->isOpaque());
4722     case ISD::TRUNCATE:
4723       if (C->isOpaque())
4724         break;
4725       LLVM_FALLTHROUGH;
4726     case ISD::ZERO_EXTEND:
4727       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4728                          C->isTargetOpcode(), C->isOpaque());
4729     case ISD::ANY_EXTEND:
4730       // Some targets like RISCV prefer to sign extend some types.
4731       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4732         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4733                            C->isTargetOpcode(), C->isOpaque());
4734       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4735                          C->isTargetOpcode(), C->isOpaque());
4736     case ISD::UINT_TO_FP:
4737     case ISD::SINT_TO_FP: {
4738       APFloat apf(EVTToAPFloatSemantics(VT),
4739                   APInt::getZero(VT.getSizeInBits()));
4740       (void)apf.convertFromAPInt(Val,
4741                                  Opcode==ISD::SINT_TO_FP,
4742                                  APFloat::rmNearestTiesToEven);
4743       return getConstantFP(apf, DL, VT);
4744     }
4745     case ISD::BITCAST:
4746       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4747         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4748       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4749         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4750       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4751         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4752       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4753         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4754       break;
4755     case ISD::ABS:
4756       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4757                          C->isOpaque());
4758     case ISD::BITREVERSE:
4759       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4760                          C->isOpaque());
4761     case ISD::BSWAP:
4762       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4763                          C->isOpaque());
4764     case ISD::CTPOP:
4765       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4766                          C->isOpaque());
4767     case ISD::CTLZ:
4768     case ISD::CTLZ_ZERO_UNDEF:
4769       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4770                          C->isOpaque());
4771     case ISD::CTTZ:
4772     case ISD::CTTZ_ZERO_UNDEF:
4773       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4774                          C->isOpaque());
4775     case ISD::FP16_TO_FP: {
4776       bool Ignored;
4777       APFloat FPV(APFloat::IEEEhalf(),
4778                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4779 
4780       // This can return overflow, underflow, or inexact; we don't care.
4781       // FIXME need to be more flexible about rounding mode.
4782       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4783                         APFloat::rmNearestTiesToEven, &Ignored);
4784       return getConstantFP(FPV, DL, VT);
4785     }
4786     case ISD::STEP_VECTOR: {
4787       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4788         return V;
4789       break;
4790     }
4791     }
4792   }
4793 
4794   // Constant fold unary operations with a floating point constant operand.
4795   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4796     APFloat V = C->getValueAPF();    // make copy
4797     switch (Opcode) {
4798     case ISD::FNEG:
4799       V.changeSign();
4800       return getConstantFP(V, DL, VT);
4801     case ISD::FABS:
4802       V.clearSign();
4803       return getConstantFP(V, DL, VT);
4804     case ISD::FCEIL: {
4805       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4806       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4807         return getConstantFP(V, DL, VT);
4808       break;
4809     }
4810     case ISD::FTRUNC: {
4811       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4812       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4813         return getConstantFP(V, DL, VT);
4814       break;
4815     }
4816     case ISD::FFLOOR: {
4817       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4818       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4819         return getConstantFP(V, DL, VT);
4820       break;
4821     }
4822     case ISD::FP_EXTEND: {
4823       bool ignored;
4824       // This can return overflow, underflow, or inexact; we don't care.
4825       // FIXME need to be more flexible about rounding mode.
4826       (void)V.convert(EVTToAPFloatSemantics(VT),
4827                       APFloat::rmNearestTiesToEven, &ignored);
4828       return getConstantFP(V, DL, VT);
4829     }
4830     case ISD::FP_TO_SINT:
4831     case ISD::FP_TO_UINT: {
4832       bool ignored;
4833       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4834       // FIXME need to be more flexible about rounding mode.
4835       APFloat::opStatus s =
4836           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4837       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4838         break;
4839       return getConstant(IntVal, DL, VT);
4840     }
4841     case ISD::BITCAST:
4842       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4843         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4844       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4845         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4846       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4847         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4848       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4849         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4850       break;
4851     case ISD::FP_TO_FP16: {
4852       bool Ignored;
4853       // This can return overflow, underflow, or inexact; we don't care.
4854       // FIXME need to be more flexible about rounding mode.
4855       (void)V.convert(APFloat::IEEEhalf(),
4856                       APFloat::rmNearestTiesToEven, &Ignored);
4857       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4858     }
4859     }
4860   }
4861 
4862   // Constant fold unary operations with a vector integer or float operand.
4863   switch (Opcode) {
4864   default:
4865     // FIXME: Entirely reasonable to perform folding of other unary
4866     // operations here as the need arises.
4867     break;
4868   case ISD::FNEG:
4869   case ISD::FABS:
4870   case ISD::FCEIL:
4871   case ISD::FTRUNC:
4872   case ISD::FFLOOR:
4873   case ISD::FP_EXTEND:
4874   case ISD::FP_TO_SINT:
4875   case ISD::FP_TO_UINT:
4876   case ISD::TRUNCATE:
4877   case ISD::ANY_EXTEND:
4878   case ISD::ZERO_EXTEND:
4879   case ISD::SIGN_EXTEND:
4880   case ISD::UINT_TO_FP:
4881   case ISD::SINT_TO_FP:
4882   case ISD::ABS:
4883   case ISD::BITREVERSE:
4884   case ISD::BSWAP:
4885   case ISD::CTLZ:
4886   case ISD::CTLZ_ZERO_UNDEF:
4887   case ISD::CTTZ:
4888   case ISD::CTTZ_ZERO_UNDEF:
4889   case ISD::CTPOP: {
4890     SDValue Ops = {Operand};
4891     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
4892       return Fold;
4893   }
4894   }
4895 
4896   unsigned OpOpcode = Operand.getNode()->getOpcode();
4897   switch (Opcode) {
4898   case ISD::STEP_VECTOR:
4899     assert(VT.isScalableVector() &&
4900            "STEP_VECTOR can only be used with scalable types");
4901     assert(OpOpcode == ISD::TargetConstant &&
4902            VT.getVectorElementType() == Operand.getValueType() &&
4903            "Unexpected step operand");
4904     break;
4905   case ISD::FREEZE:
4906     assert(VT == Operand.getValueType() && "Unexpected VT!");
4907     break;
4908   case ISD::TokenFactor:
4909   case ISD::MERGE_VALUES:
4910   case ISD::CONCAT_VECTORS:
4911     return Operand;         // Factor, merge or concat of one node?  No need.
4912   case ISD::BUILD_VECTOR: {
4913     // Attempt to simplify BUILD_VECTOR.
4914     SDValue Ops[] = {Operand};
4915     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4916       return V;
4917     break;
4918   }
4919   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4920   case ISD::FP_EXTEND:
4921     assert(VT.isFloatingPoint() &&
4922            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4923     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4924     assert((!VT.isVector() ||
4925             VT.getVectorElementCount() ==
4926             Operand.getValueType().getVectorElementCount()) &&
4927            "Vector element count mismatch!");
4928     assert(Operand.getValueType().bitsLT(VT) &&
4929            "Invalid fpext node, dst < src!");
4930     if (Operand.isUndef())
4931       return getUNDEF(VT);
4932     break;
4933   case ISD::FP_TO_SINT:
4934   case ISD::FP_TO_UINT:
4935     if (Operand.isUndef())
4936       return getUNDEF(VT);
4937     break;
4938   case ISD::SINT_TO_FP:
4939   case ISD::UINT_TO_FP:
4940     // [us]itofp(undef) = 0, because the result value is bounded.
4941     if (Operand.isUndef())
4942       return getConstantFP(0.0, DL, VT);
4943     break;
4944   case ISD::SIGN_EXTEND:
4945     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4946            "Invalid SIGN_EXTEND!");
4947     assert(VT.isVector() == Operand.getValueType().isVector() &&
4948            "SIGN_EXTEND result type type should be vector iff the operand "
4949            "type is vector!");
4950     if (Operand.getValueType() == VT) return Operand;   // noop extension
4951     assert((!VT.isVector() ||
4952             VT.getVectorElementCount() ==
4953                 Operand.getValueType().getVectorElementCount()) &&
4954            "Vector element count mismatch!");
4955     assert(Operand.getValueType().bitsLT(VT) &&
4956            "Invalid sext node, dst < src!");
4957     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4958       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4959     if (OpOpcode == ISD::UNDEF)
4960       // sext(undef) = 0, because the top bits will all be the same.
4961       return getConstant(0, DL, VT);
4962     break;
4963   case ISD::ZERO_EXTEND:
4964     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4965            "Invalid ZERO_EXTEND!");
4966     assert(VT.isVector() == Operand.getValueType().isVector() &&
4967            "ZERO_EXTEND result type type should be vector iff the operand "
4968            "type is vector!");
4969     if (Operand.getValueType() == VT) return Operand;   // noop extension
4970     assert((!VT.isVector() ||
4971             VT.getVectorElementCount() ==
4972                 Operand.getValueType().getVectorElementCount()) &&
4973            "Vector element count mismatch!");
4974     assert(Operand.getValueType().bitsLT(VT) &&
4975            "Invalid zext node, dst < src!");
4976     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4977       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4978     if (OpOpcode == ISD::UNDEF)
4979       // zext(undef) = 0, because the top bits will be zero.
4980       return getConstant(0, DL, VT);
4981     break;
4982   case ISD::ANY_EXTEND:
4983     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4984            "Invalid ANY_EXTEND!");
4985     assert(VT.isVector() == Operand.getValueType().isVector() &&
4986            "ANY_EXTEND result type type should be vector iff the operand "
4987            "type is vector!");
4988     if (Operand.getValueType() == VT) return Operand;   // noop extension
4989     assert((!VT.isVector() ||
4990             VT.getVectorElementCount() ==
4991                 Operand.getValueType().getVectorElementCount()) &&
4992            "Vector element count mismatch!");
4993     assert(Operand.getValueType().bitsLT(VT) &&
4994            "Invalid anyext node, dst < src!");
4995 
4996     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4997         OpOpcode == ISD::ANY_EXTEND)
4998       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4999       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5000     if (OpOpcode == ISD::UNDEF)
5001       return getUNDEF(VT);
5002 
5003     // (ext (trunc x)) -> x
5004     if (OpOpcode == ISD::TRUNCATE) {
5005       SDValue OpOp = Operand.getOperand(0);
5006       if (OpOp.getValueType() == VT) {
5007         transferDbgValues(Operand, OpOp);
5008         return OpOp;
5009       }
5010     }
5011     break;
5012   case ISD::TRUNCATE:
5013     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5014            "Invalid TRUNCATE!");
5015     assert(VT.isVector() == Operand.getValueType().isVector() &&
5016            "TRUNCATE result type type should be vector iff the operand "
5017            "type is vector!");
5018     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5019     assert((!VT.isVector() ||
5020             VT.getVectorElementCount() ==
5021                 Operand.getValueType().getVectorElementCount()) &&
5022            "Vector element count mismatch!");
5023     assert(Operand.getValueType().bitsGT(VT) &&
5024            "Invalid truncate node, src < dst!");
5025     if (OpOpcode == ISD::TRUNCATE)
5026       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5027     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5028         OpOpcode == ISD::ANY_EXTEND) {
5029       // If the source is smaller than the dest, we still need an extend.
5030       if (Operand.getOperand(0).getValueType().getScalarType()
5031             .bitsLT(VT.getScalarType()))
5032         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5033       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5034         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5035       return Operand.getOperand(0);
5036     }
5037     if (OpOpcode == ISD::UNDEF)
5038       return getUNDEF(VT);
5039     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5040       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5041     break;
5042   case ISD::ANY_EXTEND_VECTOR_INREG:
5043   case ISD::ZERO_EXTEND_VECTOR_INREG:
5044   case ISD::SIGN_EXTEND_VECTOR_INREG:
5045     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5046     assert(Operand.getValueType().bitsLE(VT) &&
5047            "The input must be the same size or smaller than the result.");
5048     assert(VT.getVectorMinNumElements() <
5049                Operand.getValueType().getVectorMinNumElements() &&
5050            "The destination vector type must have fewer lanes than the input.");
5051     break;
5052   case ISD::ABS:
5053     assert(VT.isInteger() && VT == Operand.getValueType() &&
5054            "Invalid ABS!");
5055     if (OpOpcode == ISD::UNDEF)
5056       return getUNDEF(VT);
5057     break;
5058   case ISD::BSWAP:
5059     assert(VT.isInteger() && VT == Operand.getValueType() &&
5060            "Invalid BSWAP!");
5061     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5062            "BSWAP types must be a multiple of 16 bits!");
5063     if (OpOpcode == ISD::UNDEF)
5064       return getUNDEF(VT);
5065     break;
5066   case ISD::BITREVERSE:
5067     assert(VT.isInteger() && VT == Operand.getValueType() &&
5068            "Invalid BITREVERSE!");
5069     if (OpOpcode == ISD::UNDEF)
5070       return getUNDEF(VT);
5071     break;
5072   case ISD::BITCAST:
5073     // Basic sanity checking.
5074     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5075            "Cannot BITCAST between types of different sizes!");
5076     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5077     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5078       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5079     if (OpOpcode == ISD::UNDEF)
5080       return getUNDEF(VT);
5081     break;
5082   case ISD::SCALAR_TO_VECTOR:
5083     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5084            (VT.getVectorElementType() == Operand.getValueType() ||
5085             (VT.getVectorElementType().isInteger() &&
5086              Operand.getValueType().isInteger() &&
5087              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5088            "Illegal SCALAR_TO_VECTOR node!");
5089     if (OpOpcode == ISD::UNDEF)
5090       return getUNDEF(VT);
5091     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5092     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5093         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5094         Operand.getConstantOperandVal(1) == 0 &&
5095         Operand.getOperand(0).getValueType() == VT)
5096       return Operand.getOperand(0);
5097     break;
5098   case ISD::FNEG:
5099     // Negation of an unknown bag of bits is still completely undefined.
5100     if (OpOpcode == ISD::UNDEF)
5101       return getUNDEF(VT);
5102 
5103     if (OpOpcode == ISD::FNEG)  // --X -> X
5104       return Operand.getOperand(0);
5105     break;
5106   case ISD::FABS:
5107     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5108       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5109     break;
5110   case ISD::VSCALE:
5111     assert(VT == Operand.getValueType() && "Unexpected VT!");
5112     break;
5113   case ISD::CTPOP:
5114     if (Operand.getValueType().getScalarType() == MVT::i1)
5115       return Operand;
5116     break;
5117   case ISD::CTLZ:
5118   case ISD::CTTZ:
5119     if (Operand.getValueType().getScalarType() == MVT::i1)
5120       return getNOT(DL, Operand, Operand.getValueType());
5121     break;
5122   case ISD::VECREDUCE_SMIN:
5123   case ISD::VECREDUCE_UMAX:
5124     if (Operand.getValueType().getScalarType() == MVT::i1)
5125       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5126     break;
5127   case ISD::VECREDUCE_SMAX:
5128   case ISD::VECREDUCE_UMIN:
5129     if (Operand.getValueType().getScalarType() == MVT::i1)
5130       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5131     break;
5132   }
5133 
5134   SDNode *N;
5135   SDVTList VTs = getVTList(VT);
5136   SDValue Ops[] = {Operand};
5137   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5138     FoldingSetNodeID ID;
5139     AddNodeIDNode(ID, Opcode, VTs, Ops);
5140     void *IP = nullptr;
5141     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5142       E->intersectFlagsWith(Flags);
5143       return SDValue(E, 0);
5144     }
5145 
5146     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5147     N->setFlags(Flags);
5148     createOperands(N, Ops);
5149     CSEMap.InsertNode(N, IP);
5150   } else {
5151     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5152     createOperands(N, Ops);
5153   }
5154 
5155   InsertNode(N);
5156   SDValue V = SDValue(N, 0);
5157   NewSDValueDbgMsg(V, "Creating new node: ", this);
5158   return V;
5159 }
5160 
5161 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5162                                        const APInt &C2) {
5163   switch (Opcode) {
5164   case ISD::ADD:  return C1 + C2;
5165   case ISD::SUB:  return C1 - C2;
5166   case ISD::MUL:  return C1 * C2;
5167   case ISD::AND:  return C1 & C2;
5168   case ISD::OR:   return C1 | C2;
5169   case ISD::XOR:  return C1 ^ C2;
5170   case ISD::SHL:  return C1 << C2;
5171   case ISD::SRL:  return C1.lshr(C2);
5172   case ISD::SRA:  return C1.ashr(C2);
5173   case ISD::ROTL: return C1.rotl(C2);
5174   case ISD::ROTR: return C1.rotr(C2);
5175   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5176   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5177   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5178   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5179   case ISD::SADDSAT: return C1.sadd_sat(C2);
5180   case ISD::UADDSAT: return C1.uadd_sat(C2);
5181   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5182   case ISD::USUBSAT: return C1.usub_sat(C2);
5183   case ISD::UDIV:
5184     if (!C2.getBoolValue())
5185       break;
5186     return C1.udiv(C2);
5187   case ISD::UREM:
5188     if (!C2.getBoolValue())
5189       break;
5190     return C1.urem(C2);
5191   case ISD::SDIV:
5192     if (!C2.getBoolValue())
5193       break;
5194     return C1.sdiv(C2);
5195   case ISD::SREM:
5196     if (!C2.getBoolValue())
5197       break;
5198     return C1.srem(C2);
5199   case ISD::MULHS: {
5200     unsigned FullWidth = C1.getBitWidth() * 2;
5201     APInt C1Ext = C1.sext(FullWidth);
5202     APInt C2Ext = C2.sext(FullWidth);
5203     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5204   }
5205   case ISD::MULHU: {
5206     unsigned FullWidth = C1.getBitWidth() * 2;
5207     APInt C1Ext = C1.zext(FullWidth);
5208     APInt C2Ext = C2.zext(FullWidth);
5209     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5210   }
5211   }
5212   return llvm::None;
5213 }
5214 
5215 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5216                                        const GlobalAddressSDNode *GA,
5217                                        const SDNode *N2) {
5218   if (GA->getOpcode() != ISD::GlobalAddress)
5219     return SDValue();
5220   if (!TLI->isOffsetFoldingLegal(GA))
5221     return SDValue();
5222   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5223   if (!C2)
5224     return SDValue();
5225   int64_t Offset = C2->getSExtValue();
5226   switch (Opcode) {
5227   case ISD::ADD: break;
5228   case ISD::SUB: Offset = -uint64_t(Offset); break;
5229   default: return SDValue();
5230   }
5231   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5232                           GA->getOffset() + uint64_t(Offset));
5233 }
5234 
5235 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5236   switch (Opcode) {
5237   case ISD::SDIV:
5238   case ISD::UDIV:
5239   case ISD::SREM:
5240   case ISD::UREM: {
5241     // If a divisor is zero/undef or any element of a divisor vector is
5242     // zero/undef, the whole op is undef.
5243     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5244     SDValue Divisor = Ops[1];
5245     if (Divisor.isUndef() || isNullConstant(Divisor))
5246       return true;
5247 
5248     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5249            llvm::any_of(Divisor->op_values(),
5250                         [](SDValue V) { return V.isUndef() ||
5251                                         isNullConstant(V); });
5252     // TODO: Handle signed overflow.
5253   }
5254   // TODO: Handle oversized shifts.
5255   default:
5256     return false;
5257   }
5258 }
5259 
5260 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5261                                              EVT VT, ArrayRef<SDValue> Ops) {
5262   // If the opcode is a target-specific ISD node, there's nothing we can
5263   // do here and the operand rules may not line up with the below, so
5264   // bail early.
5265   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5266   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5267   // foldCONCAT_VECTORS in getNode before this is called.
5268   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5269     return SDValue();
5270 
5271   unsigned NumOps = Ops.size();
5272   if (NumOps == 0)
5273     return SDValue();
5274 
5275   if (isUndef(Opcode, Ops))
5276     return getUNDEF(VT);
5277 
5278   // Handle the case of two scalars.
5279   if (NumOps == 2) {
5280     // TODO: Move foldConstantFPMath here?
5281 
5282     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5283       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5284         if (C1->isOpaque() || C2->isOpaque())
5285           return SDValue();
5286 
5287         Optional<APInt> FoldAttempt =
5288             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5289         if (!FoldAttempt)
5290           return SDValue();
5291 
5292         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5293         assert((!Folded || !VT.isVector()) &&
5294                "Can't fold vectors ops with scalar operands");
5295         return Folded;
5296       }
5297     }
5298 
5299     // fold (add Sym, c) -> Sym+c
5300     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5301       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5302     if (TLI->isCommutativeBinOp(Opcode))
5303       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5304         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5305 
5306     // If this is a bitwise logic opcode see if we can fold bitcasted ops.
5307     // TODO: Can we generalize this and fold any bitcasted constant data?
5308     if (ISD::isBitwiseLogicOp(Opcode) && Ops[0].getOpcode() == ISD::BITCAST &&
5309         Ops[1].getOpcode() == ISD::BITCAST) {
5310       SDValue InnerN1 = peekThroughBitcasts(Ops[0].getOperand(0));
5311       SDValue InnerN2 = peekThroughBitcasts(Ops[1].getOperand(0));
5312       EVT InnerVT = InnerN1.getValueType();
5313       if (InnerVT == InnerN2.getValueType() && InnerVT.isInteger())
5314         if (SDValue C =
5315                 FoldConstantArithmetic(Opcode, DL, InnerVT, {InnerN1, InnerN2}))
5316           return getBitcast(VT, C);
5317     }
5318   }
5319 
5320   // This is for vector folding only from here on.
5321   if (!VT.isVector())
5322     return SDValue();
5323 
5324   ElementCount NumElts = VT.getVectorElementCount();
5325 
5326   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5327     return !Op.getValueType().isVector() ||
5328            Op.getValueType().getVectorElementCount() == NumElts;
5329   };
5330 
5331   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5332     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5333            Op.getOpcode() == ISD::BUILD_VECTOR ||
5334            Op.getOpcode() == ISD::SPLAT_VECTOR;
5335   };
5336 
5337   // All operands must be vector types with the same number of elements as
5338   // the result type and must be either UNDEF or a build/splat vector
5339   // or UNDEF scalars.
5340   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5341       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5342     return SDValue();
5343 
5344   // If we are comparing vectors, then the result needs to be a i1 boolean
5345   // that is then sign-extended back to the legal result type.
5346   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5347 
5348   // Find legal integer scalar type for constant promotion and
5349   // ensure that its scalar size is at least as large as source.
5350   EVT LegalSVT = VT.getScalarType();
5351   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5352     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5353     if (LegalSVT.bitsLT(VT.getScalarType()))
5354       return SDValue();
5355   }
5356 
5357   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5358   // only have one operand to check. For fixed-length vector types we may have
5359   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5360   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5361 
5362   // Constant fold each scalar lane separately.
5363   SmallVector<SDValue, 4> ScalarResults;
5364   for (unsigned I = 0; I != NumVectorElts; I++) {
5365     SmallVector<SDValue, 4> ScalarOps;
5366     for (SDValue Op : Ops) {
5367       EVT InSVT = Op.getValueType().getScalarType();
5368       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5369           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5370         if (Op.isUndef())
5371           ScalarOps.push_back(getUNDEF(InSVT));
5372         else
5373           ScalarOps.push_back(Op);
5374         continue;
5375       }
5376 
5377       SDValue ScalarOp =
5378           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5379       EVT ScalarVT = ScalarOp.getValueType();
5380 
5381       // Build vector (integer) scalar operands may need implicit
5382       // truncation - do this before constant folding.
5383       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5384         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5385 
5386       ScalarOps.push_back(ScalarOp);
5387     }
5388 
5389     // Constant fold the scalar operands.
5390     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5391 
5392     // Legalize the (integer) scalar constant if necessary.
5393     if (LegalSVT != SVT)
5394       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5395 
5396     // Scalar folding only succeeded if the result is a constant or UNDEF.
5397     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5398         ScalarResult.getOpcode() != ISD::ConstantFP)
5399       return SDValue();
5400     ScalarResults.push_back(ScalarResult);
5401   }
5402 
5403   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5404                                    : getBuildVector(VT, DL, ScalarResults);
5405   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5406   return V;
5407 }
5408 
5409 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5410                                          EVT VT, SDValue N1, SDValue N2) {
5411   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5412   //       should. That will require dealing with a potentially non-default
5413   //       rounding mode, checking the "opStatus" return value from the APFloat
5414   //       math calculations, and possibly other variations.
5415   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5416   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5417   if (N1CFP && N2CFP) {
5418     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5419     switch (Opcode) {
5420     case ISD::FADD:
5421       C1.add(C2, APFloat::rmNearestTiesToEven);
5422       return getConstantFP(C1, DL, VT);
5423     case ISD::FSUB:
5424       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5425       return getConstantFP(C1, DL, VT);
5426     case ISD::FMUL:
5427       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5428       return getConstantFP(C1, DL, VT);
5429     case ISD::FDIV:
5430       C1.divide(C2, APFloat::rmNearestTiesToEven);
5431       return getConstantFP(C1, DL, VT);
5432     case ISD::FREM:
5433       C1.mod(C2);
5434       return getConstantFP(C1, DL, VT);
5435     case ISD::FCOPYSIGN:
5436       C1.copySign(C2);
5437       return getConstantFP(C1, DL, VT);
5438     default: break;
5439     }
5440   }
5441   if (N1CFP && Opcode == ISD::FP_ROUND) {
5442     APFloat C1 = N1CFP->getValueAPF();    // make copy
5443     bool Unused;
5444     // This can return overflow, underflow, or inexact; we don't care.
5445     // FIXME need to be more flexible about rounding mode.
5446     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5447                       &Unused);
5448     return getConstantFP(C1, DL, VT);
5449   }
5450 
5451   switch (Opcode) {
5452   case ISD::FSUB:
5453     // -0.0 - undef --> undef (consistent with "fneg undef")
5454     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5455       return getUNDEF(VT);
5456     LLVM_FALLTHROUGH;
5457 
5458   case ISD::FADD:
5459   case ISD::FMUL:
5460   case ISD::FDIV:
5461   case ISD::FREM:
5462     // If both operands are undef, the result is undef. If 1 operand is undef,
5463     // the result is NaN. This should match the behavior of the IR optimizer.
5464     if (N1.isUndef() && N2.isUndef())
5465       return getUNDEF(VT);
5466     if (N1.isUndef() || N2.isUndef())
5467       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5468   }
5469   return SDValue();
5470 }
5471 
5472 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5473   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5474 
5475   // There's no need to assert on a byte-aligned pointer. All pointers are at
5476   // least byte aligned.
5477   if (A == Align(1))
5478     return Val;
5479 
5480   FoldingSetNodeID ID;
5481   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5482   ID.AddInteger(A.value());
5483 
5484   void *IP = nullptr;
5485   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5486     return SDValue(E, 0);
5487 
5488   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5489                                          Val.getValueType(), A);
5490   createOperands(N, {Val});
5491 
5492   CSEMap.InsertNode(N, IP);
5493   InsertNode(N);
5494 
5495   SDValue V(N, 0);
5496   NewSDValueDbgMsg(V, "Creating new node: ", this);
5497   return V;
5498 }
5499 
5500 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5501                               SDValue N1, SDValue N2) {
5502   SDNodeFlags Flags;
5503   if (Inserter)
5504     Flags = Inserter->getFlags();
5505   return getNode(Opcode, DL, VT, N1, N2, Flags);
5506 }
5507 
5508 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5509                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5510   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5511          N2.getOpcode() != ISD::DELETED_NODE &&
5512          "Operand is DELETED_NODE!");
5513   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5514   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5515   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5516   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5517 
5518   // Canonicalize constant to RHS if commutative.
5519   if (TLI->isCommutativeBinOp(Opcode)) {
5520     if (N1C && !N2C) {
5521       std::swap(N1C, N2C);
5522       std::swap(N1, N2);
5523     } else if (N1CFP && !N2CFP) {
5524       std::swap(N1CFP, N2CFP);
5525       std::swap(N1, N2);
5526     }
5527   }
5528 
5529   switch (Opcode) {
5530   default: break;
5531   case ISD::TokenFactor:
5532     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5533            N2.getValueType() == MVT::Other && "Invalid token factor!");
5534     // Fold trivial token factors.
5535     if (N1.getOpcode() == ISD::EntryToken) return N2;
5536     if (N2.getOpcode() == ISD::EntryToken) return N1;
5537     if (N1 == N2) return N1;
5538     break;
5539   case ISD::BUILD_VECTOR: {
5540     // Attempt to simplify BUILD_VECTOR.
5541     SDValue Ops[] = {N1, N2};
5542     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5543       return V;
5544     break;
5545   }
5546   case ISD::CONCAT_VECTORS: {
5547     SDValue Ops[] = {N1, N2};
5548     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5549       return V;
5550     break;
5551   }
5552   case ISD::AND:
5553     assert(VT.isInteger() && "This operator does not apply to FP types!");
5554     assert(N1.getValueType() == N2.getValueType() &&
5555            N1.getValueType() == VT && "Binary operator types must match!");
5556     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5557     // worth handling here.
5558     if (N2C && N2C->isZero())
5559       return N2;
5560     if (N2C && N2C->isAllOnes()) // X & -1 -> X
5561       return N1;
5562     break;
5563   case ISD::OR:
5564   case ISD::XOR:
5565   case ISD::ADD:
5566   case ISD::SUB:
5567     assert(VT.isInteger() && "This operator does not apply to FP types!");
5568     assert(N1.getValueType() == N2.getValueType() &&
5569            N1.getValueType() == VT && "Binary operator types must match!");
5570     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5571     // it's worth handling here.
5572     if (N2C && N2C->isZero())
5573       return N1;
5574     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5575         VT.getVectorElementType() == MVT::i1)
5576       return getNode(ISD::XOR, DL, VT, N1, N2);
5577     break;
5578   case ISD::MUL:
5579     assert(VT.isInteger() && "This operator does not apply to FP types!");
5580     assert(N1.getValueType() == N2.getValueType() &&
5581            N1.getValueType() == VT && "Binary operator types must match!");
5582     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5583       return getNode(ISD::AND, DL, VT, N1, N2);
5584     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5585       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5586       const APInt &N2CImm = N2C->getAPIntValue();
5587       return getVScale(DL, VT, MulImm * N2CImm);
5588     }
5589     break;
5590   case ISD::UDIV:
5591   case ISD::UREM:
5592   case ISD::MULHU:
5593   case ISD::MULHS:
5594   case ISD::SDIV:
5595   case ISD::SREM:
5596   case ISD::SADDSAT:
5597   case ISD::SSUBSAT:
5598   case ISD::UADDSAT:
5599   case ISD::USUBSAT:
5600     assert(VT.isInteger() && "This operator does not apply to FP types!");
5601     assert(N1.getValueType() == N2.getValueType() &&
5602            N1.getValueType() == VT && "Binary operator types must match!");
5603     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5604       // fold (add_sat x, y) -> (or x, y) for bool types.
5605       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5606         return getNode(ISD::OR, DL, VT, N1, N2);
5607       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5608       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5609         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5610     }
5611     break;
5612   case ISD::SMIN:
5613   case ISD::UMAX:
5614     assert(VT.isInteger() && "This operator does not apply to FP types!");
5615     assert(N1.getValueType() == N2.getValueType() &&
5616            N1.getValueType() == VT && "Binary operator types must match!");
5617     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5618       return getNode(ISD::OR, DL, VT, N1, N2);
5619     break;
5620   case ISD::SMAX:
5621   case ISD::UMIN:
5622     assert(VT.isInteger() && "This operator does not apply to FP types!");
5623     assert(N1.getValueType() == N2.getValueType() &&
5624            N1.getValueType() == VT && "Binary operator types must match!");
5625     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5626       return getNode(ISD::AND, DL, VT, N1, N2);
5627     break;
5628   case ISD::FADD:
5629   case ISD::FSUB:
5630   case ISD::FMUL:
5631   case ISD::FDIV:
5632   case ISD::FREM:
5633     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5634     assert(N1.getValueType() == N2.getValueType() &&
5635            N1.getValueType() == VT && "Binary operator types must match!");
5636     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5637       return V;
5638     break;
5639   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5640     assert(N1.getValueType() == VT &&
5641            N1.getValueType().isFloatingPoint() &&
5642            N2.getValueType().isFloatingPoint() &&
5643            "Invalid FCOPYSIGN!");
5644     break;
5645   case ISD::SHL:
5646     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5647       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5648       const APInt &ShiftImm = N2C->getAPIntValue();
5649       return getVScale(DL, VT, MulImm << ShiftImm);
5650     }
5651     LLVM_FALLTHROUGH;
5652   case ISD::SRA:
5653   case ISD::SRL:
5654     if (SDValue V = simplifyShift(N1, N2))
5655       return V;
5656     LLVM_FALLTHROUGH;
5657   case ISD::ROTL:
5658   case ISD::ROTR:
5659     assert(VT == N1.getValueType() &&
5660            "Shift operators return type must be the same as their first arg");
5661     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5662            "Shifts only work on integers");
5663     assert((!VT.isVector() || VT == N2.getValueType()) &&
5664            "Vector shift amounts must be in the same as their first arg");
5665     // Verify that the shift amount VT is big enough to hold valid shift
5666     // amounts.  This catches things like trying to shift an i1024 value by an
5667     // i8, which is easy to fall into in generic code that uses
5668     // TLI.getShiftAmount().
5669     assert(N2.getValueType().getScalarSizeInBits() >=
5670                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5671            "Invalid use of small shift amount with oversized value!");
5672 
5673     // Always fold shifts of i1 values so the code generator doesn't need to
5674     // handle them.  Since we know the size of the shift has to be less than the
5675     // size of the value, the shift/rotate count is guaranteed to be zero.
5676     if (VT == MVT::i1)
5677       return N1;
5678     if (N2C && N2C->isZero())
5679       return N1;
5680     break;
5681   case ISD::FP_ROUND:
5682     assert(VT.isFloatingPoint() &&
5683            N1.getValueType().isFloatingPoint() &&
5684            VT.bitsLE(N1.getValueType()) &&
5685            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5686            "Invalid FP_ROUND!");
5687     if (N1.getValueType() == VT) return N1;  // noop conversion.
5688     break;
5689   case ISD::AssertSext:
5690   case ISD::AssertZext: {
5691     EVT EVT = cast<VTSDNode>(N2)->getVT();
5692     assert(VT == N1.getValueType() && "Not an inreg extend!");
5693     assert(VT.isInteger() && EVT.isInteger() &&
5694            "Cannot *_EXTEND_INREG FP types");
5695     assert(!EVT.isVector() &&
5696            "AssertSExt/AssertZExt type should be the vector element type "
5697            "rather than the vector type!");
5698     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5699     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5700     break;
5701   }
5702   case ISD::SIGN_EXTEND_INREG: {
5703     EVT EVT = cast<VTSDNode>(N2)->getVT();
5704     assert(VT == N1.getValueType() && "Not an inreg extend!");
5705     assert(VT.isInteger() && EVT.isInteger() &&
5706            "Cannot *_EXTEND_INREG FP types");
5707     assert(EVT.isVector() == VT.isVector() &&
5708            "SIGN_EXTEND_INREG type should be vector iff the operand "
5709            "type is vector!");
5710     assert((!EVT.isVector() ||
5711             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5712            "Vector element counts must match in SIGN_EXTEND_INREG");
5713     assert(EVT.bitsLE(VT) && "Not extending!");
5714     if (EVT == VT) return N1;  // Not actually extending
5715 
5716     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5717       unsigned FromBits = EVT.getScalarSizeInBits();
5718       Val <<= Val.getBitWidth() - FromBits;
5719       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5720       return getConstant(Val, DL, ConstantVT);
5721     };
5722 
5723     if (N1C) {
5724       const APInt &Val = N1C->getAPIntValue();
5725       return SignExtendInReg(Val, VT);
5726     }
5727 
5728     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5729       SmallVector<SDValue, 8> Ops;
5730       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5731       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5732         SDValue Op = N1.getOperand(i);
5733         if (Op.isUndef()) {
5734           Ops.push_back(getUNDEF(OpVT));
5735           continue;
5736         }
5737         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5738         APInt Val = C->getAPIntValue();
5739         Ops.push_back(SignExtendInReg(Val, OpVT));
5740       }
5741       return getBuildVector(VT, DL, Ops);
5742     }
5743     break;
5744   }
5745   case ISD::FP_TO_SINT_SAT:
5746   case ISD::FP_TO_UINT_SAT: {
5747     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5748            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5749     assert(N1.getValueType().isVector() == VT.isVector() &&
5750            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5751            "vector!");
5752     assert((!VT.isVector() || VT.getVectorNumElements() ==
5753                                   N1.getValueType().getVectorNumElements()) &&
5754            "Vector element counts must match in FP_TO_*INT_SAT");
5755     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5756            "Type to saturate to must be a scalar.");
5757     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5758            "Not extending!");
5759     break;
5760   }
5761   case ISD::EXTRACT_VECTOR_ELT:
5762     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5763            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5764              element type of the vector.");
5765 
5766     // Extract from an undefined value or using an undefined index is undefined.
5767     if (N1.isUndef() || N2.isUndef())
5768       return getUNDEF(VT);
5769 
5770     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5771     // vectors. For scalable vectors we will provide appropriate support for
5772     // dealing with arbitrary indices.
5773     if (N2C && N1.getValueType().isFixedLengthVector() &&
5774         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5775       return getUNDEF(VT);
5776 
5777     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5778     // expanding copies of large vectors from registers. This only works for
5779     // fixed length vectors, since we need to know the exact number of
5780     // elements.
5781     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5782         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5783       unsigned Factor =
5784         N1.getOperand(0).getValueType().getVectorNumElements();
5785       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5786                      N1.getOperand(N2C->getZExtValue() / Factor),
5787                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5788     }
5789 
5790     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5791     // lowering is expanding large vector constants.
5792     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5793                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5794       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5795               N1.getValueType().isFixedLengthVector()) &&
5796              "BUILD_VECTOR used for scalable vectors");
5797       unsigned Index =
5798           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5799       SDValue Elt = N1.getOperand(Index);
5800 
5801       if (VT != Elt.getValueType())
5802         // If the vector element type is not legal, the BUILD_VECTOR operands
5803         // are promoted and implicitly truncated, and the result implicitly
5804         // extended. Make that explicit here.
5805         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5806 
5807       return Elt;
5808     }
5809 
5810     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5811     // operations are lowered to scalars.
5812     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5813       // If the indices are the same, return the inserted element else
5814       // if the indices are known different, extract the element from
5815       // the original vector.
5816       SDValue N1Op2 = N1.getOperand(2);
5817       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5818 
5819       if (N1Op2C && N2C) {
5820         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5821           if (VT == N1.getOperand(1).getValueType())
5822             return N1.getOperand(1);
5823           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5824         }
5825         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5826       }
5827     }
5828 
5829     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5830     // when vector types are scalarized and v1iX is legal.
5831     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5832     // Here we are completely ignoring the extract element index (N2),
5833     // which is fine for fixed width vectors, since any index other than 0
5834     // is undefined anyway. However, this cannot be ignored for scalable
5835     // vectors - in theory we could support this, but we don't want to do this
5836     // without a profitability check.
5837     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5838         N1.getValueType().isFixedLengthVector() &&
5839         N1.getValueType().getVectorNumElements() == 1) {
5840       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5841                      N1.getOperand(1));
5842     }
5843     break;
5844   case ISD::EXTRACT_ELEMENT:
5845     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5846     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5847            (N1.getValueType().isInteger() == VT.isInteger()) &&
5848            N1.getValueType() != VT &&
5849            "Wrong types for EXTRACT_ELEMENT!");
5850 
5851     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5852     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5853     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5854     if (N1.getOpcode() == ISD::BUILD_PAIR)
5855       return N1.getOperand(N2C->getZExtValue());
5856 
5857     // EXTRACT_ELEMENT of a constant int is also very common.
5858     if (N1C) {
5859       unsigned ElementSize = VT.getSizeInBits();
5860       unsigned Shift = ElementSize * N2C->getZExtValue();
5861       const APInt &Val = N1C->getAPIntValue();
5862       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5863     }
5864     break;
5865   case ISD::EXTRACT_SUBVECTOR: {
5866     EVT N1VT = N1.getValueType();
5867     assert(VT.isVector() && N1VT.isVector() &&
5868            "Extract subvector VTs must be vectors!");
5869     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5870            "Extract subvector VTs must have the same element type!");
5871     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5872            "Cannot extract a scalable vector from a fixed length vector!");
5873     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5874             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5875            "Extract subvector must be from larger vector to smaller vector!");
5876     assert(N2C && "Extract subvector index must be a constant");
5877     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5878             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5879                 N1VT.getVectorMinNumElements()) &&
5880            "Extract subvector overflow!");
5881     assert(N2C->getAPIntValue().getBitWidth() ==
5882                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5883            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5884 
5885     // Trivial extraction.
5886     if (VT == N1VT)
5887       return N1;
5888 
5889     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5890     if (N1.isUndef())
5891       return getUNDEF(VT);
5892 
5893     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5894     // the concat have the same type as the extract.
5895     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5896         VT == N1.getOperand(0).getValueType()) {
5897       unsigned Factor = VT.getVectorMinNumElements();
5898       return N1.getOperand(N2C->getZExtValue() / Factor);
5899     }
5900 
5901     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5902     // during shuffle legalization.
5903     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5904         VT == N1.getOperand(1).getValueType())
5905       return N1.getOperand(1);
5906     break;
5907   }
5908   }
5909 
5910   // Perform trivial constant folding.
5911   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5912     return SV;
5913 
5914   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5915     return V;
5916 
5917   // Canonicalize an UNDEF to the RHS, even over a constant.
5918   if (N1.isUndef()) {
5919     if (TLI->isCommutativeBinOp(Opcode)) {
5920       std::swap(N1, N2);
5921     } else {
5922       switch (Opcode) {
5923       case ISD::SIGN_EXTEND_INREG:
5924       case ISD::SUB:
5925         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5926       case ISD::UDIV:
5927       case ISD::SDIV:
5928       case ISD::UREM:
5929       case ISD::SREM:
5930       case ISD::SSUBSAT:
5931       case ISD::USUBSAT:
5932         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5933       }
5934     }
5935   }
5936 
5937   // Fold a bunch of operators when the RHS is undef.
5938   if (N2.isUndef()) {
5939     switch (Opcode) {
5940     case ISD::XOR:
5941       if (N1.isUndef())
5942         // Handle undef ^ undef -> 0 special case. This is a common
5943         // idiom (misuse).
5944         return getConstant(0, DL, VT);
5945       LLVM_FALLTHROUGH;
5946     case ISD::ADD:
5947     case ISD::SUB:
5948     case ISD::UDIV:
5949     case ISD::SDIV:
5950     case ISD::UREM:
5951     case ISD::SREM:
5952       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5953     case ISD::MUL:
5954     case ISD::AND:
5955     case ISD::SSUBSAT:
5956     case ISD::USUBSAT:
5957       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5958     case ISD::OR:
5959     case ISD::SADDSAT:
5960     case ISD::UADDSAT:
5961       return getAllOnesConstant(DL, VT);
5962     }
5963   }
5964 
5965   // Memoize this node if possible.
5966   SDNode *N;
5967   SDVTList VTs = getVTList(VT);
5968   SDValue Ops[] = {N1, N2};
5969   if (VT != MVT::Glue) {
5970     FoldingSetNodeID ID;
5971     AddNodeIDNode(ID, Opcode, VTs, Ops);
5972     void *IP = nullptr;
5973     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5974       E->intersectFlagsWith(Flags);
5975       return SDValue(E, 0);
5976     }
5977 
5978     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5979     N->setFlags(Flags);
5980     createOperands(N, Ops);
5981     CSEMap.InsertNode(N, IP);
5982   } else {
5983     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5984     createOperands(N, Ops);
5985   }
5986 
5987   InsertNode(N);
5988   SDValue V = SDValue(N, 0);
5989   NewSDValueDbgMsg(V, "Creating new node: ", this);
5990   return V;
5991 }
5992 
5993 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5994                               SDValue N1, SDValue N2, SDValue N3) {
5995   SDNodeFlags Flags;
5996   if (Inserter)
5997     Flags = Inserter->getFlags();
5998   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
5999 }
6000 
6001 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6002                               SDValue N1, SDValue N2, SDValue N3,
6003                               const SDNodeFlags Flags) {
6004   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6005          N2.getOpcode() != ISD::DELETED_NODE &&
6006          N3.getOpcode() != ISD::DELETED_NODE &&
6007          "Operand is DELETED_NODE!");
6008   // Perform various simplifications.
6009   switch (Opcode) {
6010   case ISD::FMA: {
6011     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6012     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6013            N3.getValueType() == VT && "FMA types must match!");
6014     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6015     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6016     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6017     if (N1CFP && N2CFP && N3CFP) {
6018       APFloat  V1 = N1CFP->getValueAPF();
6019       const APFloat &V2 = N2CFP->getValueAPF();
6020       const APFloat &V3 = N3CFP->getValueAPF();
6021       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6022       return getConstantFP(V1, DL, VT);
6023     }
6024     break;
6025   }
6026   case ISD::BUILD_VECTOR: {
6027     // Attempt to simplify BUILD_VECTOR.
6028     SDValue Ops[] = {N1, N2, N3};
6029     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6030       return V;
6031     break;
6032   }
6033   case ISD::CONCAT_VECTORS: {
6034     SDValue Ops[] = {N1, N2, N3};
6035     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6036       return V;
6037     break;
6038   }
6039   case ISD::SETCC: {
6040     assert(VT.isInteger() && "SETCC result type must be an integer!");
6041     assert(N1.getValueType() == N2.getValueType() &&
6042            "SETCC operands must have the same type!");
6043     assert(VT.isVector() == N1.getValueType().isVector() &&
6044            "SETCC type should be vector iff the operand type is vector!");
6045     assert((!VT.isVector() || VT.getVectorElementCount() ==
6046                                   N1.getValueType().getVectorElementCount()) &&
6047            "SETCC vector element counts must match!");
6048     // Use FoldSetCC to simplify SETCC's.
6049     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6050       return V;
6051     // Vector constant folding.
6052     SDValue Ops[] = {N1, N2, N3};
6053     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6054       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6055       return V;
6056     }
6057     break;
6058   }
6059   case ISD::SELECT:
6060   case ISD::VSELECT:
6061     if (SDValue V = simplifySelect(N1, N2, N3))
6062       return V;
6063     break;
6064   case ISD::VECTOR_SHUFFLE:
6065     llvm_unreachable("should use getVectorShuffle constructor!");
6066   case ISD::VECTOR_SPLICE: {
6067     if (cast<ConstantSDNode>(N3)->isNullValue())
6068       return N1;
6069     break;
6070   }
6071   case ISD::INSERT_VECTOR_ELT: {
6072     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6073     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6074     // for scalable vectors where we will generate appropriate code to
6075     // deal with out-of-bounds cases correctly.
6076     if (N3C && N1.getValueType().isFixedLengthVector() &&
6077         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6078       return getUNDEF(VT);
6079 
6080     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6081     if (N3.isUndef())
6082       return getUNDEF(VT);
6083 
6084     // If the inserted element is an UNDEF, just use the input vector.
6085     if (N2.isUndef())
6086       return N1;
6087 
6088     break;
6089   }
6090   case ISD::INSERT_SUBVECTOR: {
6091     // Inserting undef into undef is still undef.
6092     if (N1.isUndef() && N2.isUndef())
6093       return getUNDEF(VT);
6094 
6095     EVT N2VT = N2.getValueType();
6096     assert(VT == N1.getValueType() &&
6097            "Dest and insert subvector source types must match!");
6098     assert(VT.isVector() && N2VT.isVector() &&
6099            "Insert subvector VTs must be vectors!");
6100     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6101            "Cannot insert a scalable vector into a fixed length vector!");
6102     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6103             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6104            "Insert subvector must be from smaller vector to larger vector!");
6105     assert(isa<ConstantSDNode>(N3) &&
6106            "Insert subvector index must be constant");
6107     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6108             (N2VT.getVectorMinNumElements() +
6109              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6110                 VT.getVectorMinNumElements()) &&
6111            "Insert subvector overflow!");
6112     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6113                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6114            "Constant index for INSERT_SUBVECTOR has an invalid size");
6115 
6116     // Trivial insertion.
6117     if (VT == N2VT)
6118       return N2;
6119 
6120     // If this is an insert of an extracted vector into an undef vector, we
6121     // can just use the input to the extract.
6122     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6123         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6124       return N2.getOperand(0);
6125     break;
6126   }
6127   case ISD::BITCAST:
6128     // Fold bit_convert nodes from a type to themselves.
6129     if (N1.getValueType() == VT)
6130       return N1;
6131     break;
6132   }
6133 
6134   // Memoize node if it doesn't produce a flag.
6135   SDNode *N;
6136   SDVTList VTs = getVTList(VT);
6137   SDValue Ops[] = {N1, N2, N3};
6138   if (VT != MVT::Glue) {
6139     FoldingSetNodeID ID;
6140     AddNodeIDNode(ID, Opcode, VTs, Ops);
6141     void *IP = nullptr;
6142     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6143       E->intersectFlagsWith(Flags);
6144       return SDValue(E, 0);
6145     }
6146 
6147     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6148     N->setFlags(Flags);
6149     createOperands(N, Ops);
6150     CSEMap.InsertNode(N, IP);
6151   } else {
6152     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6153     createOperands(N, Ops);
6154   }
6155 
6156   InsertNode(N);
6157   SDValue V = SDValue(N, 0);
6158   NewSDValueDbgMsg(V, "Creating new node: ", this);
6159   return V;
6160 }
6161 
6162 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6163                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6164   SDValue Ops[] = { N1, N2, N3, N4 };
6165   return getNode(Opcode, DL, VT, Ops);
6166 }
6167 
6168 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6169                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6170                               SDValue N5) {
6171   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6172   return getNode(Opcode, DL, VT, Ops);
6173 }
6174 
6175 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6176 /// the incoming stack arguments to be loaded from the stack.
6177 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6178   SmallVector<SDValue, 8> ArgChains;
6179 
6180   // Include the original chain at the beginning of the list. When this is
6181   // used by target LowerCall hooks, this helps legalize find the
6182   // CALLSEQ_BEGIN node.
6183   ArgChains.push_back(Chain);
6184 
6185   // Add a chain value for each stack argument.
6186   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
6187        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
6188     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
6189       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6190         if (FI->getIndex() < 0)
6191           ArgChains.push_back(SDValue(L, 1));
6192 
6193   // Build a tokenfactor for all the chains.
6194   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6195 }
6196 
6197 /// getMemsetValue - Vectorized representation of the memset value
6198 /// operand.
6199 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6200                               const SDLoc &dl) {
6201   assert(!Value.isUndef());
6202 
6203   unsigned NumBits = VT.getScalarSizeInBits();
6204   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6205     assert(C->getAPIntValue().getBitWidth() == 8);
6206     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6207     if (VT.isInteger()) {
6208       bool IsOpaque = VT.getSizeInBits() > 64 ||
6209           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6210       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6211     }
6212     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6213                              VT);
6214   }
6215 
6216   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6217   EVT IntVT = VT.getScalarType();
6218   if (!IntVT.isInteger())
6219     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6220 
6221   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6222   if (NumBits > 8) {
6223     // Use a multiplication with 0x010101... to extend the input to the
6224     // required length.
6225     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6226     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6227                         DAG.getConstant(Magic, dl, IntVT));
6228   }
6229 
6230   if (VT != Value.getValueType() && !VT.isInteger())
6231     Value = DAG.getBitcast(VT.getScalarType(), Value);
6232   if (VT != Value.getValueType())
6233     Value = DAG.getSplatBuildVector(VT, dl, Value);
6234 
6235   return Value;
6236 }
6237 
6238 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6239 /// used when a memcpy is turned into a memset when the source is a constant
6240 /// string ptr.
6241 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6242                                   const TargetLowering &TLI,
6243                                   const ConstantDataArraySlice &Slice) {
6244   // Handle vector with all elements zero.
6245   if (Slice.Array == nullptr) {
6246     if (VT.isInteger())
6247       return DAG.getConstant(0, dl, VT);
6248     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6249       return DAG.getConstantFP(0.0, dl, VT);
6250     if (VT.isVector()) {
6251       unsigned NumElts = VT.getVectorNumElements();
6252       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6253       return DAG.getNode(ISD::BITCAST, dl, VT,
6254                          DAG.getConstant(0, dl,
6255                                          EVT::getVectorVT(*DAG.getContext(),
6256                                                           EltVT, NumElts)));
6257     }
6258     llvm_unreachable("Expected type!");
6259   }
6260 
6261   assert(!VT.isVector() && "Can't handle vector type here!");
6262   unsigned NumVTBits = VT.getSizeInBits();
6263   unsigned NumVTBytes = NumVTBits / 8;
6264   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6265 
6266   APInt Val(NumVTBits, 0);
6267   if (DAG.getDataLayout().isLittleEndian()) {
6268     for (unsigned i = 0; i != NumBytes; ++i)
6269       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6270   } else {
6271     for (unsigned i = 0; i != NumBytes; ++i)
6272       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6273   }
6274 
6275   // If the "cost" of materializing the integer immediate is less than the cost
6276   // of a load, then it is cost effective to turn the load into the immediate.
6277   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6278   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6279     return DAG.getConstant(Val, dl, VT);
6280   return SDValue(nullptr, 0);
6281 }
6282 
6283 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6284                                            const SDLoc &DL,
6285                                            const SDNodeFlags Flags) {
6286   EVT VT = Base.getValueType();
6287   SDValue Index;
6288 
6289   if (Offset.isScalable())
6290     Index = getVScale(DL, Base.getValueType(),
6291                       APInt(Base.getValueSizeInBits().getFixedSize(),
6292                             Offset.getKnownMinSize()));
6293   else
6294     Index = getConstant(Offset.getFixedSize(), DL, VT);
6295 
6296   return getMemBasePlusOffset(Base, Index, DL, Flags);
6297 }
6298 
6299 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6300                                            const SDLoc &DL,
6301                                            const SDNodeFlags Flags) {
6302   assert(Offset.getValueType().isInteger());
6303   EVT BasePtrVT = Ptr.getValueType();
6304   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6305 }
6306 
6307 /// Returns true if memcpy source is constant data.
6308 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6309   uint64_t SrcDelta = 0;
6310   GlobalAddressSDNode *G = nullptr;
6311   if (Src.getOpcode() == ISD::GlobalAddress)
6312     G = cast<GlobalAddressSDNode>(Src);
6313   else if (Src.getOpcode() == ISD::ADD &&
6314            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6315            Src.getOperand(1).getOpcode() == ISD::Constant) {
6316     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6317     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6318   }
6319   if (!G)
6320     return false;
6321 
6322   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6323                                   SrcDelta + G->getOffset());
6324 }
6325 
6326 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6327                                       SelectionDAG &DAG) {
6328   // On Darwin, -Os means optimize for size without hurting performance, so
6329   // only really optimize for size when -Oz (MinSize) is used.
6330   if (MF.getTarget().getTargetTriple().isOSDarwin())
6331     return MF.getFunction().hasMinSize();
6332   return DAG.shouldOptForSize();
6333 }
6334 
6335 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6336                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6337                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6338                           SmallVector<SDValue, 16> &OutStoreChains) {
6339   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6340   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6341   SmallVector<SDValue, 16> GluedLoadChains;
6342   for (unsigned i = From; i < To; ++i) {
6343     OutChains.push_back(OutLoadChains[i]);
6344     GluedLoadChains.push_back(OutLoadChains[i]);
6345   }
6346 
6347   // Chain for all loads.
6348   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6349                                   GluedLoadChains);
6350 
6351   for (unsigned i = From; i < To; ++i) {
6352     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6353     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6354                                   ST->getBasePtr(), ST->getMemoryVT(),
6355                                   ST->getMemOperand());
6356     OutChains.push_back(NewStore);
6357   }
6358 }
6359 
6360 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6361                                        SDValue Chain, SDValue Dst, SDValue Src,
6362                                        uint64_t Size, Align Alignment,
6363                                        bool isVol, bool AlwaysInline,
6364                                        MachinePointerInfo DstPtrInfo,
6365                                        MachinePointerInfo SrcPtrInfo,
6366                                        const AAMDNodes &AAInfo) {
6367   // Turn a memcpy of undef to nop.
6368   // FIXME: We need to honor volatile even is Src is undef.
6369   if (Src.isUndef())
6370     return Chain;
6371 
6372   // Expand memcpy to a series of load and store ops if the size operand falls
6373   // below a certain threshold.
6374   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6375   // rather than maybe a humongous number of loads and stores.
6376   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6377   const DataLayout &DL = DAG.getDataLayout();
6378   LLVMContext &C = *DAG.getContext();
6379   std::vector<EVT> MemOps;
6380   bool DstAlignCanChange = false;
6381   MachineFunction &MF = DAG.getMachineFunction();
6382   MachineFrameInfo &MFI = MF.getFrameInfo();
6383   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6384   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6385   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6386     DstAlignCanChange = true;
6387   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6388   if (!SrcAlign || Alignment > *SrcAlign)
6389     SrcAlign = Alignment;
6390   assert(SrcAlign && "SrcAlign must be set");
6391   ConstantDataArraySlice Slice;
6392   // If marked as volatile, perform a copy even when marked as constant.
6393   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6394   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6395   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6396   const MemOp Op = isZeroConstant
6397                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6398                                     /*IsZeroMemset*/ true, isVol)
6399                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6400                                      *SrcAlign, isVol, CopyFromConstant);
6401   if (!TLI.findOptimalMemOpLowering(
6402           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6403           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6404     return SDValue();
6405 
6406   if (DstAlignCanChange) {
6407     Type *Ty = MemOps[0].getTypeForEVT(C);
6408     Align NewAlign = DL.getABITypeAlign(Ty);
6409 
6410     // Don't promote to an alignment that would require dynamic stack
6411     // realignment.
6412     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6413     if (!TRI->hasStackRealignment(MF))
6414       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6415         NewAlign = NewAlign / 2;
6416 
6417     if (NewAlign > Alignment) {
6418       // Give the stack frame object a larger alignment if needed.
6419       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6420         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6421       Alignment = NewAlign;
6422     }
6423   }
6424 
6425   // Prepare AAInfo for loads/stores after lowering this memcpy.
6426   AAMDNodes NewAAInfo = AAInfo;
6427   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6428 
6429   MachineMemOperand::Flags MMOFlags =
6430       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6431   SmallVector<SDValue, 16> OutLoadChains;
6432   SmallVector<SDValue, 16> OutStoreChains;
6433   SmallVector<SDValue, 32> OutChains;
6434   unsigned NumMemOps = MemOps.size();
6435   uint64_t SrcOff = 0, DstOff = 0;
6436   for (unsigned i = 0; i != NumMemOps; ++i) {
6437     EVT VT = MemOps[i];
6438     unsigned VTSize = VT.getSizeInBits() / 8;
6439     SDValue Value, Store;
6440 
6441     if (VTSize > Size) {
6442       // Issuing an unaligned load / store pair  that overlaps with the previous
6443       // pair. Adjust the offset accordingly.
6444       assert(i == NumMemOps-1 && i != 0);
6445       SrcOff -= VTSize - Size;
6446       DstOff -= VTSize - Size;
6447     }
6448 
6449     if (CopyFromConstant &&
6450         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6451       // It's unlikely a store of a vector immediate can be done in a single
6452       // instruction. It would require a load from a constantpool first.
6453       // We only handle zero vectors here.
6454       // FIXME: Handle other cases where store of vector immediate is done in
6455       // a single instruction.
6456       ConstantDataArraySlice SubSlice;
6457       if (SrcOff < Slice.Length) {
6458         SubSlice = Slice;
6459         SubSlice.move(SrcOff);
6460       } else {
6461         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6462         SubSlice.Array = nullptr;
6463         SubSlice.Offset = 0;
6464         SubSlice.Length = VTSize;
6465       }
6466       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6467       if (Value.getNode()) {
6468         Store = DAG.getStore(
6469             Chain, dl, Value,
6470             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6471             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6472         OutChains.push_back(Store);
6473       }
6474     }
6475 
6476     if (!Store.getNode()) {
6477       // The type might not be legal for the target.  This should only happen
6478       // if the type is smaller than a legal type, as on PPC, so the right
6479       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6480       // to Load/Store if NVT==VT.
6481       // FIXME does the case above also need this?
6482       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6483       assert(NVT.bitsGE(VT));
6484 
6485       bool isDereferenceable =
6486         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6487       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6488       if (isDereferenceable)
6489         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6490 
6491       Value = DAG.getExtLoad(
6492           ISD::EXTLOAD, dl, NVT, Chain,
6493           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6494           SrcPtrInfo.getWithOffset(SrcOff), VT,
6495           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6496       OutLoadChains.push_back(Value.getValue(1));
6497 
6498       Store = DAG.getTruncStore(
6499           Chain, dl, Value,
6500           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6501           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6502       OutStoreChains.push_back(Store);
6503     }
6504     SrcOff += VTSize;
6505     DstOff += VTSize;
6506     Size -= VTSize;
6507   }
6508 
6509   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6510                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6511   unsigned NumLdStInMemcpy = OutStoreChains.size();
6512 
6513   if (NumLdStInMemcpy) {
6514     // It may be that memcpy might be converted to memset if it's memcpy
6515     // of constants. In such a case, we won't have loads and stores, but
6516     // just stores. In the absence of loads, there is nothing to gang up.
6517     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6518       // If target does not care, just leave as it.
6519       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6520         OutChains.push_back(OutLoadChains[i]);
6521         OutChains.push_back(OutStoreChains[i]);
6522       }
6523     } else {
6524       // Ld/St less than/equal limit set by target.
6525       if (NumLdStInMemcpy <= GluedLdStLimit) {
6526           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6527                                         NumLdStInMemcpy, OutLoadChains,
6528                                         OutStoreChains);
6529       } else {
6530         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6531         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6532         unsigned GlueIter = 0;
6533 
6534         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6535           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6536           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6537 
6538           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6539                                        OutLoadChains, OutStoreChains);
6540           GlueIter += GluedLdStLimit;
6541         }
6542 
6543         // Residual ld/st.
6544         if (RemainingLdStInMemcpy) {
6545           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6546                                         RemainingLdStInMemcpy, OutLoadChains,
6547                                         OutStoreChains);
6548         }
6549       }
6550     }
6551   }
6552   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6553 }
6554 
6555 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6556                                         SDValue Chain, SDValue Dst, SDValue Src,
6557                                         uint64_t Size, Align Alignment,
6558                                         bool isVol, bool AlwaysInline,
6559                                         MachinePointerInfo DstPtrInfo,
6560                                         MachinePointerInfo SrcPtrInfo,
6561                                         const AAMDNodes &AAInfo) {
6562   // Turn a memmove of undef to nop.
6563   // FIXME: We need to honor volatile even is Src is undef.
6564   if (Src.isUndef())
6565     return Chain;
6566 
6567   // Expand memmove to a series of load and store ops if the size operand falls
6568   // below a certain threshold.
6569   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6570   const DataLayout &DL = DAG.getDataLayout();
6571   LLVMContext &C = *DAG.getContext();
6572   std::vector<EVT> MemOps;
6573   bool DstAlignCanChange = false;
6574   MachineFunction &MF = DAG.getMachineFunction();
6575   MachineFrameInfo &MFI = MF.getFrameInfo();
6576   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6577   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6578   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6579     DstAlignCanChange = true;
6580   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6581   if (!SrcAlign || Alignment > *SrcAlign)
6582     SrcAlign = Alignment;
6583   assert(SrcAlign && "SrcAlign must be set");
6584   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6585   if (!TLI.findOptimalMemOpLowering(
6586           MemOps, Limit,
6587           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6588                       /*IsVolatile*/ true),
6589           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6590           MF.getFunction().getAttributes()))
6591     return SDValue();
6592 
6593   if (DstAlignCanChange) {
6594     Type *Ty = MemOps[0].getTypeForEVT(C);
6595     Align NewAlign = DL.getABITypeAlign(Ty);
6596     if (NewAlign > Alignment) {
6597       // Give the stack frame object a larger alignment if needed.
6598       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6599         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6600       Alignment = NewAlign;
6601     }
6602   }
6603 
6604   // Prepare AAInfo for loads/stores after lowering this memmove.
6605   AAMDNodes NewAAInfo = AAInfo;
6606   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6607 
6608   MachineMemOperand::Flags MMOFlags =
6609       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6610   uint64_t SrcOff = 0, DstOff = 0;
6611   SmallVector<SDValue, 8> LoadValues;
6612   SmallVector<SDValue, 8> LoadChains;
6613   SmallVector<SDValue, 8> OutChains;
6614   unsigned NumMemOps = MemOps.size();
6615   for (unsigned i = 0; i < NumMemOps; i++) {
6616     EVT VT = MemOps[i];
6617     unsigned VTSize = VT.getSizeInBits() / 8;
6618     SDValue Value;
6619 
6620     bool isDereferenceable =
6621       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6622     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6623     if (isDereferenceable)
6624       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6625 
6626     Value = DAG.getLoad(
6627         VT, dl, Chain,
6628         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6629         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6630     LoadValues.push_back(Value);
6631     LoadChains.push_back(Value.getValue(1));
6632     SrcOff += VTSize;
6633   }
6634   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6635   OutChains.clear();
6636   for (unsigned i = 0; i < NumMemOps; i++) {
6637     EVT VT = MemOps[i];
6638     unsigned VTSize = VT.getSizeInBits() / 8;
6639     SDValue Store;
6640 
6641     Store = DAG.getStore(
6642         Chain, dl, LoadValues[i],
6643         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6644         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6645     OutChains.push_back(Store);
6646     DstOff += VTSize;
6647   }
6648 
6649   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6650 }
6651 
6652 /// Lower the call to 'memset' intrinsic function into a series of store
6653 /// operations.
6654 ///
6655 /// \param DAG Selection DAG where lowered code is placed.
6656 /// \param dl Link to corresponding IR location.
6657 /// \param Chain Control flow dependency.
6658 /// \param Dst Pointer to destination memory location.
6659 /// \param Src Value of byte to write into the memory.
6660 /// \param Size Number of bytes to write.
6661 /// \param Alignment Alignment of the destination in bytes.
6662 /// \param isVol True if destination is volatile.
6663 /// \param DstPtrInfo IR information on the memory pointer.
6664 /// \returns New head in the control flow, if lowering was successful, empty
6665 /// SDValue otherwise.
6666 ///
6667 /// The function tries to replace 'llvm.memset' intrinsic with several store
6668 /// operations and value calculation code. This is usually profitable for small
6669 /// memory size.
6670 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6671                                SDValue Chain, SDValue Dst, SDValue Src,
6672                                uint64_t Size, Align Alignment, bool isVol,
6673                                MachinePointerInfo DstPtrInfo,
6674                                const AAMDNodes &AAInfo) {
6675   // Turn a memset of undef to nop.
6676   // FIXME: We need to honor volatile even is Src is undef.
6677   if (Src.isUndef())
6678     return Chain;
6679 
6680   // Expand memset to a series of load/store ops if the size operand
6681   // falls below a certain threshold.
6682   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
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   bool IsZeroVal =
6692       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6693   if (!TLI.findOptimalMemOpLowering(
6694           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6695           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6696           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6697     return SDValue();
6698 
6699   if (DstAlignCanChange) {
6700     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6701     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6702     if (NewAlign > Alignment) {
6703       // Give the stack frame object a larger alignment if needed.
6704       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6705         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6706       Alignment = NewAlign;
6707     }
6708   }
6709 
6710   SmallVector<SDValue, 8> OutChains;
6711   uint64_t DstOff = 0;
6712   unsigned NumMemOps = MemOps.size();
6713 
6714   // Find the largest store and generate the bit pattern for it.
6715   EVT LargestVT = MemOps[0];
6716   for (unsigned i = 1; i < NumMemOps; i++)
6717     if (MemOps[i].bitsGT(LargestVT))
6718       LargestVT = MemOps[i];
6719   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6720 
6721   // Prepare AAInfo for loads/stores after lowering this memset.
6722   AAMDNodes NewAAInfo = AAInfo;
6723   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6724 
6725   for (unsigned i = 0; i < NumMemOps; i++) {
6726     EVT VT = MemOps[i];
6727     unsigned VTSize = VT.getSizeInBits() / 8;
6728     if (VTSize > Size) {
6729       // Issuing an unaligned load / store pair  that overlaps with the previous
6730       // pair. Adjust the offset accordingly.
6731       assert(i == NumMemOps-1 && i != 0);
6732       DstOff -= VTSize - Size;
6733     }
6734 
6735     // If this store is smaller than the largest store see whether we can get
6736     // the smaller value for free with a truncate.
6737     SDValue Value = MemSetValue;
6738     if (VT.bitsLT(LargestVT)) {
6739       if (!LargestVT.isVector() && !VT.isVector() &&
6740           TLI.isTruncateFree(LargestVT, VT))
6741         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6742       else
6743         Value = getMemsetValue(Src, VT, DAG, dl);
6744     }
6745     assert(Value.getValueType() == VT && "Value with wrong type.");
6746     SDValue Store = DAG.getStore(
6747         Chain, dl, Value,
6748         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6749         DstPtrInfo.getWithOffset(DstOff), Alignment,
6750         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6751         NewAAInfo);
6752     OutChains.push_back(Store);
6753     DstOff += VT.getSizeInBits() / 8;
6754     Size -= VTSize;
6755   }
6756 
6757   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6758 }
6759 
6760 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6761                                             unsigned AS) {
6762   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6763   // pointer operands can be losslessly bitcasted to pointers of address space 0
6764   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6765     report_fatal_error("cannot lower memory intrinsic in address space " +
6766                        Twine(AS));
6767   }
6768 }
6769 
6770 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6771                                 SDValue Src, SDValue Size, Align Alignment,
6772                                 bool isVol, bool AlwaysInline, bool isTailCall,
6773                                 MachinePointerInfo DstPtrInfo,
6774                                 MachinePointerInfo SrcPtrInfo,
6775                                 const AAMDNodes &AAInfo) {
6776   // Check to see if we should lower the memcpy to loads and stores first.
6777   // For cases within the target-specified limits, this is the best choice.
6778   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6779   if (ConstantSize) {
6780     // Memcpy with size zero? Just return the original chain.
6781     if (ConstantSize->isZero())
6782       return Chain;
6783 
6784     SDValue Result = getMemcpyLoadsAndStores(
6785         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6786         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6787     if (Result.getNode())
6788       return Result;
6789   }
6790 
6791   // Then check to see if we should lower the memcpy with target-specific
6792   // code. If the target chooses to do this, this is the next best.
6793   if (TSI) {
6794     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6795         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6796         DstPtrInfo, SrcPtrInfo);
6797     if (Result.getNode())
6798       return Result;
6799   }
6800 
6801   // If we really need inline code and the target declined to provide it,
6802   // use a (potentially long) sequence of loads and stores.
6803   if (AlwaysInline) {
6804     assert(ConstantSize && "AlwaysInline requires a constant size!");
6805     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6806                                    ConstantSize->getZExtValue(), Alignment,
6807                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6808   }
6809 
6810   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6811   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6812 
6813   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6814   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6815   // respect volatile, so they may do things like read or write memory
6816   // beyond the given memory regions. But fixing this isn't easy, and most
6817   // people don't care.
6818 
6819   // Emit a library call.
6820   TargetLowering::ArgListTy Args;
6821   TargetLowering::ArgListEntry Entry;
6822   Entry.Ty = Type::getInt8PtrTy(*getContext());
6823   Entry.Node = Dst; Args.push_back(Entry);
6824   Entry.Node = Src; Args.push_back(Entry);
6825 
6826   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6827   Entry.Node = Size; Args.push_back(Entry);
6828   // FIXME: pass in SDLoc
6829   TargetLowering::CallLoweringInfo CLI(*this);
6830   CLI.setDebugLoc(dl)
6831       .setChain(Chain)
6832       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6833                     Dst.getValueType().getTypeForEVT(*getContext()),
6834                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6835                                       TLI->getPointerTy(getDataLayout())),
6836                     std::move(Args))
6837       .setDiscardResult()
6838       .setTailCall(isTailCall);
6839 
6840   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6841   return CallResult.second;
6842 }
6843 
6844 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6845                                       SDValue Dst, unsigned DstAlign,
6846                                       SDValue Src, unsigned SrcAlign,
6847                                       SDValue Size, Type *SizeTy,
6848                                       unsigned ElemSz, bool isTailCall,
6849                                       MachinePointerInfo DstPtrInfo,
6850                                       MachinePointerInfo SrcPtrInfo) {
6851   // Emit a library call.
6852   TargetLowering::ArgListTy Args;
6853   TargetLowering::ArgListEntry Entry;
6854   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6855   Entry.Node = Dst;
6856   Args.push_back(Entry);
6857 
6858   Entry.Node = Src;
6859   Args.push_back(Entry);
6860 
6861   Entry.Ty = SizeTy;
6862   Entry.Node = Size;
6863   Args.push_back(Entry);
6864 
6865   RTLIB::Libcall LibraryCall =
6866       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6867   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6868     report_fatal_error("Unsupported element size");
6869 
6870   TargetLowering::CallLoweringInfo CLI(*this);
6871   CLI.setDebugLoc(dl)
6872       .setChain(Chain)
6873       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6874                     Type::getVoidTy(*getContext()),
6875                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6876                                       TLI->getPointerTy(getDataLayout())),
6877                     std::move(Args))
6878       .setDiscardResult()
6879       .setTailCall(isTailCall);
6880 
6881   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6882   return CallResult.second;
6883 }
6884 
6885 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6886                                  SDValue Src, SDValue Size, Align Alignment,
6887                                  bool isVol, bool isTailCall,
6888                                  MachinePointerInfo DstPtrInfo,
6889                                  MachinePointerInfo SrcPtrInfo,
6890                                  const AAMDNodes &AAInfo) {
6891   // Check to see if we should lower the memmove to loads and stores first.
6892   // For cases within the target-specified limits, this is the best choice.
6893   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6894   if (ConstantSize) {
6895     // Memmove with size zero? Just return the original chain.
6896     if (ConstantSize->isZero())
6897       return Chain;
6898 
6899     SDValue Result = getMemmoveLoadsAndStores(
6900         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6901         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6902     if (Result.getNode())
6903       return Result;
6904   }
6905 
6906   // Then check to see if we should lower the memmove with target-specific
6907   // code. If the target chooses to do this, this is the next best.
6908   if (TSI) {
6909     SDValue Result =
6910         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6911                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6912     if (Result.getNode())
6913       return Result;
6914   }
6915 
6916   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6917   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6918 
6919   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6920   // not be safe.  See memcpy above for more details.
6921 
6922   // Emit a library call.
6923   TargetLowering::ArgListTy Args;
6924   TargetLowering::ArgListEntry Entry;
6925   Entry.Ty = Type::getInt8PtrTy(*getContext());
6926   Entry.Node = Dst; Args.push_back(Entry);
6927   Entry.Node = Src; Args.push_back(Entry);
6928 
6929   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6930   Entry.Node = Size; Args.push_back(Entry);
6931   // FIXME:  pass in SDLoc
6932   TargetLowering::CallLoweringInfo CLI(*this);
6933   CLI.setDebugLoc(dl)
6934       .setChain(Chain)
6935       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6936                     Dst.getValueType().getTypeForEVT(*getContext()),
6937                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6938                                       TLI->getPointerTy(getDataLayout())),
6939                     std::move(Args))
6940       .setDiscardResult()
6941       .setTailCall(isTailCall);
6942 
6943   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6944   return CallResult.second;
6945 }
6946 
6947 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6948                                        SDValue Dst, unsigned DstAlign,
6949                                        SDValue Src, unsigned SrcAlign,
6950                                        SDValue Size, Type *SizeTy,
6951                                        unsigned ElemSz, bool isTailCall,
6952                                        MachinePointerInfo DstPtrInfo,
6953                                        MachinePointerInfo SrcPtrInfo) {
6954   // Emit a library call.
6955   TargetLowering::ArgListTy Args;
6956   TargetLowering::ArgListEntry Entry;
6957   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6958   Entry.Node = Dst;
6959   Args.push_back(Entry);
6960 
6961   Entry.Node = Src;
6962   Args.push_back(Entry);
6963 
6964   Entry.Ty = SizeTy;
6965   Entry.Node = Size;
6966   Args.push_back(Entry);
6967 
6968   RTLIB::Libcall LibraryCall =
6969       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6970   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6971     report_fatal_error("Unsupported element size");
6972 
6973   TargetLowering::CallLoweringInfo CLI(*this);
6974   CLI.setDebugLoc(dl)
6975       .setChain(Chain)
6976       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6977                     Type::getVoidTy(*getContext()),
6978                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6979                                       TLI->getPointerTy(getDataLayout())),
6980                     std::move(Args))
6981       .setDiscardResult()
6982       .setTailCall(isTailCall);
6983 
6984   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6985   return CallResult.second;
6986 }
6987 
6988 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6989                                 SDValue Src, SDValue Size, Align Alignment,
6990                                 bool isVol, bool isTailCall,
6991                                 MachinePointerInfo DstPtrInfo,
6992                                 const AAMDNodes &AAInfo) {
6993   // Check to see if we should lower the memset to stores first.
6994   // For cases within the target-specified limits, this is the best choice.
6995   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6996   if (ConstantSize) {
6997     // Memset with size zero? Just return the original chain.
6998     if (ConstantSize->isZero())
6999       return Chain;
7000 
7001     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7002                                      ConstantSize->getZExtValue(), Alignment,
7003                                      isVol, DstPtrInfo, AAInfo);
7004 
7005     if (Result.getNode())
7006       return Result;
7007   }
7008 
7009   // Then check to see if we should lower the memset with target-specific
7010   // code. If the target chooses to do this, this is the next best.
7011   if (TSI) {
7012     SDValue Result = TSI->EmitTargetCodeForMemset(
7013         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7014     if (Result.getNode())
7015       return Result;
7016   }
7017 
7018   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7019 
7020   // Emit a library call.
7021   TargetLowering::ArgListTy Args;
7022   TargetLowering::ArgListEntry Entry;
7023   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7024   Args.push_back(Entry);
7025   Entry.Node = Src;
7026   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7027   Args.push_back(Entry);
7028   Entry.Node = Size;
7029   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7030   Args.push_back(Entry);
7031 
7032   // FIXME: pass in SDLoc
7033   TargetLowering::CallLoweringInfo CLI(*this);
7034   CLI.setDebugLoc(dl)
7035       .setChain(Chain)
7036       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7037                     Dst.getValueType().getTypeForEVT(*getContext()),
7038                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7039                                       TLI->getPointerTy(getDataLayout())),
7040                     std::move(Args))
7041       .setDiscardResult()
7042       .setTailCall(isTailCall);
7043 
7044   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7045   return CallResult.second;
7046 }
7047 
7048 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7049                                       SDValue Dst, unsigned DstAlign,
7050                                       SDValue Value, SDValue Size, Type *SizeTy,
7051                                       unsigned ElemSz, bool isTailCall,
7052                                       MachinePointerInfo DstPtrInfo) {
7053   // Emit a library call.
7054   TargetLowering::ArgListTy Args;
7055   TargetLowering::ArgListEntry Entry;
7056   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7057   Entry.Node = Dst;
7058   Args.push_back(Entry);
7059 
7060   Entry.Ty = Type::getInt8Ty(*getContext());
7061   Entry.Node = Value;
7062   Args.push_back(Entry);
7063 
7064   Entry.Ty = SizeTy;
7065   Entry.Node = Size;
7066   Args.push_back(Entry);
7067 
7068   RTLIB::Libcall LibraryCall =
7069       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7070   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7071     report_fatal_error("Unsupported element size");
7072 
7073   TargetLowering::CallLoweringInfo CLI(*this);
7074   CLI.setDebugLoc(dl)
7075       .setChain(Chain)
7076       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7077                     Type::getVoidTy(*getContext()),
7078                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7079                                       TLI->getPointerTy(getDataLayout())),
7080                     std::move(Args))
7081       .setDiscardResult()
7082       .setTailCall(isTailCall);
7083 
7084   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7085   return CallResult.second;
7086 }
7087 
7088 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7089                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7090                                 MachineMemOperand *MMO) {
7091   FoldingSetNodeID ID;
7092   ID.AddInteger(MemVT.getRawBits());
7093   AddNodeIDNode(ID, Opcode, VTList, Ops);
7094   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7095   void* IP = nullptr;
7096   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7097     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7098     return SDValue(E, 0);
7099   }
7100 
7101   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7102                                     VTList, MemVT, MMO);
7103   createOperands(N, Ops);
7104 
7105   CSEMap.InsertNode(N, IP);
7106   InsertNode(N);
7107   return SDValue(N, 0);
7108 }
7109 
7110 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7111                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7112                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7113                                        MachineMemOperand *MMO) {
7114   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7115          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7116   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7117 
7118   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7119   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7120 }
7121 
7122 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7123                                 SDValue Chain, SDValue Ptr, SDValue Val,
7124                                 MachineMemOperand *MMO) {
7125   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7126           Opcode == ISD::ATOMIC_LOAD_SUB ||
7127           Opcode == ISD::ATOMIC_LOAD_AND ||
7128           Opcode == ISD::ATOMIC_LOAD_CLR ||
7129           Opcode == ISD::ATOMIC_LOAD_OR ||
7130           Opcode == ISD::ATOMIC_LOAD_XOR ||
7131           Opcode == ISD::ATOMIC_LOAD_NAND ||
7132           Opcode == ISD::ATOMIC_LOAD_MIN ||
7133           Opcode == ISD::ATOMIC_LOAD_MAX ||
7134           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7135           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7136           Opcode == ISD::ATOMIC_LOAD_FADD ||
7137           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7138           Opcode == ISD::ATOMIC_SWAP ||
7139           Opcode == ISD::ATOMIC_STORE) &&
7140          "Invalid Atomic Op");
7141 
7142   EVT VT = Val.getValueType();
7143 
7144   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7145                                                getVTList(VT, MVT::Other);
7146   SDValue Ops[] = {Chain, Ptr, Val};
7147   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7148 }
7149 
7150 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7151                                 EVT VT, SDValue Chain, SDValue Ptr,
7152                                 MachineMemOperand *MMO) {
7153   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7154 
7155   SDVTList VTs = getVTList(VT, MVT::Other);
7156   SDValue Ops[] = {Chain, Ptr};
7157   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7158 }
7159 
7160 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7161 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7162   if (Ops.size() == 1)
7163     return Ops[0];
7164 
7165   SmallVector<EVT, 4> VTs;
7166   VTs.reserve(Ops.size());
7167   for (const SDValue &Op : Ops)
7168     VTs.push_back(Op.getValueType());
7169   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7170 }
7171 
7172 SDValue SelectionDAG::getMemIntrinsicNode(
7173     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7174     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7175     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7176   if (!Size && MemVT.isScalableVector())
7177     Size = MemoryLocation::UnknownSize;
7178   else if (!Size)
7179     Size = MemVT.getStoreSize();
7180 
7181   MachineFunction &MF = getMachineFunction();
7182   MachineMemOperand *MMO =
7183       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7184 
7185   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7186 }
7187 
7188 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7189                                           SDVTList VTList,
7190                                           ArrayRef<SDValue> Ops, EVT MemVT,
7191                                           MachineMemOperand *MMO) {
7192   assert((Opcode == ISD::INTRINSIC_VOID ||
7193           Opcode == ISD::INTRINSIC_W_CHAIN ||
7194           Opcode == ISD::PREFETCH ||
7195           ((int)Opcode <= std::numeric_limits<int>::max() &&
7196            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7197          "Opcode is not a memory-accessing opcode!");
7198 
7199   // Memoize the node unless it returns a flag.
7200   MemIntrinsicSDNode *N;
7201   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7202     FoldingSetNodeID ID;
7203     AddNodeIDNode(ID, Opcode, VTList, Ops);
7204     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7205         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7206     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7207     void *IP = nullptr;
7208     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7209       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7210       return SDValue(E, 0);
7211     }
7212 
7213     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7214                                       VTList, MemVT, MMO);
7215     createOperands(N, Ops);
7216 
7217   CSEMap.InsertNode(N, IP);
7218   } else {
7219     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7220                                       VTList, MemVT, MMO);
7221     createOperands(N, Ops);
7222   }
7223   InsertNode(N);
7224   SDValue V(N, 0);
7225   NewSDValueDbgMsg(V, "Creating new node: ", this);
7226   return V;
7227 }
7228 
7229 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7230                                       SDValue Chain, int FrameIndex,
7231                                       int64_t Size, int64_t Offset) {
7232   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7233   const auto VTs = getVTList(MVT::Other);
7234   SDValue Ops[2] = {
7235       Chain,
7236       getFrameIndex(FrameIndex,
7237                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7238                     true)};
7239 
7240   FoldingSetNodeID ID;
7241   AddNodeIDNode(ID, Opcode, VTs, Ops);
7242   ID.AddInteger(FrameIndex);
7243   ID.AddInteger(Size);
7244   ID.AddInteger(Offset);
7245   void *IP = nullptr;
7246   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7247     return SDValue(E, 0);
7248 
7249   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7250       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7251   createOperands(N, Ops);
7252   CSEMap.InsertNode(N, IP);
7253   InsertNode(N);
7254   SDValue V(N, 0);
7255   NewSDValueDbgMsg(V, "Creating new node: ", this);
7256   return V;
7257 }
7258 
7259 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7260                                          uint64_t Guid, uint64_t Index,
7261                                          uint32_t Attr) {
7262   const unsigned Opcode = ISD::PSEUDO_PROBE;
7263   const auto VTs = getVTList(MVT::Other);
7264   SDValue Ops[] = {Chain};
7265   FoldingSetNodeID ID;
7266   AddNodeIDNode(ID, Opcode, VTs, Ops);
7267   ID.AddInteger(Guid);
7268   ID.AddInteger(Index);
7269   void *IP = nullptr;
7270   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7271     return SDValue(E, 0);
7272 
7273   auto *N = newSDNode<PseudoProbeSDNode>(
7274       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7275   createOperands(N, Ops);
7276   CSEMap.InsertNode(N, IP);
7277   InsertNode(N);
7278   SDValue V(N, 0);
7279   NewSDValueDbgMsg(V, "Creating new node: ", this);
7280   return V;
7281 }
7282 
7283 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7284 /// MachinePointerInfo record from it.  This is particularly useful because the
7285 /// code generator has many cases where it doesn't bother passing in a
7286 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7287 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7288                                            SelectionDAG &DAG, SDValue Ptr,
7289                                            int64_t Offset = 0) {
7290   // If this is FI+Offset, we can model it.
7291   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7292     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7293                                              FI->getIndex(), Offset);
7294 
7295   // If this is (FI+Offset1)+Offset2, we can model it.
7296   if (Ptr.getOpcode() != ISD::ADD ||
7297       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7298       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7299     return Info;
7300 
7301   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7302   return MachinePointerInfo::getFixedStack(
7303       DAG.getMachineFunction(), FI,
7304       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7305 }
7306 
7307 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7308 /// MachinePointerInfo record from it.  This is particularly useful because the
7309 /// code generator has many cases where it doesn't bother passing in a
7310 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7311 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7312                                            SelectionDAG &DAG, SDValue Ptr,
7313                                            SDValue OffsetOp) {
7314   // If the 'Offset' value isn't a constant, we can't handle this.
7315   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7316     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7317   if (OffsetOp.isUndef())
7318     return InferPointerInfo(Info, DAG, Ptr);
7319   return Info;
7320 }
7321 
7322 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7323                               EVT VT, const SDLoc &dl, SDValue Chain,
7324                               SDValue Ptr, SDValue Offset,
7325                               MachinePointerInfo PtrInfo, EVT MemVT,
7326                               Align Alignment,
7327                               MachineMemOperand::Flags MMOFlags,
7328                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7329   assert(Chain.getValueType() == MVT::Other &&
7330         "Invalid chain type");
7331 
7332   MMOFlags |= MachineMemOperand::MOLoad;
7333   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7334   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7335   // clients.
7336   if (PtrInfo.V.isNull())
7337     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7338 
7339   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7340   MachineFunction &MF = getMachineFunction();
7341   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7342                                                    Alignment, AAInfo, Ranges);
7343   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7344 }
7345 
7346 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7347                               EVT VT, const SDLoc &dl, SDValue Chain,
7348                               SDValue Ptr, SDValue Offset, EVT MemVT,
7349                               MachineMemOperand *MMO) {
7350   if (VT == MemVT) {
7351     ExtType = ISD::NON_EXTLOAD;
7352   } else if (ExtType == ISD::NON_EXTLOAD) {
7353     assert(VT == MemVT && "Non-extending load from different memory type!");
7354   } else {
7355     // Extending load.
7356     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7357            "Should only be an extending load, not truncating!");
7358     assert(VT.isInteger() == MemVT.isInteger() &&
7359            "Cannot convert from FP to Int or Int -> FP!");
7360     assert(VT.isVector() == MemVT.isVector() &&
7361            "Cannot use an ext load to convert to or from a vector!");
7362     assert((!VT.isVector() ||
7363             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7364            "Cannot use an ext load to change the number of vector elements!");
7365   }
7366 
7367   bool Indexed = AM != ISD::UNINDEXED;
7368   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7369 
7370   SDVTList VTs = Indexed ?
7371     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7372   SDValue Ops[] = { Chain, Ptr, Offset };
7373   FoldingSetNodeID ID;
7374   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7375   ID.AddInteger(MemVT.getRawBits());
7376   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7377       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7378   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7379   void *IP = nullptr;
7380   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7381     cast<LoadSDNode>(E)->refineAlignment(MMO);
7382     return SDValue(E, 0);
7383   }
7384   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7385                                   ExtType, MemVT, MMO);
7386   createOperands(N, Ops);
7387 
7388   CSEMap.InsertNode(N, IP);
7389   InsertNode(N);
7390   SDValue V(N, 0);
7391   NewSDValueDbgMsg(V, "Creating new node: ", this);
7392   return V;
7393 }
7394 
7395 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7396                               SDValue Ptr, MachinePointerInfo PtrInfo,
7397                               MaybeAlign Alignment,
7398                               MachineMemOperand::Flags MMOFlags,
7399                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7400   SDValue Undef = getUNDEF(Ptr.getValueType());
7401   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7402                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7403 }
7404 
7405 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7406                               SDValue Ptr, MachineMemOperand *MMO) {
7407   SDValue Undef = getUNDEF(Ptr.getValueType());
7408   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7409                  VT, MMO);
7410 }
7411 
7412 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7413                                  EVT VT, SDValue Chain, SDValue Ptr,
7414                                  MachinePointerInfo PtrInfo, EVT MemVT,
7415                                  MaybeAlign Alignment,
7416                                  MachineMemOperand::Flags MMOFlags,
7417                                  const AAMDNodes &AAInfo) {
7418   SDValue Undef = getUNDEF(Ptr.getValueType());
7419   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7420                  MemVT, Alignment, MMOFlags, AAInfo);
7421 }
7422 
7423 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7424                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7425                                  MachineMemOperand *MMO) {
7426   SDValue Undef = getUNDEF(Ptr.getValueType());
7427   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7428                  MemVT, MMO);
7429 }
7430 
7431 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7432                                      SDValue Base, SDValue Offset,
7433                                      ISD::MemIndexedMode AM) {
7434   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7435   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7436   // Don't propagate the invariant or dereferenceable flags.
7437   auto MMOFlags =
7438       LD->getMemOperand()->getFlags() &
7439       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7440   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7441                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7442                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7443 }
7444 
7445 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7446                                SDValue Ptr, MachinePointerInfo PtrInfo,
7447                                Align Alignment,
7448                                MachineMemOperand::Flags MMOFlags,
7449                                const AAMDNodes &AAInfo) {
7450   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7451 
7452   MMOFlags |= MachineMemOperand::MOStore;
7453   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7454 
7455   if (PtrInfo.V.isNull())
7456     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7457 
7458   MachineFunction &MF = getMachineFunction();
7459   uint64_t Size =
7460       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7461   MachineMemOperand *MMO =
7462       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7463   return getStore(Chain, dl, Val, Ptr, MMO);
7464 }
7465 
7466 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7467                                SDValue Ptr, MachineMemOperand *MMO) {
7468   assert(Chain.getValueType() == MVT::Other &&
7469         "Invalid chain type");
7470   EVT VT = Val.getValueType();
7471   SDVTList VTs = getVTList(MVT::Other);
7472   SDValue Undef = getUNDEF(Ptr.getValueType());
7473   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7474   FoldingSetNodeID ID;
7475   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7476   ID.AddInteger(VT.getRawBits());
7477   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7478       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7479   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7480   void *IP = nullptr;
7481   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7482     cast<StoreSDNode>(E)->refineAlignment(MMO);
7483     return SDValue(E, 0);
7484   }
7485   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7486                                    ISD::UNINDEXED, false, VT, MMO);
7487   createOperands(N, Ops);
7488 
7489   CSEMap.InsertNode(N, IP);
7490   InsertNode(N);
7491   SDValue V(N, 0);
7492   NewSDValueDbgMsg(V, "Creating new node: ", this);
7493   return V;
7494 }
7495 
7496 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7497                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7498                                     EVT SVT, Align Alignment,
7499                                     MachineMemOperand::Flags MMOFlags,
7500                                     const AAMDNodes &AAInfo) {
7501   assert(Chain.getValueType() == MVT::Other &&
7502         "Invalid chain type");
7503 
7504   MMOFlags |= MachineMemOperand::MOStore;
7505   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7506 
7507   if (PtrInfo.V.isNull())
7508     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7509 
7510   MachineFunction &MF = getMachineFunction();
7511   MachineMemOperand *MMO = MF.getMachineMemOperand(
7512       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7513       Alignment, AAInfo);
7514   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7515 }
7516 
7517 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7518                                     SDValue Ptr, EVT SVT,
7519                                     MachineMemOperand *MMO) {
7520   EVT VT = Val.getValueType();
7521 
7522   assert(Chain.getValueType() == MVT::Other &&
7523         "Invalid chain type");
7524   if (VT == SVT)
7525     return getStore(Chain, dl, Val, Ptr, MMO);
7526 
7527   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7528          "Should only be a truncating store, not extending!");
7529   assert(VT.isInteger() == SVT.isInteger() &&
7530          "Can't do FP-INT conversion!");
7531   assert(VT.isVector() == SVT.isVector() &&
7532          "Cannot use trunc store to convert to or from a vector!");
7533   assert((!VT.isVector() ||
7534           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7535          "Cannot use trunc store to change the number of vector elements!");
7536 
7537   SDVTList VTs = getVTList(MVT::Other);
7538   SDValue Undef = getUNDEF(Ptr.getValueType());
7539   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7540   FoldingSetNodeID ID;
7541   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7542   ID.AddInteger(SVT.getRawBits());
7543   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7544       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7545   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7546   void *IP = nullptr;
7547   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7548     cast<StoreSDNode>(E)->refineAlignment(MMO);
7549     return SDValue(E, 0);
7550   }
7551   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7552                                    ISD::UNINDEXED, true, SVT, MMO);
7553   createOperands(N, Ops);
7554 
7555   CSEMap.InsertNode(N, IP);
7556   InsertNode(N);
7557   SDValue V(N, 0);
7558   NewSDValueDbgMsg(V, "Creating new node: ", this);
7559   return V;
7560 }
7561 
7562 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7563                                       SDValue Base, SDValue Offset,
7564                                       ISD::MemIndexedMode AM) {
7565   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7566   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7567   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7568   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7569   FoldingSetNodeID ID;
7570   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7571   ID.AddInteger(ST->getMemoryVT().getRawBits());
7572   ID.AddInteger(ST->getRawSubclassData());
7573   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7574   void *IP = nullptr;
7575   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7576     return SDValue(E, 0);
7577 
7578   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7579                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7580                                    ST->getMemOperand());
7581   createOperands(N, Ops);
7582 
7583   CSEMap.InsertNode(N, IP);
7584   InsertNode(N);
7585   SDValue V(N, 0);
7586   NewSDValueDbgMsg(V, "Creating new node: ", this);
7587   return V;
7588 }
7589 
7590 SDValue SelectionDAG::getLoadVP(
7591     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7592     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7593     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7594     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7595     const MDNode *Ranges, bool IsExpanding) {
7596   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7597 
7598   MMOFlags |= MachineMemOperand::MOLoad;
7599   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7600   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7601   // clients.
7602   if (PtrInfo.V.isNull())
7603     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7604 
7605   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7606   MachineFunction &MF = getMachineFunction();
7607   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7608                                                    Alignment, AAInfo, Ranges);
7609   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7610                    MMO, IsExpanding);
7611 }
7612 
7613 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7614                                 ISD::LoadExtType ExtType, EVT VT,
7615                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7616                                 SDValue Offset, SDValue Mask, SDValue EVL,
7617                                 EVT MemVT, MachineMemOperand *MMO,
7618                                 bool IsExpanding) {
7619   if (VT == MemVT) {
7620     ExtType = ISD::NON_EXTLOAD;
7621   } else if (ExtType == ISD::NON_EXTLOAD) {
7622     assert(VT == MemVT && "Non-extending load from different memory type!");
7623   } else {
7624     // Extending load.
7625     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7626            "Should only be an extending load, not truncating!");
7627     assert(VT.isInteger() == MemVT.isInteger() &&
7628            "Cannot convert from FP to Int or Int -> FP!");
7629     assert(VT.isVector() == MemVT.isVector() &&
7630            "Cannot use an ext load to convert to or from a vector!");
7631     assert((!VT.isVector() ||
7632             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7633            "Cannot use an ext load to change the number of vector elements!");
7634   }
7635 
7636   bool Indexed = AM != ISD::UNINDEXED;
7637   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7638 
7639   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7640                          : getVTList(VT, MVT::Other);
7641   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7642   FoldingSetNodeID ID;
7643   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7644   ID.AddInteger(VT.getRawBits());
7645   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7646       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7647   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7648   void *IP = nullptr;
7649   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7650     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7651     return SDValue(E, 0);
7652   }
7653   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7654                                     ExtType, IsExpanding, MemVT, MMO);
7655   createOperands(N, Ops);
7656 
7657   CSEMap.InsertNode(N, IP);
7658   InsertNode(N);
7659   SDValue V(N, 0);
7660   NewSDValueDbgMsg(V, "Creating new node: ", this);
7661   return V;
7662 }
7663 
7664 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7665                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7666                                 MachinePointerInfo PtrInfo,
7667                                 MaybeAlign Alignment,
7668                                 MachineMemOperand::Flags MMOFlags,
7669                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7670                                 bool IsExpanding) {
7671   SDValue Undef = getUNDEF(Ptr.getValueType());
7672   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7673                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7674                    IsExpanding);
7675 }
7676 
7677 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7678                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7679                                 MachineMemOperand *MMO, bool IsExpanding) {
7680   SDValue Undef = getUNDEF(Ptr.getValueType());
7681   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7682                    Mask, EVL, VT, MMO, IsExpanding);
7683 }
7684 
7685 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7686                                    EVT VT, SDValue Chain, SDValue Ptr,
7687                                    SDValue Mask, SDValue EVL,
7688                                    MachinePointerInfo PtrInfo, EVT MemVT,
7689                                    MaybeAlign Alignment,
7690                                    MachineMemOperand::Flags MMOFlags,
7691                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7692   SDValue Undef = getUNDEF(Ptr.getValueType());
7693   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7694                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7695                    IsExpanding);
7696 }
7697 
7698 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7699                                    EVT VT, SDValue Chain, SDValue Ptr,
7700                                    SDValue Mask, SDValue EVL, EVT MemVT,
7701                                    MachineMemOperand *MMO, bool IsExpanding) {
7702   SDValue Undef = getUNDEF(Ptr.getValueType());
7703   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7704                    EVL, MemVT, MMO, IsExpanding);
7705 }
7706 
7707 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7708                                        SDValue Base, SDValue Offset,
7709                                        ISD::MemIndexedMode AM) {
7710   auto *LD = cast<VPLoadSDNode>(OrigLoad);
7711   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7712   // Don't propagate the invariant or dereferenceable flags.
7713   auto MMOFlags =
7714       LD->getMemOperand()->getFlags() &
7715       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7716   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7717                    LD->getChain(), Base, Offset, LD->getMask(),
7718                    LD->getVectorLength(), LD->getPointerInfo(),
7719                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7720                    nullptr, LD->isExpandingLoad());
7721 }
7722 
7723 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7724                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7725                                  MachinePointerInfo PtrInfo, Align Alignment,
7726                                  MachineMemOperand::Flags MMOFlags,
7727                                  const AAMDNodes &AAInfo, bool IsCompressing) {
7728   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7729 
7730   MMOFlags |= MachineMemOperand::MOStore;
7731   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7732 
7733   if (PtrInfo.V.isNull())
7734     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7735 
7736   MachineFunction &MF = getMachineFunction();
7737   uint64_t Size =
7738       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7739   MachineMemOperand *MMO =
7740       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7741   return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7742 }
7743 
7744 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7745                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7746                                  MachineMemOperand *MMO, bool IsCompressing) {
7747   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7748   EVT VT = Val.getValueType();
7749   SDVTList VTs = getVTList(MVT::Other);
7750   SDValue Undef = getUNDEF(Ptr.getValueType());
7751   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7752   FoldingSetNodeID ID;
7753   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7754   ID.AddInteger(VT.getRawBits());
7755   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7756       dl.getIROrder(), VTs, ISD::UNINDEXED, false, IsCompressing, VT, MMO));
7757   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7758   void *IP = nullptr;
7759   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7760     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7761     return SDValue(E, 0);
7762   }
7763   auto *N =
7764       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7765                                ISD::UNINDEXED, false, IsCompressing, VT, MMO);
7766   createOperands(N, Ops);
7767 
7768   CSEMap.InsertNode(N, IP);
7769   InsertNode(N);
7770   SDValue V(N, 0);
7771   NewSDValueDbgMsg(V, "Creating new node: ", this);
7772   return V;
7773 }
7774 
7775 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7776                                       SDValue Val, SDValue Ptr, SDValue Mask,
7777                                       SDValue EVL, MachinePointerInfo PtrInfo,
7778                                       EVT SVT, Align Alignment,
7779                                       MachineMemOperand::Flags MMOFlags,
7780                                       const AAMDNodes &AAInfo,
7781                                       bool IsCompressing) {
7782   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7783 
7784   MMOFlags |= MachineMemOperand::MOStore;
7785   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7786 
7787   if (PtrInfo.V.isNull())
7788     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7789 
7790   MachineFunction &MF = getMachineFunction();
7791   MachineMemOperand *MMO = MF.getMachineMemOperand(
7792       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7793       Alignment, AAInfo);
7794   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7795                          IsCompressing);
7796 }
7797 
7798 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7799                                       SDValue Val, SDValue Ptr, SDValue Mask,
7800                                       SDValue EVL, EVT SVT,
7801                                       MachineMemOperand *MMO,
7802                                       bool IsCompressing) {
7803   EVT VT = Val.getValueType();
7804 
7805   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7806   if (VT == SVT)
7807     return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7808 
7809   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7810          "Should only be a truncating store, not extending!");
7811   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
7812   assert(VT.isVector() == SVT.isVector() &&
7813          "Cannot use trunc store to convert to or from a vector!");
7814   assert((!VT.isVector() ||
7815           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7816          "Cannot use trunc store to change the number of vector elements!");
7817 
7818   SDVTList VTs = getVTList(MVT::Other);
7819   SDValue Undef = getUNDEF(Ptr.getValueType());
7820   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7821   FoldingSetNodeID ID;
7822   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7823   ID.AddInteger(SVT.getRawBits());
7824   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7825       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
7826   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7827   void *IP = nullptr;
7828   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7829     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7830     return SDValue(E, 0);
7831   }
7832   auto *N =
7833       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7834                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
7835   createOperands(N, Ops);
7836 
7837   CSEMap.InsertNode(N, IP);
7838   InsertNode(N);
7839   SDValue V(N, 0);
7840   NewSDValueDbgMsg(V, "Creating new node: ", this);
7841   return V;
7842 }
7843 
7844 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
7845                                         SDValue Base, SDValue Offset,
7846                                         ISD::MemIndexedMode AM) {
7847   auto *ST = cast<VPStoreSDNode>(OrigStore);
7848   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
7849   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7850   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
7851                    Offset,         ST->getMask(),  ST->getVectorLength()};
7852   FoldingSetNodeID ID;
7853   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7854   ID.AddInteger(ST->getMemoryVT().getRawBits());
7855   ID.AddInteger(ST->getRawSubclassData());
7856   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7857   void *IP = nullptr;
7858   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7859     return SDValue(E, 0);
7860 
7861   auto *N = newSDNode<VPStoreSDNode>(
7862       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
7863       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
7864   createOperands(N, Ops);
7865 
7866   CSEMap.InsertNode(N, IP);
7867   InsertNode(N);
7868   SDValue V(N, 0);
7869   NewSDValueDbgMsg(V, "Creating new node: ", this);
7870   return V;
7871 }
7872 
7873 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7874                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
7875                                   ISD::MemIndexType IndexType) {
7876   assert(Ops.size() == 6 && "Incompatible number of operands");
7877 
7878   FoldingSetNodeID ID;
7879   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
7880   ID.AddInteger(VT.getRawBits());
7881   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
7882       dl.getIROrder(), VTs, VT, MMO, IndexType));
7883   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7884   void *IP = nullptr;
7885   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7886     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
7887     return SDValue(E, 0);
7888   }
7889 
7890   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7891                                       VT, MMO, IndexType);
7892   createOperands(N, Ops);
7893 
7894   assert(N->getMask().getValueType().getVectorElementCount() ==
7895              N->getValueType(0).getVectorElementCount() &&
7896          "Vector width mismatch between mask and data");
7897   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7898              N->getValueType(0).getVectorElementCount().isScalable() &&
7899          "Scalable flags of index and data do not match");
7900   assert(ElementCount::isKnownGE(
7901              N->getIndex().getValueType().getVectorElementCount(),
7902              N->getValueType(0).getVectorElementCount()) &&
7903          "Vector width mismatch between index and data");
7904   assert(isa<ConstantSDNode>(N->getScale()) &&
7905          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7906          "Scale should be a constant power of 2");
7907 
7908   CSEMap.InsertNode(N, IP);
7909   InsertNode(N);
7910   SDValue V(N, 0);
7911   NewSDValueDbgMsg(V, "Creating new node: ", this);
7912   return V;
7913 }
7914 
7915 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7916                                    ArrayRef<SDValue> Ops,
7917                                    MachineMemOperand *MMO,
7918                                    ISD::MemIndexType IndexType) {
7919   assert(Ops.size() == 7 && "Incompatible number of operands");
7920 
7921   FoldingSetNodeID ID;
7922   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
7923   ID.AddInteger(VT.getRawBits());
7924   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
7925       dl.getIROrder(), VTs, VT, MMO, IndexType));
7926   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7927   void *IP = nullptr;
7928   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7929     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
7930     return SDValue(E, 0);
7931   }
7932   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7933                                        VT, MMO, IndexType);
7934   createOperands(N, Ops);
7935 
7936   assert(N->getMask().getValueType().getVectorElementCount() ==
7937              N->getValue().getValueType().getVectorElementCount() &&
7938          "Vector width mismatch between mask and data");
7939   assert(
7940       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7941           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7942       "Scalable flags of index and data do not match");
7943   assert(ElementCount::isKnownGE(
7944              N->getIndex().getValueType().getVectorElementCount(),
7945              N->getValue().getValueType().getVectorElementCount()) &&
7946          "Vector width mismatch between index and data");
7947   assert(isa<ConstantSDNode>(N->getScale()) &&
7948          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7949          "Scale should be a constant power of 2");
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::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7959                                     SDValue Base, SDValue Offset, SDValue Mask,
7960                                     SDValue PassThru, EVT MemVT,
7961                                     MachineMemOperand *MMO,
7962                                     ISD::MemIndexedMode AM,
7963                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7964   bool Indexed = AM != ISD::UNINDEXED;
7965   assert((Indexed || Offset.isUndef()) &&
7966          "Unindexed masked load with an offset!");
7967   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
7968                          : getVTList(VT, MVT::Other);
7969   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
7970   FoldingSetNodeID ID;
7971   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
7972   ID.AddInteger(MemVT.getRawBits());
7973   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
7974       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
7975   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7976   void *IP = nullptr;
7977   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7978     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
7979     return SDValue(E, 0);
7980   }
7981   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7982                                         AM, ExtTy, isExpanding, MemVT, MMO);
7983   createOperands(N, Ops);
7984 
7985   CSEMap.InsertNode(N, IP);
7986   InsertNode(N);
7987   SDValue V(N, 0);
7988   NewSDValueDbgMsg(V, "Creating new node: ", this);
7989   return V;
7990 }
7991 
7992 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
7993                                            SDValue Base, SDValue Offset,
7994                                            ISD::MemIndexedMode AM) {
7995   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
7996   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
7997   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
7998                        Offset, LD->getMask(), LD->getPassThru(),
7999                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8000                        LD->getExtensionType(), LD->isExpandingLoad());
8001 }
8002 
8003 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8004                                      SDValue Val, SDValue Base, SDValue Offset,
8005                                      SDValue Mask, EVT MemVT,
8006                                      MachineMemOperand *MMO,
8007                                      ISD::MemIndexedMode AM, bool IsTruncating,
8008                                      bool IsCompressing) {
8009   assert(Chain.getValueType() == MVT::Other &&
8010         "Invalid chain type");
8011   bool Indexed = AM != ISD::UNINDEXED;
8012   assert((Indexed || Offset.isUndef()) &&
8013          "Unindexed masked store with an offset!");
8014   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8015                          : getVTList(MVT::Other);
8016   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8017   FoldingSetNodeID ID;
8018   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8019   ID.AddInteger(MemVT.getRawBits());
8020   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8021       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8022   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8023   void *IP = nullptr;
8024   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8025     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8026     return SDValue(E, 0);
8027   }
8028   auto *N =
8029       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8030                                    IsTruncating, IsCompressing, MemVT, MMO);
8031   createOperands(N, Ops);
8032 
8033   CSEMap.InsertNode(N, IP);
8034   InsertNode(N);
8035   SDValue V(N, 0);
8036   NewSDValueDbgMsg(V, "Creating new node: ", this);
8037   return V;
8038 }
8039 
8040 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8041                                             SDValue Base, SDValue Offset,
8042                                             ISD::MemIndexedMode AM) {
8043   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8044   assert(ST->getOffset().isUndef() &&
8045          "Masked store is already a indexed store!");
8046   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8047                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8048                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8049 }
8050 
8051 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8052                                       ArrayRef<SDValue> Ops,
8053                                       MachineMemOperand *MMO,
8054                                       ISD::MemIndexType IndexType,
8055                                       ISD::LoadExtType ExtTy) {
8056   assert(Ops.size() == 6 && "Incompatible number of operands");
8057 
8058   FoldingSetNodeID ID;
8059   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8060   ID.AddInteger(MemVT.getRawBits());
8061   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8062       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8063   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8064   void *IP = nullptr;
8065   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8066     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8067     return SDValue(E, 0);
8068   }
8069 
8070   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8071   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8072                                           VTs, MemVT, MMO, IndexType, ExtTy);
8073   createOperands(N, Ops);
8074 
8075   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8076          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8077   assert(N->getMask().getValueType().getVectorElementCount() ==
8078              N->getValueType(0).getVectorElementCount() &&
8079          "Vector width mismatch between mask and data");
8080   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8081              N->getValueType(0).getVectorElementCount().isScalable() &&
8082          "Scalable flags of index and data do not match");
8083   assert(ElementCount::isKnownGE(
8084              N->getIndex().getValueType().getVectorElementCount(),
8085              N->getValueType(0).getVectorElementCount()) &&
8086          "Vector width mismatch between index and data");
8087   assert(isa<ConstantSDNode>(N->getScale()) &&
8088          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8089          "Scale should be a constant power of 2");
8090 
8091   CSEMap.InsertNode(N, IP);
8092   InsertNode(N);
8093   SDValue V(N, 0);
8094   NewSDValueDbgMsg(V, "Creating new node: ", this);
8095   return V;
8096 }
8097 
8098 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8099                                        ArrayRef<SDValue> Ops,
8100                                        MachineMemOperand *MMO,
8101                                        ISD::MemIndexType IndexType,
8102                                        bool IsTrunc) {
8103   assert(Ops.size() == 6 && "Incompatible number of operands");
8104 
8105   FoldingSetNodeID ID;
8106   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8107   ID.AddInteger(MemVT.getRawBits());
8108   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8109       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8110   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8111   void *IP = nullptr;
8112   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8113     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8114     return SDValue(E, 0);
8115   }
8116 
8117   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8118   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8119                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8120   createOperands(N, Ops);
8121 
8122   assert(N->getMask().getValueType().getVectorElementCount() ==
8123              N->getValue().getValueType().getVectorElementCount() &&
8124          "Vector width mismatch between mask and data");
8125   assert(
8126       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8127           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8128       "Scalable flags of index and data do not match");
8129   assert(ElementCount::isKnownGE(
8130              N->getIndex().getValueType().getVectorElementCount(),
8131              N->getValue().getValueType().getVectorElementCount()) &&
8132          "Vector width mismatch between index and data");
8133   assert(isa<ConstantSDNode>(N->getScale()) &&
8134          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8135          "Scale should be a constant power of 2");
8136 
8137   CSEMap.InsertNode(N, IP);
8138   InsertNode(N);
8139   SDValue V(N, 0);
8140   NewSDValueDbgMsg(V, "Creating new node: ", this);
8141   return V;
8142 }
8143 
8144 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8145   // select undef, T, F --> T (if T is a constant), otherwise F
8146   // select, ?, undef, F --> F
8147   // select, ?, T, undef --> T
8148   if (Cond.isUndef())
8149     return isConstantValueOfAnyType(T) ? T : F;
8150   if (T.isUndef())
8151     return F;
8152   if (F.isUndef())
8153     return T;
8154 
8155   // select true, T, F --> T
8156   // select false, T, F --> F
8157   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8158     return CondC->isZero() ? F : T;
8159 
8160   // TODO: This should simplify VSELECT with constant condition using something
8161   // like this (but check boolean contents to be complete?):
8162   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8163   //    return T;
8164   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8165   //    return F;
8166 
8167   // select ?, T, T --> T
8168   if (T == F)
8169     return T;
8170 
8171   return SDValue();
8172 }
8173 
8174 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8175   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8176   if (X.isUndef())
8177     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8178   // shift X, undef --> undef (because it may shift by the bitwidth)
8179   if (Y.isUndef())
8180     return getUNDEF(X.getValueType());
8181 
8182   // shift 0, Y --> 0
8183   // shift X, 0 --> X
8184   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8185     return X;
8186 
8187   // shift X, C >= bitwidth(X) --> undef
8188   // All vector elements must be too big (or undef) to avoid partial undefs.
8189   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8190     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8191   };
8192   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8193     return getUNDEF(X.getValueType());
8194 
8195   return SDValue();
8196 }
8197 
8198 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8199                                       SDNodeFlags Flags) {
8200   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8201   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8202   // operation is poison. That result can be relaxed to undef.
8203   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8204   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8205   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8206                 (YC && YC->getValueAPF().isNaN());
8207   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8208                 (YC && YC->getValueAPF().isInfinity());
8209 
8210   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8211     return getUNDEF(X.getValueType());
8212 
8213   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8214     return getUNDEF(X.getValueType());
8215 
8216   if (!YC)
8217     return SDValue();
8218 
8219   // X + -0.0 --> X
8220   if (Opcode == ISD::FADD)
8221     if (YC->getValueAPF().isNegZero())
8222       return X;
8223 
8224   // X - +0.0 --> X
8225   if (Opcode == ISD::FSUB)
8226     if (YC->getValueAPF().isPosZero())
8227       return X;
8228 
8229   // X * 1.0 --> X
8230   // X / 1.0 --> X
8231   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8232     if (YC->getValueAPF().isExactlyValue(1.0))
8233       return X;
8234 
8235   // X * 0.0 --> 0.0
8236   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8237     if (YC->getValueAPF().isZero())
8238       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8239 
8240   return SDValue();
8241 }
8242 
8243 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8244                                SDValue Ptr, SDValue SV, unsigned Align) {
8245   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8246   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8247 }
8248 
8249 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8250                               ArrayRef<SDUse> Ops) {
8251   switch (Ops.size()) {
8252   case 0: return getNode(Opcode, DL, VT);
8253   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8254   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8255   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8256   default: break;
8257   }
8258 
8259   // Copy from an SDUse array into an SDValue array for use with
8260   // the regular getNode logic.
8261   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8262   return getNode(Opcode, DL, VT, NewOps);
8263 }
8264 
8265 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8266                               ArrayRef<SDValue> Ops) {
8267   SDNodeFlags Flags;
8268   if (Inserter)
8269     Flags = Inserter->getFlags();
8270   return getNode(Opcode, DL, VT, Ops, Flags);
8271 }
8272 
8273 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8274                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8275   unsigned NumOps = Ops.size();
8276   switch (NumOps) {
8277   case 0: return getNode(Opcode, DL, VT);
8278   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8279   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8280   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8281   default: break;
8282   }
8283 
8284 #ifndef NDEBUG
8285   for (auto &Op : Ops)
8286     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8287            "Operand is DELETED_NODE!");
8288 #endif
8289 
8290   switch (Opcode) {
8291   default: break;
8292   case ISD::BUILD_VECTOR:
8293     // Attempt to simplify BUILD_VECTOR.
8294     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8295       return V;
8296     break;
8297   case ISD::CONCAT_VECTORS:
8298     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8299       return V;
8300     break;
8301   case ISD::SELECT_CC:
8302     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8303     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8304            "LHS and RHS of condition must have same type!");
8305     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8306            "True and False arms of SelectCC must have same type!");
8307     assert(Ops[2].getValueType() == VT &&
8308            "select_cc node must be of same type as true and false value!");
8309     break;
8310   case ISD::BR_CC:
8311     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8312     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8313            "LHS/RHS of comparison should match types!");
8314     break;
8315   }
8316 
8317   // Memoize nodes.
8318   SDNode *N;
8319   SDVTList VTs = getVTList(VT);
8320 
8321   if (VT != MVT::Glue) {
8322     FoldingSetNodeID ID;
8323     AddNodeIDNode(ID, Opcode, VTs, Ops);
8324     void *IP = nullptr;
8325 
8326     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8327       return SDValue(E, 0);
8328 
8329     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8330     createOperands(N, Ops);
8331 
8332     CSEMap.InsertNode(N, IP);
8333   } else {
8334     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8335     createOperands(N, Ops);
8336   }
8337 
8338   N->setFlags(Flags);
8339   InsertNode(N);
8340   SDValue V(N, 0);
8341   NewSDValueDbgMsg(V, "Creating new node: ", this);
8342   return V;
8343 }
8344 
8345 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8346                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8347   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8348 }
8349 
8350 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8351                               ArrayRef<SDValue> Ops) {
8352   SDNodeFlags Flags;
8353   if (Inserter)
8354     Flags = Inserter->getFlags();
8355   return getNode(Opcode, DL, VTList, Ops, Flags);
8356 }
8357 
8358 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8359                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8360   if (VTList.NumVTs == 1)
8361     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8362 
8363 #ifndef NDEBUG
8364   for (auto &Op : Ops)
8365     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8366            "Operand is DELETED_NODE!");
8367 #endif
8368 
8369   switch (Opcode) {
8370   case ISD::STRICT_FP_EXTEND:
8371     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8372            "Invalid STRICT_FP_EXTEND!");
8373     assert(VTList.VTs[0].isFloatingPoint() &&
8374            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8375     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8376            "STRICT_FP_EXTEND result type should be vector iff the operand "
8377            "type is vector!");
8378     assert((!VTList.VTs[0].isVector() ||
8379             VTList.VTs[0].getVectorNumElements() ==
8380             Ops[1].getValueType().getVectorNumElements()) &&
8381            "Vector element count mismatch!");
8382     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8383            "Invalid fpext node, dst <= src!");
8384     break;
8385   case ISD::STRICT_FP_ROUND:
8386     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8387     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8388            "STRICT_FP_ROUND result type should be vector iff the operand "
8389            "type is vector!");
8390     assert((!VTList.VTs[0].isVector() ||
8391             VTList.VTs[0].getVectorNumElements() ==
8392             Ops[1].getValueType().getVectorNumElements()) &&
8393            "Vector element count mismatch!");
8394     assert(VTList.VTs[0].isFloatingPoint() &&
8395            Ops[1].getValueType().isFloatingPoint() &&
8396            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8397            isa<ConstantSDNode>(Ops[2]) &&
8398            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8399             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8400            "Invalid STRICT_FP_ROUND!");
8401     break;
8402 #if 0
8403   // FIXME: figure out how to safely handle things like
8404   // int foo(int x) { return 1 << (x & 255); }
8405   // int bar() { return foo(256); }
8406   case ISD::SRA_PARTS:
8407   case ISD::SRL_PARTS:
8408   case ISD::SHL_PARTS:
8409     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8410         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8411       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8412     else if (N3.getOpcode() == ISD::AND)
8413       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8414         // If the and is only masking out bits that cannot effect the shift,
8415         // eliminate the and.
8416         unsigned NumBits = VT.getScalarSizeInBits()*2;
8417         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8418           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8419       }
8420     break;
8421 #endif
8422   }
8423 
8424   // Memoize the node unless it returns a flag.
8425   SDNode *N;
8426   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8427     FoldingSetNodeID ID;
8428     AddNodeIDNode(ID, Opcode, VTList, Ops);
8429     void *IP = nullptr;
8430     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8431       return SDValue(E, 0);
8432 
8433     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8434     createOperands(N, Ops);
8435     CSEMap.InsertNode(N, IP);
8436   } else {
8437     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8438     createOperands(N, Ops);
8439   }
8440 
8441   N->setFlags(Flags);
8442   InsertNode(N);
8443   SDValue V(N, 0);
8444   NewSDValueDbgMsg(V, "Creating new node: ", this);
8445   return V;
8446 }
8447 
8448 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8449                               SDVTList VTList) {
8450   return getNode(Opcode, DL, VTList, None);
8451 }
8452 
8453 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8454                               SDValue N1) {
8455   SDValue Ops[] = { N1 };
8456   return getNode(Opcode, DL, VTList, Ops);
8457 }
8458 
8459 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8460                               SDValue N1, SDValue N2) {
8461   SDValue Ops[] = { N1, N2 };
8462   return getNode(Opcode, DL, VTList, Ops);
8463 }
8464 
8465 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8466                               SDValue N1, SDValue N2, SDValue N3) {
8467   SDValue Ops[] = { N1, N2, N3 };
8468   return getNode(Opcode, DL, VTList, Ops);
8469 }
8470 
8471 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8472                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8473   SDValue Ops[] = { N1, N2, N3, N4 };
8474   return getNode(Opcode, DL, VTList, Ops);
8475 }
8476 
8477 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8478                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8479                               SDValue N5) {
8480   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8481   return getNode(Opcode, DL, VTList, Ops);
8482 }
8483 
8484 SDVTList SelectionDAG::getVTList(EVT VT) {
8485   return makeVTList(SDNode::getValueTypeList(VT), 1);
8486 }
8487 
8488 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8489   FoldingSetNodeID ID;
8490   ID.AddInteger(2U);
8491   ID.AddInteger(VT1.getRawBits());
8492   ID.AddInteger(VT2.getRawBits());
8493 
8494   void *IP = nullptr;
8495   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8496   if (!Result) {
8497     EVT *Array = Allocator.Allocate<EVT>(2);
8498     Array[0] = VT1;
8499     Array[1] = VT2;
8500     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8501     VTListMap.InsertNode(Result, IP);
8502   }
8503   return Result->getSDVTList();
8504 }
8505 
8506 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8507   FoldingSetNodeID ID;
8508   ID.AddInteger(3U);
8509   ID.AddInteger(VT1.getRawBits());
8510   ID.AddInteger(VT2.getRawBits());
8511   ID.AddInteger(VT3.getRawBits());
8512 
8513   void *IP = nullptr;
8514   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8515   if (!Result) {
8516     EVT *Array = Allocator.Allocate<EVT>(3);
8517     Array[0] = VT1;
8518     Array[1] = VT2;
8519     Array[2] = VT3;
8520     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8521     VTListMap.InsertNode(Result, IP);
8522   }
8523   return Result->getSDVTList();
8524 }
8525 
8526 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8527   FoldingSetNodeID ID;
8528   ID.AddInteger(4U);
8529   ID.AddInteger(VT1.getRawBits());
8530   ID.AddInteger(VT2.getRawBits());
8531   ID.AddInteger(VT3.getRawBits());
8532   ID.AddInteger(VT4.getRawBits());
8533 
8534   void *IP = nullptr;
8535   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8536   if (!Result) {
8537     EVT *Array = Allocator.Allocate<EVT>(4);
8538     Array[0] = VT1;
8539     Array[1] = VT2;
8540     Array[2] = VT3;
8541     Array[3] = VT4;
8542     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8543     VTListMap.InsertNode(Result, IP);
8544   }
8545   return Result->getSDVTList();
8546 }
8547 
8548 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8549   unsigned NumVTs = VTs.size();
8550   FoldingSetNodeID ID;
8551   ID.AddInteger(NumVTs);
8552   for (unsigned index = 0; index < NumVTs; index++) {
8553     ID.AddInteger(VTs[index].getRawBits());
8554   }
8555 
8556   void *IP = nullptr;
8557   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8558   if (!Result) {
8559     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8560     llvm::copy(VTs, Array);
8561     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8562     VTListMap.InsertNode(Result, IP);
8563   }
8564   return Result->getSDVTList();
8565 }
8566 
8567 
8568 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8569 /// specified operands.  If the resultant node already exists in the DAG,
8570 /// this does not modify the specified node, instead it returns the node that
8571 /// already exists.  If the resultant node does not exist in the DAG, the
8572 /// input node is returned.  As a degenerate case, if you specify the same
8573 /// input operands as the node already has, the input node is returned.
8574 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8575   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8576 
8577   // Check to see if there is no change.
8578   if (Op == N->getOperand(0)) return N;
8579 
8580   // See if the modified node already exists.
8581   void *InsertPos = nullptr;
8582   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8583     return Existing;
8584 
8585   // Nope it doesn't.  Remove the node from its current place in the maps.
8586   if (InsertPos)
8587     if (!RemoveNodeFromCSEMaps(N))
8588       InsertPos = nullptr;
8589 
8590   // Now we update the operands.
8591   N->OperandList[0].set(Op);
8592 
8593   updateDivergence(N);
8594   // If this gets put into a CSE map, add it.
8595   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8596   return N;
8597 }
8598 
8599 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8600   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8601 
8602   // Check to see if there is no change.
8603   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8604     return N;   // No operands changed, just return the input node.
8605 
8606   // See if the modified node already exists.
8607   void *InsertPos = nullptr;
8608   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8609     return Existing;
8610 
8611   // Nope it doesn't.  Remove the node from its current place in the maps.
8612   if (InsertPos)
8613     if (!RemoveNodeFromCSEMaps(N))
8614       InsertPos = nullptr;
8615 
8616   // Now we update the operands.
8617   if (N->OperandList[0] != Op1)
8618     N->OperandList[0].set(Op1);
8619   if (N->OperandList[1] != Op2)
8620     N->OperandList[1].set(Op2);
8621 
8622   updateDivergence(N);
8623   // If this gets put into a CSE map, add it.
8624   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8625   return N;
8626 }
8627 
8628 SDNode *SelectionDAG::
8629 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8630   SDValue Ops[] = { Op1, Op2, Op3 };
8631   return UpdateNodeOperands(N, Ops);
8632 }
8633 
8634 SDNode *SelectionDAG::
8635 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8636                    SDValue Op3, SDValue Op4) {
8637   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8638   return UpdateNodeOperands(N, Ops);
8639 }
8640 
8641 SDNode *SelectionDAG::
8642 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8643                    SDValue Op3, SDValue Op4, SDValue Op5) {
8644   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8645   return UpdateNodeOperands(N, Ops);
8646 }
8647 
8648 SDNode *SelectionDAG::
8649 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8650   unsigned NumOps = Ops.size();
8651   assert(N->getNumOperands() == NumOps &&
8652          "Update with wrong number of operands");
8653 
8654   // If no operands changed just return the input node.
8655   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8656     return N;
8657 
8658   // See if the modified node already exists.
8659   void *InsertPos = nullptr;
8660   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8661     return Existing;
8662 
8663   // Nope it doesn't.  Remove the node from its current place in the maps.
8664   if (InsertPos)
8665     if (!RemoveNodeFromCSEMaps(N))
8666       InsertPos = nullptr;
8667 
8668   // Now we update the operands.
8669   for (unsigned i = 0; i != NumOps; ++i)
8670     if (N->OperandList[i] != Ops[i])
8671       N->OperandList[i].set(Ops[i]);
8672 
8673   updateDivergence(N);
8674   // If this gets put into a CSE map, add it.
8675   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8676   return N;
8677 }
8678 
8679 /// DropOperands - Release the operands and set this node to have
8680 /// zero operands.
8681 void SDNode::DropOperands() {
8682   // Unlike the code in MorphNodeTo that does this, we don't need to
8683   // watch for dead nodes here.
8684   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8685     SDUse &Use = *I++;
8686     Use.set(SDValue());
8687   }
8688 }
8689 
8690 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8691                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8692   if (NewMemRefs.empty()) {
8693     N->clearMemRefs();
8694     return;
8695   }
8696 
8697   // Check if we can avoid allocating by storing a single reference directly.
8698   if (NewMemRefs.size() == 1) {
8699     N->MemRefs = NewMemRefs[0];
8700     N->NumMemRefs = 1;
8701     return;
8702   }
8703 
8704   MachineMemOperand **MemRefsBuffer =
8705       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8706   llvm::copy(NewMemRefs, MemRefsBuffer);
8707   N->MemRefs = MemRefsBuffer;
8708   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8709 }
8710 
8711 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8712 /// machine opcode.
8713 ///
8714 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8715                                    EVT VT) {
8716   SDVTList VTs = getVTList(VT);
8717   return SelectNodeTo(N, MachineOpc, VTs, None);
8718 }
8719 
8720 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8721                                    EVT VT, SDValue Op1) {
8722   SDVTList VTs = getVTList(VT);
8723   SDValue Ops[] = { Op1 };
8724   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8725 }
8726 
8727 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8728                                    EVT VT, SDValue Op1,
8729                                    SDValue Op2) {
8730   SDVTList VTs = getVTList(VT);
8731   SDValue Ops[] = { Op1, Op2 };
8732   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8733 }
8734 
8735 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8736                                    EVT VT, SDValue Op1,
8737                                    SDValue Op2, SDValue Op3) {
8738   SDVTList VTs = getVTList(VT);
8739   SDValue Ops[] = { Op1, Op2, Op3 };
8740   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8741 }
8742 
8743 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8744                                    EVT VT, ArrayRef<SDValue> Ops) {
8745   SDVTList VTs = getVTList(VT);
8746   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8747 }
8748 
8749 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8750                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8751   SDVTList VTs = getVTList(VT1, VT2);
8752   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8753 }
8754 
8755 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8756                                    EVT VT1, EVT VT2) {
8757   SDVTList VTs = getVTList(VT1, VT2);
8758   return SelectNodeTo(N, MachineOpc, VTs, None);
8759 }
8760 
8761 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8762                                    EVT VT1, EVT VT2, EVT VT3,
8763                                    ArrayRef<SDValue> Ops) {
8764   SDVTList VTs = getVTList(VT1, VT2, VT3);
8765   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8766 }
8767 
8768 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8769                                    EVT VT1, EVT VT2,
8770                                    SDValue Op1, SDValue Op2) {
8771   SDVTList VTs = getVTList(VT1, VT2);
8772   SDValue Ops[] = { Op1, Op2 };
8773   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8774 }
8775 
8776 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8777                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8778   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8779   // Reset the NodeID to -1.
8780   New->setNodeId(-1);
8781   if (New != N) {
8782     ReplaceAllUsesWith(N, New);
8783     RemoveDeadNode(N);
8784   }
8785   return New;
8786 }
8787 
8788 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8789 /// the line number information on the merged node since it is not possible to
8790 /// preserve the information that operation is associated with multiple lines.
8791 /// This will make the debugger working better at -O0, were there is a higher
8792 /// probability having other instructions associated with that line.
8793 ///
8794 /// For IROrder, we keep the smaller of the two
8795 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8796   DebugLoc NLoc = N->getDebugLoc();
8797   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8798     N->setDebugLoc(DebugLoc());
8799   }
8800   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8801   N->setIROrder(Order);
8802   return N;
8803 }
8804 
8805 /// MorphNodeTo - This *mutates* the specified node to have the specified
8806 /// return type, opcode, and operands.
8807 ///
8808 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8809 /// node of the specified opcode and operands, it returns that node instead of
8810 /// the current one.  Note that the SDLoc need not be the same.
8811 ///
8812 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8813 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8814 /// node, and because it doesn't require CSE recalculation for any of
8815 /// the node's users.
8816 ///
8817 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8818 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8819 /// the legalizer which maintain worklists that would need to be updated when
8820 /// deleting things.
8821 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8822                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8823   // If an identical node already exists, use it.
8824   void *IP = nullptr;
8825   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8826     FoldingSetNodeID ID;
8827     AddNodeIDNode(ID, Opc, VTs, Ops);
8828     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8829       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8830   }
8831 
8832   if (!RemoveNodeFromCSEMaps(N))
8833     IP = nullptr;
8834 
8835   // Start the morphing.
8836   N->NodeType = Opc;
8837   N->ValueList = VTs.VTs;
8838   N->NumValues = VTs.NumVTs;
8839 
8840   // Clear the operands list, updating used nodes to remove this from their
8841   // use list.  Keep track of any operands that become dead as a result.
8842   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8843   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8844     SDUse &Use = *I++;
8845     SDNode *Used = Use.getNode();
8846     Use.set(SDValue());
8847     if (Used->use_empty())
8848       DeadNodeSet.insert(Used);
8849   }
8850 
8851   // For MachineNode, initialize the memory references information.
8852   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8853     MN->clearMemRefs();
8854 
8855   // Swap for an appropriately sized array from the recycler.
8856   removeOperands(N);
8857   createOperands(N, Ops);
8858 
8859   // Delete any nodes that are still dead after adding the uses for the
8860   // new operands.
8861   if (!DeadNodeSet.empty()) {
8862     SmallVector<SDNode *, 16> DeadNodes;
8863     for (SDNode *N : DeadNodeSet)
8864       if (N->use_empty())
8865         DeadNodes.push_back(N);
8866     RemoveDeadNodes(DeadNodes);
8867   }
8868 
8869   if (IP)
8870     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8871   return N;
8872 }
8873 
8874 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8875   unsigned OrigOpc = Node->getOpcode();
8876   unsigned NewOpc;
8877   switch (OrigOpc) {
8878   default:
8879     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8880 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8881   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8882 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8883   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8884 #include "llvm/IR/ConstrainedOps.def"
8885   }
8886 
8887   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8888 
8889   // We're taking this node out of the chain, so we need to re-link things.
8890   SDValue InputChain = Node->getOperand(0);
8891   SDValue OutputChain = SDValue(Node, 1);
8892   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8893 
8894   SmallVector<SDValue, 3> Ops;
8895   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8896     Ops.push_back(Node->getOperand(i));
8897 
8898   SDVTList VTs = getVTList(Node->getValueType(0));
8899   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8900 
8901   // MorphNodeTo can operate in two ways: if an existing node with the
8902   // specified operands exists, it can just return it.  Otherwise, it
8903   // updates the node in place to have the requested operands.
8904   if (Res == Node) {
8905     // If we updated the node in place, reset the node ID.  To the isel,
8906     // this should be just like a newly allocated machine node.
8907     Res->setNodeId(-1);
8908   } else {
8909     ReplaceAllUsesWith(Node, Res);
8910     RemoveDeadNode(Node);
8911   }
8912 
8913   return Res;
8914 }
8915 
8916 /// getMachineNode - These are used for target selectors to create a new node
8917 /// with specified return type(s), MachineInstr opcode, and operands.
8918 ///
8919 /// Note that getMachineNode returns the resultant node.  If there is already a
8920 /// node of the specified opcode and operands, it returns that node instead of
8921 /// the current one.
8922 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8923                                             EVT VT) {
8924   SDVTList VTs = getVTList(VT);
8925   return getMachineNode(Opcode, dl, VTs, None);
8926 }
8927 
8928 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8929                                             EVT VT, SDValue Op1) {
8930   SDVTList VTs = getVTList(VT);
8931   SDValue Ops[] = { Op1 };
8932   return getMachineNode(Opcode, dl, VTs, Ops);
8933 }
8934 
8935 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8936                                             EVT VT, SDValue Op1, SDValue Op2) {
8937   SDVTList VTs = getVTList(VT);
8938   SDValue Ops[] = { Op1, Op2 };
8939   return getMachineNode(Opcode, dl, VTs, Ops);
8940 }
8941 
8942 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8943                                             EVT VT, SDValue Op1, SDValue Op2,
8944                                             SDValue Op3) {
8945   SDVTList VTs = getVTList(VT);
8946   SDValue Ops[] = { Op1, Op2, Op3 };
8947   return getMachineNode(Opcode, dl, VTs, Ops);
8948 }
8949 
8950 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8951                                             EVT VT, ArrayRef<SDValue> Ops) {
8952   SDVTList VTs = getVTList(VT);
8953   return getMachineNode(Opcode, dl, VTs, Ops);
8954 }
8955 
8956 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8957                                             EVT VT1, EVT VT2, SDValue Op1,
8958                                             SDValue Op2) {
8959   SDVTList VTs = getVTList(VT1, VT2);
8960   SDValue Ops[] = { Op1, Op2 };
8961   return getMachineNode(Opcode, dl, VTs, Ops);
8962 }
8963 
8964 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8965                                             EVT VT1, EVT VT2, SDValue Op1,
8966                                             SDValue Op2, SDValue Op3) {
8967   SDVTList VTs = getVTList(VT1, VT2);
8968   SDValue Ops[] = { Op1, Op2, Op3 };
8969   return getMachineNode(Opcode, dl, VTs, Ops);
8970 }
8971 
8972 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8973                                             EVT VT1, EVT VT2,
8974                                             ArrayRef<SDValue> Ops) {
8975   SDVTList VTs = getVTList(VT1, VT2);
8976   return getMachineNode(Opcode, dl, VTs, Ops);
8977 }
8978 
8979 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8980                                             EVT VT1, EVT VT2, EVT VT3,
8981                                             SDValue Op1, SDValue Op2) {
8982   SDVTList VTs = getVTList(VT1, VT2, VT3);
8983   SDValue Ops[] = { Op1, Op2 };
8984   return getMachineNode(Opcode, dl, VTs, Ops);
8985 }
8986 
8987 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8988                                             EVT VT1, EVT VT2, EVT VT3,
8989                                             SDValue Op1, SDValue Op2,
8990                                             SDValue Op3) {
8991   SDVTList VTs = getVTList(VT1, VT2, VT3);
8992   SDValue Ops[] = { Op1, Op2, Op3 };
8993   return getMachineNode(Opcode, dl, VTs, Ops);
8994 }
8995 
8996 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8997                                             EVT VT1, EVT VT2, EVT VT3,
8998                                             ArrayRef<SDValue> Ops) {
8999   SDVTList VTs = getVTList(VT1, VT2, VT3);
9000   return getMachineNode(Opcode, dl, VTs, Ops);
9001 }
9002 
9003 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9004                                             ArrayRef<EVT> ResultTys,
9005                                             ArrayRef<SDValue> Ops) {
9006   SDVTList VTs = getVTList(ResultTys);
9007   return getMachineNode(Opcode, dl, VTs, Ops);
9008 }
9009 
9010 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9011                                             SDVTList VTs,
9012                                             ArrayRef<SDValue> Ops) {
9013   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9014   MachineSDNode *N;
9015   void *IP = nullptr;
9016 
9017   if (DoCSE) {
9018     FoldingSetNodeID ID;
9019     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9020     IP = nullptr;
9021     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9022       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9023     }
9024   }
9025 
9026   // Allocate a new MachineSDNode.
9027   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9028   createOperands(N, Ops);
9029 
9030   if (DoCSE)
9031     CSEMap.InsertNode(N, IP);
9032 
9033   InsertNode(N);
9034   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9035   return N;
9036 }
9037 
9038 /// getTargetExtractSubreg - A convenience function for creating
9039 /// TargetOpcode::EXTRACT_SUBREG nodes.
9040 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9041                                              SDValue Operand) {
9042   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9043   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9044                                   VT, Operand, SRIdxVal);
9045   return SDValue(Subreg, 0);
9046 }
9047 
9048 /// getTargetInsertSubreg - A convenience function for creating
9049 /// TargetOpcode::INSERT_SUBREG nodes.
9050 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9051                                             SDValue Operand, SDValue Subreg) {
9052   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9053   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9054                                   VT, Operand, Subreg, SRIdxVal);
9055   return SDValue(Result, 0);
9056 }
9057 
9058 /// getNodeIfExists - Get the specified node if it's already available, or
9059 /// else return NULL.
9060 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9061                                       ArrayRef<SDValue> Ops) {
9062   SDNodeFlags Flags;
9063   if (Inserter)
9064     Flags = Inserter->getFlags();
9065   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9066 }
9067 
9068 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9069                                       ArrayRef<SDValue> Ops,
9070                                       const SDNodeFlags Flags) {
9071   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9072     FoldingSetNodeID ID;
9073     AddNodeIDNode(ID, Opcode, VTList, Ops);
9074     void *IP = nullptr;
9075     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9076       E->intersectFlagsWith(Flags);
9077       return E;
9078     }
9079   }
9080   return nullptr;
9081 }
9082 
9083 /// doesNodeExist - Check if a node exists without modifying its flags.
9084 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9085                                  ArrayRef<SDValue> Ops) {
9086   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9087     FoldingSetNodeID ID;
9088     AddNodeIDNode(ID, Opcode, VTList, Ops);
9089     void *IP = nullptr;
9090     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9091       return true;
9092   }
9093   return false;
9094 }
9095 
9096 /// getDbgValue - Creates a SDDbgValue node.
9097 ///
9098 /// SDNode
9099 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9100                                       SDNode *N, unsigned R, bool IsIndirect,
9101                                       const DebugLoc &DL, unsigned O) {
9102   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9103          "Expected inlined-at fields to agree");
9104   return new (DbgInfo->getAlloc())
9105       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9106                  {}, IsIndirect, DL, O,
9107                  /*IsVariadic=*/false);
9108 }
9109 
9110 /// Constant
9111 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9112                                               DIExpression *Expr,
9113                                               const Value *C,
9114                                               const DebugLoc &DL, unsigned O) {
9115   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9116          "Expected inlined-at fields to agree");
9117   return new (DbgInfo->getAlloc())
9118       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9119                  /*IsIndirect=*/false, DL, O,
9120                  /*IsVariadic=*/false);
9121 }
9122 
9123 /// FrameIndex
9124 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9125                                                 DIExpression *Expr, unsigned FI,
9126                                                 bool IsIndirect,
9127                                                 const DebugLoc &DL,
9128                                                 unsigned O) {
9129   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9130          "Expected inlined-at fields to agree");
9131   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9132 }
9133 
9134 /// FrameIndex with dependencies
9135 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9136                                                 DIExpression *Expr, unsigned FI,
9137                                                 ArrayRef<SDNode *> Dependencies,
9138                                                 bool IsIndirect,
9139                                                 const DebugLoc &DL,
9140                                                 unsigned O) {
9141   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9142          "Expected inlined-at fields to agree");
9143   return new (DbgInfo->getAlloc())
9144       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9145                  Dependencies, IsIndirect, DL, O,
9146                  /*IsVariadic=*/false);
9147 }
9148 
9149 /// VReg
9150 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9151                                           unsigned VReg, bool IsIndirect,
9152                                           const DebugLoc &DL, unsigned O) {
9153   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9154          "Expected inlined-at fields to agree");
9155   return new (DbgInfo->getAlloc())
9156       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9157                  {}, IsIndirect, DL, O,
9158                  /*IsVariadic=*/false);
9159 }
9160 
9161 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9162                                           ArrayRef<SDDbgOperand> Locs,
9163                                           ArrayRef<SDNode *> Dependencies,
9164                                           bool IsIndirect, const DebugLoc &DL,
9165                                           unsigned O, bool IsVariadic) {
9166   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9167          "Expected inlined-at fields to agree");
9168   return new (DbgInfo->getAlloc())
9169       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9170                  DL, O, IsVariadic);
9171 }
9172 
9173 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9174                                      unsigned OffsetInBits, unsigned SizeInBits,
9175                                      bool InvalidateDbg) {
9176   SDNode *FromNode = From.getNode();
9177   SDNode *ToNode = To.getNode();
9178   assert(FromNode && ToNode && "Can't modify dbg values");
9179 
9180   // PR35338
9181   // TODO: assert(From != To && "Redundant dbg value transfer");
9182   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9183   if (From == To || FromNode == ToNode)
9184     return;
9185 
9186   if (!FromNode->getHasDebugValue())
9187     return;
9188 
9189   SDDbgOperand FromLocOp =
9190       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9191   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9192 
9193   SmallVector<SDDbgValue *, 2> ClonedDVs;
9194   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9195     if (Dbg->isInvalidated())
9196       continue;
9197 
9198     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9199 
9200     // Create a new location ops vector that is equal to the old vector, but
9201     // with each instance of FromLocOp replaced with ToLocOp.
9202     bool Changed = false;
9203     auto NewLocOps = Dbg->copyLocationOps();
9204     std::replace_if(
9205         NewLocOps.begin(), NewLocOps.end(),
9206         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9207           bool Match = Op == FromLocOp;
9208           Changed |= Match;
9209           return Match;
9210         },
9211         ToLocOp);
9212     // Ignore this SDDbgValue if we didn't find a matching location.
9213     if (!Changed)
9214       continue;
9215 
9216     DIVariable *Var = Dbg->getVariable();
9217     auto *Expr = Dbg->getExpression();
9218     // If a fragment is requested, update the expression.
9219     if (SizeInBits) {
9220       // When splitting a larger (e.g., sign-extended) value whose
9221       // lower bits are described with an SDDbgValue, do not attempt
9222       // to transfer the SDDbgValue to the upper bits.
9223       if (auto FI = Expr->getFragmentInfo())
9224         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9225           continue;
9226       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9227                                                              SizeInBits);
9228       if (!Fragment)
9229         continue;
9230       Expr = *Fragment;
9231     }
9232 
9233     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9234     // Clone the SDDbgValue and move it to To.
9235     SDDbgValue *Clone = getDbgValueList(
9236         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9237         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9238         Dbg->isVariadic());
9239     ClonedDVs.push_back(Clone);
9240 
9241     if (InvalidateDbg) {
9242       // Invalidate value and indicate the SDDbgValue should not be emitted.
9243       Dbg->setIsInvalidated();
9244       Dbg->setIsEmitted();
9245     }
9246   }
9247 
9248   for (SDDbgValue *Dbg : ClonedDVs) {
9249     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9250            "Transferred DbgValues should depend on the new SDNode");
9251     AddDbgValue(Dbg, false);
9252   }
9253 }
9254 
9255 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9256   if (!N.getHasDebugValue())
9257     return;
9258 
9259   SmallVector<SDDbgValue *, 2> ClonedDVs;
9260   for (auto DV : GetDbgValues(&N)) {
9261     if (DV->isInvalidated())
9262       continue;
9263     switch (N.getOpcode()) {
9264     default:
9265       break;
9266     case ISD::ADD:
9267       SDValue N0 = N.getOperand(0);
9268       SDValue N1 = N.getOperand(1);
9269       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9270           isConstantIntBuildVectorOrConstantInt(N1)) {
9271         uint64_t Offset = N.getConstantOperandVal(1);
9272 
9273         // Rewrite an ADD constant node into a DIExpression. Since we are
9274         // performing arithmetic to compute the variable's *value* in the
9275         // DIExpression, we need to mark the expression with a
9276         // DW_OP_stack_value.
9277         auto *DIExpr = DV->getExpression();
9278         auto NewLocOps = DV->copyLocationOps();
9279         bool Changed = false;
9280         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9281           // We're not given a ResNo to compare against because the whole
9282           // node is going away. We know that any ISD::ADD only has one
9283           // result, so we can assume any node match is using the result.
9284           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9285               NewLocOps[i].getSDNode() != &N)
9286             continue;
9287           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9288           SmallVector<uint64_t, 3> ExprOps;
9289           DIExpression::appendOffset(ExprOps, Offset);
9290           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9291           Changed = true;
9292         }
9293         (void)Changed;
9294         assert(Changed && "Salvage target doesn't use N");
9295 
9296         auto AdditionalDependencies = DV->getAdditionalDependencies();
9297         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9298                                             NewLocOps, AdditionalDependencies,
9299                                             DV->isIndirect(), DV->getDebugLoc(),
9300                                             DV->getOrder(), DV->isVariadic());
9301         ClonedDVs.push_back(Clone);
9302         DV->setIsInvalidated();
9303         DV->setIsEmitted();
9304         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9305                    N0.getNode()->dumprFull(this);
9306                    dbgs() << " into " << *DIExpr << '\n');
9307       }
9308     }
9309   }
9310 
9311   for (SDDbgValue *Dbg : ClonedDVs) {
9312     assert(!Dbg->getSDNodes().empty() &&
9313            "Salvaged DbgValue should depend on a new SDNode");
9314     AddDbgValue(Dbg, false);
9315   }
9316 }
9317 
9318 /// Creates a SDDbgLabel node.
9319 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9320                                       const DebugLoc &DL, unsigned O) {
9321   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9322          "Expected inlined-at fields to agree");
9323   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9324 }
9325 
9326 namespace {
9327 
9328 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9329 /// pointed to by a use iterator is deleted, increment the use iterator
9330 /// so that it doesn't dangle.
9331 ///
9332 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9333   SDNode::use_iterator &UI;
9334   SDNode::use_iterator &UE;
9335 
9336   void NodeDeleted(SDNode *N, SDNode *E) override {
9337     // Increment the iterator as needed.
9338     while (UI != UE && N == *UI)
9339       ++UI;
9340   }
9341 
9342 public:
9343   RAUWUpdateListener(SelectionDAG &d,
9344                      SDNode::use_iterator &ui,
9345                      SDNode::use_iterator &ue)
9346     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9347 };
9348 
9349 } // end anonymous namespace
9350 
9351 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9352 /// This can cause recursive merging of nodes in the DAG.
9353 ///
9354 /// This version assumes From has a single result value.
9355 ///
9356 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9357   SDNode *From = FromN.getNode();
9358   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9359          "Cannot replace with this method!");
9360   assert(From != To.getNode() && "Cannot replace uses of with self");
9361 
9362   // Preserve Debug Values
9363   transferDbgValues(FromN, To);
9364 
9365   // Iterate over all the existing uses of From. New uses will be added
9366   // to the beginning of the use list, which we avoid visiting.
9367   // This specifically avoids visiting uses of From that arise while the
9368   // replacement is happening, because any such uses would be the result
9369   // of CSE: If an existing node looks like From after one of its operands
9370   // is replaced by To, we don't want to replace of all its users with To
9371   // too. See PR3018 for more info.
9372   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9373   RAUWUpdateListener Listener(*this, UI, UE);
9374   while (UI != UE) {
9375     SDNode *User = *UI;
9376 
9377     // This node is about to morph, remove its old self from the CSE maps.
9378     RemoveNodeFromCSEMaps(User);
9379 
9380     // A user can appear in a use list multiple times, and when this
9381     // happens the uses are usually next to each other in the list.
9382     // To help reduce the number of CSE recomputations, process all
9383     // the uses of this user that we can find this way.
9384     do {
9385       SDUse &Use = UI.getUse();
9386       ++UI;
9387       Use.set(To);
9388       if (To->isDivergent() != From->isDivergent())
9389         updateDivergence(User);
9390     } while (UI != UE && *UI == User);
9391     // Now that we have modified User, add it back to the CSE maps.  If it
9392     // already exists there, recursively merge the results together.
9393     AddModifiedNodeToCSEMaps(User);
9394   }
9395 
9396   // If we just RAUW'd the root, take note.
9397   if (FromN == getRoot())
9398     setRoot(To);
9399 }
9400 
9401 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9402 /// This can cause recursive merging of nodes in the DAG.
9403 ///
9404 /// This version assumes that for each value of From, there is a
9405 /// corresponding value in To in the same position with the same type.
9406 ///
9407 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9408 #ifndef NDEBUG
9409   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9410     assert((!From->hasAnyUseOfValue(i) ||
9411             From->getValueType(i) == To->getValueType(i)) &&
9412            "Cannot use this version of ReplaceAllUsesWith!");
9413 #endif
9414 
9415   // Handle the trivial case.
9416   if (From == To)
9417     return;
9418 
9419   // Preserve Debug Info. Only do this if there's a use.
9420   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9421     if (From->hasAnyUseOfValue(i)) {
9422       assert((i < To->getNumValues()) && "Invalid To location");
9423       transferDbgValues(SDValue(From, i), SDValue(To, i));
9424     }
9425 
9426   // Iterate over just the existing users of From. See the comments in
9427   // the ReplaceAllUsesWith above.
9428   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9429   RAUWUpdateListener Listener(*this, UI, UE);
9430   while (UI != UE) {
9431     SDNode *User = *UI;
9432 
9433     // This node is about to morph, remove its old self from the CSE maps.
9434     RemoveNodeFromCSEMaps(User);
9435 
9436     // A user can appear in a use list multiple times, and when this
9437     // happens the uses are usually next to each other in the list.
9438     // To help reduce the number of CSE recomputations, process all
9439     // the uses of this user that we can find this way.
9440     do {
9441       SDUse &Use = UI.getUse();
9442       ++UI;
9443       Use.setNode(To);
9444       if (To->isDivergent() != From->isDivergent())
9445         updateDivergence(User);
9446     } while (UI != UE && *UI == User);
9447 
9448     // Now that we have modified User, add it back to the CSE maps.  If it
9449     // already exists there, recursively merge the results together.
9450     AddModifiedNodeToCSEMaps(User);
9451   }
9452 
9453   // If we just RAUW'd the root, take note.
9454   if (From == getRoot().getNode())
9455     setRoot(SDValue(To, getRoot().getResNo()));
9456 }
9457 
9458 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9459 /// This can cause recursive merging of nodes in the DAG.
9460 ///
9461 /// This version can replace From with any result values.  To must match the
9462 /// number and types of values returned by From.
9463 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9464   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9465     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9466 
9467   // Preserve Debug Info.
9468   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9469     transferDbgValues(SDValue(From, i), To[i]);
9470 
9471   // Iterate over just the existing users of From. See the comments in
9472   // the ReplaceAllUsesWith above.
9473   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9474   RAUWUpdateListener Listener(*this, UI, UE);
9475   while (UI != UE) {
9476     SDNode *User = *UI;
9477 
9478     // This node is about to morph, remove its old self from the CSE maps.
9479     RemoveNodeFromCSEMaps(User);
9480 
9481     // A user can appear in a use list multiple times, and when this happens the
9482     // uses are usually next to each other in the list.  To help reduce the
9483     // number of CSE and divergence recomputations, process all the uses of this
9484     // user that we can find this way.
9485     bool To_IsDivergent = false;
9486     do {
9487       SDUse &Use = UI.getUse();
9488       const SDValue &ToOp = To[Use.getResNo()];
9489       ++UI;
9490       Use.set(ToOp);
9491       To_IsDivergent |= ToOp->isDivergent();
9492     } while (UI != UE && *UI == User);
9493 
9494     if (To_IsDivergent != From->isDivergent())
9495       updateDivergence(User);
9496 
9497     // Now that we have modified User, add it back to the CSE maps.  If it
9498     // already exists there, recursively merge the results together.
9499     AddModifiedNodeToCSEMaps(User);
9500   }
9501 
9502   // If we just RAUW'd the root, take note.
9503   if (From == getRoot().getNode())
9504     setRoot(SDValue(To[getRoot().getResNo()]));
9505 }
9506 
9507 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9508 /// uses of other values produced by From.getNode() alone.  The Deleted
9509 /// vector is handled the same way as for ReplaceAllUsesWith.
9510 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9511   // Handle the really simple, really trivial case efficiently.
9512   if (From == To) return;
9513 
9514   // Handle the simple, trivial, case efficiently.
9515   if (From.getNode()->getNumValues() == 1) {
9516     ReplaceAllUsesWith(From, To);
9517     return;
9518   }
9519 
9520   // Preserve Debug Info.
9521   transferDbgValues(From, To);
9522 
9523   // Iterate over just the existing users of From. See the comments in
9524   // the ReplaceAllUsesWith above.
9525   SDNode::use_iterator UI = From.getNode()->use_begin(),
9526                        UE = From.getNode()->use_end();
9527   RAUWUpdateListener Listener(*this, UI, UE);
9528   while (UI != UE) {
9529     SDNode *User = *UI;
9530     bool UserRemovedFromCSEMaps = false;
9531 
9532     // A user can appear in a use list multiple times, and when this
9533     // happens the uses are usually next to each other in the list.
9534     // To help reduce the number of CSE recomputations, process all
9535     // the uses of this user that we can find this way.
9536     do {
9537       SDUse &Use = UI.getUse();
9538 
9539       // Skip uses of different values from the same node.
9540       if (Use.getResNo() != From.getResNo()) {
9541         ++UI;
9542         continue;
9543       }
9544 
9545       // If this node hasn't been modified yet, it's still in the CSE maps,
9546       // so remove its old self from the CSE maps.
9547       if (!UserRemovedFromCSEMaps) {
9548         RemoveNodeFromCSEMaps(User);
9549         UserRemovedFromCSEMaps = true;
9550       }
9551 
9552       ++UI;
9553       Use.set(To);
9554       if (To->isDivergent() != From->isDivergent())
9555         updateDivergence(User);
9556     } while (UI != UE && *UI == User);
9557     // We are iterating over all uses of the From node, so if a use
9558     // doesn't use the specific value, no changes are made.
9559     if (!UserRemovedFromCSEMaps)
9560       continue;
9561 
9562     // Now that we have modified User, add it back to the CSE maps.  If it
9563     // already exists there, recursively merge the results together.
9564     AddModifiedNodeToCSEMaps(User);
9565   }
9566 
9567   // If we just RAUW'd the root, take note.
9568   if (From == getRoot())
9569     setRoot(To);
9570 }
9571 
9572 namespace {
9573 
9574   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9575   /// to record information about a use.
9576   struct UseMemo {
9577     SDNode *User;
9578     unsigned Index;
9579     SDUse *Use;
9580   };
9581 
9582   /// operator< - Sort Memos by User.
9583   bool operator<(const UseMemo &L, const UseMemo &R) {
9584     return (intptr_t)L.User < (intptr_t)R.User;
9585   }
9586 
9587 } // end anonymous namespace
9588 
9589 bool SelectionDAG::calculateDivergence(SDNode *N) {
9590   if (TLI->isSDNodeAlwaysUniform(N)) {
9591     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9592            "Conflicting divergence information!");
9593     return false;
9594   }
9595   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9596     return true;
9597   for (auto &Op : N->ops()) {
9598     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9599       return true;
9600   }
9601   return false;
9602 }
9603 
9604 void SelectionDAG::updateDivergence(SDNode *N) {
9605   SmallVector<SDNode *, 16> Worklist(1, N);
9606   do {
9607     N = Worklist.pop_back_val();
9608     bool IsDivergent = calculateDivergence(N);
9609     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9610       N->SDNodeBits.IsDivergent = IsDivergent;
9611       llvm::append_range(Worklist, N->uses());
9612     }
9613   } while (!Worklist.empty());
9614 }
9615 
9616 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9617   DenseMap<SDNode *, unsigned> Degree;
9618   Order.reserve(AllNodes.size());
9619   for (auto &N : allnodes()) {
9620     unsigned NOps = N.getNumOperands();
9621     Degree[&N] = NOps;
9622     if (0 == NOps)
9623       Order.push_back(&N);
9624   }
9625   for (size_t I = 0; I != Order.size(); ++I) {
9626     SDNode *N = Order[I];
9627     for (auto U : N->uses()) {
9628       unsigned &UnsortedOps = Degree[U];
9629       if (0 == --UnsortedOps)
9630         Order.push_back(U);
9631     }
9632   }
9633 }
9634 
9635 #ifndef NDEBUG
9636 void SelectionDAG::VerifyDAGDivergence() {
9637   std::vector<SDNode *> TopoOrder;
9638   CreateTopologicalOrder(TopoOrder);
9639   for (auto *N : TopoOrder) {
9640     assert(calculateDivergence(N) == N->isDivergent() &&
9641            "Divergence bit inconsistency detected");
9642   }
9643 }
9644 #endif
9645 
9646 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9647 /// uses of other values produced by From.getNode() alone.  The same value
9648 /// may appear in both the From and To list.  The Deleted vector is
9649 /// handled the same way as for ReplaceAllUsesWith.
9650 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9651                                               const SDValue *To,
9652                                               unsigned Num){
9653   // Handle the simple, trivial case efficiently.
9654   if (Num == 1)
9655     return ReplaceAllUsesOfValueWith(*From, *To);
9656 
9657   transferDbgValues(*From, *To);
9658 
9659   // Read up all the uses and make records of them. This helps
9660   // processing new uses that are introduced during the
9661   // replacement process.
9662   SmallVector<UseMemo, 4> Uses;
9663   for (unsigned i = 0; i != Num; ++i) {
9664     unsigned FromResNo = From[i].getResNo();
9665     SDNode *FromNode = From[i].getNode();
9666     for (SDNode::use_iterator UI = FromNode->use_begin(),
9667          E = FromNode->use_end(); UI != E; ++UI) {
9668       SDUse &Use = UI.getUse();
9669       if (Use.getResNo() == FromResNo) {
9670         UseMemo Memo = { *UI, i, &Use };
9671         Uses.push_back(Memo);
9672       }
9673     }
9674   }
9675 
9676   // Sort the uses, so that all the uses from a given User are together.
9677   llvm::sort(Uses);
9678 
9679   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9680        UseIndex != UseIndexEnd; ) {
9681     // We know that this user uses some value of From.  If it is the right
9682     // value, update it.
9683     SDNode *User = Uses[UseIndex].User;
9684 
9685     // This node is about to morph, remove its old self from the CSE maps.
9686     RemoveNodeFromCSEMaps(User);
9687 
9688     // The Uses array is sorted, so all the uses for a given User
9689     // are next to each other in the list.
9690     // To help reduce the number of CSE recomputations, process all
9691     // the uses of this user that we can find this way.
9692     do {
9693       unsigned i = Uses[UseIndex].Index;
9694       SDUse &Use = *Uses[UseIndex].Use;
9695       ++UseIndex;
9696 
9697       Use.set(To[i]);
9698     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9699 
9700     // Now that we have modified User, add it back to the CSE maps.  If it
9701     // already exists there, recursively merge the results together.
9702     AddModifiedNodeToCSEMaps(User);
9703   }
9704 }
9705 
9706 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9707 /// based on their topological order. It returns the maximum id and a vector
9708 /// of the SDNodes* in assigned order by reference.
9709 unsigned SelectionDAG::AssignTopologicalOrder() {
9710   unsigned DAGSize = 0;
9711 
9712   // SortedPos tracks the progress of the algorithm. Nodes before it are
9713   // sorted, nodes after it are unsorted. When the algorithm completes
9714   // it is at the end of the list.
9715   allnodes_iterator SortedPos = allnodes_begin();
9716 
9717   // Visit all the nodes. Move nodes with no operands to the front of
9718   // the list immediately. Annotate nodes that do have operands with their
9719   // operand count. Before we do this, the Node Id fields of the nodes
9720   // may contain arbitrary values. After, the Node Id fields for nodes
9721   // before SortedPos will contain the topological sort index, and the
9722   // Node Id fields for nodes At SortedPos and after will contain the
9723   // count of outstanding operands.
9724   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
9725     checkForCycles(&N, this);
9726     unsigned Degree = N.getNumOperands();
9727     if (Degree == 0) {
9728       // A node with no uses, add it to the result array immediately.
9729       N.setNodeId(DAGSize++);
9730       allnodes_iterator Q(&N);
9731       if (Q != SortedPos)
9732         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9733       assert(SortedPos != AllNodes.end() && "Overran node list");
9734       ++SortedPos;
9735     } else {
9736       // Temporarily use the Node Id as scratch space for the degree count.
9737       N.setNodeId(Degree);
9738     }
9739   }
9740 
9741   // Visit all the nodes. As we iterate, move nodes into sorted order,
9742   // such that by the time the end is reached all nodes will be sorted.
9743   for (SDNode &Node : allnodes()) {
9744     SDNode *N = &Node;
9745     checkForCycles(N, this);
9746     // N is in sorted position, so all its uses have one less operand
9747     // that needs to be sorted.
9748     for (SDNode *P : N->uses()) {
9749       unsigned Degree = P->getNodeId();
9750       assert(Degree != 0 && "Invalid node degree");
9751       --Degree;
9752       if (Degree == 0) {
9753         // All of P's operands are sorted, so P may sorted now.
9754         P->setNodeId(DAGSize++);
9755         if (P->getIterator() != SortedPos)
9756           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9757         assert(SortedPos != AllNodes.end() && "Overran node list");
9758         ++SortedPos;
9759       } else {
9760         // Update P's outstanding operand count.
9761         P->setNodeId(Degree);
9762       }
9763     }
9764     if (Node.getIterator() == SortedPos) {
9765 #ifndef NDEBUG
9766       allnodes_iterator I(N);
9767       SDNode *S = &*++I;
9768       dbgs() << "Overran sorted position:\n";
9769       S->dumprFull(this); dbgs() << "\n";
9770       dbgs() << "Checking if this is due to cycles\n";
9771       checkForCycles(this, true);
9772 #endif
9773       llvm_unreachable(nullptr);
9774     }
9775   }
9776 
9777   assert(SortedPos == AllNodes.end() &&
9778          "Topological sort incomplete!");
9779   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9780          "First node in topological sort is not the entry token!");
9781   assert(AllNodes.front().getNodeId() == 0 &&
9782          "First node in topological sort has non-zero id!");
9783   assert(AllNodes.front().getNumOperands() == 0 &&
9784          "First node in topological sort has operands!");
9785   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9786          "Last node in topologic sort has unexpected id!");
9787   assert(AllNodes.back().use_empty() &&
9788          "Last node in topologic sort has users!");
9789   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9790   return DAGSize;
9791 }
9792 
9793 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9794 /// value is produced by SD.
9795 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9796   for (SDNode *SD : DB->getSDNodes()) {
9797     if (!SD)
9798       continue;
9799     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9800     SD->setHasDebugValue(true);
9801   }
9802   DbgInfo->add(DB, isParameter);
9803 }
9804 
9805 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9806 
9807 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9808                                                    SDValue NewMemOpChain) {
9809   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9810   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9811   // The new memory operation must have the same position as the old load in
9812   // terms of memory dependency. Create a TokenFactor for the old load and new
9813   // memory operation and update uses of the old load's output chain to use that
9814   // TokenFactor.
9815   if (OldChain == NewMemOpChain || OldChain.use_empty())
9816     return NewMemOpChain;
9817 
9818   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9819                                 OldChain, NewMemOpChain);
9820   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9821   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9822   return TokenFactor;
9823 }
9824 
9825 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9826                                                    SDValue NewMemOp) {
9827   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9828   SDValue OldChain = SDValue(OldLoad, 1);
9829   SDValue NewMemOpChain = NewMemOp.getValue(1);
9830   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9831 }
9832 
9833 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9834                                                      Function **OutFunction) {
9835   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9836 
9837   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9838   auto *Module = MF->getFunction().getParent();
9839   auto *Function = Module->getFunction(Symbol);
9840 
9841   if (OutFunction != nullptr)
9842       *OutFunction = Function;
9843 
9844   if (Function != nullptr) {
9845     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9846     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9847   }
9848 
9849   std::string ErrorStr;
9850   raw_string_ostream ErrorFormatter(ErrorStr);
9851   ErrorFormatter << "Undefined external symbol ";
9852   ErrorFormatter << '"' << Symbol << '"';
9853   report_fatal_error(Twine(ErrorFormatter.str()));
9854 }
9855 
9856 //===----------------------------------------------------------------------===//
9857 //                              SDNode Class
9858 //===----------------------------------------------------------------------===//
9859 
9860 bool llvm::isNullConstant(SDValue V) {
9861   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9862   return Const != nullptr && Const->isZero();
9863 }
9864 
9865 bool llvm::isNullFPConstant(SDValue V) {
9866   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9867   return Const != nullptr && Const->isZero() && !Const->isNegative();
9868 }
9869 
9870 bool llvm::isAllOnesConstant(SDValue V) {
9871   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9872   return Const != nullptr && Const->isAllOnes();
9873 }
9874 
9875 bool llvm::isOneConstant(SDValue V) {
9876   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9877   return Const != nullptr && Const->isOne();
9878 }
9879 
9880 SDValue llvm::peekThroughBitcasts(SDValue V) {
9881   while (V.getOpcode() == ISD::BITCAST)
9882     V = V.getOperand(0);
9883   return V;
9884 }
9885 
9886 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9887   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9888     V = V.getOperand(0);
9889   return V;
9890 }
9891 
9892 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9893   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9894     V = V.getOperand(0);
9895   return V;
9896 }
9897 
9898 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9899   if (V.getOpcode() != ISD::XOR)
9900     return false;
9901   V = peekThroughBitcasts(V.getOperand(1));
9902   unsigned NumBits = V.getScalarValueSizeInBits();
9903   ConstantSDNode *C =
9904       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9905   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9906 }
9907 
9908 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9909                                           bool AllowTruncation) {
9910   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9911     return CN;
9912 
9913   // SplatVectors can truncate their operands. Ignore that case here unless
9914   // AllowTruncation is set.
9915   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9916     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9917     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9918       EVT CVT = CN->getValueType(0);
9919       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9920       if (AllowTruncation || CVT == VecEltVT)
9921         return CN;
9922     }
9923   }
9924 
9925   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9926     BitVector UndefElements;
9927     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9928 
9929     // BuildVectors can truncate their operands. Ignore that case here unless
9930     // AllowTruncation is set.
9931     if (CN && (UndefElements.none() || AllowUndefs)) {
9932       EVT CVT = CN->getValueType(0);
9933       EVT NSVT = N.getValueType().getScalarType();
9934       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9935       if (AllowTruncation || (CVT == NSVT))
9936         return CN;
9937     }
9938   }
9939 
9940   return nullptr;
9941 }
9942 
9943 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9944                                           bool AllowUndefs,
9945                                           bool AllowTruncation) {
9946   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9947     return CN;
9948 
9949   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9950     BitVector UndefElements;
9951     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9952 
9953     // BuildVectors can truncate their operands. Ignore that case here unless
9954     // AllowTruncation is set.
9955     if (CN && (UndefElements.none() || AllowUndefs)) {
9956       EVT CVT = CN->getValueType(0);
9957       EVT NSVT = N.getValueType().getScalarType();
9958       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9959       if (AllowTruncation || (CVT == NSVT))
9960         return CN;
9961     }
9962   }
9963 
9964   return nullptr;
9965 }
9966 
9967 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
9968   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9969     return CN;
9970 
9971   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9972     BitVector UndefElements;
9973     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
9974     if (CN && (UndefElements.none() || AllowUndefs))
9975       return CN;
9976   }
9977 
9978   if (N.getOpcode() == ISD::SPLAT_VECTOR)
9979     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
9980       return CN;
9981 
9982   return nullptr;
9983 }
9984 
9985 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
9986                                               const APInt &DemandedElts,
9987                                               bool AllowUndefs) {
9988   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9989     return CN;
9990 
9991   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9992     BitVector UndefElements;
9993     ConstantFPSDNode *CN =
9994         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
9995     if (CN && (UndefElements.none() || AllowUndefs))
9996       return CN;
9997   }
9998 
9999   return nullptr;
10000 }
10001 
10002 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10003   // TODO: may want to use peekThroughBitcast() here.
10004   ConstantSDNode *C =
10005       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10006   return C && C->isZero();
10007 }
10008 
10009 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10010   // TODO: may want to use peekThroughBitcast() here.
10011   unsigned BitWidth = N.getScalarValueSizeInBits();
10012   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10013   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10014 }
10015 
10016 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10017   N = peekThroughBitcasts(N);
10018   unsigned BitWidth = N.getScalarValueSizeInBits();
10019   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10020   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10021 }
10022 
10023 HandleSDNode::~HandleSDNode() {
10024   DropOperands();
10025 }
10026 
10027 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10028                                          const DebugLoc &DL,
10029                                          const GlobalValue *GA, EVT VT,
10030                                          int64_t o, unsigned TF)
10031     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10032   TheGlobal = GA;
10033 }
10034 
10035 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10036                                          EVT VT, unsigned SrcAS,
10037                                          unsigned DestAS)
10038     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10039       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10040 
10041 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10042                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10043     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10044   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10045   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10046   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10047   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10048 
10049   // We check here that the size of the memory operand fits within the size of
10050   // the MMO. This is because the MMO might indicate only a possible address
10051   // range instead of specifying the affected memory addresses precisely.
10052   // TODO: Make MachineMemOperands aware of scalable vectors.
10053   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10054          "Size mismatch!");
10055 }
10056 
10057 /// Profile - Gather unique data for the node.
10058 ///
10059 void SDNode::Profile(FoldingSetNodeID &ID) const {
10060   AddNodeIDNode(ID, this);
10061 }
10062 
10063 namespace {
10064 
10065   struct EVTArray {
10066     std::vector<EVT> VTs;
10067 
10068     EVTArray() {
10069       VTs.reserve(MVT::VALUETYPE_SIZE);
10070       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10071         VTs.push_back(MVT((MVT::SimpleValueType)i));
10072     }
10073   };
10074 
10075 } // end anonymous namespace
10076 
10077 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10078 static ManagedStatic<EVTArray> SimpleVTArray;
10079 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10080 
10081 /// getValueTypeList - Return a pointer to the specified value type.
10082 ///
10083 const EVT *SDNode::getValueTypeList(EVT VT) {
10084   if (VT.isExtended()) {
10085     sys::SmartScopedLock<true> Lock(*VTMutex);
10086     return &(*EVTs->insert(VT).first);
10087   }
10088   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10089   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10090 }
10091 
10092 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10093 /// indicated value.  This method ignores uses of other values defined by this
10094 /// operation.
10095 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10096   assert(Value < getNumValues() && "Bad value!");
10097 
10098   // TODO: Only iterate over uses of a given value of the node
10099   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10100     if (UI.getUse().getResNo() == Value) {
10101       if (NUses == 0)
10102         return false;
10103       --NUses;
10104     }
10105   }
10106 
10107   // Found exactly the right number of uses?
10108   return NUses == 0;
10109 }
10110 
10111 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10112 /// value. This method ignores uses of other values defined by this operation.
10113 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10114   assert(Value < getNumValues() && "Bad value!");
10115 
10116   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10117     if (UI.getUse().getResNo() == Value)
10118       return true;
10119 
10120   return false;
10121 }
10122 
10123 /// isOnlyUserOf - Return true if this node is the only use of N.
10124 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10125   bool Seen = false;
10126   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
10127     SDNode *User = *I;
10128     if (User == this)
10129       Seen = true;
10130     else
10131       return false;
10132   }
10133 
10134   return Seen;
10135 }
10136 
10137 /// Return true if the only users of N are contained in Nodes.
10138 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10139   bool Seen = false;
10140   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
10141     SDNode *User = *I;
10142     if (llvm::is_contained(Nodes, User))
10143       Seen = true;
10144     else
10145       return false;
10146   }
10147 
10148   return Seen;
10149 }
10150 
10151 /// isOperand - Return true if this node is an operand of N.
10152 bool SDValue::isOperandOf(const SDNode *N) const {
10153   return is_contained(N->op_values(), *this);
10154 }
10155 
10156 bool SDNode::isOperandOf(const SDNode *N) const {
10157   return any_of(N->op_values(),
10158                 [this](SDValue Op) { return this == Op.getNode(); });
10159 }
10160 
10161 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10162 /// be a chain) reaches the specified operand without crossing any
10163 /// side-effecting instructions on any chain path.  In practice, this looks
10164 /// through token factors and non-volatile loads.  In order to remain efficient,
10165 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10166 ///
10167 /// Note that we only need to examine chains when we're searching for
10168 /// side-effects; SelectionDAG requires that all side-effects are represented
10169 /// by chains, even if another operand would force a specific ordering. This
10170 /// constraint is necessary to allow transformations like splitting loads.
10171 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10172                                              unsigned Depth) const {
10173   if (*this == Dest) return true;
10174 
10175   // Don't search too deeply, we just want to be able to see through
10176   // TokenFactor's etc.
10177   if (Depth == 0) return false;
10178 
10179   // If this is a token factor, all inputs to the TF happen in parallel.
10180   if (getOpcode() == ISD::TokenFactor) {
10181     // First, try a shallow search.
10182     if (is_contained((*this)->ops(), Dest)) {
10183       // We found the chain we want as an operand of this TokenFactor.
10184       // Essentially, we reach the chain without side-effects if we could
10185       // serialize the TokenFactor into a simple chain of operations with
10186       // Dest as the last operation. This is automatically true if the
10187       // chain has one use: there are no other ordering constraints.
10188       // If the chain has more than one use, we give up: some other
10189       // use of Dest might force a side-effect between Dest and the current
10190       // node.
10191       if (Dest.hasOneUse())
10192         return true;
10193     }
10194     // Next, try a deep search: check whether every operand of the TokenFactor
10195     // reaches Dest.
10196     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10197       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10198     });
10199   }
10200 
10201   // Loads don't have side effects, look through them.
10202   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10203     if (Ld->isUnordered())
10204       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10205   }
10206   return false;
10207 }
10208 
10209 bool SDNode::hasPredecessor(const SDNode *N) const {
10210   SmallPtrSet<const SDNode *, 32> Visited;
10211   SmallVector<const SDNode *, 16> Worklist;
10212   Worklist.push_back(this);
10213   return hasPredecessorHelper(N, Visited, Worklist);
10214 }
10215 
10216 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10217   this->Flags.intersectWith(Flags);
10218 }
10219 
10220 SDValue
10221 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10222                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10223                                   bool AllowPartials) {
10224   // The pattern must end in an extract from index 0.
10225   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10226       !isNullConstant(Extract->getOperand(1)))
10227     return SDValue();
10228 
10229   // Match against one of the candidate binary ops.
10230   SDValue Op = Extract->getOperand(0);
10231   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10232         return Op.getOpcode() == unsigned(BinOp);
10233       }))
10234     return SDValue();
10235 
10236   // Floating-point reductions may require relaxed constraints on the final step
10237   // of the reduction because they may reorder intermediate operations.
10238   unsigned CandidateBinOp = Op.getOpcode();
10239   if (Op.getValueType().isFloatingPoint()) {
10240     SDNodeFlags Flags = Op->getFlags();
10241     switch (CandidateBinOp) {
10242     case ISD::FADD:
10243       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10244         return SDValue();
10245       break;
10246     default:
10247       llvm_unreachable("Unhandled FP opcode for binop reduction");
10248     }
10249   }
10250 
10251   // Matching failed - attempt to see if we did enough stages that a partial
10252   // reduction from a subvector is possible.
10253   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10254     if (!AllowPartials || !Op)
10255       return SDValue();
10256     EVT OpVT = Op.getValueType();
10257     EVT OpSVT = OpVT.getScalarType();
10258     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10259     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10260       return SDValue();
10261     BinOp = (ISD::NodeType)CandidateBinOp;
10262     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10263                    getVectorIdxConstant(0, SDLoc(Op)));
10264   };
10265 
10266   // At each stage, we're looking for something that looks like:
10267   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10268   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10269   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10270   // %a = binop <8 x i32> %op, %s
10271   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10272   // we expect something like:
10273   // <4,5,6,7,u,u,u,u>
10274   // <2,3,u,u,u,u,u,u>
10275   // <1,u,u,u,u,u,u,u>
10276   // While a partial reduction match would be:
10277   // <2,3,u,u,u,u,u,u>
10278   // <1,u,u,u,u,u,u,u>
10279   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10280   SDValue PrevOp;
10281   for (unsigned i = 0; i < Stages; ++i) {
10282     unsigned MaskEnd = (1 << i);
10283 
10284     if (Op.getOpcode() != CandidateBinOp)
10285       return PartialReduction(PrevOp, MaskEnd);
10286 
10287     SDValue Op0 = Op.getOperand(0);
10288     SDValue Op1 = Op.getOperand(1);
10289 
10290     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10291     if (Shuffle) {
10292       Op = Op1;
10293     } else {
10294       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10295       Op = Op0;
10296     }
10297 
10298     // The first operand of the shuffle should be the same as the other operand
10299     // of the binop.
10300     if (!Shuffle || Shuffle->getOperand(0) != Op)
10301       return PartialReduction(PrevOp, MaskEnd);
10302 
10303     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10304     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10305       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10306         return PartialReduction(PrevOp, MaskEnd);
10307 
10308     PrevOp = Op;
10309   }
10310 
10311   // Handle subvector reductions, which tend to appear after the shuffle
10312   // reduction stages.
10313   while (Op.getOpcode() == CandidateBinOp) {
10314     unsigned NumElts = Op.getValueType().getVectorNumElements();
10315     SDValue Op0 = Op.getOperand(0);
10316     SDValue Op1 = Op.getOperand(1);
10317     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10318         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10319         Op0.getOperand(0) != Op1.getOperand(0))
10320       break;
10321     SDValue Src = Op0.getOperand(0);
10322     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10323     if (NumSrcElts != (2 * NumElts))
10324       break;
10325     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10326           Op1.getConstantOperandAPInt(1) == NumElts) &&
10327         !(Op1.getConstantOperandAPInt(1) == 0 &&
10328           Op0.getConstantOperandAPInt(1) == NumElts))
10329       break;
10330     Op = Src;
10331   }
10332 
10333   BinOp = (ISD::NodeType)CandidateBinOp;
10334   return Op;
10335 }
10336 
10337 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10338   assert(N->getNumValues() == 1 &&
10339          "Can't unroll a vector with multiple results!");
10340 
10341   EVT VT = N->getValueType(0);
10342   unsigned NE = VT.getVectorNumElements();
10343   EVT EltVT = VT.getVectorElementType();
10344   SDLoc dl(N);
10345 
10346   SmallVector<SDValue, 8> Scalars;
10347   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10348 
10349   // If ResNE is 0, fully unroll the vector op.
10350   if (ResNE == 0)
10351     ResNE = NE;
10352   else if (NE > ResNE)
10353     NE = ResNE;
10354 
10355   unsigned i;
10356   for (i= 0; i != NE; ++i) {
10357     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10358       SDValue Operand = N->getOperand(j);
10359       EVT OperandVT = Operand.getValueType();
10360       if (OperandVT.isVector()) {
10361         // A vector operand; extract a single element.
10362         EVT OperandEltVT = OperandVT.getVectorElementType();
10363         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10364                               Operand, getVectorIdxConstant(i, dl));
10365       } else {
10366         // A scalar operand; just use it as is.
10367         Operands[j] = Operand;
10368       }
10369     }
10370 
10371     switch (N->getOpcode()) {
10372     default: {
10373       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10374                                 N->getFlags()));
10375       break;
10376     }
10377     case ISD::VSELECT:
10378       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10379       break;
10380     case ISD::SHL:
10381     case ISD::SRA:
10382     case ISD::SRL:
10383     case ISD::ROTL:
10384     case ISD::ROTR:
10385       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10386                                getShiftAmountOperand(Operands[0].getValueType(),
10387                                                      Operands[1])));
10388       break;
10389     case ISD::SIGN_EXTEND_INREG: {
10390       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10391       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10392                                 Operands[0],
10393                                 getValueType(ExtVT)));
10394     }
10395     }
10396   }
10397 
10398   for (; i < ResNE; ++i)
10399     Scalars.push_back(getUNDEF(EltVT));
10400 
10401   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10402   return getBuildVector(VecVT, dl, Scalars);
10403 }
10404 
10405 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10406     SDNode *N, unsigned ResNE) {
10407   unsigned Opcode = N->getOpcode();
10408   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10409           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10410           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10411          "Expected an overflow opcode");
10412 
10413   EVT ResVT = N->getValueType(0);
10414   EVT OvVT = N->getValueType(1);
10415   EVT ResEltVT = ResVT.getVectorElementType();
10416   EVT OvEltVT = OvVT.getVectorElementType();
10417   SDLoc dl(N);
10418 
10419   // If ResNE is 0, fully unroll the vector op.
10420   unsigned NE = ResVT.getVectorNumElements();
10421   if (ResNE == 0)
10422     ResNE = NE;
10423   else if (NE > ResNE)
10424     NE = ResNE;
10425 
10426   SmallVector<SDValue, 8> LHSScalars;
10427   SmallVector<SDValue, 8> RHSScalars;
10428   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10429   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10430 
10431   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10432   SDVTList VTs = getVTList(ResEltVT, SVT);
10433   SmallVector<SDValue, 8> ResScalars;
10434   SmallVector<SDValue, 8> OvScalars;
10435   for (unsigned i = 0; i < NE; ++i) {
10436     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10437     SDValue Ov =
10438         getSelect(dl, OvEltVT, Res.getValue(1),
10439                   getBoolConstant(true, dl, OvEltVT, ResVT),
10440                   getConstant(0, dl, OvEltVT));
10441 
10442     ResScalars.push_back(Res);
10443     OvScalars.push_back(Ov);
10444   }
10445 
10446   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10447   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10448 
10449   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10450   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10451   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10452                         getBuildVector(NewOvVT, dl, OvScalars));
10453 }
10454 
10455 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10456                                                   LoadSDNode *Base,
10457                                                   unsigned Bytes,
10458                                                   int Dist) const {
10459   if (LD->isVolatile() || Base->isVolatile())
10460     return false;
10461   // TODO: probably too restrictive for atomics, revisit
10462   if (!LD->isSimple())
10463     return false;
10464   if (LD->isIndexed() || Base->isIndexed())
10465     return false;
10466   if (LD->getChain() != Base->getChain())
10467     return false;
10468   EVT VT = LD->getValueType(0);
10469   if (VT.getSizeInBits() / 8 != Bytes)
10470     return false;
10471 
10472   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10473   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10474 
10475   int64_t Offset = 0;
10476   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10477     return (Dist * Bytes == Offset);
10478   return false;
10479 }
10480 
10481 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10482 /// if it cannot be inferred.
10483 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10484   // If this is a GlobalAddress + cst, return the alignment.
10485   const GlobalValue *GV = nullptr;
10486   int64_t GVOffset = 0;
10487   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10488     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10489     KnownBits Known(PtrWidth);
10490     llvm::computeKnownBits(GV, Known, getDataLayout());
10491     unsigned AlignBits = Known.countMinTrailingZeros();
10492     if (AlignBits)
10493       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10494   }
10495 
10496   // If this is a direct reference to a stack slot, use information about the
10497   // stack slot's alignment.
10498   int FrameIdx = INT_MIN;
10499   int64_t FrameOffset = 0;
10500   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10501     FrameIdx = FI->getIndex();
10502   } else if (isBaseWithConstantOffset(Ptr) &&
10503              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10504     // Handle FI+Cst
10505     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10506     FrameOffset = Ptr.getConstantOperandVal(1);
10507   }
10508 
10509   if (FrameIdx != INT_MIN) {
10510     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10511     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10512   }
10513 
10514   return None;
10515 }
10516 
10517 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10518 /// which is split (or expanded) into two not necessarily identical pieces.
10519 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10520   // Currently all types are split in half.
10521   EVT LoVT, HiVT;
10522   if (!VT.isVector())
10523     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10524   else
10525     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10526 
10527   return std::make_pair(LoVT, HiVT);
10528 }
10529 
10530 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10531 /// type, dependent on an enveloping VT that has been split into two identical
10532 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10533 std::pair<EVT, EVT>
10534 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10535                                        bool *HiIsEmpty) const {
10536   EVT EltTp = VT.getVectorElementType();
10537   // Examples:
10538   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10539   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10540   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10541   //   etc.
10542   ElementCount VTNumElts = VT.getVectorElementCount();
10543   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10544   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10545          "Mixing fixed width and scalable vectors when enveloping a type");
10546   EVT LoVT, HiVT;
10547   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10548     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10549     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10550     *HiIsEmpty = false;
10551   } else {
10552     // Flag that hi type has zero storage size, but return split envelop type
10553     // (this would be easier if vector types with zero elements were allowed).
10554     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10555     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10556     *HiIsEmpty = true;
10557   }
10558   return std::make_pair(LoVT, HiVT);
10559 }
10560 
10561 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10562 /// low/high part.
10563 std::pair<SDValue, SDValue>
10564 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10565                           const EVT &HiVT) {
10566   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10567          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10568          "Splitting vector with an invalid mixture of fixed and scalable "
10569          "vector types");
10570   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10571              N.getValueType().getVectorMinNumElements() &&
10572          "More vector elements requested than available!");
10573   SDValue Lo, Hi;
10574   Lo =
10575       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10576   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10577   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10578   // IDX with the runtime scaling factor of the result vector type. For
10579   // fixed-width result vectors, that runtime scaling factor is 1.
10580   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10581                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10582   return std::make_pair(Lo, Hi);
10583 }
10584 
10585 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10586 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10587   EVT VT = N.getValueType();
10588   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10589                                 NextPowerOf2(VT.getVectorNumElements()));
10590   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10591                  getVectorIdxConstant(0, DL));
10592 }
10593 
10594 void SelectionDAG::ExtractVectorElements(SDValue Op,
10595                                          SmallVectorImpl<SDValue> &Args,
10596                                          unsigned Start, unsigned Count,
10597                                          EVT EltVT) {
10598   EVT VT = Op.getValueType();
10599   if (Count == 0)
10600     Count = VT.getVectorNumElements();
10601   if (EltVT == EVT())
10602     EltVT = VT.getVectorElementType();
10603   SDLoc SL(Op);
10604   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10605     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10606                            getVectorIdxConstant(i, SL)));
10607   }
10608 }
10609 
10610 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10611 unsigned GlobalAddressSDNode::getAddressSpace() const {
10612   return getGlobal()->getType()->getAddressSpace();
10613 }
10614 
10615 Type *ConstantPoolSDNode::getType() const {
10616   if (isMachineConstantPoolEntry())
10617     return Val.MachineCPVal->getType();
10618   return Val.ConstVal->getType();
10619 }
10620 
10621 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10622                                         unsigned &SplatBitSize,
10623                                         bool &HasAnyUndefs,
10624                                         unsigned MinSplatBits,
10625                                         bool IsBigEndian) const {
10626   EVT VT = getValueType(0);
10627   assert(VT.isVector() && "Expected a vector type");
10628   unsigned VecWidth = VT.getSizeInBits();
10629   if (MinSplatBits > VecWidth)
10630     return false;
10631 
10632   // FIXME: The widths are based on this node's type, but build vectors can
10633   // truncate their operands.
10634   SplatValue = APInt(VecWidth, 0);
10635   SplatUndef = APInt(VecWidth, 0);
10636 
10637   // Get the bits. Bits with undefined values (when the corresponding element
10638   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10639   // in SplatValue. If any of the values are not constant, give up and return
10640   // false.
10641   unsigned int NumOps = getNumOperands();
10642   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10643   unsigned EltWidth = VT.getScalarSizeInBits();
10644 
10645   for (unsigned j = 0; j < NumOps; ++j) {
10646     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10647     SDValue OpVal = getOperand(i);
10648     unsigned BitPos = j * EltWidth;
10649 
10650     if (OpVal.isUndef())
10651       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10652     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10653       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10654     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10655       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10656     else
10657       return false;
10658   }
10659 
10660   // The build_vector is all constants or undefs. Find the smallest element
10661   // size that splats the vector.
10662   HasAnyUndefs = (SplatUndef != 0);
10663 
10664   // FIXME: This does not work for vectors with elements less than 8 bits.
10665   while (VecWidth > 8) {
10666     unsigned HalfSize = VecWidth / 2;
10667     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10668     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10669     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10670     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10671 
10672     // If the two halves do not match (ignoring undef bits), stop here.
10673     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10674         MinSplatBits > HalfSize)
10675       break;
10676 
10677     SplatValue = HighValue | LowValue;
10678     SplatUndef = HighUndef & LowUndef;
10679 
10680     VecWidth = HalfSize;
10681   }
10682 
10683   SplatBitSize = VecWidth;
10684   return true;
10685 }
10686 
10687 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10688                                          BitVector *UndefElements) const {
10689   unsigned NumOps = getNumOperands();
10690   if (UndefElements) {
10691     UndefElements->clear();
10692     UndefElements->resize(NumOps);
10693   }
10694   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10695   if (!DemandedElts)
10696     return SDValue();
10697   SDValue Splatted;
10698   for (unsigned i = 0; i != NumOps; ++i) {
10699     if (!DemandedElts[i])
10700       continue;
10701     SDValue Op = getOperand(i);
10702     if (Op.isUndef()) {
10703       if (UndefElements)
10704         (*UndefElements)[i] = true;
10705     } else if (!Splatted) {
10706       Splatted = Op;
10707     } else if (Splatted != Op) {
10708       return SDValue();
10709     }
10710   }
10711 
10712   if (!Splatted) {
10713     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10714     assert(getOperand(FirstDemandedIdx).isUndef() &&
10715            "Can only have a splat without a constant for all undefs.");
10716     return getOperand(FirstDemandedIdx);
10717   }
10718 
10719   return Splatted;
10720 }
10721 
10722 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10723   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10724   return getSplatValue(DemandedElts, UndefElements);
10725 }
10726 
10727 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10728                                             SmallVectorImpl<SDValue> &Sequence,
10729                                             BitVector *UndefElements) const {
10730   unsigned NumOps = getNumOperands();
10731   Sequence.clear();
10732   if (UndefElements) {
10733     UndefElements->clear();
10734     UndefElements->resize(NumOps);
10735   }
10736   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10737   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10738     return false;
10739 
10740   // Set the undefs even if we don't find a sequence (like getSplatValue).
10741   if (UndefElements)
10742     for (unsigned I = 0; I != NumOps; ++I)
10743       if (DemandedElts[I] && getOperand(I).isUndef())
10744         (*UndefElements)[I] = true;
10745 
10746   // Iteratively widen the sequence length looking for repetitions.
10747   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10748     Sequence.append(SeqLen, SDValue());
10749     for (unsigned I = 0; I != NumOps; ++I) {
10750       if (!DemandedElts[I])
10751         continue;
10752       SDValue &SeqOp = Sequence[I % SeqLen];
10753       SDValue Op = getOperand(I);
10754       if (Op.isUndef()) {
10755         if (!SeqOp)
10756           SeqOp = Op;
10757         continue;
10758       }
10759       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10760         Sequence.clear();
10761         break;
10762       }
10763       SeqOp = Op;
10764     }
10765     if (!Sequence.empty())
10766       return true;
10767   }
10768 
10769   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10770   return false;
10771 }
10772 
10773 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10774                                             BitVector *UndefElements) const {
10775   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10776   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10777 }
10778 
10779 ConstantSDNode *
10780 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10781                                         BitVector *UndefElements) const {
10782   return dyn_cast_or_null<ConstantSDNode>(
10783       getSplatValue(DemandedElts, UndefElements));
10784 }
10785 
10786 ConstantSDNode *
10787 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10788   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10789 }
10790 
10791 ConstantFPSDNode *
10792 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10793                                           BitVector *UndefElements) const {
10794   return dyn_cast_or_null<ConstantFPSDNode>(
10795       getSplatValue(DemandedElts, UndefElements));
10796 }
10797 
10798 ConstantFPSDNode *
10799 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10800   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10801 }
10802 
10803 int32_t
10804 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10805                                                    uint32_t BitWidth) const {
10806   if (ConstantFPSDNode *CN =
10807           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10808     bool IsExact;
10809     APSInt IntVal(BitWidth);
10810     const APFloat &APF = CN->getValueAPF();
10811     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10812             APFloat::opOK ||
10813         !IsExact)
10814       return -1;
10815 
10816     return IntVal.exactLogBase2();
10817   }
10818   return -1;
10819 }
10820 
10821 bool BuildVectorSDNode::getConstantRawBits(
10822     bool IsLittleEndian, unsigned DstEltSizeInBits,
10823     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
10824   // Early-out if this contains anything but Undef/Constant/ConstantFP.
10825   if (!isConstant())
10826     return false;
10827 
10828   unsigned NumSrcOps = getNumOperands();
10829   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
10830   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10831          "Invalid bitcast scale");
10832 
10833   // Extract raw src bits.
10834   SmallVector<APInt> SrcBitElements(NumSrcOps,
10835                                     APInt::getNullValue(SrcEltSizeInBits));
10836   BitVector SrcUndeElements(NumSrcOps, false);
10837 
10838   for (unsigned I = 0; I != NumSrcOps; ++I) {
10839     SDValue Op = getOperand(I);
10840     if (Op.isUndef()) {
10841       SrcUndeElements.set(I);
10842       continue;
10843     }
10844     auto *CInt = dyn_cast<ConstantSDNode>(Op);
10845     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
10846     assert((CInt || CFP) && "Unknown constant");
10847     SrcBitElements[I] =
10848         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
10849              : CFP->getValueAPF().bitcastToAPInt();
10850   }
10851 
10852   // Recast to dst width.
10853   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
10854                 SrcBitElements, UndefElements, SrcUndeElements);
10855   return true;
10856 }
10857 
10858 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
10859                                       unsigned DstEltSizeInBits,
10860                                       SmallVectorImpl<APInt> &DstBitElements,
10861                                       ArrayRef<APInt> SrcBitElements,
10862                                       BitVector &DstUndefElements,
10863                                       const BitVector &SrcUndefElements) {
10864   unsigned NumSrcOps = SrcBitElements.size();
10865   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
10866   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10867          "Invalid bitcast scale");
10868   assert(NumSrcOps == SrcUndefElements.size() &&
10869          "Vector size mismatch");
10870 
10871   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
10872   DstUndefElements.clear();
10873   DstUndefElements.resize(NumDstOps, false);
10874   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
10875 
10876   // Concatenate src elements constant bits together into dst element.
10877   if (SrcEltSizeInBits <= DstEltSizeInBits) {
10878     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
10879     for (unsigned I = 0; I != NumDstOps; ++I) {
10880       DstUndefElements.set(I);
10881       APInt &DstBits = DstBitElements[I];
10882       for (unsigned J = 0; J != Scale; ++J) {
10883         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10884         if (SrcUndefElements[Idx])
10885           continue;
10886         DstUndefElements.reset(I);
10887         const APInt &SrcBits = SrcBitElements[Idx];
10888         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
10889                "Illegal constant bitwidths");
10890         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
10891       }
10892     }
10893     return;
10894   }
10895 
10896   // Split src element constant bits into dst elements.
10897   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
10898   for (unsigned I = 0; I != NumSrcOps; ++I) {
10899     if (SrcUndefElements[I]) {
10900       DstUndefElements.set(I * Scale, (I + 1) * Scale);
10901       continue;
10902     }
10903     const APInt &SrcBits = SrcBitElements[I];
10904     for (unsigned J = 0; J != Scale; ++J) {
10905       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10906       APInt &DstBits = DstBitElements[Idx];
10907       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
10908     }
10909   }
10910 }
10911 
10912 bool BuildVectorSDNode::isConstant() const {
10913   for (const SDValue &Op : op_values()) {
10914     unsigned Opc = Op.getOpcode();
10915     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10916       return false;
10917   }
10918   return true;
10919 }
10920 
10921 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10922   // Find the first non-undef value in the shuffle mask.
10923   unsigned i, e;
10924   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10925     /* search */;
10926 
10927   // If all elements are undefined, this shuffle can be considered a splat
10928   // (although it should eventually get simplified away completely).
10929   if (i == e)
10930     return true;
10931 
10932   // Make sure all remaining elements are either undef or the same as the first
10933   // non-undef value.
10934   for (int Idx = Mask[i]; i != e; ++i)
10935     if (Mask[i] >= 0 && Mask[i] != Idx)
10936       return false;
10937   return true;
10938 }
10939 
10940 // Returns the SDNode if it is a constant integer BuildVector
10941 // or constant integer.
10942 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10943   if (isa<ConstantSDNode>(N))
10944     return N.getNode();
10945   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10946     return N.getNode();
10947   // Treat a GlobalAddress supporting constant offset folding as a
10948   // constant integer.
10949   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10950     if (GA->getOpcode() == ISD::GlobalAddress &&
10951         TLI->isOffsetFoldingLegal(GA))
10952       return GA;
10953   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10954       isa<ConstantSDNode>(N.getOperand(0)))
10955     return N.getNode();
10956   return nullptr;
10957 }
10958 
10959 // Returns the SDNode if it is a constant float BuildVector
10960 // or constant float.
10961 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10962   if (isa<ConstantFPSDNode>(N))
10963     return N.getNode();
10964 
10965   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10966     return N.getNode();
10967 
10968   return nullptr;
10969 }
10970 
10971 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10972   assert(!Node->OperandList && "Node already has operands");
10973   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
10974          "too many operands to fit into SDNode");
10975   SDUse *Ops = OperandRecycler.allocate(
10976       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10977 
10978   bool IsDivergent = false;
10979   for (unsigned I = 0; I != Vals.size(); ++I) {
10980     Ops[I].setUser(Node);
10981     Ops[I].setInitial(Vals[I]);
10982     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10983       IsDivergent |= Ops[I].getNode()->isDivergent();
10984   }
10985   Node->NumOperands = Vals.size();
10986   Node->OperandList = Ops;
10987   if (!TLI->isSDNodeAlwaysUniform(Node)) {
10988     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10989     Node->SDNodeBits.IsDivergent = IsDivergent;
10990   }
10991   checkForCycles(Node);
10992 }
10993 
10994 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10995                                      SmallVectorImpl<SDValue> &Vals) {
10996   size_t Limit = SDNode::getMaxNumOperands();
10997   while (Vals.size() > Limit) {
10998     unsigned SliceIdx = Vals.size() - Limit;
10999     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11000     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11001     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11002     Vals.emplace_back(NewTF);
11003   }
11004   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11005 }
11006 
11007 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11008                                         EVT VT, SDNodeFlags Flags) {
11009   switch (Opcode) {
11010   default:
11011     return SDValue();
11012   case ISD::ADD:
11013   case ISD::OR:
11014   case ISD::XOR:
11015   case ISD::UMAX:
11016     return getConstant(0, DL, VT);
11017   case ISD::MUL:
11018     return getConstant(1, DL, VT);
11019   case ISD::AND:
11020   case ISD::UMIN:
11021     return getAllOnesConstant(DL, VT);
11022   case ISD::SMAX:
11023     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11024   case ISD::SMIN:
11025     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11026   case ISD::FADD:
11027     return getConstantFP(-0.0, DL, VT);
11028   case ISD::FMUL:
11029     return getConstantFP(1.0, DL, VT);
11030   case ISD::FMINNUM:
11031   case ISD::FMAXNUM: {
11032     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11033     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11034     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11035                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11036                         APFloat::getLargest(Semantics);
11037     if (Opcode == ISD::FMAXNUM)
11038       NeutralAF.changeSign();
11039 
11040     return getConstantFP(NeutralAF, DL, VT);
11041   }
11042   }
11043 }
11044 
11045 #ifndef NDEBUG
11046 static void checkForCyclesHelper(const SDNode *N,
11047                                  SmallPtrSetImpl<const SDNode*> &Visited,
11048                                  SmallPtrSetImpl<const SDNode*> &Checked,
11049                                  const llvm::SelectionDAG *DAG) {
11050   // If this node has already been checked, don't check it again.
11051   if (Checked.count(N))
11052     return;
11053 
11054   // If a node has already been visited on this depth-first walk, reject it as
11055   // a cycle.
11056   if (!Visited.insert(N).second) {
11057     errs() << "Detected cycle in SelectionDAG\n";
11058     dbgs() << "Offending node:\n";
11059     N->dumprFull(DAG); dbgs() << "\n";
11060     abort();
11061   }
11062 
11063   for (const SDValue &Op : N->op_values())
11064     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11065 
11066   Checked.insert(N);
11067   Visited.erase(N);
11068 }
11069 #endif
11070 
11071 void llvm::checkForCycles(const llvm::SDNode *N,
11072                           const llvm::SelectionDAG *DAG,
11073                           bool force) {
11074 #ifndef NDEBUG
11075   bool check = force;
11076 #ifdef EXPENSIVE_CHECKS
11077   check = true;
11078 #endif  // EXPENSIVE_CHECKS
11079   if (check) {
11080     assert(N && "Checking nonexistent SDNode");
11081     SmallPtrSet<const SDNode*, 32> visited;
11082     SmallPtrSet<const SDNode*, 32> checked;
11083     checkForCyclesHelper(N, visited, checked, DAG);
11084   }
11085 #endif  // !NDEBUG
11086 }
11087 
11088 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11089   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11090 }
11091