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(VPSD, ...)                                    \
410   case ISD::VPSD:                                                              \
411     return true;
412 #include "llvm/IR/VPIntrinsics.def"
413   }
414 }
415 
416 bool ISD::isVPBinaryOp(unsigned Opcode) {
417   switch (Opcode) {
418   default:
419     break;
420 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
421 #define VP_PROPERTY_BINARYOP return true;
422 #define END_REGISTER_VP_SDNODE(VPSD) break;
423 #include "llvm/IR/VPIntrinsics.def"
424   }
425   return false;
426 }
427 
428 bool ISD::isVPReduction(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     break;
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437   return false;
438 }
439 
440 /// The operand position of the vector mask.
441 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
442   switch (Opcode) {
443   default:
444     return None;
445 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
446   case ISD::VPSD:                                                              \
447     return MASKPOS;
448 #include "llvm/IR/VPIntrinsics.def"
449   }
450 }
451 
452 /// The operand position of the explicit vector length parameter.
453 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
454   switch (Opcode) {
455   default:
456     return None;
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
458   case ISD::VPSD:                                                              \
459     return EVLPOS;
460 #include "llvm/IR/VPIntrinsics.def"
461   }
462 }
463 
464 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
465   switch (ExtType) {
466   case ISD::EXTLOAD:
467     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
468   case ISD::SEXTLOAD:
469     return ISD::SIGN_EXTEND;
470   case ISD::ZEXTLOAD:
471     return ISD::ZERO_EXTEND;
472   default:
473     break;
474   }
475 
476   llvm_unreachable("Invalid LoadExtType");
477 }
478 
479 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
480   // To perform this operation, we just need to swap the L and G bits of the
481   // operation.
482   unsigned OldL = (Operation >> 2) & 1;
483   unsigned OldG = (Operation >> 1) & 1;
484   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
485                        (OldL << 1) |       // New G bit
486                        (OldG << 2));       // New L bit.
487 }
488 
489 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
490   unsigned Operation = Op;
491   if (isIntegerLike)
492     Operation ^= 7;   // Flip L, G, E bits, but not U.
493   else
494     Operation ^= 15;  // Flip all of the condition bits.
495 
496   if (Operation > ISD::SETTRUE2)
497     Operation &= ~8;  // Don't let N and U bits get set.
498 
499   return ISD::CondCode(Operation);
500 }
501 
502 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
503   return getSetCCInverseImpl(Op, Type.isInteger());
504 }
505 
506 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
507                                                bool isIntegerLike) {
508   return getSetCCInverseImpl(Op, isIntegerLike);
509 }
510 
511 /// For an integer comparison, return 1 if the comparison is a signed operation
512 /// and 2 if the result is an unsigned comparison. Return zero if the operation
513 /// does not depend on the sign of the input (setne and seteq).
514 static int isSignedOp(ISD::CondCode Opcode) {
515   switch (Opcode) {
516   default: llvm_unreachable("Illegal integer setcc operation!");
517   case ISD::SETEQ:
518   case ISD::SETNE: return 0;
519   case ISD::SETLT:
520   case ISD::SETLE:
521   case ISD::SETGT:
522   case ISD::SETGE: return 1;
523   case ISD::SETULT:
524   case ISD::SETULE:
525   case ISD::SETUGT:
526   case ISD::SETUGE: return 2;
527   }
528 }
529 
530 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
531                                        EVT Type) {
532   bool IsInteger = Type.isInteger();
533   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
534     // Cannot fold a signed integer setcc with an unsigned integer setcc.
535     return ISD::SETCC_INVALID;
536 
537   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
538 
539   // If the N and U bits get set, then the resultant comparison DOES suddenly
540   // care about orderedness, and it is true when ordered.
541   if (Op > ISD::SETTRUE2)
542     Op &= ~16;     // Clear the U bit if the N bit is set.
543 
544   // Canonicalize illegal integer setcc's.
545   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
546     Op = ISD::SETNE;
547 
548   return ISD::CondCode(Op);
549 }
550 
551 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
552                                         EVT Type) {
553   bool IsInteger = Type.isInteger();
554   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
555     // Cannot fold a signed setcc with an unsigned setcc.
556     return ISD::SETCC_INVALID;
557 
558   // Combine all of the condition bits.
559   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
560 
561   // Canonicalize illegal integer setcc's.
562   if (IsInteger) {
563     switch (Result) {
564     default: break;
565     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
566     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
567     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
568     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
569     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
570     }
571   }
572 
573   return Result;
574 }
575 
576 //===----------------------------------------------------------------------===//
577 //                           SDNode Profile Support
578 //===----------------------------------------------------------------------===//
579 
580 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
581 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
582   ID.AddInteger(OpC);
583 }
584 
585 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
586 /// solely with their pointer.
587 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
588   ID.AddPointer(VTList.VTs);
589 }
590 
591 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
592 static void AddNodeIDOperands(FoldingSetNodeID &ID,
593                               ArrayRef<SDValue> Ops) {
594   for (auto& Op : Ops) {
595     ID.AddPointer(Op.getNode());
596     ID.AddInteger(Op.getResNo());
597   }
598 }
599 
600 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
601 static void AddNodeIDOperands(FoldingSetNodeID &ID,
602                               ArrayRef<SDUse> Ops) {
603   for (auto& Op : Ops) {
604     ID.AddPointer(Op.getNode());
605     ID.AddInteger(Op.getResNo());
606   }
607 }
608 
609 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
610                           SDVTList VTList, ArrayRef<SDValue> OpList) {
611   AddNodeIDOpcode(ID, OpC);
612   AddNodeIDValueTypes(ID, VTList);
613   AddNodeIDOperands(ID, OpList);
614 }
615 
616 /// If this is an SDNode with special info, add this info to the NodeID data.
617 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
618   switch (N->getOpcode()) {
619   case ISD::TargetExternalSymbol:
620   case ISD::ExternalSymbol:
621   case ISD::MCSymbol:
622     llvm_unreachable("Should only be used on nodes with operands");
623   default: break;  // Normal nodes don't need extra info.
624   case ISD::TargetConstant:
625   case ISD::Constant: {
626     const ConstantSDNode *C = cast<ConstantSDNode>(N);
627     ID.AddPointer(C->getConstantIntValue());
628     ID.AddBoolean(C->isOpaque());
629     break;
630   }
631   case ISD::TargetConstantFP:
632   case ISD::ConstantFP:
633     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
634     break;
635   case ISD::TargetGlobalAddress:
636   case ISD::GlobalAddress:
637   case ISD::TargetGlobalTLSAddress:
638   case ISD::GlobalTLSAddress: {
639     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
640     ID.AddPointer(GA->getGlobal());
641     ID.AddInteger(GA->getOffset());
642     ID.AddInteger(GA->getTargetFlags());
643     break;
644   }
645   case ISD::BasicBlock:
646     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
647     break;
648   case ISD::Register:
649     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
650     break;
651   case ISD::RegisterMask:
652     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
653     break;
654   case ISD::SRCVALUE:
655     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
656     break;
657   case ISD::FrameIndex:
658   case ISD::TargetFrameIndex:
659     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
660     break;
661   case ISD::LIFETIME_START:
662   case ISD::LIFETIME_END:
663     if (cast<LifetimeSDNode>(N)->hasOffset()) {
664       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
665       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
666     }
667     break;
668   case ISD::PSEUDO_PROBE:
669     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
670     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
671     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
672     break;
673   case ISD::JumpTable:
674   case ISD::TargetJumpTable:
675     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
676     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
677     break;
678   case ISD::ConstantPool:
679   case ISD::TargetConstantPool: {
680     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
681     ID.AddInteger(CP->getAlign().value());
682     ID.AddInteger(CP->getOffset());
683     if (CP->isMachineConstantPoolEntry())
684       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
685     else
686       ID.AddPointer(CP->getConstVal());
687     ID.AddInteger(CP->getTargetFlags());
688     break;
689   }
690   case ISD::TargetIndex: {
691     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
692     ID.AddInteger(TI->getIndex());
693     ID.AddInteger(TI->getOffset());
694     ID.AddInteger(TI->getTargetFlags());
695     break;
696   }
697   case ISD::LOAD: {
698     const LoadSDNode *LD = cast<LoadSDNode>(N);
699     ID.AddInteger(LD->getMemoryVT().getRawBits());
700     ID.AddInteger(LD->getRawSubclassData());
701     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
702     break;
703   }
704   case ISD::STORE: {
705     const StoreSDNode *ST = cast<StoreSDNode>(N);
706     ID.AddInteger(ST->getMemoryVT().getRawBits());
707     ID.AddInteger(ST->getRawSubclassData());
708     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
709     break;
710   }
711   case ISD::VP_LOAD: {
712     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
713     ID.AddInteger(ELD->getMemoryVT().getRawBits());
714     ID.AddInteger(ELD->getRawSubclassData());
715     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
716     break;
717   }
718   case ISD::VP_STORE: {
719     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
720     ID.AddInteger(EST->getMemoryVT().getRawBits());
721     ID.AddInteger(EST->getRawSubclassData());
722     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
723     break;
724   }
725   case ISD::VP_GATHER: {
726     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
727     ID.AddInteger(EG->getMemoryVT().getRawBits());
728     ID.AddInteger(EG->getRawSubclassData());
729     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
730     break;
731   }
732   case ISD::VP_SCATTER: {
733     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
734     ID.AddInteger(ES->getMemoryVT().getRawBits());
735     ID.AddInteger(ES->getRawSubclassData());
736     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
737     break;
738   }
739   case ISD::MLOAD: {
740     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
741     ID.AddInteger(MLD->getMemoryVT().getRawBits());
742     ID.AddInteger(MLD->getRawSubclassData());
743     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
744     break;
745   }
746   case ISD::MSTORE: {
747     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
748     ID.AddInteger(MST->getMemoryVT().getRawBits());
749     ID.AddInteger(MST->getRawSubclassData());
750     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
751     break;
752   }
753   case ISD::MGATHER: {
754     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
755     ID.AddInteger(MG->getMemoryVT().getRawBits());
756     ID.AddInteger(MG->getRawSubclassData());
757     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
758     break;
759   }
760   case ISD::MSCATTER: {
761     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
762     ID.AddInteger(MS->getMemoryVT().getRawBits());
763     ID.AddInteger(MS->getRawSubclassData());
764     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
765     break;
766   }
767   case ISD::ATOMIC_CMP_SWAP:
768   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
769   case ISD::ATOMIC_SWAP:
770   case ISD::ATOMIC_LOAD_ADD:
771   case ISD::ATOMIC_LOAD_SUB:
772   case ISD::ATOMIC_LOAD_AND:
773   case ISD::ATOMIC_LOAD_CLR:
774   case ISD::ATOMIC_LOAD_OR:
775   case ISD::ATOMIC_LOAD_XOR:
776   case ISD::ATOMIC_LOAD_NAND:
777   case ISD::ATOMIC_LOAD_MIN:
778   case ISD::ATOMIC_LOAD_MAX:
779   case ISD::ATOMIC_LOAD_UMIN:
780   case ISD::ATOMIC_LOAD_UMAX:
781   case ISD::ATOMIC_LOAD:
782   case ISD::ATOMIC_STORE: {
783     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
784     ID.AddInteger(AT->getMemoryVT().getRawBits());
785     ID.AddInteger(AT->getRawSubclassData());
786     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
787     break;
788   }
789   case ISD::PREFETCH: {
790     const MemSDNode *PF = cast<MemSDNode>(N);
791     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
792     break;
793   }
794   case ISD::VECTOR_SHUFFLE: {
795     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
796     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
797          i != e; ++i)
798       ID.AddInteger(SVN->getMaskElt(i));
799     break;
800   }
801   case ISD::TargetBlockAddress:
802   case ISD::BlockAddress: {
803     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
804     ID.AddPointer(BA->getBlockAddress());
805     ID.AddInteger(BA->getOffset());
806     ID.AddInteger(BA->getTargetFlags());
807     break;
808   }
809   } // end switch (N->getOpcode())
810 
811   // Target specific memory nodes could also have address spaces to check.
812   if (N->isTargetMemoryOpcode())
813     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
814 }
815 
816 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
817 /// data.
818 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
819   AddNodeIDOpcode(ID, N->getOpcode());
820   // Add the return value info.
821   AddNodeIDValueTypes(ID, N->getVTList());
822   // Add the operand info.
823   AddNodeIDOperands(ID, N->ops());
824 
825   // Handle SDNode leafs with special info.
826   AddNodeIDCustom(ID, N);
827 }
828 
829 //===----------------------------------------------------------------------===//
830 //                              SelectionDAG Class
831 //===----------------------------------------------------------------------===//
832 
833 /// doNotCSE - Return true if CSE should not be performed for this node.
834 static bool doNotCSE(SDNode *N) {
835   if (N->getValueType(0) == MVT::Glue)
836     return true; // Never CSE anything that produces a flag.
837 
838   switch (N->getOpcode()) {
839   default: break;
840   case ISD::HANDLENODE:
841   case ISD::EH_LABEL:
842     return true;   // Never CSE these nodes.
843   }
844 
845   // Check that remaining values produced are not flags.
846   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
847     if (N->getValueType(i) == MVT::Glue)
848       return true; // Never CSE anything that produces a flag.
849 
850   return false;
851 }
852 
853 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
854 /// SelectionDAG.
855 void SelectionDAG::RemoveDeadNodes() {
856   // Create a dummy node (which is not added to allnodes), that adds a reference
857   // to the root node, preventing it from being deleted.
858   HandleSDNode Dummy(getRoot());
859 
860   SmallVector<SDNode*, 128> DeadNodes;
861 
862   // Add all obviously-dead nodes to the DeadNodes worklist.
863   for (SDNode &Node : allnodes())
864     if (Node.use_empty())
865       DeadNodes.push_back(&Node);
866 
867   RemoveDeadNodes(DeadNodes);
868 
869   // If the root changed (e.g. it was a dead load, update the root).
870   setRoot(Dummy.getValue());
871 }
872 
873 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
874 /// given list, and any nodes that become unreachable as a result.
875 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
876 
877   // Process the worklist, deleting the nodes and adding their uses to the
878   // worklist.
879   while (!DeadNodes.empty()) {
880     SDNode *N = DeadNodes.pop_back_val();
881     // Skip to next node if we've already managed to delete the node. This could
882     // happen if replacing a node causes a node previously added to the node to
883     // be deleted.
884     if (N->getOpcode() == ISD::DELETED_NODE)
885       continue;
886 
887     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
888       DUL->NodeDeleted(N, nullptr);
889 
890     // Take the node out of the appropriate CSE map.
891     RemoveNodeFromCSEMaps(N);
892 
893     // Next, brutally remove the operand list.  This is safe to do, as there are
894     // no cycles in the graph.
895     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
896       SDUse &Use = *I++;
897       SDNode *Operand = Use.getNode();
898       Use.set(SDValue());
899 
900       // Now that we removed this operand, see if there are no uses of it left.
901       if (Operand->use_empty())
902         DeadNodes.push_back(Operand);
903     }
904 
905     DeallocateNode(N);
906   }
907 }
908 
909 void SelectionDAG::RemoveDeadNode(SDNode *N){
910   SmallVector<SDNode*, 16> DeadNodes(1, N);
911 
912   // Create a dummy node that adds a reference to the root node, preventing
913   // it from being deleted.  (This matters if the root is an operand of the
914   // dead node.)
915   HandleSDNode Dummy(getRoot());
916 
917   RemoveDeadNodes(DeadNodes);
918 }
919 
920 void SelectionDAG::DeleteNode(SDNode *N) {
921   // First take this out of the appropriate CSE map.
922   RemoveNodeFromCSEMaps(N);
923 
924   // Finally, remove uses due to operands of this node, remove from the
925   // AllNodes list, and delete the node.
926   DeleteNodeNotInCSEMaps(N);
927 }
928 
929 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
930   assert(N->getIterator() != AllNodes.begin() &&
931          "Cannot delete the entry node!");
932   assert(N->use_empty() && "Cannot delete a node that is not dead!");
933 
934   // Drop all of the operands and decrement used node's use counts.
935   N->DropOperands();
936 
937   DeallocateNode(N);
938 }
939 
940 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
941   assert(!(V->isVariadic() && isParameter));
942   if (isParameter)
943     ByvalParmDbgValues.push_back(V);
944   else
945     DbgValues.push_back(V);
946   for (const SDNode *Node : V->getSDNodes())
947     if (Node)
948       DbgValMap[Node].push_back(V);
949 }
950 
951 void SDDbgInfo::erase(const SDNode *Node) {
952   DbgValMapType::iterator I = DbgValMap.find(Node);
953   if (I == DbgValMap.end())
954     return;
955   for (auto &Val: I->second)
956     Val->setIsInvalidated();
957   DbgValMap.erase(I);
958 }
959 
960 void SelectionDAG::DeallocateNode(SDNode *N) {
961   // If we have operands, deallocate them.
962   removeOperands(N);
963 
964   NodeAllocator.Deallocate(AllNodes.remove(N));
965 
966   // Set the opcode to DELETED_NODE to help catch bugs when node
967   // memory is reallocated.
968   // FIXME: There are places in SDag that have grown a dependency on the opcode
969   // value in the released node.
970   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
971   N->NodeType = ISD::DELETED_NODE;
972 
973   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
974   // them and forget about that node.
975   DbgInfo->erase(N);
976 }
977 
978 #ifndef NDEBUG
979 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
980 static void VerifySDNode(SDNode *N) {
981   switch (N->getOpcode()) {
982   default:
983     break;
984   case ISD::BUILD_PAIR: {
985     EVT VT = N->getValueType(0);
986     assert(N->getNumValues() == 1 && "Too many results!");
987     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
988            "Wrong return type!");
989     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
990     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
991            "Mismatched operand types!");
992     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
993            "Wrong operand type!");
994     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
995            "Wrong return type size");
996     break;
997   }
998   case ISD::BUILD_VECTOR: {
999     assert(N->getNumValues() == 1 && "Too many results!");
1000     assert(N->getValueType(0).isVector() && "Wrong return type!");
1001     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1002            "Wrong number of operands!");
1003     EVT EltVT = N->getValueType(0).getVectorElementType();
1004     for (const SDUse &Op : N->ops()) {
1005       assert((Op.getValueType() == EltVT ||
1006               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1007                EltVT.bitsLE(Op.getValueType()))) &&
1008              "Wrong operand type!");
1009       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1010              "Operands must all have the same type");
1011     }
1012     break;
1013   }
1014   }
1015 }
1016 #endif // NDEBUG
1017 
1018 /// Insert a newly allocated node into the DAG.
1019 ///
1020 /// Handles insertion into the all nodes list and CSE map, as well as
1021 /// verification and other common operations when a new node is allocated.
1022 void SelectionDAG::InsertNode(SDNode *N) {
1023   AllNodes.push_back(N);
1024 #ifndef NDEBUG
1025   N->PersistentId = NextPersistentId++;
1026   VerifySDNode(N);
1027 #endif
1028   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1029     DUL->NodeInserted(N);
1030 }
1031 
1032 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1033 /// correspond to it.  This is useful when we're about to delete or repurpose
1034 /// the node.  We don't want future request for structurally identical nodes
1035 /// to return N anymore.
1036 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1037   bool Erased = false;
1038   switch (N->getOpcode()) {
1039   case ISD::HANDLENODE: return false;  // noop.
1040   case ISD::CONDCODE:
1041     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1042            "Cond code doesn't exist!");
1043     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1044     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1045     break;
1046   case ISD::ExternalSymbol:
1047     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1048     break;
1049   case ISD::TargetExternalSymbol: {
1050     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1051     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1052         ESN->getSymbol(), ESN->getTargetFlags()));
1053     break;
1054   }
1055   case ISD::MCSymbol: {
1056     auto *MCSN = cast<MCSymbolSDNode>(N);
1057     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1058     break;
1059   }
1060   case ISD::VALUETYPE: {
1061     EVT VT = cast<VTSDNode>(N)->getVT();
1062     if (VT.isExtended()) {
1063       Erased = ExtendedValueTypeNodes.erase(VT);
1064     } else {
1065       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1066       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1067     }
1068     break;
1069   }
1070   default:
1071     // Remove it from the CSE Map.
1072     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1073     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1074     Erased = CSEMap.RemoveNode(N);
1075     break;
1076   }
1077 #ifndef NDEBUG
1078   // Verify that the node was actually in one of the CSE maps, unless it has a
1079   // flag result (which cannot be CSE'd) or is one of the special cases that are
1080   // not subject to CSE.
1081   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1082       !N->isMachineOpcode() && !doNotCSE(N)) {
1083     N->dump(this);
1084     dbgs() << "\n";
1085     llvm_unreachable("Node is not in map!");
1086   }
1087 #endif
1088   return Erased;
1089 }
1090 
1091 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1092 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1093 /// node already exists, in which case transfer all its users to the existing
1094 /// node. This transfer can potentially trigger recursive merging.
1095 void
1096 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1097   // For node types that aren't CSE'd, just act as if no identical node
1098   // already exists.
1099   if (!doNotCSE(N)) {
1100     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1101     if (Existing != N) {
1102       // If there was already an existing matching node, use ReplaceAllUsesWith
1103       // to replace the dead one with the existing one.  This can cause
1104       // recursive merging of other unrelated nodes down the line.
1105       ReplaceAllUsesWith(N, Existing);
1106 
1107       // N is now dead. Inform the listeners and delete it.
1108       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1109         DUL->NodeDeleted(N, Existing);
1110       DeleteNodeNotInCSEMaps(N);
1111       return;
1112     }
1113   }
1114 
1115   // If the node doesn't already exist, we updated it.  Inform listeners.
1116   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1117     DUL->NodeUpdated(N);
1118 }
1119 
1120 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1121 /// were replaced with those specified.  If this node is never memoized,
1122 /// return null, otherwise return a pointer to the slot it would take.  If a
1123 /// node already exists with these operands, the slot will be non-null.
1124 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1125                                            void *&InsertPos) {
1126   if (doNotCSE(N))
1127     return nullptr;
1128 
1129   SDValue Ops[] = { Op };
1130   FoldingSetNodeID ID;
1131   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1132   AddNodeIDCustom(ID, N);
1133   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1134   if (Node)
1135     Node->intersectFlagsWith(N->getFlags());
1136   return Node;
1137 }
1138 
1139 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1140 /// were replaced with those specified.  If this node is never memoized,
1141 /// return null, otherwise return a pointer to the slot it would take.  If a
1142 /// node already exists with these operands, the slot will be non-null.
1143 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1144                                            SDValue Op1, SDValue Op2,
1145                                            void *&InsertPos) {
1146   if (doNotCSE(N))
1147     return nullptr;
1148 
1149   SDValue Ops[] = { Op1, Op2 };
1150   FoldingSetNodeID ID;
1151   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1152   AddNodeIDCustom(ID, N);
1153   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1154   if (Node)
1155     Node->intersectFlagsWith(N->getFlags());
1156   return Node;
1157 }
1158 
1159 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1160 /// were replaced with those specified.  If this node is never memoized,
1161 /// return null, otherwise return a pointer to the slot it would take.  If a
1162 /// node already exists with these operands, the slot will be non-null.
1163 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1164                                            void *&InsertPos) {
1165   if (doNotCSE(N))
1166     return nullptr;
1167 
1168   FoldingSetNodeID ID;
1169   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1170   AddNodeIDCustom(ID, N);
1171   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1172   if (Node)
1173     Node->intersectFlagsWith(N->getFlags());
1174   return Node;
1175 }
1176 
1177 Align SelectionDAG::getEVTAlign(EVT VT) const {
1178   Type *Ty = VT == MVT::iPTR ?
1179                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1180                    VT.getTypeForEVT(*getContext());
1181 
1182   return getDataLayout().getABITypeAlign(Ty);
1183 }
1184 
1185 // EntryNode could meaningfully have debug info if we can find it...
1186 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1187     : TM(tm), OptLevel(OL),
1188       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1189       Root(getEntryNode()) {
1190   InsertNode(&EntryNode);
1191   DbgInfo = new SDDbgInfo();
1192 }
1193 
1194 void SelectionDAG::init(MachineFunction &NewMF,
1195                         OptimizationRemarkEmitter &NewORE,
1196                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1197                         LegacyDivergenceAnalysis * Divergence,
1198                         ProfileSummaryInfo *PSIin,
1199                         BlockFrequencyInfo *BFIin) {
1200   MF = &NewMF;
1201   SDAGISelPass = PassPtr;
1202   ORE = &NewORE;
1203   TLI = getSubtarget().getTargetLowering();
1204   TSI = getSubtarget().getSelectionDAGInfo();
1205   LibInfo = LibraryInfo;
1206   Context = &MF->getFunction().getContext();
1207   DA = Divergence;
1208   PSI = PSIin;
1209   BFI = BFIin;
1210 }
1211 
1212 SelectionDAG::~SelectionDAG() {
1213   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1214   allnodes_clear();
1215   OperandRecycler.clear(OperandAllocator);
1216   delete DbgInfo;
1217 }
1218 
1219 bool SelectionDAG::shouldOptForSize() const {
1220   return MF->getFunction().hasOptSize() ||
1221       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1222 }
1223 
1224 void SelectionDAG::allnodes_clear() {
1225   assert(&*AllNodes.begin() == &EntryNode);
1226   AllNodes.remove(AllNodes.begin());
1227   while (!AllNodes.empty())
1228     DeallocateNode(&AllNodes.front());
1229 #ifndef NDEBUG
1230   NextPersistentId = 0;
1231 #endif
1232 }
1233 
1234 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1235                                           void *&InsertPos) {
1236   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1237   if (N) {
1238     switch (N->getOpcode()) {
1239     default: break;
1240     case ISD::Constant:
1241     case ISD::ConstantFP:
1242       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1243                        "debug location.  Use another overload.");
1244     }
1245   }
1246   return N;
1247 }
1248 
1249 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1250                                           const SDLoc &DL, void *&InsertPos) {
1251   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1252   if (N) {
1253     switch (N->getOpcode()) {
1254     case ISD::Constant:
1255     case ISD::ConstantFP:
1256       // Erase debug location from the node if the node is used at several
1257       // different places. Do not propagate one location to all uses as it
1258       // will cause a worse single stepping debugging experience.
1259       if (N->getDebugLoc() != DL.getDebugLoc())
1260         N->setDebugLoc(DebugLoc());
1261       break;
1262     default:
1263       // When the node's point of use is located earlier in the instruction
1264       // sequence than its prior point of use, update its debug info to the
1265       // earlier location.
1266       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1267         N->setDebugLoc(DL.getDebugLoc());
1268       break;
1269     }
1270   }
1271   return N;
1272 }
1273 
1274 void SelectionDAG::clear() {
1275   allnodes_clear();
1276   OperandRecycler.clear(OperandAllocator);
1277   OperandAllocator.Reset();
1278   CSEMap.clear();
1279 
1280   ExtendedValueTypeNodes.clear();
1281   ExternalSymbols.clear();
1282   TargetExternalSymbols.clear();
1283   MCSymbols.clear();
1284   SDCallSiteDbgInfo.clear();
1285   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1286             static_cast<CondCodeSDNode*>(nullptr));
1287   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1288             static_cast<SDNode*>(nullptr));
1289 
1290   EntryNode.UseList = nullptr;
1291   InsertNode(&EntryNode);
1292   Root = getEntryNode();
1293   DbgInfo->clear();
1294 }
1295 
1296 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1297   return VT.bitsGT(Op.getValueType())
1298              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1299              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1300 }
1301 
1302 std::pair<SDValue, SDValue>
1303 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1304                                        const SDLoc &DL, EVT VT) {
1305   assert(!VT.bitsEq(Op.getValueType()) &&
1306          "Strict no-op FP extend/round not allowed.");
1307   SDValue Res =
1308       VT.bitsGT(Op.getValueType())
1309           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1310           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1311                     {Chain, Op, getIntPtrConstant(0, DL)});
1312 
1313   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1314 }
1315 
1316 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1317   return VT.bitsGT(Op.getValueType()) ?
1318     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1319     getNode(ISD::TRUNCATE, DL, VT, Op);
1320 }
1321 
1322 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1323   return VT.bitsGT(Op.getValueType()) ?
1324     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1325     getNode(ISD::TRUNCATE, DL, VT, Op);
1326 }
1327 
1328 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1329   return VT.bitsGT(Op.getValueType()) ?
1330     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1331     getNode(ISD::TRUNCATE, DL, VT, Op);
1332 }
1333 
1334 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1335                                         EVT OpVT) {
1336   if (VT.bitsLE(Op.getValueType()))
1337     return getNode(ISD::TRUNCATE, SL, VT, Op);
1338 
1339   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1340   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1341 }
1342 
1343 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1344   EVT OpVT = Op.getValueType();
1345   assert(VT.isInteger() && OpVT.isInteger() &&
1346          "Cannot getZeroExtendInReg FP types");
1347   assert(VT.isVector() == OpVT.isVector() &&
1348          "getZeroExtendInReg type should be vector iff the operand "
1349          "type is vector!");
1350   assert((!VT.isVector() ||
1351           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1352          "Vector element counts must match in getZeroExtendInReg");
1353   assert(VT.bitsLE(OpVT) && "Not extending!");
1354   if (OpVT == VT)
1355     return Op;
1356   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1357                                    VT.getScalarSizeInBits());
1358   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1359 }
1360 
1361 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362   // Only unsigned pointer semantics are supported right now. In the future this
1363   // might delegate to TLI to check pointer signedness.
1364   return getZExtOrTrunc(Op, DL, VT);
1365 }
1366 
1367 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1368   // Only unsigned pointer semantics are supported right now. In the future this
1369   // might delegate to TLI to check pointer signedness.
1370   return getZeroExtendInReg(Op, DL, VT);
1371 }
1372 
1373 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1374 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1375   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1376 }
1377 
1378 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1379   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1380   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1381 }
1382 
1383 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1384                                       EVT OpVT) {
1385   if (!V)
1386     return getConstant(0, DL, VT);
1387 
1388   switch (TLI->getBooleanContents(OpVT)) {
1389   case TargetLowering::ZeroOrOneBooleanContent:
1390   case TargetLowering::UndefinedBooleanContent:
1391     return getConstant(1, DL, VT);
1392   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1393     return getAllOnesConstant(DL, VT);
1394   }
1395   llvm_unreachable("Unexpected boolean content enum!");
1396 }
1397 
1398 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1399                                   bool isT, bool isO) {
1400   EVT EltVT = VT.getScalarType();
1401   assert((EltVT.getSizeInBits() >= 64 ||
1402           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1403          "getConstant with a uint64_t value that doesn't fit in the type!");
1404   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1405 }
1406 
1407 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1408                                   bool isT, bool isO) {
1409   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1410 }
1411 
1412 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1413                                   EVT VT, bool isT, bool isO) {
1414   assert(VT.isInteger() && "Cannot create FP integer constant!");
1415 
1416   EVT EltVT = VT.getScalarType();
1417   const ConstantInt *Elt = &Val;
1418 
1419   // In some cases the vector type is legal but the element type is illegal and
1420   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1421   // inserted value (the type does not need to match the vector element type).
1422   // Any extra bits introduced will be truncated away.
1423   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1424                            TargetLowering::TypePromoteInteger) {
1425     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1426     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1427     Elt = ConstantInt::get(*getContext(), NewVal);
1428   }
1429   // In other cases the element type is illegal and needs to be expanded, for
1430   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1431   // the value into n parts and use a vector type with n-times the elements.
1432   // Then bitcast to the type requested.
1433   // Legalizing constants too early makes the DAGCombiner's job harder so we
1434   // only legalize if the DAG tells us we must produce legal types.
1435   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1436            TLI->getTypeAction(*getContext(), EltVT) ==
1437                TargetLowering::TypeExpandInteger) {
1438     const APInt &NewVal = Elt->getValue();
1439     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1440     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1441 
1442     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1443     if (VT.isScalableVector()) {
1444       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1445              "Can only handle an even split!");
1446       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1447 
1448       SmallVector<SDValue, 2> ScalarParts;
1449       for (unsigned i = 0; i != Parts; ++i)
1450         ScalarParts.push_back(getConstant(
1451             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1452             ViaEltVT, isT, isO));
1453 
1454       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1455     }
1456 
1457     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1458     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1459 
1460     // Check the temporary vector is the correct size. If this fails then
1461     // getTypeToTransformTo() probably returned a type whose size (in bits)
1462     // isn't a power-of-2 factor of the requested type size.
1463     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1464 
1465     SmallVector<SDValue, 2> EltParts;
1466     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1467       EltParts.push_back(getConstant(
1468           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1469           ViaEltVT, isT, isO));
1470 
1471     // EltParts is currently in little endian order. If we actually want
1472     // big-endian order then reverse it now.
1473     if (getDataLayout().isBigEndian())
1474       std::reverse(EltParts.begin(), EltParts.end());
1475 
1476     // The elements must be reversed when the element order is different
1477     // to the endianness of the elements (because the BITCAST is itself a
1478     // vector shuffle in this situation). However, we do not need any code to
1479     // perform this reversal because getConstant() is producing a vector
1480     // splat.
1481     // This situation occurs in MIPS MSA.
1482 
1483     SmallVector<SDValue, 8> Ops;
1484     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1485       llvm::append_range(Ops, EltParts);
1486 
1487     SDValue V =
1488         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1489     return V;
1490   }
1491 
1492   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1493          "APInt size does not match type size!");
1494   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1495   FoldingSetNodeID ID;
1496   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1497   ID.AddPointer(Elt);
1498   ID.AddBoolean(isO);
1499   void *IP = nullptr;
1500   SDNode *N = nullptr;
1501   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1502     if (!VT.isVector())
1503       return SDValue(N, 0);
1504 
1505   if (!N) {
1506     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1507     CSEMap.InsertNode(N, IP);
1508     InsertNode(N);
1509     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1510   }
1511 
1512   SDValue Result(N, 0);
1513   if (VT.isScalableVector())
1514     Result = getSplatVector(VT, DL, Result);
1515   else if (VT.isVector())
1516     Result = getSplatBuildVector(VT, DL, Result);
1517 
1518   return Result;
1519 }
1520 
1521 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1522                                         bool isTarget) {
1523   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1524 }
1525 
1526 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1527                                              const SDLoc &DL, bool LegalTypes) {
1528   assert(VT.isInteger() && "Shift amount is not an integer type!");
1529   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1530   return getConstant(Val, DL, ShiftVT);
1531 }
1532 
1533 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1534                                            bool isTarget) {
1535   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1536 }
1537 
1538 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1539                                     bool isTarget) {
1540   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1541 }
1542 
1543 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1544                                     EVT VT, bool isTarget) {
1545   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1546 
1547   EVT EltVT = VT.getScalarType();
1548 
1549   // Do the map lookup using the actual bit pattern for the floating point
1550   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1551   // we don't have issues with SNANs.
1552   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1553   FoldingSetNodeID ID;
1554   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1555   ID.AddPointer(&V);
1556   void *IP = nullptr;
1557   SDNode *N = nullptr;
1558   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1559     if (!VT.isVector())
1560       return SDValue(N, 0);
1561 
1562   if (!N) {
1563     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1564     CSEMap.InsertNode(N, IP);
1565     InsertNode(N);
1566   }
1567 
1568   SDValue Result(N, 0);
1569   if (VT.isScalableVector())
1570     Result = getSplatVector(VT, DL, Result);
1571   else if (VT.isVector())
1572     Result = getSplatBuildVector(VT, DL, Result);
1573   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1574   return Result;
1575 }
1576 
1577 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1578                                     bool isTarget) {
1579   EVT EltVT = VT.getScalarType();
1580   if (EltVT == MVT::f32)
1581     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1582   if (EltVT == MVT::f64)
1583     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1584   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1585       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1586     bool Ignored;
1587     APFloat APF = APFloat(Val);
1588     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1589                 &Ignored);
1590     return getConstantFP(APF, DL, VT, isTarget);
1591   }
1592   llvm_unreachable("Unsupported type in getConstantFP");
1593 }
1594 
1595 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1596                                        EVT VT, int64_t Offset, bool isTargetGA,
1597                                        unsigned TargetFlags) {
1598   assert((TargetFlags == 0 || isTargetGA) &&
1599          "Cannot set target flags on target-independent globals");
1600 
1601   // Truncate (with sign-extension) the offset value to the pointer size.
1602   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1603   if (BitWidth < 64)
1604     Offset = SignExtend64(Offset, BitWidth);
1605 
1606   unsigned Opc;
1607   if (GV->isThreadLocal())
1608     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1609   else
1610     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1611 
1612   FoldingSetNodeID ID;
1613   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1614   ID.AddPointer(GV);
1615   ID.AddInteger(Offset);
1616   ID.AddInteger(TargetFlags);
1617   void *IP = nullptr;
1618   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1619     return SDValue(E, 0);
1620 
1621   auto *N = newSDNode<GlobalAddressSDNode>(
1622       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1623   CSEMap.InsertNode(N, IP);
1624     InsertNode(N);
1625   return SDValue(N, 0);
1626 }
1627 
1628 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1629   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1630   FoldingSetNodeID ID;
1631   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1632   ID.AddInteger(FI);
1633   void *IP = nullptr;
1634   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1635     return SDValue(E, 0);
1636 
1637   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1638   CSEMap.InsertNode(N, IP);
1639   InsertNode(N);
1640   return SDValue(N, 0);
1641 }
1642 
1643 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1644                                    unsigned TargetFlags) {
1645   assert((TargetFlags == 0 || isTarget) &&
1646          "Cannot set target flags on target-independent jump tables");
1647   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1648   FoldingSetNodeID ID;
1649   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1650   ID.AddInteger(JTI);
1651   ID.AddInteger(TargetFlags);
1652   void *IP = nullptr;
1653   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1654     return SDValue(E, 0);
1655 
1656   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1657   CSEMap.InsertNode(N, IP);
1658   InsertNode(N);
1659   return SDValue(N, 0);
1660 }
1661 
1662 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1663                                       MaybeAlign Alignment, int Offset,
1664                                       bool isTarget, unsigned TargetFlags) {
1665   assert((TargetFlags == 0 || isTarget) &&
1666          "Cannot set target flags on target-independent globals");
1667   if (!Alignment)
1668     Alignment = shouldOptForSize()
1669                     ? getDataLayout().getABITypeAlign(C->getType())
1670                     : getDataLayout().getPrefTypeAlign(C->getType());
1671   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1672   FoldingSetNodeID ID;
1673   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1674   ID.AddInteger(Alignment->value());
1675   ID.AddInteger(Offset);
1676   ID.AddPointer(C);
1677   ID.AddInteger(TargetFlags);
1678   void *IP = nullptr;
1679   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1680     return SDValue(E, 0);
1681 
1682   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1683                                           TargetFlags);
1684   CSEMap.InsertNode(N, IP);
1685   InsertNode(N);
1686   SDValue V = SDValue(N, 0);
1687   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1688   return V;
1689 }
1690 
1691 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1692                                       MaybeAlign Alignment, int Offset,
1693                                       bool isTarget, unsigned TargetFlags) {
1694   assert((TargetFlags == 0 || isTarget) &&
1695          "Cannot set target flags on target-independent globals");
1696   if (!Alignment)
1697     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1698   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1699   FoldingSetNodeID ID;
1700   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1701   ID.AddInteger(Alignment->value());
1702   ID.AddInteger(Offset);
1703   C->addSelectionDAGCSEId(ID);
1704   ID.AddInteger(TargetFlags);
1705   void *IP = nullptr;
1706   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1707     return SDValue(E, 0);
1708 
1709   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1710                                           TargetFlags);
1711   CSEMap.InsertNode(N, IP);
1712   InsertNode(N);
1713   return SDValue(N, 0);
1714 }
1715 
1716 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1717                                      unsigned TargetFlags) {
1718   FoldingSetNodeID ID;
1719   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1720   ID.AddInteger(Index);
1721   ID.AddInteger(Offset);
1722   ID.AddInteger(TargetFlags);
1723   void *IP = nullptr;
1724   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1725     return SDValue(E, 0);
1726 
1727   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1728   CSEMap.InsertNode(N, IP);
1729   InsertNode(N);
1730   return SDValue(N, 0);
1731 }
1732 
1733 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1734   FoldingSetNodeID ID;
1735   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1736   ID.AddPointer(MBB);
1737   void *IP = nullptr;
1738   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1739     return SDValue(E, 0);
1740 
1741   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1742   CSEMap.InsertNode(N, IP);
1743   InsertNode(N);
1744   return SDValue(N, 0);
1745 }
1746 
1747 SDValue SelectionDAG::getValueType(EVT VT) {
1748   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1749       ValueTypeNodes.size())
1750     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1751 
1752   SDNode *&N = VT.isExtended() ?
1753     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1754 
1755   if (N) return SDValue(N, 0);
1756   N = newSDNode<VTSDNode>(VT);
1757   InsertNode(N);
1758   return SDValue(N, 0);
1759 }
1760 
1761 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1762   SDNode *&N = ExternalSymbols[Sym];
1763   if (N) return SDValue(N, 0);
1764   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1765   InsertNode(N);
1766   return SDValue(N, 0);
1767 }
1768 
1769 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1770   SDNode *&N = MCSymbols[Sym];
1771   if (N)
1772     return SDValue(N, 0);
1773   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1774   InsertNode(N);
1775   return SDValue(N, 0);
1776 }
1777 
1778 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1779                                               unsigned TargetFlags) {
1780   SDNode *&N =
1781       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1782   if (N) return SDValue(N, 0);
1783   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1784   InsertNode(N);
1785   return SDValue(N, 0);
1786 }
1787 
1788 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1789   if ((unsigned)Cond >= CondCodeNodes.size())
1790     CondCodeNodes.resize(Cond+1);
1791 
1792   if (!CondCodeNodes[Cond]) {
1793     auto *N = newSDNode<CondCodeSDNode>(Cond);
1794     CondCodeNodes[Cond] = N;
1795     InsertNode(N);
1796   }
1797 
1798   return SDValue(CondCodeNodes[Cond], 0);
1799 }
1800 
1801 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1802   APInt One(ResVT.getScalarSizeInBits(), 1);
1803   return getStepVector(DL, ResVT, One);
1804 }
1805 
1806 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1807   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1808   if (ResVT.isScalableVector())
1809     return getNode(
1810         ISD::STEP_VECTOR, DL, ResVT,
1811         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1812 
1813   SmallVector<SDValue, 16> OpsStepConstants;
1814   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1815     OpsStepConstants.push_back(
1816         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1817   return getBuildVector(ResVT, DL, OpsStepConstants);
1818 }
1819 
1820 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1821 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1822 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1823   std::swap(N1, N2);
1824   ShuffleVectorSDNode::commuteMask(M);
1825 }
1826 
1827 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1828                                        SDValue N2, ArrayRef<int> Mask) {
1829   assert(VT.getVectorNumElements() == Mask.size() &&
1830          "Must have the same number of vector elements as mask elements!");
1831   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1832          "Invalid VECTOR_SHUFFLE");
1833 
1834   // Canonicalize shuffle undef, undef -> undef
1835   if (N1.isUndef() && N2.isUndef())
1836     return getUNDEF(VT);
1837 
1838   // Validate that all indices in Mask are within the range of the elements
1839   // input to the shuffle.
1840   int NElts = Mask.size();
1841   assert(llvm::all_of(Mask,
1842                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1843          "Index out of range");
1844 
1845   // Copy the mask so we can do any needed cleanup.
1846   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1847 
1848   // Canonicalize shuffle v, v -> v, undef
1849   if (N1 == N2) {
1850     N2 = getUNDEF(VT);
1851     for (int i = 0; i != NElts; ++i)
1852       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1853   }
1854 
1855   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1856   if (N1.isUndef())
1857     commuteShuffle(N1, N2, MaskVec);
1858 
1859   if (TLI->hasVectorBlend()) {
1860     // If shuffling a splat, try to blend the splat instead. We do this here so
1861     // that even when this arises during lowering we don't have to re-handle it.
1862     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1863       BitVector UndefElements;
1864       SDValue Splat = BV->getSplatValue(&UndefElements);
1865       if (!Splat)
1866         return;
1867 
1868       for (int i = 0; i < NElts; ++i) {
1869         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1870           continue;
1871 
1872         // If this input comes from undef, mark it as such.
1873         if (UndefElements[MaskVec[i] - Offset]) {
1874           MaskVec[i] = -1;
1875           continue;
1876         }
1877 
1878         // If we can blend a non-undef lane, use that instead.
1879         if (!UndefElements[i])
1880           MaskVec[i] = i + Offset;
1881       }
1882     };
1883     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1884       BlendSplat(N1BV, 0);
1885     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1886       BlendSplat(N2BV, NElts);
1887   }
1888 
1889   // Canonicalize all index into lhs, -> shuffle lhs, undef
1890   // Canonicalize all index into rhs, -> shuffle rhs, undef
1891   bool AllLHS = true, AllRHS = true;
1892   bool N2Undef = N2.isUndef();
1893   for (int i = 0; i != NElts; ++i) {
1894     if (MaskVec[i] >= NElts) {
1895       if (N2Undef)
1896         MaskVec[i] = -1;
1897       else
1898         AllLHS = false;
1899     } else if (MaskVec[i] >= 0) {
1900       AllRHS = false;
1901     }
1902   }
1903   if (AllLHS && AllRHS)
1904     return getUNDEF(VT);
1905   if (AllLHS && !N2Undef)
1906     N2 = getUNDEF(VT);
1907   if (AllRHS) {
1908     N1 = getUNDEF(VT);
1909     commuteShuffle(N1, N2, MaskVec);
1910   }
1911   // Reset our undef status after accounting for the mask.
1912   N2Undef = N2.isUndef();
1913   // Re-check whether both sides ended up undef.
1914   if (N1.isUndef() && N2Undef)
1915     return getUNDEF(VT);
1916 
1917   // If Identity shuffle return that node.
1918   bool Identity = true, AllSame = true;
1919   for (int i = 0; i != NElts; ++i) {
1920     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1921     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1922   }
1923   if (Identity && NElts)
1924     return N1;
1925 
1926   // Shuffling a constant splat doesn't change the result.
1927   if (N2Undef) {
1928     SDValue V = N1;
1929 
1930     // Look through any bitcasts. We check that these don't change the number
1931     // (and size) of elements and just changes their types.
1932     while (V.getOpcode() == ISD::BITCAST)
1933       V = V->getOperand(0);
1934 
1935     // A splat should always show up as a build vector node.
1936     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1937       BitVector UndefElements;
1938       SDValue Splat = BV->getSplatValue(&UndefElements);
1939       // If this is a splat of an undef, shuffling it is also undef.
1940       if (Splat && Splat.isUndef())
1941         return getUNDEF(VT);
1942 
1943       bool SameNumElts =
1944           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1945 
1946       // We only have a splat which can skip shuffles if there is a splatted
1947       // value and no undef lanes rearranged by the shuffle.
1948       if (Splat && UndefElements.none()) {
1949         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1950         // number of elements match or the value splatted is a zero constant.
1951         if (SameNumElts)
1952           return N1;
1953         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1954           if (C->isZero())
1955             return N1;
1956       }
1957 
1958       // If the shuffle itself creates a splat, build the vector directly.
1959       if (AllSame && SameNumElts) {
1960         EVT BuildVT = BV->getValueType(0);
1961         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1962         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1963 
1964         // We may have jumped through bitcasts, so the type of the
1965         // BUILD_VECTOR may not match the type of the shuffle.
1966         if (BuildVT != VT)
1967           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1968         return NewBV;
1969       }
1970     }
1971   }
1972 
1973   FoldingSetNodeID ID;
1974   SDValue Ops[2] = { N1, N2 };
1975   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1976   for (int i = 0; i != NElts; ++i)
1977     ID.AddInteger(MaskVec[i]);
1978 
1979   void* IP = nullptr;
1980   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1981     return SDValue(E, 0);
1982 
1983   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1984   // SDNode doesn't have access to it.  This memory will be "leaked" when
1985   // the node is deallocated, but recovered when the NodeAllocator is released.
1986   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1987   llvm::copy(MaskVec, MaskAlloc);
1988 
1989   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1990                                            dl.getDebugLoc(), MaskAlloc);
1991   createOperands(N, Ops);
1992 
1993   CSEMap.InsertNode(N, IP);
1994   InsertNode(N);
1995   SDValue V = SDValue(N, 0);
1996   NewSDValueDbgMsg(V, "Creating new node: ", this);
1997   return V;
1998 }
1999 
2000 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2001   EVT VT = SV.getValueType(0);
2002   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2003   ShuffleVectorSDNode::commuteMask(MaskVec);
2004 
2005   SDValue Op0 = SV.getOperand(0);
2006   SDValue Op1 = SV.getOperand(1);
2007   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2008 }
2009 
2010 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2011   FoldingSetNodeID ID;
2012   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2013   ID.AddInteger(RegNo);
2014   void *IP = nullptr;
2015   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2016     return SDValue(E, 0);
2017 
2018   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2019   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2020   CSEMap.InsertNode(N, IP);
2021   InsertNode(N);
2022   return SDValue(N, 0);
2023 }
2024 
2025 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2026   FoldingSetNodeID ID;
2027   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2028   ID.AddPointer(RegMask);
2029   void *IP = nullptr;
2030   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2031     return SDValue(E, 0);
2032 
2033   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2034   CSEMap.InsertNode(N, IP);
2035   InsertNode(N);
2036   return SDValue(N, 0);
2037 }
2038 
2039 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2040                                  MCSymbol *Label) {
2041   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2042 }
2043 
2044 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2045                                    SDValue Root, MCSymbol *Label) {
2046   FoldingSetNodeID ID;
2047   SDValue Ops[] = { Root };
2048   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2049   ID.AddPointer(Label);
2050   void *IP = nullptr;
2051   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2052     return SDValue(E, 0);
2053 
2054   auto *N =
2055       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2056   createOperands(N, Ops);
2057 
2058   CSEMap.InsertNode(N, IP);
2059   InsertNode(N);
2060   return SDValue(N, 0);
2061 }
2062 
2063 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2064                                       int64_t Offset, bool isTarget,
2065                                       unsigned TargetFlags) {
2066   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2067 
2068   FoldingSetNodeID ID;
2069   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2070   ID.AddPointer(BA);
2071   ID.AddInteger(Offset);
2072   ID.AddInteger(TargetFlags);
2073   void *IP = nullptr;
2074   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2075     return SDValue(E, 0);
2076 
2077   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2078   CSEMap.InsertNode(N, IP);
2079   InsertNode(N);
2080   return SDValue(N, 0);
2081 }
2082 
2083 SDValue SelectionDAG::getSrcValue(const Value *V) {
2084   FoldingSetNodeID ID;
2085   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2086   ID.AddPointer(V);
2087 
2088   void *IP = nullptr;
2089   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2090     return SDValue(E, 0);
2091 
2092   auto *N = newSDNode<SrcValueSDNode>(V);
2093   CSEMap.InsertNode(N, IP);
2094   InsertNode(N);
2095   return SDValue(N, 0);
2096 }
2097 
2098 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2099   FoldingSetNodeID ID;
2100   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2101   ID.AddPointer(MD);
2102 
2103   void *IP = nullptr;
2104   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2105     return SDValue(E, 0);
2106 
2107   auto *N = newSDNode<MDNodeSDNode>(MD);
2108   CSEMap.InsertNode(N, IP);
2109   InsertNode(N);
2110   return SDValue(N, 0);
2111 }
2112 
2113 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2114   if (VT == V.getValueType())
2115     return V;
2116 
2117   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2118 }
2119 
2120 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2121                                        unsigned SrcAS, unsigned DestAS) {
2122   SDValue Ops[] = {Ptr};
2123   FoldingSetNodeID ID;
2124   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2125   ID.AddInteger(SrcAS);
2126   ID.AddInteger(DestAS);
2127 
2128   void *IP = nullptr;
2129   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2130     return SDValue(E, 0);
2131 
2132   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2133                                            VT, SrcAS, DestAS);
2134   createOperands(N, Ops);
2135 
2136   CSEMap.InsertNode(N, IP);
2137   InsertNode(N);
2138   return SDValue(N, 0);
2139 }
2140 
2141 SDValue SelectionDAG::getFreeze(SDValue V) {
2142   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2143 }
2144 
2145 /// getShiftAmountOperand - Return the specified value casted to
2146 /// the target's desired shift amount type.
2147 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2148   EVT OpTy = Op.getValueType();
2149   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2150   if (OpTy == ShTy || OpTy.isVector()) return Op;
2151 
2152   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2153 }
2154 
2155 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2156   SDLoc dl(Node);
2157   const TargetLowering &TLI = getTargetLoweringInfo();
2158   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2159   EVT VT = Node->getValueType(0);
2160   SDValue Tmp1 = Node->getOperand(0);
2161   SDValue Tmp2 = Node->getOperand(1);
2162   const MaybeAlign MA(Node->getConstantOperandVal(3));
2163 
2164   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2165                                Tmp2, MachinePointerInfo(V));
2166   SDValue VAList = VAListLoad;
2167 
2168   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2169     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2170                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2171 
2172     VAList =
2173         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2174                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2175   }
2176 
2177   // Increment the pointer, VAList, to the next vaarg
2178   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2179                  getConstant(getDataLayout().getTypeAllocSize(
2180                                                VT.getTypeForEVT(*getContext())),
2181                              dl, VAList.getValueType()));
2182   // Store the incremented VAList to the legalized pointer
2183   Tmp1 =
2184       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2185   // Load the actual argument out of the pointer VAList
2186   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2187 }
2188 
2189 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2190   SDLoc dl(Node);
2191   const TargetLowering &TLI = getTargetLoweringInfo();
2192   // This defaults to loading a pointer from the input and storing it to the
2193   // output, returning the chain.
2194   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2195   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2196   SDValue Tmp1 =
2197       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2198               Node->getOperand(2), MachinePointerInfo(VS));
2199   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2200                   MachinePointerInfo(VD));
2201 }
2202 
2203 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2204   const DataLayout &DL = getDataLayout();
2205   Type *Ty = VT.getTypeForEVT(*getContext());
2206   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2207 
2208   if (TLI->isTypeLegal(VT) || !VT.isVector())
2209     return RedAlign;
2210 
2211   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2212   const Align StackAlign = TFI->getStackAlign();
2213 
2214   // See if we can choose a smaller ABI alignment in cases where it's an
2215   // illegal vector type that will get broken down.
2216   if (RedAlign > StackAlign) {
2217     EVT IntermediateVT;
2218     MVT RegisterVT;
2219     unsigned NumIntermediates;
2220     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2221                                 NumIntermediates, RegisterVT);
2222     Ty = IntermediateVT.getTypeForEVT(*getContext());
2223     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2224     if (RedAlign2 < RedAlign)
2225       RedAlign = RedAlign2;
2226   }
2227 
2228   return RedAlign;
2229 }
2230 
2231 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2232   MachineFrameInfo &MFI = MF->getFrameInfo();
2233   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2234   int StackID = 0;
2235   if (Bytes.isScalable())
2236     StackID = TFI->getStackIDForScalableVectors();
2237   // The stack id gives an indication of whether the object is scalable or
2238   // not, so it's safe to pass in the minimum size here.
2239   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2240                                        false, nullptr, StackID);
2241   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2242 }
2243 
2244 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2245   Type *Ty = VT.getTypeForEVT(*getContext());
2246   Align StackAlign =
2247       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2248   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2249 }
2250 
2251 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2252   TypeSize VT1Size = VT1.getStoreSize();
2253   TypeSize VT2Size = VT2.getStoreSize();
2254   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2255          "Don't know how to choose the maximum size when creating a stack "
2256          "temporary");
2257   TypeSize Bytes =
2258       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2259 
2260   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2261   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2262   const DataLayout &DL = getDataLayout();
2263   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2264   return CreateStackTemporary(Bytes, Align);
2265 }
2266 
2267 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2268                                 ISD::CondCode Cond, const SDLoc &dl) {
2269   EVT OpVT = N1.getValueType();
2270 
2271   // These setcc operations always fold.
2272   switch (Cond) {
2273   default: break;
2274   case ISD::SETFALSE:
2275   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2276   case ISD::SETTRUE:
2277   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2278 
2279   case ISD::SETOEQ:
2280   case ISD::SETOGT:
2281   case ISD::SETOGE:
2282   case ISD::SETOLT:
2283   case ISD::SETOLE:
2284   case ISD::SETONE:
2285   case ISD::SETO:
2286   case ISD::SETUO:
2287   case ISD::SETUEQ:
2288   case ISD::SETUNE:
2289     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2290     break;
2291   }
2292 
2293   if (OpVT.isInteger()) {
2294     // For EQ and NE, we can always pick a value for the undef to make the
2295     // predicate pass or fail, so we can return undef.
2296     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2297     // icmp eq/ne X, undef -> undef.
2298     if ((N1.isUndef() || N2.isUndef()) &&
2299         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2300       return getUNDEF(VT);
2301 
2302     // If both operands are undef, we can return undef for int comparison.
2303     // icmp undef, undef -> undef.
2304     if (N1.isUndef() && N2.isUndef())
2305       return getUNDEF(VT);
2306 
2307     // icmp X, X -> true/false
2308     // icmp X, undef -> true/false because undef could be X.
2309     if (N1 == N2)
2310       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2311   }
2312 
2313   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2314     const APInt &C2 = N2C->getAPIntValue();
2315     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2316       const APInt &C1 = N1C->getAPIntValue();
2317 
2318       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2319                              dl, VT, OpVT);
2320     }
2321   }
2322 
2323   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2324   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2325 
2326   if (N1CFP && N2CFP) {
2327     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2328     switch (Cond) {
2329     default: break;
2330     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2331                         return getUNDEF(VT);
2332                       LLVM_FALLTHROUGH;
2333     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2334                                              OpVT);
2335     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2336                         return getUNDEF(VT);
2337                       LLVM_FALLTHROUGH;
2338     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2339                                              R==APFloat::cmpLessThan, dl, VT,
2340                                              OpVT);
2341     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2342                         return getUNDEF(VT);
2343                       LLVM_FALLTHROUGH;
2344     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2345                                              OpVT);
2346     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2347                         return getUNDEF(VT);
2348                       LLVM_FALLTHROUGH;
2349     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2350                                              VT, OpVT);
2351     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2352                         return getUNDEF(VT);
2353                       LLVM_FALLTHROUGH;
2354     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2355                                              R==APFloat::cmpEqual, dl, VT,
2356                                              OpVT);
2357     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2358                         return getUNDEF(VT);
2359                       LLVM_FALLTHROUGH;
2360     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2361                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2362     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2363                                              OpVT);
2364     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2365                                              OpVT);
2366     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2367                                              R==APFloat::cmpEqual, dl, VT,
2368                                              OpVT);
2369     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2370                                              OpVT);
2371     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2372                                              R==APFloat::cmpLessThan, dl, VT,
2373                                              OpVT);
2374     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2375                                              R==APFloat::cmpUnordered, dl, VT,
2376                                              OpVT);
2377     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2378                                              VT, OpVT);
2379     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2380                                              OpVT);
2381     }
2382   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2383     // Ensure that the constant occurs on the RHS.
2384     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2385     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2386       return SDValue();
2387     return getSetCC(dl, VT, N2, N1, SwappedCond);
2388   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2389              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2390     // If an operand is known to be a nan (or undef that could be a nan), we can
2391     // fold it.
2392     // Choosing NaN for the undef will always make unordered comparison succeed
2393     // and ordered comparison fails.
2394     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2395     switch (ISD::getUnorderedFlavor(Cond)) {
2396     default:
2397       llvm_unreachable("Unknown flavor!");
2398     case 0: // Known false.
2399       return getBoolConstant(false, dl, VT, OpVT);
2400     case 1: // Known true.
2401       return getBoolConstant(true, dl, VT, OpVT);
2402     case 2: // Undefined.
2403       return getUNDEF(VT);
2404     }
2405   }
2406 
2407   // Could not fold it.
2408   return SDValue();
2409 }
2410 
2411 /// See if the specified operand can be simplified with the knowledge that only
2412 /// the bits specified by DemandedBits are used.
2413 /// TODO: really we should be making this into the DAG equivalent of
2414 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2415 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2416   EVT VT = V.getValueType();
2417 
2418   if (VT.isScalableVector())
2419     return SDValue();
2420 
2421   APInt DemandedElts = VT.isVector()
2422                            ? APInt::getAllOnes(VT.getVectorNumElements())
2423                            : APInt(1, 1);
2424   return GetDemandedBits(V, DemandedBits, DemandedElts);
2425 }
2426 
2427 /// See if the specified operand can be simplified with the knowledge that only
2428 /// the bits specified by DemandedBits are used in the elements specified by
2429 /// DemandedElts.
2430 /// TODO: really we should be making this into the DAG equivalent of
2431 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2432 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2433                                       const APInt &DemandedElts) {
2434   switch (V.getOpcode()) {
2435   default:
2436     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2437                                                 *this, 0);
2438   case ISD::Constant: {
2439     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2440     APInt NewVal = CVal & DemandedBits;
2441     if (NewVal != CVal)
2442       return getConstant(NewVal, SDLoc(V), V.getValueType());
2443     break;
2444   }
2445   case ISD::SRL:
2446     // Only look at single-use SRLs.
2447     if (!V.getNode()->hasOneUse())
2448       break;
2449     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2450       // See if we can recursively simplify the LHS.
2451       unsigned Amt = RHSC->getZExtValue();
2452 
2453       // Watch out for shift count overflow though.
2454       if (Amt >= DemandedBits.getBitWidth())
2455         break;
2456       APInt SrcDemandedBits = DemandedBits << Amt;
2457       if (SDValue SimplifyLHS =
2458               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2459         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2460                        V.getOperand(1));
2461     }
2462     break;
2463   }
2464   return SDValue();
2465 }
2466 
2467 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2468 /// use this predicate to simplify operations downstream.
2469 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2470   unsigned BitWidth = Op.getScalarValueSizeInBits();
2471   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2472 }
2473 
2474 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2475 /// this predicate to simplify operations downstream.  Mask is known to be zero
2476 /// for bits that V cannot have.
2477 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2478                                      unsigned Depth) const {
2479   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2480 }
2481 
2482 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2483 /// DemandedElts.  We use this predicate to simplify operations downstream.
2484 /// Mask is known to be zero for bits that V cannot have.
2485 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2486                                      const APInt &DemandedElts,
2487                                      unsigned Depth) const {
2488   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2489 }
2490 
2491 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2492 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2493                                         unsigned Depth) const {
2494   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2495 }
2496 
2497 /// isSplatValue - Return true if the vector V has the same value
2498 /// across all DemandedElts. For scalable vectors it does not make
2499 /// sense to specify which elements are demanded or undefined, therefore
2500 /// they are simply ignored.
2501 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2502                                 APInt &UndefElts, unsigned Depth) {
2503   EVT VT = V.getValueType();
2504   assert(VT.isVector() && "Vector type expected");
2505 
2506   if (!VT.isScalableVector() && !DemandedElts)
2507     return false; // No demanded elts, better to assume we don't know anything.
2508 
2509   if (Depth >= MaxRecursionDepth)
2510     return false; // Limit search depth.
2511 
2512   // Deal with some common cases here that work for both fixed and scalable
2513   // vector types.
2514   switch (V.getOpcode()) {
2515   case ISD::SPLAT_VECTOR:
2516     UndefElts = V.getOperand(0).isUndef()
2517                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2518                     : APInt(DemandedElts.getBitWidth(), 0);
2519     return true;
2520   case ISD::ADD:
2521   case ISD::SUB:
2522   case ISD::AND:
2523   case ISD::XOR:
2524   case ISD::OR: {
2525     APInt UndefLHS, UndefRHS;
2526     SDValue LHS = V.getOperand(0);
2527     SDValue RHS = V.getOperand(1);
2528     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2529         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2530       UndefElts = UndefLHS | UndefRHS;
2531       return true;
2532     }
2533     return false;
2534   }
2535   case ISD::ABS:
2536   case ISD::TRUNCATE:
2537   case ISD::SIGN_EXTEND:
2538   case ISD::ZERO_EXTEND:
2539     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2540   }
2541 
2542   // We don't support other cases than those above for scalable vectors at
2543   // the moment.
2544   if (VT.isScalableVector())
2545     return false;
2546 
2547   unsigned NumElts = VT.getVectorNumElements();
2548   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2549   UndefElts = APInt::getZero(NumElts);
2550 
2551   switch (V.getOpcode()) {
2552   case ISD::BUILD_VECTOR: {
2553     SDValue Scl;
2554     for (unsigned i = 0; i != NumElts; ++i) {
2555       SDValue Op = V.getOperand(i);
2556       if (Op.isUndef()) {
2557         UndefElts.setBit(i);
2558         continue;
2559       }
2560       if (!DemandedElts[i])
2561         continue;
2562       if (Scl && Scl != Op)
2563         return false;
2564       Scl = Op;
2565     }
2566     return true;
2567   }
2568   case ISD::VECTOR_SHUFFLE: {
2569     // Check if this is a shuffle node doing a splat.
2570     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2571     int SplatIndex = -1;
2572     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2573     for (int i = 0; i != (int)NumElts; ++i) {
2574       int M = Mask[i];
2575       if (M < 0) {
2576         UndefElts.setBit(i);
2577         continue;
2578       }
2579       if (!DemandedElts[i])
2580         continue;
2581       if (0 <= SplatIndex && SplatIndex != M)
2582         return false;
2583       SplatIndex = M;
2584     }
2585     return true;
2586   }
2587   case ISD::EXTRACT_SUBVECTOR: {
2588     // Offset the demanded elts by the subvector index.
2589     SDValue Src = V.getOperand(0);
2590     // We don't support scalable vectors at the moment.
2591     if (Src.getValueType().isScalableVector())
2592       return false;
2593     uint64_t Idx = V.getConstantOperandVal(1);
2594     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2595     APInt UndefSrcElts;
2596     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2597     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2598       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2599       return true;
2600     }
2601     break;
2602   }
2603   }
2604 
2605   return false;
2606 }
2607 
2608 /// Helper wrapper to main isSplatValue function.
2609 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2610   EVT VT = V.getValueType();
2611   assert(VT.isVector() && "Vector type expected");
2612 
2613   APInt UndefElts;
2614   APInt DemandedElts;
2615 
2616   // For now we don't support this with scalable vectors.
2617   if (!VT.isScalableVector())
2618     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2619   return isSplatValue(V, DemandedElts, UndefElts) &&
2620          (AllowUndefs || !UndefElts);
2621 }
2622 
2623 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2624   V = peekThroughExtractSubvectors(V);
2625 
2626   EVT VT = V.getValueType();
2627   unsigned Opcode = V.getOpcode();
2628   switch (Opcode) {
2629   default: {
2630     APInt UndefElts;
2631     APInt DemandedElts;
2632 
2633     if (!VT.isScalableVector())
2634       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2635 
2636     if (isSplatValue(V, DemandedElts, UndefElts)) {
2637       if (VT.isScalableVector()) {
2638         // DemandedElts and UndefElts are ignored for scalable vectors, since
2639         // the only supported cases are SPLAT_VECTOR nodes.
2640         SplatIdx = 0;
2641       } else {
2642         // Handle case where all demanded elements are UNDEF.
2643         if (DemandedElts.isSubsetOf(UndefElts)) {
2644           SplatIdx = 0;
2645           return getUNDEF(VT);
2646         }
2647         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2648       }
2649       return V;
2650     }
2651     break;
2652   }
2653   case ISD::SPLAT_VECTOR:
2654     SplatIdx = 0;
2655     return V;
2656   case ISD::VECTOR_SHUFFLE: {
2657     if (VT.isScalableVector())
2658       return SDValue();
2659 
2660     // Check if this is a shuffle node doing a splat.
2661     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2662     // getTargetVShiftNode currently struggles without the splat source.
2663     auto *SVN = cast<ShuffleVectorSDNode>(V);
2664     if (!SVN->isSplat())
2665       break;
2666     int Idx = SVN->getSplatIndex();
2667     int NumElts = V.getValueType().getVectorNumElements();
2668     SplatIdx = Idx % NumElts;
2669     return V.getOperand(Idx / NumElts);
2670   }
2671   }
2672 
2673   return SDValue();
2674 }
2675 
2676 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2677   int SplatIdx;
2678   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2679     EVT SVT = SrcVector.getValueType().getScalarType();
2680     EVT LegalSVT = SVT;
2681     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2682       if (!SVT.isInteger())
2683         return SDValue();
2684       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2685       if (LegalSVT.bitsLT(SVT))
2686         return SDValue();
2687     }
2688     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2689                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2690   }
2691   return SDValue();
2692 }
2693 
2694 const APInt *
2695 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2696                                           const APInt &DemandedElts) const {
2697   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2698           V.getOpcode() == ISD::SRA) &&
2699          "Unknown shift node");
2700   unsigned BitWidth = V.getScalarValueSizeInBits();
2701   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2702     // Shifting more than the bitwidth is not valid.
2703     const APInt &ShAmt = SA->getAPIntValue();
2704     if (ShAmt.ult(BitWidth))
2705       return &ShAmt;
2706   }
2707   return nullptr;
2708 }
2709 
2710 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2711     SDValue V, const APInt &DemandedElts) const {
2712   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2713           V.getOpcode() == ISD::SRA) &&
2714          "Unknown shift node");
2715   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2716     return ValidAmt;
2717   unsigned BitWidth = V.getScalarValueSizeInBits();
2718   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2719   if (!BV)
2720     return nullptr;
2721   const APInt *MinShAmt = nullptr;
2722   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2723     if (!DemandedElts[i])
2724       continue;
2725     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2726     if (!SA)
2727       return nullptr;
2728     // Shifting more than the bitwidth is not valid.
2729     const APInt &ShAmt = SA->getAPIntValue();
2730     if (ShAmt.uge(BitWidth))
2731       return nullptr;
2732     if (MinShAmt && MinShAmt->ule(ShAmt))
2733       continue;
2734     MinShAmt = &ShAmt;
2735   }
2736   return MinShAmt;
2737 }
2738 
2739 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2740     SDValue V, const APInt &DemandedElts) const {
2741   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2742           V.getOpcode() == ISD::SRA) &&
2743          "Unknown shift node");
2744   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2745     return ValidAmt;
2746   unsigned BitWidth = V.getScalarValueSizeInBits();
2747   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2748   if (!BV)
2749     return nullptr;
2750   const APInt *MaxShAmt = nullptr;
2751   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2752     if (!DemandedElts[i])
2753       continue;
2754     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2755     if (!SA)
2756       return nullptr;
2757     // Shifting more than the bitwidth is not valid.
2758     const APInt &ShAmt = SA->getAPIntValue();
2759     if (ShAmt.uge(BitWidth))
2760       return nullptr;
2761     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2762       continue;
2763     MaxShAmt = &ShAmt;
2764   }
2765   return MaxShAmt;
2766 }
2767 
2768 /// Determine which bits of Op are known to be either zero or one and return
2769 /// them in Known. For vectors, the known bits are those that are shared by
2770 /// every vector element.
2771 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2772   EVT VT = Op.getValueType();
2773 
2774   // TOOD: Until we have a plan for how to represent demanded elements for
2775   // scalable vectors, we can just bail out for now.
2776   if (Op.getValueType().isScalableVector()) {
2777     unsigned BitWidth = Op.getScalarValueSizeInBits();
2778     return KnownBits(BitWidth);
2779   }
2780 
2781   APInt DemandedElts = VT.isVector()
2782                            ? APInt::getAllOnes(VT.getVectorNumElements())
2783                            : APInt(1, 1);
2784   return computeKnownBits(Op, DemandedElts, Depth);
2785 }
2786 
2787 /// Determine which bits of Op are known to be either zero or one and return
2788 /// them in Known. The DemandedElts argument allows us to only collect the known
2789 /// bits that are shared by the requested vector elements.
2790 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2791                                          unsigned Depth) const {
2792   unsigned BitWidth = Op.getScalarValueSizeInBits();
2793 
2794   KnownBits Known(BitWidth);   // Don't know anything.
2795 
2796   // TOOD: Until we have a plan for how to represent demanded elements for
2797   // scalable vectors, we can just bail out for now.
2798   if (Op.getValueType().isScalableVector())
2799     return Known;
2800 
2801   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2802     // We know all of the bits for a constant!
2803     return KnownBits::makeConstant(C->getAPIntValue());
2804   }
2805   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2806     // We know all of the bits for a constant fp!
2807     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2808   }
2809 
2810   if (Depth >= MaxRecursionDepth)
2811     return Known;  // Limit search depth.
2812 
2813   KnownBits Known2;
2814   unsigned NumElts = DemandedElts.getBitWidth();
2815   assert((!Op.getValueType().isVector() ||
2816           NumElts == Op.getValueType().getVectorNumElements()) &&
2817          "Unexpected vector size");
2818 
2819   if (!DemandedElts)
2820     return Known;  // No demanded elts, better to assume we don't know anything.
2821 
2822   unsigned Opcode = Op.getOpcode();
2823   switch (Opcode) {
2824   case ISD::BUILD_VECTOR:
2825     // Collect the known bits that are shared by every demanded vector element.
2826     Known.Zero.setAllBits(); Known.One.setAllBits();
2827     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2828       if (!DemandedElts[i])
2829         continue;
2830 
2831       SDValue SrcOp = Op.getOperand(i);
2832       Known2 = computeKnownBits(SrcOp, Depth + 1);
2833 
2834       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2835       if (SrcOp.getValueSizeInBits() != BitWidth) {
2836         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2837                "Expected BUILD_VECTOR implicit truncation");
2838         Known2 = Known2.trunc(BitWidth);
2839       }
2840 
2841       // Known bits are the values that are shared by every demanded element.
2842       Known = KnownBits::commonBits(Known, Known2);
2843 
2844       // If we don't know any bits, early out.
2845       if (Known.isUnknown())
2846         break;
2847     }
2848     break;
2849   case ISD::VECTOR_SHUFFLE: {
2850     // Collect the known bits that are shared by every vector element referenced
2851     // by the shuffle.
2852     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2853     Known.Zero.setAllBits(); Known.One.setAllBits();
2854     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2855     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2856     for (unsigned i = 0; i != NumElts; ++i) {
2857       if (!DemandedElts[i])
2858         continue;
2859 
2860       int M = SVN->getMaskElt(i);
2861       if (M < 0) {
2862         // For UNDEF elements, we don't know anything about the common state of
2863         // the shuffle result.
2864         Known.resetAll();
2865         DemandedLHS.clearAllBits();
2866         DemandedRHS.clearAllBits();
2867         break;
2868       }
2869 
2870       if ((unsigned)M < NumElts)
2871         DemandedLHS.setBit((unsigned)M % NumElts);
2872       else
2873         DemandedRHS.setBit((unsigned)M % NumElts);
2874     }
2875     // Known bits are the values that are shared by every demanded element.
2876     if (!!DemandedLHS) {
2877       SDValue LHS = Op.getOperand(0);
2878       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2879       Known = KnownBits::commonBits(Known, Known2);
2880     }
2881     // If we don't know any bits, early out.
2882     if (Known.isUnknown())
2883       break;
2884     if (!!DemandedRHS) {
2885       SDValue RHS = Op.getOperand(1);
2886       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2887       Known = KnownBits::commonBits(Known, Known2);
2888     }
2889     break;
2890   }
2891   case ISD::CONCAT_VECTORS: {
2892     // Split DemandedElts and test each of the demanded subvectors.
2893     Known.Zero.setAllBits(); Known.One.setAllBits();
2894     EVT SubVectorVT = Op.getOperand(0).getValueType();
2895     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2896     unsigned NumSubVectors = Op.getNumOperands();
2897     for (unsigned i = 0; i != NumSubVectors; ++i) {
2898       APInt DemandedSub =
2899           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2900       if (!!DemandedSub) {
2901         SDValue Sub = Op.getOperand(i);
2902         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2903         Known = KnownBits::commonBits(Known, Known2);
2904       }
2905       // If we don't know any bits, early out.
2906       if (Known.isUnknown())
2907         break;
2908     }
2909     break;
2910   }
2911   case ISD::INSERT_SUBVECTOR: {
2912     // Demand any elements from the subvector and the remainder from the src its
2913     // inserted into.
2914     SDValue Src = Op.getOperand(0);
2915     SDValue Sub = Op.getOperand(1);
2916     uint64_t Idx = Op.getConstantOperandVal(2);
2917     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2918     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2919     APInt DemandedSrcElts = DemandedElts;
2920     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2921 
2922     Known.One.setAllBits();
2923     Known.Zero.setAllBits();
2924     if (!!DemandedSubElts) {
2925       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2926       if (Known.isUnknown())
2927         break; // early-out.
2928     }
2929     if (!!DemandedSrcElts) {
2930       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2931       Known = KnownBits::commonBits(Known, Known2);
2932     }
2933     break;
2934   }
2935   case ISD::EXTRACT_SUBVECTOR: {
2936     // Offset the demanded elts by the subvector index.
2937     SDValue Src = Op.getOperand(0);
2938     // Bail until we can represent demanded elements for scalable vectors.
2939     if (Src.getValueType().isScalableVector())
2940       break;
2941     uint64_t Idx = Op.getConstantOperandVal(1);
2942     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2943     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2944     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2945     break;
2946   }
2947   case ISD::SCALAR_TO_VECTOR: {
2948     // We know about scalar_to_vector as much as we know about it source,
2949     // which becomes the first element of otherwise unknown vector.
2950     if (DemandedElts != 1)
2951       break;
2952 
2953     SDValue N0 = Op.getOperand(0);
2954     Known = computeKnownBits(N0, Depth + 1);
2955     if (N0.getValueSizeInBits() != BitWidth)
2956       Known = Known.trunc(BitWidth);
2957 
2958     break;
2959   }
2960   case ISD::BITCAST: {
2961     SDValue N0 = Op.getOperand(0);
2962     EVT SubVT = N0.getValueType();
2963     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2964 
2965     // Ignore bitcasts from unsupported types.
2966     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2967       break;
2968 
2969     // Fast handling of 'identity' bitcasts.
2970     if (BitWidth == SubBitWidth) {
2971       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2972       break;
2973     }
2974 
2975     bool IsLE = getDataLayout().isLittleEndian();
2976 
2977     // Bitcast 'small element' vector to 'large element' scalar/vector.
2978     if ((BitWidth % SubBitWidth) == 0) {
2979       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2980 
2981       // Collect known bits for the (larger) output by collecting the known
2982       // bits from each set of sub elements and shift these into place.
2983       // We need to separately call computeKnownBits for each set of
2984       // sub elements as the knownbits for each is likely to be different.
2985       unsigned SubScale = BitWidth / SubBitWidth;
2986       APInt SubDemandedElts(NumElts * SubScale, 0);
2987       for (unsigned i = 0; i != NumElts; ++i)
2988         if (DemandedElts[i])
2989           SubDemandedElts.setBit(i * SubScale);
2990 
2991       for (unsigned i = 0; i != SubScale; ++i) {
2992         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2993                          Depth + 1);
2994         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2995         Known.insertBits(Known2, SubBitWidth * Shifts);
2996       }
2997     }
2998 
2999     // Bitcast 'large element' scalar/vector to 'small element' vector.
3000     if ((SubBitWidth % BitWidth) == 0) {
3001       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3002 
3003       // Collect known bits for the (smaller) output by collecting the known
3004       // bits from the overlapping larger input elements and extracting the
3005       // sub sections we actually care about.
3006       unsigned SubScale = SubBitWidth / BitWidth;
3007       APInt SubDemandedElts =
3008           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3009       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3010 
3011       Known.Zero.setAllBits(); Known.One.setAllBits();
3012       for (unsigned i = 0; i != NumElts; ++i)
3013         if (DemandedElts[i]) {
3014           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3015           unsigned Offset = (Shifts % SubScale) * BitWidth;
3016           Known = KnownBits::commonBits(Known,
3017                                         Known2.extractBits(BitWidth, Offset));
3018           // If we don't know any bits, early out.
3019           if (Known.isUnknown())
3020             break;
3021         }
3022     }
3023     break;
3024   }
3025   case ISD::AND:
3026     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3027     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3028 
3029     Known &= Known2;
3030     break;
3031   case ISD::OR:
3032     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3033     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3034 
3035     Known |= Known2;
3036     break;
3037   case ISD::XOR:
3038     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3039     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3040 
3041     Known ^= Known2;
3042     break;
3043   case ISD::MUL: {
3044     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3045     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3046     Known = KnownBits::mul(Known, Known2);
3047     break;
3048   }
3049   case ISD::MULHU: {
3050     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3051     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3052     Known = KnownBits::mulhu(Known, Known2);
3053     break;
3054   }
3055   case ISD::MULHS: {
3056     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3057     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3058     Known = KnownBits::mulhs(Known, Known2);
3059     break;
3060   }
3061   case ISD::UMUL_LOHI: {
3062     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3063     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3064     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3065     if (Op.getResNo() == 0)
3066       Known = KnownBits::mul(Known, Known2);
3067     else
3068       Known = KnownBits::mulhu(Known, Known2);
3069     break;
3070   }
3071   case ISD::SMUL_LOHI: {
3072     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3073     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3074     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3075     if (Op.getResNo() == 0)
3076       Known = KnownBits::mul(Known, Known2);
3077     else
3078       Known = KnownBits::mulhs(Known, Known2);
3079     break;
3080   }
3081   case ISD::UDIV: {
3082     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3083     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3084     Known = KnownBits::udiv(Known, Known2);
3085     break;
3086   }
3087   case ISD::SELECT:
3088   case ISD::VSELECT:
3089     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3090     // If we don't know any bits, early out.
3091     if (Known.isUnknown())
3092       break;
3093     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3094 
3095     // Only known if known in both the LHS and RHS.
3096     Known = KnownBits::commonBits(Known, Known2);
3097     break;
3098   case ISD::SELECT_CC:
3099     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3100     // If we don't know any bits, early out.
3101     if (Known.isUnknown())
3102       break;
3103     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3104 
3105     // Only known if known in both the LHS and RHS.
3106     Known = KnownBits::commonBits(Known, Known2);
3107     break;
3108   case ISD::SMULO:
3109   case ISD::UMULO:
3110     if (Op.getResNo() != 1)
3111       break;
3112     // The boolean result conforms to getBooleanContents.
3113     // If we know the result of a setcc has the top bits zero, use this info.
3114     // We know that we have an integer-based boolean since these operations
3115     // are only available for integer.
3116     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3117             TargetLowering::ZeroOrOneBooleanContent &&
3118         BitWidth > 1)
3119       Known.Zero.setBitsFrom(1);
3120     break;
3121   case ISD::SETCC:
3122   case ISD::STRICT_FSETCC:
3123   case ISD::STRICT_FSETCCS: {
3124     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3125     // If we know the result of a setcc has the top bits zero, use this info.
3126     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3127             TargetLowering::ZeroOrOneBooleanContent &&
3128         BitWidth > 1)
3129       Known.Zero.setBitsFrom(1);
3130     break;
3131   }
3132   case ISD::SHL:
3133     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3134     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3135     Known = KnownBits::shl(Known, Known2);
3136 
3137     // Minimum shift low bits are known zero.
3138     if (const APInt *ShMinAmt =
3139             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3140       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3141     break;
3142   case ISD::SRL:
3143     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3144     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3145     Known = KnownBits::lshr(Known, Known2);
3146 
3147     // Minimum shift high bits are known zero.
3148     if (const APInt *ShMinAmt =
3149             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3150       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3151     break;
3152   case ISD::SRA:
3153     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3154     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3155     Known = KnownBits::ashr(Known, Known2);
3156     // TODO: Add minimum shift high known sign bits.
3157     break;
3158   case ISD::FSHL:
3159   case ISD::FSHR:
3160     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3161       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3162 
3163       // For fshl, 0-shift returns the 1st arg.
3164       // For fshr, 0-shift returns the 2nd arg.
3165       if (Amt == 0) {
3166         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3167                                  DemandedElts, Depth + 1);
3168         break;
3169       }
3170 
3171       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3172       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3173       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3174       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3175       if (Opcode == ISD::FSHL) {
3176         Known.One <<= Amt;
3177         Known.Zero <<= Amt;
3178         Known2.One.lshrInPlace(BitWidth - Amt);
3179         Known2.Zero.lshrInPlace(BitWidth - Amt);
3180       } else {
3181         Known.One <<= BitWidth - Amt;
3182         Known.Zero <<= BitWidth - Amt;
3183         Known2.One.lshrInPlace(Amt);
3184         Known2.Zero.lshrInPlace(Amt);
3185       }
3186       Known.One |= Known2.One;
3187       Known.Zero |= Known2.Zero;
3188     }
3189     break;
3190   case ISD::SIGN_EXTEND_INREG: {
3191     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3192     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3193     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3194     break;
3195   }
3196   case ISD::CTTZ:
3197   case ISD::CTTZ_ZERO_UNDEF: {
3198     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3199     // If we have a known 1, its position is our upper bound.
3200     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3201     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3202     Known.Zero.setBitsFrom(LowBits);
3203     break;
3204   }
3205   case ISD::CTLZ:
3206   case ISD::CTLZ_ZERO_UNDEF: {
3207     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3208     // If we have a known 1, its position is our upper bound.
3209     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3210     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3211     Known.Zero.setBitsFrom(LowBits);
3212     break;
3213   }
3214   case ISD::CTPOP: {
3215     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3216     // If we know some of the bits are zero, they can't be one.
3217     unsigned PossibleOnes = Known2.countMaxPopulation();
3218     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3219     break;
3220   }
3221   case ISD::PARITY: {
3222     // Parity returns 0 everywhere but the LSB.
3223     Known.Zero.setBitsFrom(1);
3224     break;
3225   }
3226   case ISD::LOAD: {
3227     LoadSDNode *LD = cast<LoadSDNode>(Op);
3228     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3229     if (ISD::isNON_EXTLoad(LD) && Cst) {
3230       // Determine any common known bits from the loaded constant pool value.
3231       Type *CstTy = Cst->getType();
3232       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3233         // If its a vector splat, then we can (quickly) reuse the scalar path.
3234         // NOTE: We assume all elements match and none are UNDEF.
3235         if (CstTy->isVectorTy()) {
3236           if (const Constant *Splat = Cst->getSplatValue()) {
3237             Cst = Splat;
3238             CstTy = Cst->getType();
3239           }
3240         }
3241         // TODO - do we need to handle different bitwidths?
3242         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3243           // Iterate across all vector elements finding common known bits.
3244           Known.One.setAllBits();
3245           Known.Zero.setAllBits();
3246           for (unsigned i = 0; i != NumElts; ++i) {
3247             if (!DemandedElts[i])
3248               continue;
3249             if (Constant *Elt = Cst->getAggregateElement(i)) {
3250               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3251                 const APInt &Value = CInt->getValue();
3252                 Known.One &= Value;
3253                 Known.Zero &= ~Value;
3254                 continue;
3255               }
3256               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3257                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3258                 Known.One &= Value;
3259                 Known.Zero &= ~Value;
3260                 continue;
3261               }
3262             }
3263             Known.One.clearAllBits();
3264             Known.Zero.clearAllBits();
3265             break;
3266           }
3267         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3268           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3269             Known = KnownBits::makeConstant(CInt->getValue());
3270           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3271             Known =
3272                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3273           }
3274         }
3275       }
3276     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3277       // If this is a ZEXTLoad and we are looking at the loaded value.
3278       EVT VT = LD->getMemoryVT();
3279       unsigned MemBits = VT.getScalarSizeInBits();
3280       Known.Zero.setBitsFrom(MemBits);
3281     } else if (const MDNode *Ranges = LD->getRanges()) {
3282       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3283         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3284     }
3285     break;
3286   }
3287   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3288     EVT InVT = Op.getOperand(0).getValueType();
3289     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3290     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3291     Known = Known.zext(BitWidth);
3292     break;
3293   }
3294   case ISD::ZERO_EXTEND: {
3295     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3296     Known = Known.zext(BitWidth);
3297     break;
3298   }
3299   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3300     EVT InVT = Op.getOperand(0).getValueType();
3301     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3302     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3303     // If the sign bit is known to be zero or one, then sext will extend
3304     // it to the top bits, else it will just zext.
3305     Known = Known.sext(BitWidth);
3306     break;
3307   }
3308   case ISD::SIGN_EXTEND: {
3309     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3310     // If the sign bit is known to be zero or one, then sext will extend
3311     // it to the top bits, else it will just zext.
3312     Known = Known.sext(BitWidth);
3313     break;
3314   }
3315   case ISD::ANY_EXTEND_VECTOR_INREG: {
3316     EVT InVT = Op.getOperand(0).getValueType();
3317     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3318     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3319     Known = Known.anyext(BitWidth);
3320     break;
3321   }
3322   case ISD::ANY_EXTEND: {
3323     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3324     Known = Known.anyext(BitWidth);
3325     break;
3326   }
3327   case ISD::TRUNCATE: {
3328     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3329     Known = Known.trunc(BitWidth);
3330     break;
3331   }
3332   case ISD::AssertZext: {
3333     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3334     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3335     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3336     Known.Zero |= (~InMask);
3337     Known.One  &= (~Known.Zero);
3338     break;
3339   }
3340   case ISD::AssertAlign: {
3341     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3342     assert(LogOfAlign != 0);
3343     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3344     // well as clearing one bits.
3345     Known.Zero.setLowBits(LogOfAlign);
3346     Known.One.clearLowBits(LogOfAlign);
3347     break;
3348   }
3349   case ISD::FGETSIGN:
3350     // All bits are zero except the low bit.
3351     Known.Zero.setBitsFrom(1);
3352     break;
3353   case ISD::USUBO:
3354   case ISD::SSUBO:
3355     if (Op.getResNo() == 1) {
3356       // If we know the result of a setcc has the top bits zero, use this info.
3357       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3358               TargetLowering::ZeroOrOneBooleanContent &&
3359           BitWidth > 1)
3360         Known.Zero.setBitsFrom(1);
3361       break;
3362     }
3363     LLVM_FALLTHROUGH;
3364   case ISD::SUB:
3365   case ISD::SUBC: {
3366     assert(Op.getResNo() == 0 &&
3367            "We only compute knownbits for the difference here.");
3368 
3369     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3370     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3371     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3372                                         Known, Known2);
3373     break;
3374   }
3375   case ISD::UADDO:
3376   case ISD::SADDO:
3377   case ISD::ADDCARRY:
3378     if (Op.getResNo() == 1) {
3379       // If we know the result of a setcc has the top bits zero, use this info.
3380       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3381               TargetLowering::ZeroOrOneBooleanContent &&
3382           BitWidth > 1)
3383         Known.Zero.setBitsFrom(1);
3384       break;
3385     }
3386     LLVM_FALLTHROUGH;
3387   case ISD::ADD:
3388   case ISD::ADDC:
3389   case ISD::ADDE: {
3390     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3391 
3392     // With ADDE and ADDCARRY, a carry bit may be added in.
3393     KnownBits Carry(1);
3394     if (Opcode == ISD::ADDE)
3395       // Can't track carry from glue, set carry to unknown.
3396       Carry.resetAll();
3397     else if (Opcode == ISD::ADDCARRY)
3398       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3399       // the trouble (how often will we find a known carry bit). And I haven't
3400       // tested this very much yet, but something like this might work:
3401       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3402       //   Carry = Carry.zextOrTrunc(1, false);
3403       Carry.resetAll();
3404     else
3405       Carry.setAllZero();
3406 
3407     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3408     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3409     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3410     break;
3411   }
3412   case ISD::SREM: {
3413     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3414     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3415     Known = KnownBits::srem(Known, Known2);
3416     break;
3417   }
3418   case ISD::UREM: {
3419     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3420     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3421     Known = KnownBits::urem(Known, Known2);
3422     break;
3423   }
3424   case ISD::EXTRACT_ELEMENT: {
3425     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3426     const unsigned Index = Op.getConstantOperandVal(1);
3427     const unsigned EltBitWidth = Op.getValueSizeInBits();
3428 
3429     // Remove low part of known bits mask
3430     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3431     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3432 
3433     // Remove high part of known bit mask
3434     Known = Known.trunc(EltBitWidth);
3435     break;
3436   }
3437   case ISD::EXTRACT_VECTOR_ELT: {
3438     SDValue InVec = Op.getOperand(0);
3439     SDValue EltNo = Op.getOperand(1);
3440     EVT VecVT = InVec.getValueType();
3441     // computeKnownBits not yet implemented for scalable vectors.
3442     if (VecVT.isScalableVector())
3443       break;
3444     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3445     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3446 
3447     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3448     // anything about the extended bits.
3449     if (BitWidth > EltBitWidth)
3450       Known = Known.trunc(EltBitWidth);
3451 
3452     // If we know the element index, just demand that vector element, else for
3453     // an unknown element index, ignore DemandedElts and demand them all.
3454     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3455     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3456     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3457       DemandedSrcElts =
3458           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3459 
3460     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3461     if (BitWidth > EltBitWidth)
3462       Known = Known.anyext(BitWidth);
3463     break;
3464   }
3465   case ISD::INSERT_VECTOR_ELT: {
3466     // If we know the element index, split the demand between the
3467     // source vector and the inserted element, otherwise assume we need
3468     // the original demanded vector elements and the value.
3469     SDValue InVec = Op.getOperand(0);
3470     SDValue InVal = Op.getOperand(1);
3471     SDValue EltNo = Op.getOperand(2);
3472     bool DemandedVal = true;
3473     APInt DemandedVecElts = DemandedElts;
3474     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3475     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3476       unsigned EltIdx = CEltNo->getZExtValue();
3477       DemandedVal = !!DemandedElts[EltIdx];
3478       DemandedVecElts.clearBit(EltIdx);
3479     }
3480     Known.One.setAllBits();
3481     Known.Zero.setAllBits();
3482     if (DemandedVal) {
3483       Known2 = computeKnownBits(InVal, Depth + 1);
3484       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3485     }
3486     if (!!DemandedVecElts) {
3487       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3488       Known = KnownBits::commonBits(Known, Known2);
3489     }
3490     break;
3491   }
3492   case ISD::BITREVERSE: {
3493     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3494     Known = Known2.reverseBits();
3495     break;
3496   }
3497   case ISD::BSWAP: {
3498     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3499     Known = Known2.byteSwap();
3500     break;
3501   }
3502   case ISD::ABS: {
3503     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3504     Known = Known2.abs();
3505     break;
3506   }
3507   case ISD::USUBSAT: {
3508     // The result of usubsat will never be larger than the LHS.
3509     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3510     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3511     break;
3512   }
3513   case ISD::UMIN: {
3514     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3515     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3516     Known = KnownBits::umin(Known, Known2);
3517     break;
3518   }
3519   case ISD::UMAX: {
3520     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3521     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3522     Known = KnownBits::umax(Known, Known2);
3523     break;
3524   }
3525   case ISD::SMIN:
3526   case ISD::SMAX: {
3527     // If we have a clamp pattern, we know that the number of sign bits will be
3528     // the minimum of the clamp min/max range.
3529     bool IsMax = (Opcode == ISD::SMAX);
3530     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3531     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3532       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3533         CstHigh =
3534             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3535     if (CstLow && CstHigh) {
3536       if (!IsMax)
3537         std::swap(CstLow, CstHigh);
3538 
3539       const APInt &ValueLow = CstLow->getAPIntValue();
3540       const APInt &ValueHigh = CstHigh->getAPIntValue();
3541       if (ValueLow.sle(ValueHigh)) {
3542         unsigned LowSignBits = ValueLow.getNumSignBits();
3543         unsigned HighSignBits = ValueHigh.getNumSignBits();
3544         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3545         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3546           Known.One.setHighBits(MinSignBits);
3547           break;
3548         }
3549         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3550           Known.Zero.setHighBits(MinSignBits);
3551           break;
3552         }
3553       }
3554     }
3555 
3556     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3557     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3558     if (IsMax)
3559       Known = KnownBits::smax(Known, Known2);
3560     else
3561       Known = KnownBits::smin(Known, Known2);
3562     break;
3563   }
3564   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3565     if (Op.getResNo() == 1) {
3566       // The boolean result conforms to getBooleanContents.
3567       // If we know the result of a setcc has the top bits zero, use this info.
3568       // We know that we have an integer-based boolean since these operations
3569       // are only available for integer.
3570       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3571               TargetLowering::ZeroOrOneBooleanContent &&
3572           BitWidth > 1)
3573         Known.Zero.setBitsFrom(1);
3574       break;
3575     }
3576     LLVM_FALLTHROUGH;
3577   case ISD::ATOMIC_CMP_SWAP:
3578   case ISD::ATOMIC_SWAP:
3579   case ISD::ATOMIC_LOAD_ADD:
3580   case ISD::ATOMIC_LOAD_SUB:
3581   case ISD::ATOMIC_LOAD_AND:
3582   case ISD::ATOMIC_LOAD_CLR:
3583   case ISD::ATOMIC_LOAD_OR:
3584   case ISD::ATOMIC_LOAD_XOR:
3585   case ISD::ATOMIC_LOAD_NAND:
3586   case ISD::ATOMIC_LOAD_MIN:
3587   case ISD::ATOMIC_LOAD_MAX:
3588   case ISD::ATOMIC_LOAD_UMIN:
3589   case ISD::ATOMIC_LOAD_UMAX:
3590   case ISD::ATOMIC_LOAD: {
3591     unsigned MemBits =
3592         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3593     // If we are looking at the loaded value.
3594     if (Op.getResNo() == 0) {
3595       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3596         Known.Zero.setBitsFrom(MemBits);
3597     }
3598     break;
3599   }
3600   case ISD::FrameIndex:
3601   case ISD::TargetFrameIndex:
3602     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3603                                        Known, getMachineFunction());
3604     break;
3605 
3606   default:
3607     if (Opcode < ISD::BUILTIN_OP_END)
3608       break;
3609     LLVM_FALLTHROUGH;
3610   case ISD::INTRINSIC_WO_CHAIN:
3611   case ISD::INTRINSIC_W_CHAIN:
3612   case ISD::INTRINSIC_VOID:
3613     // Allow the target to implement this method for its nodes.
3614     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3615     break;
3616   }
3617 
3618   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3619   return Known;
3620 }
3621 
3622 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3623                                                              SDValue N1) const {
3624   // X + 0 never overflow
3625   if (isNullConstant(N1))
3626     return OFK_Never;
3627 
3628   KnownBits N1Known = computeKnownBits(N1);
3629   if (N1Known.Zero.getBoolValue()) {
3630     KnownBits N0Known = computeKnownBits(N0);
3631 
3632     bool overflow;
3633     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3634     if (!overflow)
3635       return OFK_Never;
3636   }
3637 
3638   // mulhi + 1 never overflow
3639   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3640       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3641     return OFK_Never;
3642 
3643   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3644     KnownBits N0Known = computeKnownBits(N0);
3645 
3646     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3647       return OFK_Never;
3648   }
3649 
3650   return OFK_Sometime;
3651 }
3652 
3653 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3654   EVT OpVT = Val.getValueType();
3655   unsigned BitWidth = OpVT.getScalarSizeInBits();
3656 
3657   // Is the constant a known power of 2?
3658   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3659     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3660 
3661   // A left-shift of a constant one will have exactly one bit set because
3662   // shifting the bit off the end is undefined.
3663   if (Val.getOpcode() == ISD::SHL) {
3664     auto *C = isConstOrConstSplat(Val.getOperand(0));
3665     if (C && C->getAPIntValue() == 1)
3666       return true;
3667   }
3668 
3669   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3670   // one bit set.
3671   if (Val.getOpcode() == ISD::SRL) {
3672     auto *C = isConstOrConstSplat(Val.getOperand(0));
3673     if (C && C->getAPIntValue().isSignMask())
3674       return true;
3675   }
3676 
3677   // Are all operands of a build vector constant powers of two?
3678   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3679     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3680           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3681             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3682           return false;
3683         }))
3684       return true;
3685 
3686   // Is the operand of a splat vector a constant power of two?
3687   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3688     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3689       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3690         return true;
3691 
3692   // More could be done here, though the above checks are enough
3693   // to handle some common cases.
3694 
3695   // Fall back to computeKnownBits to catch other known cases.
3696   KnownBits Known = computeKnownBits(Val);
3697   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3698 }
3699 
3700 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3701   EVT VT = Op.getValueType();
3702 
3703   // TODO: Assume we don't know anything for now.
3704   if (VT.isScalableVector())
3705     return 1;
3706 
3707   APInt DemandedElts = VT.isVector()
3708                            ? APInt::getAllOnes(VT.getVectorNumElements())
3709                            : APInt(1, 1);
3710   return ComputeNumSignBits(Op, DemandedElts, Depth);
3711 }
3712 
3713 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3714                                           unsigned Depth) const {
3715   EVT VT = Op.getValueType();
3716   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3717   unsigned VTBits = VT.getScalarSizeInBits();
3718   unsigned NumElts = DemandedElts.getBitWidth();
3719   unsigned Tmp, Tmp2;
3720   unsigned FirstAnswer = 1;
3721 
3722   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3723     const APInt &Val = C->getAPIntValue();
3724     return Val.getNumSignBits();
3725   }
3726 
3727   if (Depth >= MaxRecursionDepth)
3728     return 1;  // Limit search depth.
3729 
3730   if (!DemandedElts || VT.isScalableVector())
3731     return 1;  // No demanded elts, better to assume we don't know anything.
3732 
3733   unsigned Opcode = Op.getOpcode();
3734   switch (Opcode) {
3735   default: break;
3736   case ISD::AssertSext:
3737     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3738     return VTBits-Tmp+1;
3739   case ISD::AssertZext:
3740     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3741     return VTBits-Tmp;
3742 
3743   case ISD::BUILD_VECTOR:
3744     Tmp = VTBits;
3745     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3746       if (!DemandedElts[i])
3747         continue;
3748 
3749       SDValue SrcOp = Op.getOperand(i);
3750       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3751 
3752       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3753       if (SrcOp.getValueSizeInBits() != VTBits) {
3754         assert(SrcOp.getValueSizeInBits() > VTBits &&
3755                "Expected BUILD_VECTOR implicit truncation");
3756         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3757         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3758       }
3759       Tmp = std::min(Tmp, Tmp2);
3760     }
3761     return Tmp;
3762 
3763   case ISD::VECTOR_SHUFFLE: {
3764     // Collect the minimum number of sign bits that are shared by every vector
3765     // element referenced by the shuffle.
3766     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3767     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3768     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3769     for (unsigned i = 0; i != NumElts; ++i) {
3770       int M = SVN->getMaskElt(i);
3771       if (!DemandedElts[i])
3772         continue;
3773       // For UNDEF elements, we don't know anything about the common state of
3774       // the shuffle result.
3775       if (M < 0)
3776         return 1;
3777       if ((unsigned)M < NumElts)
3778         DemandedLHS.setBit((unsigned)M % NumElts);
3779       else
3780         DemandedRHS.setBit((unsigned)M % NumElts);
3781     }
3782     Tmp = std::numeric_limits<unsigned>::max();
3783     if (!!DemandedLHS)
3784       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3785     if (!!DemandedRHS) {
3786       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3787       Tmp = std::min(Tmp, Tmp2);
3788     }
3789     // If we don't know anything, early out and try computeKnownBits fall-back.
3790     if (Tmp == 1)
3791       break;
3792     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3793     return Tmp;
3794   }
3795 
3796   case ISD::BITCAST: {
3797     SDValue N0 = Op.getOperand(0);
3798     EVT SrcVT = N0.getValueType();
3799     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3800 
3801     // Ignore bitcasts from unsupported types..
3802     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3803       break;
3804 
3805     // Fast handling of 'identity' bitcasts.
3806     if (VTBits == SrcBits)
3807       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3808 
3809     bool IsLE = getDataLayout().isLittleEndian();
3810 
3811     // Bitcast 'large element' scalar/vector to 'small element' vector.
3812     if ((SrcBits % VTBits) == 0) {
3813       assert(VT.isVector() && "Expected bitcast to vector");
3814 
3815       unsigned Scale = SrcBits / VTBits;
3816       APInt SrcDemandedElts =
3817           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3818 
3819       // Fast case - sign splat can be simply split across the small elements.
3820       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3821       if (Tmp == SrcBits)
3822         return VTBits;
3823 
3824       // Slow case - determine how far the sign extends into each sub-element.
3825       Tmp2 = VTBits;
3826       for (unsigned i = 0; i != NumElts; ++i)
3827         if (DemandedElts[i]) {
3828           unsigned SubOffset = i % Scale;
3829           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3830           SubOffset = SubOffset * VTBits;
3831           if (Tmp <= SubOffset)
3832             return 1;
3833           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3834         }
3835       return Tmp2;
3836     }
3837     break;
3838   }
3839 
3840   case ISD::SIGN_EXTEND:
3841     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3842     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3843   case ISD::SIGN_EXTEND_INREG:
3844     // Max of the input and what this extends.
3845     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3846     Tmp = VTBits-Tmp+1;
3847     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3848     return std::max(Tmp, Tmp2);
3849   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3850     SDValue Src = Op.getOperand(0);
3851     EVT SrcVT = Src.getValueType();
3852     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3853     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3854     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3855   }
3856   case ISD::SRA:
3857     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3858     // SRA X, C -> adds C sign bits.
3859     if (const APInt *ShAmt =
3860             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3861       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3862     return Tmp;
3863   case ISD::SHL:
3864     if (const APInt *ShAmt =
3865             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3866       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3867       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3868       if (ShAmt->ult(Tmp))
3869         return Tmp - ShAmt->getZExtValue();
3870     }
3871     break;
3872   case ISD::AND:
3873   case ISD::OR:
3874   case ISD::XOR:    // NOT is handled here.
3875     // Logical binary ops preserve the number of sign bits at the worst.
3876     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3877     if (Tmp != 1) {
3878       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3879       FirstAnswer = std::min(Tmp, Tmp2);
3880       // We computed what we know about the sign bits as our first
3881       // answer. Now proceed to the generic code that uses
3882       // computeKnownBits, and pick whichever answer is better.
3883     }
3884     break;
3885 
3886   case ISD::SELECT:
3887   case ISD::VSELECT:
3888     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3889     if (Tmp == 1) return 1;  // Early out.
3890     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3891     return std::min(Tmp, Tmp2);
3892   case ISD::SELECT_CC:
3893     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3894     if (Tmp == 1) return 1;  // Early out.
3895     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3896     return std::min(Tmp, Tmp2);
3897 
3898   case ISD::SMIN:
3899   case ISD::SMAX: {
3900     // If we have a clamp pattern, we know that the number of sign bits will be
3901     // the minimum of the clamp min/max range.
3902     bool IsMax = (Opcode == ISD::SMAX);
3903     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3904     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3905       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3906         CstHigh =
3907             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3908     if (CstLow && CstHigh) {
3909       if (!IsMax)
3910         std::swap(CstLow, CstHigh);
3911       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3912         Tmp = CstLow->getAPIntValue().getNumSignBits();
3913         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3914         return std::min(Tmp, Tmp2);
3915       }
3916     }
3917 
3918     // Fallback - just get the minimum number of sign bits of the operands.
3919     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3920     if (Tmp == 1)
3921       return 1;  // Early out.
3922     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3923     return std::min(Tmp, Tmp2);
3924   }
3925   case ISD::UMIN:
3926   case ISD::UMAX:
3927     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3928     if (Tmp == 1)
3929       return 1;  // Early out.
3930     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3931     return std::min(Tmp, Tmp2);
3932   case ISD::SADDO:
3933   case ISD::UADDO:
3934   case ISD::SSUBO:
3935   case ISD::USUBO:
3936   case ISD::SMULO:
3937   case ISD::UMULO:
3938     if (Op.getResNo() != 1)
3939       break;
3940     // The boolean result conforms to getBooleanContents.  Fall through.
3941     // If setcc returns 0/-1, all bits are sign bits.
3942     // We know that we have an integer-based boolean since these operations
3943     // are only available for integer.
3944     if (TLI->getBooleanContents(VT.isVector(), false) ==
3945         TargetLowering::ZeroOrNegativeOneBooleanContent)
3946       return VTBits;
3947     break;
3948   case ISD::SETCC:
3949   case ISD::STRICT_FSETCC:
3950   case ISD::STRICT_FSETCCS: {
3951     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3952     // If setcc returns 0/-1, all bits are sign bits.
3953     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3954         TargetLowering::ZeroOrNegativeOneBooleanContent)
3955       return VTBits;
3956     break;
3957   }
3958   case ISD::ROTL:
3959   case ISD::ROTR:
3960     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3961 
3962     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3963     if (Tmp == VTBits)
3964       return VTBits;
3965 
3966     if (ConstantSDNode *C =
3967             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3968       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3969 
3970       // Handle rotate right by N like a rotate left by 32-N.
3971       if (Opcode == ISD::ROTR)
3972         RotAmt = (VTBits - RotAmt) % VTBits;
3973 
3974       // If we aren't rotating out all of the known-in sign bits, return the
3975       // number that are left.  This handles rotl(sext(x), 1) for example.
3976       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3977     }
3978     break;
3979   case ISD::ADD:
3980   case ISD::ADDC:
3981     // Add can have at most one carry bit.  Thus we know that the output
3982     // is, at worst, one more bit than the inputs.
3983     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3984     if (Tmp == 1) return 1; // Early out.
3985 
3986     // Special case decrementing a value (ADD X, -1):
3987     if (ConstantSDNode *CRHS =
3988             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3989       if (CRHS->isAllOnes()) {
3990         KnownBits Known =
3991             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3992 
3993         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3994         // sign bits set.
3995         if ((Known.Zero | 1).isAllOnes())
3996           return VTBits;
3997 
3998         // If we are subtracting one from a positive number, there is no carry
3999         // out of the result.
4000         if (Known.isNonNegative())
4001           return Tmp;
4002       }
4003 
4004     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4005     if (Tmp2 == 1) return 1; // Early out.
4006     return std::min(Tmp, Tmp2) - 1;
4007   case ISD::SUB:
4008     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4009     if (Tmp2 == 1) return 1; // Early out.
4010 
4011     // Handle NEG.
4012     if (ConstantSDNode *CLHS =
4013             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4014       if (CLHS->isZero()) {
4015         KnownBits Known =
4016             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4017         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4018         // sign bits set.
4019         if ((Known.Zero | 1).isAllOnes())
4020           return VTBits;
4021 
4022         // If the input is known to be positive (the sign bit is known clear),
4023         // the output of the NEG has the same number of sign bits as the input.
4024         if (Known.isNonNegative())
4025           return Tmp2;
4026 
4027         // Otherwise, we treat this like a SUB.
4028       }
4029 
4030     // Sub can have at most one carry bit.  Thus we know that the output
4031     // is, at worst, one more bit than the inputs.
4032     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4033     if (Tmp == 1) return 1; // Early out.
4034     return std::min(Tmp, Tmp2) - 1;
4035   case ISD::MUL: {
4036     // The output of the Mul can be at most twice the valid bits in the inputs.
4037     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4038     if (SignBitsOp0 == 1)
4039       break;
4040     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4041     if (SignBitsOp1 == 1)
4042       break;
4043     unsigned OutValidBits =
4044         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4045     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4046   }
4047   case ISD::SREM:
4048     // The sign bit is the LHS's sign bit, except when the result of the
4049     // remainder is zero. The magnitude of the result should be less than or
4050     // equal to the magnitude of the LHS. Therefore, the result should have
4051     // at least as many sign bits as the left hand side.
4052     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4053   case ISD::TRUNCATE: {
4054     // Check if the sign bits of source go down as far as the truncated value.
4055     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4056     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4057     if (NumSrcSignBits > (NumSrcBits - VTBits))
4058       return NumSrcSignBits - (NumSrcBits - VTBits);
4059     break;
4060   }
4061   case ISD::EXTRACT_ELEMENT: {
4062     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4063     const int BitWidth = Op.getValueSizeInBits();
4064     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4065 
4066     // Get reverse index (starting from 1), Op1 value indexes elements from
4067     // little end. Sign starts at big end.
4068     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4069 
4070     // If the sign portion ends in our element the subtraction gives correct
4071     // result. Otherwise it gives either negative or > bitwidth result
4072     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4073   }
4074   case ISD::INSERT_VECTOR_ELT: {
4075     // If we know the element index, split the demand between the
4076     // source vector and the inserted element, otherwise assume we need
4077     // the original demanded vector elements and the value.
4078     SDValue InVec = Op.getOperand(0);
4079     SDValue InVal = Op.getOperand(1);
4080     SDValue EltNo = Op.getOperand(2);
4081     bool DemandedVal = true;
4082     APInt DemandedVecElts = DemandedElts;
4083     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4084     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4085       unsigned EltIdx = CEltNo->getZExtValue();
4086       DemandedVal = !!DemandedElts[EltIdx];
4087       DemandedVecElts.clearBit(EltIdx);
4088     }
4089     Tmp = std::numeric_limits<unsigned>::max();
4090     if (DemandedVal) {
4091       // TODO - handle implicit truncation of inserted elements.
4092       if (InVal.getScalarValueSizeInBits() != VTBits)
4093         break;
4094       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4095       Tmp = std::min(Tmp, Tmp2);
4096     }
4097     if (!!DemandedVecElts) {
4098       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4099       Tmp = std::min(Tmp, Tmp2);
4100     }
4101     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4102     return Tmp;
4103   }
4104   case ISD::EXTRACT_VECTOR_ELT: {
4105     SDValue InVec = Op.getOperand(0);
4106     SDValue EltNo = Op.getOperand(1);
4107     EVT VecVT = InVec.getValueType();
4108     // ComputeNumSignBits not yet implemented for scalable vectors.
4109     if (VecVT.isScalableVector())
4110       break;
4111     const unsigned BitWidth = Op.getValueSizeInBits();
4112     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4113     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4114 
4115     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4116     // anything about sign bits. But if the sizes match we can derive knowledge
4117     // about sign bits from the vector operand.
4118     if (BitWidth != EltBitWidth)
4119       break;
4120 
4121     // If we know the element index, just demand that vector element, else for
4122     // an unknown element index, ignore DemandedElts and demand them all.
4123     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4124     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4125     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4126       DemandedSrcElts =
4127           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4128 
4129     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4130   }
4131   case ISD::EXTRACT_SUBVECTOR: {
4132     // Offset the demanded elts by the subvector index.
4133     SDValue Src = Op.getOperand(0);
4134     // Bail until we can represent demanded elements for scalable vectors.
4135     if (Src.getValueType().isScalableVector())
4136       break;
4137     uint64_t Idx = Op.getConstantOperandVal(1);
4138     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4139     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4140     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4141   }
4142   case ISD::CONCAT_VECTORS: {
4143     // Determine the minimum number of sign bits across all demanded
4144     // elts of the input vectors. Early out if the result is already 1.
4145     Tmp = std::numeric_limits<unsigned>::max();
4146     EVT SubVectorVT = Op.getOperand(0).getValueType();
4147     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4148     unsigned NumSubVectors = Op.getNumOperands();
4149     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4150       APInt DemandedSub =
4151           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4152       if (!DemandedSub)
4153         continue;
4154       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4155       Tmp = std::min(Tmp, Tmp2);
4156     }
4157     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4158     return Tmp;
4159   }
4160   case ISD::INSERT_SUBVECTOR: {
4161     // Demand any elements from the subvector and the remainder from the src its
4162     // inserted into.
4163     SDValue Src = Op.getOperand(0);
4164     SDValue Sub = Op.getOperand(1);
4165     uint64_t Idx = Op.getConstantOperandVal(2);
4166     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4167     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4168     APInt DemandedSrcElts = DemandedElts;
4169     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4170 
4171     Tmp = std::numeric_limits<unsigned>::max();
4172     if (!!DemandedSubElts) {
4173       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4174       if (Tmp == 1)
4175         return 1; // early-out
4176     }
4177     if (!!DemandedSrcElts) {
4178       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4179       Tmp = std::min(Tmp, Tmp2);
4180     }
4181     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4182     return Tmp;
4183   }
4184   case ISD::ATOMIC_CMP_SWAP:
4185   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4186   case ISD::ATOMIC_SWAP:
4187   case ISD::ATOMIC_LOAD_ADD:
4188   case ISD::ATOMIC_LOAD_SUB:
4189   case ISD::ATOMIC_LOAD_AND:
4190   case ISD::ATOMIC_LOAD_CLR:
4191   case ISD::ATOMIC_LOAD_OR:
4192   case ISD::ATOMIC_LOAD_XOR:
4193   case ISD::ATOMIC_LOAD_NAND:
4194   case ISD::ATOMIC_LOAD_MIN:
4195   case ISD::ATOMIC_LOAD_MAX:
4196   case ISD::ATOMIC_LOAD_UMIN:
4197   case ISD::ATOMIC_LOAD_UMAX:
4198   case ISD::ATOMIC_LOAD: {
4199     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4200     // If we are looking at the loaded value.
4201     if (Op.getResNo() == 0) {
4202       if (Tmp == VTBits)
4203         return 1; // early-out
4204       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4205         return VTBits - Tmp + 1;
4206       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4207         return VTBits - Tmp;
4208     }
4209     break;
4210   }
4211   }
4212 
4213   // If we are looking at the loaded value of the SDNode.
4214   if (Op.getResNo() == 0) {
4215     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4216     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4217       unsigned ExtType = LD->getExtensionType();
4218       switch (ExtType) {
4219       default: break;
4220       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4221         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4222         return VTBits - Tmp + 1;
4223       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4224         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4225         return VTBits - Tmp;
4226       case ISD::NON_EXTLOAD:
4227         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4228           // We only need to handle vectors - computeKnownBits should handle
4229           // scalar cases.
4230           Type *CstTy = Cst->getType();
4231           if (CstTy->isVectorTy() &&
4232               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4233             Tmp = VTBits;
4234             for (unsigned i = 0; i != NumElts; ++i) {
4235               if (!DemandedElts[i])
4236                 continue;
4237               if (Constant *Elt = Cst->getAggregateElement(i)) {
4238                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4239                   const APInt &Value = CInt->getValue();
4240                   Tmp = std::min(Tmp, Value.getNumSignBits());
4241                   continue;
4242                 }
4243                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4244                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4245                   Tmp = std::min(Tmp, Value.getNumSignBits());
4246                   continue;
4247                 }
4248               }
4249               // Unknown type. Conservatively assume no bits match sign bit.
4250               return 1;
4251             }
4252             return Tmp;
4253           }
4254         }
4255         break;
4256       }
4257     }
4258   }
4259 
4260   // Allow the target to implement this method for its nodes.
4261   if (Opcode >= ISD::BUILTIN_OP_END ||
4262       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4263       Opcode == ISD::INTRINSIC_W_CHAIN ||
4264       Opcode == ISD::INTRINSIC_VOID) {
4265     unsigned NumBits =
4266         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4267     if (NumBits > 1)
4268       FirstAnswer = std::max(FirstAnswer, NumBits);
4269   }
4270 
4271   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4272   // use this information.
4273   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4274 
4275   APInt Mask;
4276   if (Known.isNonNegative()) {        // sign bit is 0
4277     Mask = Known.Zero;
4278   } else if (Known.isNegative()) {  // sign bit is 1;
4279     Mask = Known.One;
4280   } else {
4281     // Nothing known.
4282     return FirstAnswer;
4283   }
4284 
4285   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4286   // the number of identical bits in the top of the input value.
4287   Mask <<= Mask.getBitWidth()-VTBits;
4288   return std::max(FirstAnswer, Mask.countLeadingOnes());
4289 }
4290 
4291 unsigned SelectionDAG::ComputeMinSignedBits(SDValue Op, unsigned Depth) const {
4292   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4293   return Op.getScalarValueSizeInBits() - SignBits + 1;
4294 }
4295 
4296 unsigned SelectionDAG::ComputeMinSignedBits(SDValue Op,
4297                                             const APInt &DemandedElts,
4298                                             unsigned Depth) const {
4299   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4300   return Op.getScalarValueSizeInBits() - SignBits + 1;
4301 }
4302 
4303 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4304                                                     unsigned Depth) const {
4305   // Early out for FREEZE.
4306   if (Op.getOpcode() == ISD::FREEZE)
4307     return true;
4308 
4309   // TODO: Assume we don't know anything for now.
4310   EVT VT = Op.getValueType();
4311   if (VT.isScalableVector())
4312     return false;
4313 
4314   APInt DemandedElts = VT.isVector()
4315                            ? APInt::getAllOnes(VT.getVectorNumElements())
4316                            : APInt(1, 1);
4317   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4318 }
4319 
4320 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4321                                                     const APInt &DemandedElts,
4322                                                     bool PoisonOnly,
4323                                                     unsigned Depth) const {
4324   unsigned Opcode = Op.getOpcode();
4325 
4326   // Early out for FREEZE.
4327   if (Opcode == ISD::FREEZE)
4328     return true;
4329 
4330   if (Depth >= MaxRecursionDepth)
4331     return false; // Limit search depth.
4332 
4333   if (isIntOrFPConstant(Op))
4334     return true;
4335 
4336   switch (Opcode) {
4337   case ISD::UNDEF:
4338     return PoisonOnly;
4339 
4340   case ISD::BUILD_VECTOR:
4341     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4342     // this shouldn't affect the result.
4343     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4344       if (!DemandedElts[i])
4345         continue;
4346       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4347                                             Depth + 1))
4348         return false;
4349     }
4350     return true;
4351 
4352   // TODO: Search for noundef attributes from library functions.
4353 
4354   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4355 
4356   default:
4357     // Allow the target to implement this method for its nodes.
4358     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4359         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4360       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4361           Op, DemandedElts, *this, PoisonOnly, Depth);
4362     break;
4363   }
4364 
4365   return false;
4366 }
4367 
4368 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4369   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4370       !isa<ConstantSDNode>(Op.getOperand(1)))
4371     return false;
4372 
4373   if (Op.getOpcode() == ISD::OR &&
4374       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4375     return false;
4376 
4377   return true;
4378 }
4379 
4380 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4381   // If we're told that NaNs won't happen, assume they won't.
4382   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4383     return true;
4384 
4385   if (Depth >= MaxRecursionDepth)
4386     return false; // Limit search depth.
4387 
4388   // TODO: Handle vectors.
4389   // If the value is a constant, we can obviously see if it is a NaN or not.
4390   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4391     return !C->getValueAPF().isNaN() ||
4392            (SNaN && !C->getValueAPF().isSignaling());
4393   }
4394 
4395   unsigned Opcode = Op.getOpcode();
4396   switch (Opcode) {
4397   case ISD::FADD:
4398   case ISD::FSUB:
4399   case ISD::FMUL:
4400   case ISD::FDIV:
4401   case ISD::FREM:
4402   case ISD::FSIN:
4403   case ISD::FCOS: {
4404     if (SNaN)
4405       return true;
4406     // TODO: Need isKnownNeverInfinity
4407     return false;
4408   }
4409   case ISD::FCANONICALIZE:
4410   case ISD::FEXP:
4411   case ISD::FEXP2:
4412   case ISD::FTRUNC:
4413   case ISD::FFLOOR:
4414   case ISD::FCEIL:
4415   case ISD::FROUND:
4416   case ISD::FROUNDEVEN:
4417   case ISD::FRINT:
4418   case ISD::FNEARBYINT: {
4419     if (SNaN)
4420       return true;
4421     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4422   }
4423   case ISD::FABS:
4424   case ISD::FNEG:
4425   case ISD::FCOPYSIGN: {
4426     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4427   }
4428   case ISD::SELECT:
4429     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4430            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4431   case ISD::FP_EXTEND:
4432   case ISD::FP_ROUND: {
4433     if (SNaN)
4434       return true;
4435     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4436   }
4437   case ISD::SINT_TO_FP:
4438   case ISD::UINT_TO_FP:
4439     return true;
4440   case ISD::FMA:
4441   case ISD::FMAD: {
4442     if (SNaN)
4443       return true;
4444     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4445            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4446            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4447   }
4448   case ISD::FSQRT: // Need is known positive
4449   case ISD::FLOG:
4450   case ISD::FLOG2:
4451   case ISD::FLOG10:
4452   case ISD::FPOWI:
4453   case ISD::FPOW: {
4454     if (SNaN)
4455       return true;
4456     // TODO: Refine on operand
4457     return false;
4458   }
4459   case ISD::FMINNUM:
4460   case ISD::FMAXNUM: {
4461     // Only one needs to be known not-nan, since it will be returned if the
4462     // other ends up being one.
4463     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4464            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4465   }
4466   case ISD::FMINNUM_IEEE:
4467   case ISD::FMAXNUM_IEEE: {
4468     if (SNaN)
4469       return true;
4470     // This can return a NaN if either operand is an sNaN, or if both operands
4471     // are NaN.
4472     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4473             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4474            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4475             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4476   }
4477   case ISD::FMINIMUM:
4478   case ISD::FMAXIMUM: {
4479     // TODO: Does this quiet or return the origina NaN as-is?
4480     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4481            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4482   }
4483   case ISD::EXTRACT_VECTOR_ELT: {
4484     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4485   }
4486   default:
4487     if (Opcode >= ISD::BUILTIN_OP_END ||
4488         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4489         Opcode == ISD::INTRINSIC_W_CHAIN ||
4490         Opcode == ISD::INTRINSIC_VOID) {
4491       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4492     }
4493 
4494     return false;
4495   }
4496 }
4497 
4498 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4499   assert(Op.getValueType().isFloatingPoint() &&
4500          "Floating point type expected");
4501 
4502   // If the value is a constant, we can obviously see if it is a zero or not.
4503   // TODO: Add BuildVector support.
4504   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4505     return !C->isZero();
4506   return false;
4507 }
4508 
4509 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4510   assert(!Op.getValueType().isFloatingPoint() &&
4511          "Floating point types unsupported - use isKnownNeverZeroFloat");
4512 
4513   // If the value is a constant, we can obviously see if it is a zero or not.
4514   if (ISD::matchUnaryPredicate(Op,
4515                                [](ConstantSDNode *C) { return !C->isZero(); }))
4516     return true;
4517 
4518   // TODO: Recognize more cases here.
4519   switch (Op.getOpcode()) {
4520   default: break;
4521   case ISD::OR:
4522     if (isKnownNeverZero(Op.getOperand(1)) ||
4523         isKnownNeverZero(Op.getOperand(0)))
4524       return true;
4525     break;
4526   }
4527 
4528   return false;
4529 }
4530 
4531 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4532   // Check the obvious case.
4533   if (A == B) return true;
4534 
4535   // For for negative and positive zero.
4536   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4537     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4538       if (CA->isZero() && CB->isZero()) return true;
4539 
4540   // Otherwise they may not be equal.
4541   return false;
4542 }
4543 
4544 // FIXME: unify with llvm::haveNoCommonBitsSet.
4545 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4546   assert(A.getValueType() == B.getValueType() &&
4547          "Values must have the same type");
4548   // Match masked merge pattern (X & ~M) op (Y & M)
4549   if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) {
4550     auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) {
4551       if (isBitwiseNot(NotM, true)) {
4552         SDValue NotOperand = NotM->getOperand(0);
4553         return NotOperand == And->getOperand(0) ||
4554                NotOperand == And->getOperand(1);
4555       }
4556       return false;
4557     };
4558     if (MatchNoCommonBitsPattern(A->getOperand(0), B) ||
4559         MatchNoCommonBitsPattern(A->getOperand(1), B) ||
4560         MatchNoCommonBitsPattern(B->getOperand(0), A) ||
4561         MatchNoCommonBitsPattern(B->getOperand(1), A))
4562       return true;
4563   }
4564   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4565                                         computeKnownBits(B));
4566 }
4567 
4568 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4569                                SelectionDAG &DAG) {
4570   if (cast<ConstantSDNode>(Step)->isZero())
4571     return DAG.getConstant(0, DL, VT);
4572 
4573   return SDValue();
4574 }
4575 
4576 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4577                                 ArrayRef<SDValue> Ops,
4578                                 SelectionDAG &DAG) {
4579   int NumOps = Ops.size();
4580   assert(NumOps != 0 && "Can't build an empty vector!");
4581   assert(!VT.isScalableVector() &&
4582          "BUILD_VECTOR cannot be used with scalable types");
4583   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4584          "Incorrect element count in BUILD_VECTOR!");
4585 
4586   // BUILD_VECTOR of UNDEFs is UNDEF.
4587   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4588     return DAG.getUNDEF(VT);
4589 
4590   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4591   SDValue IdentitySrc;
4592   bool IsIdentity = true;
4593   for (int i = 0; i != NumOps; ++i) {
4594     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4595         Ops[i].getOperand(0).getValueType() != VT ||
4596         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4597         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4598         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4599       IsIdentity = false;
4600       break;
4601     }
4602     IdentitySrc = Ops[i].getOperand(0);
4603   }
4604   if (IsIdentity)
4605     return IdentitySrc;
4606 
4607   return SDValue();
4608 }
4609 
4610 /// Try to simplify vector concatenation to an input value, undef, or build
4611 /// vector.
4612 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4613                                   ArrayRef<SDValue> Ops,
4614                                   SelectionDAG &DAG) {
4615   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4616   assert(llvm::all_of(Ops,
4617                       [Ops](SDValue Op) {
4618                         return Ops[0].getValueType() == Op.getValueType();
4619                       }) &&
4620          "Concatenation of vectors with inconsistent value types!");
4621   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4622              VT.getVectorElementCount() &&
4623          "Incorrect element count in vector concatenation!");
4624 
4625   if (Ops.size() == 1)
4626     return Ops[0];
4627 
4628   // Concat of UNDEFs is UNDEF.
4629   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4630     return DAG.getUNDEF(VT);
4631 
4632   // Scan the operands and look for extract operations from a single source
4633   // that correspond to insertion at the same location via this concatenation:
4634   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4635   SDValue IdentitySrc;
4636   bool IsIdentity = true;
4637   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4638     SDValue Op = Ops[i];
4639     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4640     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4641         Op.getOperand(0).getValueType() != VT ||
4642         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4643         Op.getConstantOperandVal(1) != IdentityIndex) {
4644       IsIdentity = false;
4645       break;
4646     }
4647     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4648            "Unexpected identity source vector for concat of extracts");
4649     IdentitySrc = Op.getOperand(0);
4650   }
4651   if (IsIdentity) {
4652     assert(IdentitySrc && "Failed to set source vector of extracts");
4653     return IdentitySrc;
4654   }
4655 
4656   // The code below this point is only designed to work for fixed width
4657   // vectors, so we bail out for now.
4658   if (VT.isScalableVector())
4659     return SDValue();
4660 
4661   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4662   // simplified to one big BUILD_VECTOR.
4663   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4664   EVT SVT = VT.getScalarType();
4665   SmallVector<SDValue, 16> Elts;
4666   for (SDValue Op : Ops) {
4667     EVT OpVT = Op.getValueType();
4668     if (Op.isUndef())
4669       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4670     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4671       Elts.append(Op->op_begin(), Op->op_end());
4672     else
4673       return SDValue();
4674   }
4675 
4676   // BUILD_VECTOR requires all inputs to be of the same type, find the
4677   // maximum type and extend them all.
4678   for (SDValue Op : Elts)
4679     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4680 
4681   if (SVT.bitsGT(VT.getScalarType())) {
4682     for (SDValue &Op : Elts) {
4683       if (Op.isUndef())
4684         Op = DAG.getUNDEF(SVT);
4685       else
4686         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4687                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4688                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4689     }
4690   }
4691 
4692   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4693   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4694   return V;
4695 }
4696 
4697 /// Gets or creates the specified node.
4698 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4699   FoldingSetNodeID ID;
4700   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4701   void *IP = nullptr;
4702   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4703     return SDValue(E, 0);
4704 
4705   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4706                               getVTList(VT));
4707   CSEMap.InsertNode(N, IP);
4708 
4709   InsertNode(N);
4710   SDValue V = SDValue(N, 0);
4711   NewSDValueDbgMsg(V, "Creating new node: ", this);
4712   return V;
4713 }
4714 
4715 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4716                               SDValue Operand) {
4717   SDNodeFlags Flags;
4718   if (Inserter)
4719     Flags = Inserter->getFlags();
4720   return getNode(Opcode, DL, VT, Operand, Flags);
4721 }
4722 
4723 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4724                               SDValue Operand, const SDNodeFlags Flags) {
4725   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4726          "Operand is DELETED_NODE!");
4727   // Constant fold unary operations with an integer constant operand. Even
4728   // opaque constant will be folded, because the folding of unary operations
4729   // doesn't create new constants with different values. Nevertheless, the
4730   // opaque flag is preserved during folding to prevent future folding with
4731   // other constants.
4732   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4733     const APInt &Val = C->getAPIntValue();
4734     switch (Opcode) {
4735     default: break;
4736     case ISD::SIGN_EXTEND:
4737       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4738                          C->isTargetOpcode(), C->isOpaque());
4739     case ISD::TRUNCATE:
4740       if (C->isOpaque())
4741         break;
4742       LLVM_FALLTHROUGH;
4743     case ISD::ZERO_EXTEND:
4744       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4745                          C->isTargetOpcode(), C->isOpaque());
4746     case ISD::ANY_EXTEND:
4747       // Some targets like RISCV prefer to sign extend some types.
4748       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4749         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4750                            C->isTargetOpcode(), C->isOpaque());
4751       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4752                          C->isTargetOpcode(), C->isOpaque());
4753     case ISD::UINT_TO_FP:
4754     case ISD::SINT_TO_FP: {
4755       APFloat apf(EVTToAPFloatSemantics(VT),
4756                   APInt::getZero(VT.getSizeInBits()));
4757       (void)apf.convertFromAPInt(Val,
4758                                  Opcode==ISD::SINT_TO_FP,
4759                                  APFloat::rmNearestTiesToEven);
4760       return getConstantFP(apf, DL, VT);
4761     }
4762     case ISD::BITCAST:
4763       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4764         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4765       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4766         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4767       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4768         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4769       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4770         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4771       break;
4772     case ISD::ABS:
4773       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4774                          C->isOpaque());
4775     case ISD::BITREVERSE:
4776       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4777                          C->isOpaque());
4778     case ISD::BSWAP:
4779       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4780                          C->isOpaque());
4781     case ISD::CTPOP:
4782       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4783                          C->isOpaque());
4784     case ISD::CTLZ:
4785     case ISD::CTLZ_ZERO_UNDEF:
4786       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4787                          C->isOpaque());
4788     case ISD::CTTZ:
4789     case ISD::CTTZ_ZERO_UNDEF:
4790       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4791                          C->isOpaque());
4792     case ISD::FP16_TO_FP: {
4793       bool Ignored;
4794       APFloat FPV(APFloat::IEEEhalf(),
4795                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4796 
4797       // This can return overflow, underflow, or inexact; we don't care.
4798       // FIXME need to be more flexible about rounding mode.
4799       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4800                         APFloat::rmNearestTiesToEven, &Ignored);
4801       return getConstantFP(FPV, DL, VT);
4802     }
4803     case ISD::STEP_VECTOR: {
4804       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4805         return V;
4806       break;
4807     }
4808     }
4809   }
4810 
4811   // Constant fold unary operations with a floating point constant operand.
4812   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4813     APFloat V = C->getValueAPF();    // make copy
4814     switch (Opcode) {
4815     case ISD::FNEG:
4816       V.changeSign();
4817       return getConstantFP(V, DL, VT);
4818     case ISD::FABS:
4819       V.clearSign();
4820       return getConstantFP(V, DL, VT);
4821     case ISD::FCEIL: {
4822       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4823       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4824         return getConstantFP(V, DL, VT);
4825       break;
4826     }
4827     case ISD::FTRUNC: {
4828       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4829       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4830         return getConstantFP(V, DL, VT);
4831       break;
4832     }
4833     case ISD::FFLOOR: {
4834       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4835       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4836         return getConstantFP(V, DL, VT);
4837       break;
4838     }
4839     case ISD::FP_EXTEND: {
4840       bool ignored;
4841       // This can return overflow, underflow, or inexact; we don't care.
4842       // FIXME need to be more flexible about rounding mode.
4843       (void)V.convert(EVTToAPFloatSemantics(VT),
4844                       APFloat::rmNearestTiesToEven, &ignored);
4845       return getConstantFP(V, DL, VT);
4846     }
4847     case ISD::FP_TO_SINT:
4848     case ISD::FP_TO_UINT: {
4849       bool ignored;
4850       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4851       // FIXME need to be more flexible about rounding mode.
4852       APFloat::opStatus s =
4853           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4854       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4855         break;
4856       return getConstant(IntVal, DL, VT);
4857     }
4858     case ISD::BITCAST:
4859       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4860         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4861       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4862         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4863       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4864         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4865       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4866         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4867       break;
4868     case ISD::FP_TO_FP16: {
4869       bool Ignored;
4870       // This can return overflow, underflow, or inexact; we don't care.
4871       // FIXME need to be more flexible about rounding mode.
4872       (void)V.convert(APFloat::IEEEhalf(),
4873                       APFloat::rmNearestTiesToEven, &Ignored);
4874       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4875     }
4876     }
4877   }
4878 
4879   // Constant fold unary operations with a vector integer or float operand.
4880   switch (Opcode) {
4881   default:
4882     // FIXME: Entirely reasonable to perform folding of other unary
4883     // operations here as the need arises.
4884     break;
4885   case ISD::FNEG:
4886   case ISD::FABS:
4887   case ISD::FCEIL:
4888   case ISD::FTRUNC:
4889   case ISD::FFLOOR:
4890   case ISD::FP_EXTEND:
4891   case ISD::FP_TO_SINT:
4892   case ISD::FP_TO_UINT:
4893   case ISD::TRUNCATE:
4894   case ISD::ANY_EXTEND:
4895   case ISD::ZERO_EXTEND:
4896   case ISD::SIGN_EXTEND:
4897   case ISD::UINT_TO_FP:
4898   case ISD::SINT_TO_FP:
4899   case ISD::ABS:
4900   case ISD::BITREVERSE:
4901   case ISD::BSWAP:
4902   case ISD::CTLZ:
4903   case ISD::CTLZ_ZERO_UNDEF:
4904   case ISD::CTTZ:
4905   case ISD::CTTZ_ZERO_UNDEF:
4906   case ISD::CTPOP: {
4907     SDValue Ops = {Operand};
4908     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
4909       return Fold;
4910   }
4911   }
4912 
4913   unsigned OpOpcode = Operand.getNode()->getOpcode();
4914   switch (Opcode) {
4915   case ISD::STEP_VECTOR:
4916     assert(VT.isScalableVector() &&
4917            "STEP_VECTOR can only be used with scalable types");
4918     assert(OpOpcode == ISD::TargetConstant &&
4919            VT.getVectorElementType() == Operand.getValueType() &&
4920            "Unexpected step operand");
4921     break;
4922   case ISD::FREEZE:
4923     assert(VT == Operand.getValueType() && "Unexpected VT!");
4924     break;
4925   case ISD::TokenFactor:
4926   case ISD::MERGE_VALUES:
4927   case ISD::CONCAT_VECTORS:
4928     return Operand;         // Factor, merge or concat of one node?  No need.
4929   case ISD::BUILD_VECTOR: {
4930     // Attempt to simplify BUILD_VECTOR.
4931     SDValue Ops[] = {Operand};
4932     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4933       return V;
4934     break;
4935   }
4936   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4937   case ISD::FP_EXTEND:
4938     assert(VT.isFloatingPoint() &&
4939            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4940     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4941     assert((!VT.isVector() ||
4942             VT.getVectorElementCount() ==
4943             Operand.getValueType().getVectorElementCount()) &&
4944            "Vector element count mismatch!");
4945     assert(Operand.getValueType().bitsLT(VT) &&
4946            "Invalid fpext node, dst < src!");
4947     if (Operand.isUndef())
4948       return getUNDEF(VT);
4949     break;
4950   case ISD::FP_TO_SINT:
4951   case ISD::FP_TO_UINT:
4952     if (Operand.isUndef())
4953       return getUNDEF(VT);
4954     break;
4955   case ISD::SINT_TO_FP:
4956   case ISD::UINT_TO_FP:
4957     // [us]itofp(undef) = 0, because the result value is bounded.
4958     if (Operand.isUndef())
4959       return getConstantFP(0.0, DL, VT);
4960     break;
4961   case ISD::SIGN_EXTEND:
4962     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4963            "Invalid SIGN_EXTEND!");
4964     assert(VT.isVector() == Operand.getValueType().isVector() &&
4965            "SIGN_EXTEND result type type should be vector iff the operand "
4966            "type is vector!");
4967     if (Operand.getValueType() == VT) return Operand;   // noop extension
4968     assert((!VT.isVector() ||
4969             VT.getVectorElementCount() ==
4970                 Operand.getValueType().getVectorElementCount()) &&
4971            "Vector element count mismatch!");
4972     assert(Operand.getValueType().bitsLT(VT) &&
4973            "Invalid sext node, dst < src!");
4974     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4975       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4976     if (OpOpcode == ISD::UNDEF)
4977       // sext(undef) = 0, because the top bits will all be the same.
4978       return getConstant(0, DL, VT);
4979     break;
4980   case ISD::ZERO_EXTEND:
4981     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4982            "Invalid ZERO_EXTEND!");
4983     assert(VT.isVector() == Operand.getValueType().isVector() &&
4984            "ZERO_EXTEND result type type should be vector iff the operand "
4985            "type is vector!");
4986     if (Operand.getValueType() == VT) return Operand;   // noop extension
4987     assert((!VT.isVector() ||
4988             VT.getVectorElementCount() ==
4989                 Operand.getValueType().getVectorElementCount()) &&
4990            "Vector element count mismatch!");
4991     assert(Operand.getValueType().bitsLT(VT) &&
4992            "Invalid zext node, dst < src!");
4993     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4994       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4995     if (OpOpcode == ISD::UNDEF)
4996       // zext(undef) = 0, because the top bits will be zero.
4997       return getConstant(0, DL, VT);
4998     break;
4999   case ISD::ANY_EXTEND:
5000     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5001            "Invalid ANY_EXTEND!");
5002     assert(VT.isVector() == Operand.getValueType().isVector() &&
5003            "ANY_EXTEND result type type should be vector iff the operand "
5004            "type is vector!");
5005     if (Operand.getValueType() == VT) return Operand;   // noop extension
5006     assert((!VT.isVector() ||
5007             VT.getVectorElementCount() ==
5008                 Operand.getValueType().getVectorElementCount()) &&
5009            "Vector element count mismatch!");
5010     assert(Operand.getValueType().bitsLT(VT) &&
5011            "Invalid anyext node, dst < src!");
5012 
5013     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5014         OpOpcode == ISD::ANY_EXTEND)
5015       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5016       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5017     if (OpOpcode == ISD::UNDEF)
5018       return getUNDEF(VT);
5019 
5020     // (ext (trunc x)) -> x
5021     if (OpOpcode == ISD::TRUNCATE) {
5022       SDValue OpOp = Operand.getOperand(0);
5023       if (OpOp.getValueType() == VT) {
5024         transferDbgValues(Operand, OpOp);
5025         return OpOp;
5026       }
5027     }
5028     break;
5029   case ISD::TRUNCATE:
5030     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5031            "Invalid TRUNCATE!");
5032     assert(VT.isVector() == Operand.getValueType().isVector() &&
5033            "TRUNCATE result type type should be vector iff the operand "
5034            "type is vector!");
5035     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5036     assert((!VT.isVector() ||
5037             VT.getVectorElementCount() ==
5038                 Operand.getValueType().getVectorElementCount()) &&
5039            "Vector element count mismatch!");
5040     assert(Operand.getValueType().bitsGT(VT) &&
5041            "Invalid truncate node, src < dst!");
5042     if (OpOpcode == ISD::TRUNCATE)
5043       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5044     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5045         OpOpcode == ISD::ANY_EXTEND) {
5046       // If the source is smaller than the dest, we still need an extend.
5047       if (Operand.getOperand(0).getValueType().getScalarType()
5048             .bitsLT(VT.getScalarType()))
5049         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5050       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5051         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5052       return Operand.getOperand(0);
5053     }
5054     if (OpOpcode == ISD::UNDEF)
5055       return getUNDEF(VT);
5056     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5057       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5058     break;
5059   case ISD::ANY_EXTEND_VECTOR_INREG:
5060   case ISD::ZERO_EXTEND_VECTOR_INREG:
5061   case ISD::SIGN_EXTEND_VECTOR_INREG:
5062     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5063     assert(Operand.getValueType().bitsLE(VT) &&
5064            "The input must be the same size or smaller than the result.");
5065     assert(VT.getVectorMinNumElements() <
5066                Operand.getValueType().getVectorMinNumElements() &&
5067            "The destination vector type must have fewer lanes than the input.");
5068     break;
5069   case ISD::ABS:
5070     assert(VT.isInteger() && VT == Operand.getValueType() &&
5071            "Invalid ABS!");
5072     if (OpOpcode == ISD::UNDEF)
5073       return getUNDEF(VT);
5074     break;
5075   case ISD::BSWAP:
5076     assert(VT.isInteger() && VT == Operand.getValueType() &&
5077            "Invalid BSWAP!");
5078     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5079            "BSWAP types must be a multiple of 16 bits!");
5080     if (OpOpcode == ISD::UNDEF)
5081       return getUNDEF(VT);
5082     break;
5083   case ISD::BITREVERSE:
5084     assert(VT.isInteger() && VT == Operand.getValueType() &&
5085            "Invalid BITREVERSE!");
5086     if (OpOpcode == ISD::UNDEF)
5087       return getUNDEF(VT);
5088     break;
5089   case ISD::BITCAST:
5090     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5091            "Cannot BITCAST between types of different sizes!");
5092     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5093     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5094       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5095     if (OpOpcode == ISD::UNDEF)
5096       return getUNDEF(VT);
5097     break;
5098   case ISD::SCALAR_TO_VECTOR:
5099     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5100            (VT.getVectorElementType() == Operand.getValueType() ||
5101             (VT.getVectorElementType().isInteger() &&
5102              Operand.getValueType().isInteger() &&
5103              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5104            "Illegal SCALAR_TO_VECTOR node!");
5105     if (OpOpcode == ISD::UNDEF)
5106       return getUNDEF(VT);
5107     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5108     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5109         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5110         Operand.getConstantOperandVal(1) == 0 &&
5111         Operand.getOperand(0).getValueType() == VT)
5112       return Operand.getOperand(0);
5113     break;
5114   case ISD::FNEG:
5115     // Negation of an unknown bag of bits is still completely undefined.
5116     if (OpOpcode == ISD::UNDEF)
5117       return getUNDEF(VT);
5118 
5119     if (OpOpcode == ISD::FNEG)  // --X -> X
5120       return Operand.getOperand(0);
5121     break;
5122   case ISD::FABS:
5123     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5124       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5125     break;
5126   case ISD::VSCALE:
5127     assert(VT == Operand.getValueType() && "Unexpected VT!");
5128     break;
5129   case ISD::CTPOP:
5130     if (Operand.getValueType().getScalarType() == MVT::i1)
5131       return Operand;
5132     break;
5133   case ISD::CTLZ:
5134   case ISD::CTTZ:
5135     if (Operand.getValueType().getScalarType() == MVT::i1)
5136       return getNOT(DL, Operand, Operand.getValueType());
5137     break;
5138   case ISD::VECREDUCE_SMIN:
5139   case ISD::VECREDUCE_UMAX:
5140     if (Operand.getValueType().getScalarType() == MVT::i1)
5141       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5142     break;
5143   case ISD::VECREDUCE_SMAX:
5144   case ISD::VECREDUCE_UMIN:
5145     if (Operand.getValueType().getScalarType() == MVT::i1)
5146       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5147     break;
5148   }
5149 
5150   SDNode *N;
5151   SDVTList VTs = getVTList(VT);
5152   SDValue Ops[] = {Operand};
5153   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5154     FoldingSetNodeID ID;
5155     AddNodeIDNode(ID, Opcode, VTs, Ops);
5156     void *IP = nullptr;
5157     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5158       E->intersectFlagsWith(Flags);
5159       return SDValue(E, 0);
5160     }
5161 
5162     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5163     N->setFlags(Flags);
5164     createOperands(N, Ops);
5165     CSEMap.InsertNode(N, IP);
5166   } else {
5167     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5168     createOperands(N, Ops);
5169   }
5170 
5171   InsertNode(N);
5172   SDValue V = SDValue(N, 0);
5173   NewSDValueDbgMsg(V, "Creating new node: ", this);
5174   return V;
5175 }
5176 
5177 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5178                                        const APInt &C2) {
5179   switch (Opcode) {
5180   case ISD::ADD:  return C1 + C2;
5181   case ISD::SUB:  return C1 - C2;
5182   case ISD::MUL:  return C1 * C2;
5183   case ISD::AND:  return C1 & C2;
5184   case ISD::OR:   return C1 | C2;
5185   case ISD::XOR:  return C1 ^ C2;
5186   case ISD::SHL:  return C1 << C2;
5187   case ISD::SRL:  return C1.lshr(C2);
5188   case ISD::SRA:  return C1.ashr(C2);
5189   case ISD::ROTL: return C1.rotl(C2);
5190   case ISD::ROTR: return C1.rotr(C2);
5191   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5192   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5193   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5194   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5195   case ISD::SADDSAT: return C1.sadd_sat(C2);
5196   case ISD::UADDSAT: return C1.uadd_sat(C2);
5197   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5198   case ISD::USUBSAT: return C1.usub_sat(C2);
5199   case ISD::UDIV:
5200     if (!C2.getBoolValue())
5201       break;
5202     return C1.udiv(C2);
5203   case ISD::UREM:
5204     if (!C2.getBoolValue())
5205       break;
5206     return C1.urem(C2);
5207   case ISD::SDIV:
5208     if (!C2.getBoolValue())
5209       break;
5210     return C1.sdiv(C2);
5211   case ISD::SREM:
5212     if (!C2.getBoolValue())
5213       break;
5214     return C1.srem(C2);
5215   case ISD::MULHS: {
5216     unsigned FullWidth = C1.getBitWidth() * 2;
5217     APInt C1Ext = C1.sext(FullWidth);
5218     APInt C2Ext = C2.sext(FullWidth);
5219     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5220   }
5221   case ISD::MULHU: {
5222     unsigned FullWidth = C1.getBitWidth() * 2;
5223     APInt C1Ext = C1.zext(FullWidth);
5224     APInt C2Ext = C2.zext(FullWidth);
5225     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5226   }
5227   }
5228   return llvm::None;
5229 }
5230 
5231 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5232                                        const GlobalAddressSDNode *GA,
5233                                        const SDNode *N2) {
5234   if (GA->getOpcode() != ISD::GlobalAddress)
5235     return SDValue();
5236   if (!TLI->isOffsetFoldingLegal(GA))
5237     return SDValue();
5238   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5239   if (!C2)
5240     return SDValue();
5241   int64_t Offset = C2->getSExtValue();
5242   switch (Opcode) {
5243   case ISD::ADD: break;
5244   case ISD::SUB: Offset = -uint64_t(Offset); break;
5245   default: return SDValue();
5246   }
5247   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5248                           GA->getOffset() + uint64_t(Offset));
5249 }
5250 
5251 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5252   switch (Opcode) {
5253   case ISD::SDIV:
5254   case ISD::UDIV:
5255   case ISD::SREM:
5256   case ISD::UREM: {
5257     // If a divisor is zero/undef or any element of a divisor vector is
5258     // zero/undef, the whole op is undef.
5259     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5260     SDValue Divisor = Ops[1];
5261     if (Divisor.isUndef() || isNullConstant(Divisor))
5262       return true;
5263 
5264     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5265            llvm::any_of(Divisor->op_values(),
5266                         [](SDValue V) { return V.isUndef() ||
5267                                         isNullConstant(V); });
5268     // TODO: Handle signed overflow.
5269   }
5270   // TODO: Handle oversized shifts.
5271   default:
5272     return false;
5273   }
5274 }
5275 
5276 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5277                                              EVT VT, ArrayRef<SDValue> Ops) {
5278   // If the opcode is a target-specific ISD node, there's nothing we can
5279   // do here and the operand rules may not line up with the below, so
5280   // bail early.
5281   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5282   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5283   // foldCONCAT_VECTORS in getNode before this is called.
5284   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5285     return SDValue();
5286 
5287   unsigned NumOps = Ops.size();
5288   if (NumOps == 0)
5289     return SDValue();
5290 
5291   if (isUndef(Opcode, Ops))
5292     return getUNDEF(VT);
5293 
5294   // Handle the case of two scalars.
5295   if (NumOps == 2) {
5296     // TODO: Move foldConstantFPMath here?
5297 
5298     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5299       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5300         if (C1->isOpaque() || C2->isOpaque())
5301           return SDValue();
5302 
5303         Optional<APInt> FoldAttempt =
5304             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5305         if (!FoldAttempt)
5306           return SDValue();
5307 
5308         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5309         assert((!Folded || !VT.isVector()) &&
5310                "Can't fold vectors ops with scalar operands");
5311         return Folded;
5312       }
5313     }
5314 
5315     // fold (add Sym, c) -> Sym+c
5316     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5317       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5318     if (TLI->isCommutativeBinOp(Opcode))
5319       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5320         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5321   }
5322 
5323   // This is for vector folding only from here on.
5324   if (!VT.isVector())
5325     return SDValue();
5326 
5327   ElementCount NumElts = VT.getVectorElementCount();
5328 
5329   // See if we can fold through bitcasted integer ops.
5330   // TODO: Can we handle undef elements?
5331   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5332       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5333       Ops[0].getOpcode() == ISD::BITCAST &&
5334       Ops[1].getOpcode() == ISD::BITCAST) {
5335     SDValue N1 = peekThroughBitcasts(Ops[0]);
5336     SDValue N2 = peekThroughBitcasts(Ops[1]);
5337     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5338     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5339     EVT BVVT = N1.getValueType();
5340     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5341       bool IsLE = getDataLayout().isLittleEndian();
5342       unsigned EltBits = VT.getScalarSizeInBits();
5343       SmallVector<APInt> RawBits1, RawBits2;
5344       BitVector UndefElts1, UndefElts2;
5345       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5346           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5347           UndefElts1.none() && UndefElts2.none()) {
5348         SmallVector<APInt> RawBits;
5349         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5350           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5351           if (!Fold)
5352             break;
5353           RawBits.push_back(Fold.getValue());
5354         }
5355         if (RawBits.size() == NumElts.getFixedValue()) {
5356           // We have constant folded, but we need to cast this again back to
5357           // the original (possibly legalized) type.
5358           SmallVector<APInt> DstBits;
5359           BitVector DstUndefs;
5360           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5361                                            DstBits, RawBits, DstUndefs,
5362                                            BitVector(RawBits.size(), false));
5363           EVT BVEltVT = BV1->getOperand(0).getValueType();
5364           unsigned BVEltBits = BVEltVT.getSizeInBits();
5365           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5366           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5367             if (DstUndefs[I])
5368               continue;
5369             Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5370           }
5371           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5372         }
5373       }
5374     }
5375   }
5376 
5377   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5378     return !Op.getValueType().isVector() ||
5379            Op.getValueType().getVectorElementCount() == NumElts;
5380   };
5381 
5382   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5383     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5384            Op.getOpcode() == ISD::BUILD_VECTOR ||
5385            Op.getOpcode() == ISD::SPLAT_VECTOR;
5386   };
5387 
5388   // All operands must be vector types with the same number of elements as
5389   // the result type and must be either UNDEF or a build/splat vector
5390   // or UNDEF scalars.
5391   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5392       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5393     return SDValue();
5394 
5395   // If we are comparing vectors, then the result needs to be a i1 boolean
5396   // that is then sign-extended back to the legal result type.
5397   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5398 
5399   // Find legal integer scalar type for constant promotion and
5400   // ensure that its scalar size is at least as large as source.
5401   EVT LegalSVT = VT.getScalarType();
5402   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5403     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5404     if (LegalSVT.bitsLT(VT.getScalarType()))
5405       return SDValue();
5406   }
5407 
5408   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5409   // only have one operand to check. For fixed-length vector types we may have
5410   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5411   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5412 
5413   // Constant fold each scalar lane separately.
5414   SmallVector<SDValue, 4> ScalarResults;
5415   for (unsigned I = 0; I != NumVectorElts; I++) {
5416     SmallVector<SDValue, 4> ScalarOps;
5417     for (SDValue Op : Ops) {
5418       EVT InSVT = Op.getValueType().getScalarType();
5419       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5420           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5421         if (Op.isUndef())
5422           ScalarOps.push_back(getUNDEF(InSVT));
5423         else
5424           ScalarOps.push_back(Op);
5425         continue;
5426       }
5427 
5428       SDValue ScalarOp =
5429           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5430       EVT ScalarVT = ScalarOp.getValueType();
5431 
5432       // Build vector (integer) scalar operands may need implicit
5433       // truncation - do this before constant folding.
5434       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5435         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5436 
5437       ScalarOps.push_back(ScalarOp);
5438     }
5439 
5440     // Constant fold the scalar operands.
5441     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5442 
5443     // Legalize the (integer) scalar constant if necessary.
5444     if (LegalSVT != SVT)
5445       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5446 
5447     // Scalar folding only succeeded if the result is a constant or UNDEF.
5448     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5449         ScalarResult.getOpcode() != ISD::ConstantFP)
5450       return SDValue();
5451     ScalarResults.push_back(ScalarResult);
5452   }
5453 
5454   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5455                                    : getBuildVector(VT, DL, ScalarResults);
5456   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5457   return V;
5458 }
5459 
5460 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5461                                          EVT VT, SDValue N1, SDValue N2) {
5462   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5463   //       should. That will require dealing with a potentially non-default
5464   //       rounding mode, checking the "opStatus" return value from the APFloat
5465   //       math calculations, and possibly other variations.
5466   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5467   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5468   if (N1CFP && N2CFP) {
5469     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5470     switch (Opcode) {
5471     case ISD::FADD:
5472       C1.add(C2, APFloat::rmNearestTiesToEven);
5473       return getConstantFP(C1, DL, VT);
5474     case ISD::FSUB:
5475       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5476       return getConstantFP(C1, DL, VT);
5477     case ISD::FMUL:
5478       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5479       return getConstantFP(C1, DL, VT);
5480     case ISD::FDIV:
5481       C1.divide(C2, APFloat::rmNearestTiesToEven);
5482       return getConstantFP(C1, DL, VT);
5483     case ISD::FREM:
5484       C1.mod(C2);
5485       return getConstantFP(C1, DL, VT);
5486     case ISD::FCOPYSIGN:
5487       C1.copySign(C2);
5488       return getConstantFP(C1, DL, VT);
5489     default: break;
5490     }
5491   }
5492   if (N1CFP && Opcode == ISD::FP_ROUND) {
5493     APFloat C1 = N1CFP->getValueAPF();    // make copy
5494     bool Unused;
5495     // This can return overflow, underflow, or inexact; we don't care.
5496     // FIXME need to be more flexible about rounding mode.
5497     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5498                       &Unused);
5499     return getConstantFP(C1, DL, VT);
5500   }
5501 
5502   switch (Opcode) {
5503   case ISD::FSUB:
5504     // -0.0 - undef --> undef (consistent with "fneg undef")
5505     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5506       return getUNDEF(VT);
5507     LLVM_FALLTHROUGH;
5508 
5509   case ISD::FADD:
5510   case ISD::FMUL:
5511   case ISD::FDIV:
5512   case ISD::FREM:
5513     // If both operands are undef, the result is undef. If 1 operand is undef,
5514     // the result is NaN. This should match the behavior of the IR optimizer.
5515     if (N1.isUndef() && N2.isUndef())
5516       return getUNDEF(VT);
5517     if (N1.isUndef() || N2.isUndef())
5518       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5519   }
5520   return SDValue();
5521 }
5522 
5523 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5524   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5525 
5526   // There's no need to assert on a byte-aligned pointer. All pointers are at
5527   // least byte aligned.
5528   if (A == Align(1))
5529     return Val;
5530 
5531   FoldingSetNodeID ID;
5532   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5533   ID.AddInteger(A.value());
5534 
5535   void *IP = nullptr;
5536   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5537     return SDValue(E, 0);
5538 
5539   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5540                                          Val.getValueType(), A);
5541   createOperands(N, {Val});
5542 
5543   CSEMap.InsertNode(N, IP);
5544   InsertNode(N);
5545 
5546   SDValue V(N, 0);
5547   NewSDValueDbgMsg(V, "Creating new node: ", this);
5548   return V;
5549 }
5550 
5551 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5552                               SDValue N1, SDValue N2) {
5553   SDNodeFlags Flags;
5554   if (Inserter)
5555     Flags = Inserter->getFlags();
5556   return getNode(Opcode, DL, VT, N1, N2, Flags);
5557 }
5558 
5559 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5560                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5561   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5562          N2.getOpcode() != ISD::DELETED_NODE &&
5563          "Operand is DELETED_NODE!");
5564   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5565   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5566   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5567   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5568 
5569   // Canonicalize constant to RHS if commutative.
5570   if (TLI->isCommutativeBinOp(Opcode)) {
5571     if (N1C && !N2C) {
5572       std::swap(N1C, N2C);
5573       std::swap(N1, N2);
5574     } else if (N1CFP && !N2CFP) {
5575       std::swap(N1CFP, N2CFP);
5576       std::swap(N1, N2);
5577     }
5578   }
5579 
5580   switch (Opcode) {
5581   default: break;
5582   case ISD::TokenFactor:
5583     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5584            N2.getValueType() == MVT::Other && "Invalid token factor!");
5585     // Fold trivial token factors.
5586     if (N1.getOpcode() == ISD::EntryToken) return N2;
5587     if (N2.getOpcode() == ISD::EntryToken) return N1;
5588     if (N1 == N2) return N1;
5589     break;
5590   case ISD::BUILD_VECTOR: {
5591     // Attempt to simplify BUILD_VECTOR.
5592     SDValue Ops[] = {N1, N2};
5593     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5594       return V;
5595     break;
5596   }
5597   case ISD::CONCAT_VECTORS: {
5598     SDValue Ops[] = {N1, N2};
5599     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5600       return V;
5601     break;
5602   }
5603   case ISD::AND:
5604     assert(VT.isInteger() && "This operator does not apply to FP types!");
5605     assert(N1.getValueType() == N2.getValueType() &&
5606            N1.getValueType() == VT && "Binary operator types must match!");
5607     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5608     // worth handling here.
5609     if (N2C && N2C->isZero())
5610       return N2;
5611     if (N2C && N2C->isAllOnes()) // X & -1 -> X
5612       return N1;
5613     break;
5614   case ISD::OR:
5615   case ISD::XOR:
5616   case ISD::ADD:
5617   case ISD::SUB:
5618     assert(VT.isInteger() && "This operator does not apply to FP types!");
5619     assert(N1.getValueType() == N2.getValueType() &&
5620            N1.getValueType() == VT && "Binary operator types must match!");
5621     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5622     // it's worth handling here.
5623     if (N2C && N2C->isZero())
5624       return N1;
5625     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5626         VT.getVectorElementType() == MVT::i1)
5627       return getNode(ISD::XOR, DL, VT, N1, N2);
5628     break;
5629   case ISD::MUL:
5630     assert(VT.isInteger() && "This operator does not apply to FP types!");
5631     assert(N1.getValueType() == N2.getValueType() &&
5632            N1.getValueType() == VT && "Binary operator types must match!");
5633     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5634       return getNode(ISD::AND, DL, VT, N1, N2);
5635     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5636       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5637       const APInt &N2CImm = N2C->getAPIntValue();
5638       return getVScale(DL, VT, MulImm * N2CImm);
5639     }
5640     break;
5641   case ISD::UDIV:
5642   case ISD::UREM:
5643   case ISD::MULHU:
5644   case ISD::MULHS:
5645   case ISD::SDIV:
5646   case ISD::SREM:
5647   case ISD::SADDSAT:
5648   case ISD::SSUBSAT:
5649   case ISD::UADDSAT:
5650   case ISD::USUBSAT:
5651     assert(VT.isInteger() && "This operator does not apply to FP types!");
5652     assert(N1.getValueType() == N2.getValueType() &&
5653            N1.getValueType() == VT && "Binary operator types must match!");
5654     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5655       // fold (add_sat x, y) -> (or x, y) for bool types.
5656       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5657         return getNode(ISD::OR, DL, VT, N1, N2);
5658       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5659       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5660         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5661     }
5662     break;
5663   case ISD::SMIN:
5664   case ISD::UMAX:
5665     assert(VT.isInteger() && "This operator does not apply to FP types!");
5666     assert(N1.getValueType() == N2.getValueType() &&
5667            N1.getValueType() == VT && "Binary operator types must match!");
5668     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5669       return getNode(ISD::OR, DL, VT, N1, N2);
5670     break;
5671   case ISD::SMAX:
5672   case ISD::UMIN:
5673     assert(VT.isInteger() && "This operator does not apply to FP types!");
5674     assert(N1.getValueType() == N2.getValueType() &&
5675            N1.getValueType() == VT && "Binary operator types must match!");
5676     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5677       return getNode(ISD::AND, DL, VT, N1, N2);
5678     break;
5679   case ISD::FADD:
5680   case ISD::FSUB:
5681   case ISD::FMUL:
5682   case ISD::FDIV:
5683   case ISD::FREM:
5684     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5685     assert(N1.getValueType() == N2.getValueType() &&
5686            N1.getValueType() == VT && "Binary operator types must match!");
5687     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5688       return V;
5689     break;
5690   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5691     assert(N1.getValueType() == VT &&
5692            N1.getValueType().isFloatingPoint() &&
5693            N2.getValueType().isFloatingPoint() &&
5694            "Invalid FCOPYSIGN!");
5695     break;
5696   case ISD::SHL:
5697     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5698       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5699       const APInt &ShiftImm = N2C->getAPIntValue();
5700       return getVScale(DL, VT, MulImm << ShiftImm);
5701     }
5702     LLVM_FALLTHROUGH;
5703   case ISD::SRA:
5704   case ISD::SRL:
5705     if (SDValue V = simplifyShift(N1, N2))
5706       return V;
5707     LLVM_FALLTHROUGH;
5708   case ISD::ROTL:
5709   case ISD::ROTR:
5710     assert(VT == N1.getValueType() &&
5711            "Shift operators return type must be the same as their first arg");
5712     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5713            "Shifts only work on integers");
5714     assert((!VT.isVector() || VT == N2.getValueType()) &&
5715            "Vector shift amounts must be in the same as their first arg");
5716     // Verify that the shift amount VT is big enough to hold valid shift
5717     // amounts.  This catches things like trying to shift an i1024 value by an
5718     // i8, which is easy to fall into in generic code that uses
5719     // TLI.getShiftAmount().
5720     assert(N2.getValueType().getScalarSizeInBits() >=
5721                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5722            "Invalid use of small shift amount with oversized value!");
5723 
5724     // Always fold shifts of i1 values so the code generator doesn't need to
5725     // handle them.  Since we know the size of the shift has to be less than the
5726     // size of the value, the shift/rotate count is guaranteed to be zero.
5727     if (VT == MVT::i1)
5728       return N1;
5729     if (N2C && N2C->isZero())
5730       return N1;
5731     break;
5732   case ISD::FP_ROUND:
5733     assert(VT.isFloatingPoint() &&
5734            N1.getValueType().isFloatingPoint() &&
5735            VT.bitsLE(N1.getValueType()) &&
5736            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5737            "Invalid FP_ROUND!");
5738     if (N1.getValueType() == VT) return N1;  // noop conversion.
5739     break;
5740   case ISD::AssertSext:
5741   case ISD::AssertZext: {
5742     EVT EVT = cast<VTSDNode>(N2)->getVT();
5743     assert(VT == N1.getValueType() && "Not an inreg extend!");
5744     assert(VT.isInteger() && EVT.isInteger() &&
5745            "Cannot *_EXTEND_INREG FP types");
5746     assert(!EVT.isVector() &&
5747            "AssertSExt/AssertZExt type should be the vector element type "
5748            "rather than the vector type!");
5749     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5750     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5751     break;
5752   }
5753   case ISD::SIGN_EXTEND_INREG: {
5754     EVT EVT = cast<VTSDNode>(N2)->getVT();
5755     assert(VT == N1.getValueType() && "Not an inreg extend!");
5756     assert(VT.isInteger() && EVT.isInteger() &&
5757            "Cannot *_EXTEND_INREG FP types");
5758     assert(EVT.isVector() == VT.isVector() &&
5759            "SIGN_EXTEND_INREG type should be vector iff the operand "
5760            "type is vector!");
5761     assert((!EVT.isVector() ||
5762             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5763            "Vector element counts must match in SIGN_EXTEND_INREG");
5764     assert(EVT.bitsLE(VT) && "Not extending!");
5765     if (EVT == VT) return N1;  // Not actually extending
5766 
5767     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5768       unsigned FromBits = EVT.getScalarSizeInBits();
5769       Val <<= Val.getBitWidth() - FromBits;
5770       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5771       return getConstant(Val, DL, ConstantVT);
5772     };
5773 
5774     if (N1C) {
5775       const APInt &Val = N1C->getAPIntValue();
5776       return SignExtendInReg(Val, VT);
5777     }
5778 
5779     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5780       SmallVector<SDValue, 8> Ops;
5781       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5782       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5783         SDValue Op = N1.getOperand(i);
5784         if (Op.isUndef()) {
5785           Ops.push_back(getUNDEF(OpVT));
5786           continue;
5787         }
5788         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5789         APInt Val = C->getAPIntValue();
5790         Ops.push_back(SignExtendInReg(Val, OpVT));
5791       }
5792       return getBuildVector(VT, DL, Ops);
5793     }
5794     break;
5795   }
5796   case ISD::FP_TO_SINT_SAT:
5797   case ISD::FP_TO_UINT_SAT: {
5798     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5799            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5800     assert(N1.getValueType().isVector() == VT.isVector() &&
5801            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5802            "vector!");
5803     assert((!VT.isVector() || VT.getVectorNumElements() ==
5804                                   N1.getValueType().getVectorNumElements()) &&
5805            "Vector element counts must match in FP_TO_*INT_SAT");
5806     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5807            "Type to saturate to must be a scalar.");
5808     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5809            "Not extending!");
5810     break;
5811   }
5812   case ISD::EXTRACT_VECTOR_ELT:
5813     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5814            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5815              element type of the vector.");
5816 
5817     // Extract from an undefined value or using an undefined index is undefined.
5818     if (N1.isUndef() || N2.isUndef())
5819       return getUNDEF(VT);
5820 
5821     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5822     // vectors. For scalable vectors we will provide appropriate support for
5823     // dealing with arbitrary indices.
5824     if (N2C && N1.getValueType().isFixedLengthVector() &&
5825         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5826       return getUNDEF(VT);
5827 
5828     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5829     // expanding copies of large vectors from registers. This only works for
5830     // fixed length vectors, since we need to know the exact number of
5831     // elements.
5832     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5833         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5834       unsigned Factor =
5835         N1.getOperand(0).getValueType().getVectorNumElements();
5836       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5837                      N1.getOperand(N2C->getZExtValue() / Factor),
5838                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5839     }
5840 
5841     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5842     // lowering is expanding large vector constants.
5843     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5844                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5845       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5846               N1.getValueType().isFixedLengthVector()) &&
5847              "BUILD_VECTOR used for scalable vectors");
5848       unsigned Index =
5849           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5850       SDValue Elt = N1.getOperand(Index);
5851 
5852       if (VT != Elt.getValueType())
5853         // If the vector element type is not legal, the BUILD_VECTOR operands
5854         // are promoted and implicitly truncated, and the result implicitly
5855         // extended. Make that explicit here.
5856         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5857 
5858       return Elt;
5859     }
5860 
5861     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5862     // operations are lowered to scalars.
5863     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5864       // If the indices are the same, return the inserted element else
5865       // if the indices are known different, extract the element from
5866       // the original vector.
5867       SDValue N1Op2 = N1.getOperand(2);
5868       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5869 
5870       if (N1Op2C && N2C) {
5871         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5872           if (VT == N1.getOperand(1).getValueType())
5873             return N1.getOperand(1);
5874           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5875         }
5876         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5877       }
5878     }
5879 
5880     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5881     // when vector types are scalarized and v1iX is legal.
5882     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5883     // Here we are completely ignoring the extract element index (N2),
5884     // which is fine for fixed width vectors, since any index other than 0
5885     // is undefined anyway. However, this cannot be ignored for scalable
5886     // vectors - in theory we could support this, but we don't want to do this
5887     // without a profitability check.
5888     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5889         N1.getValueType().isFixedLengthVector() &&
5890         N1.getValueType().getVectorNumElements() == 1) {
5891       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5892                      N1.getOperand(1));
5893     }
5894     break;
5895   case ISD::EXTRACT_ELEMENT:
5896     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5897     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5898            (N1.getValueType().isInteger() == VT.isInteger()) &&
5899            N1.getValueType() != VT &&
5900            "Wrong types for EXTRACT_ELEMENT!");
5901 
5902     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5903     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5904     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5905     if (N1.getOpcode() == ISD::BUILD_PAIR)
5906       return N1.getOperand(N2C->getZExtValue());
5907 
5908     // EXTRACT_ELEMENT of a constant int is also very common.
5909     if (N1C) {
5910       unsigned ElementSize = VT.getSizeInBits();
5911       unsigned Shift = ElementSize * N2C->getZExtValue();
5912       const APInt &Val = N1C->getAPIntValue();
5913       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5914     }
5915     break;
5916   case ISD::EXTRACT_SUBVECTOR: {
5917     EVT N1VT = N1.getValueType();
5918     assert(VT.isVector() && N1VT.isVector() &&
5919            "Extract subvector VTs must be vectors!");
5920     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5921            "Extract subvector VTs must have the same element type!");
5922     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5923            "Cannot extract a scalable vector from a fixed length vector!");
5924     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5925             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5926            "Extract subvector must be from larger vector to smaller vector!");
5927     assert(N2C && "Extract subvector index must be a constant");
5928     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5929             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5930                 N1VT.getVectorMinNumElements()) &&
5931            "Extract subvector overflow!");
5932     assert(N2C->getAPIntValue().getBitWidth() ==
5933                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5934            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5935 
5936     // Trivial extraction.
5937     if (VT == N1VT)
5938       return N1;
5939 
5940     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5941     if (N1.isUndef())
5942       return getUNDEF(VT);
5943 
5944     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5945     // the concat have the same type as the extract.
5946     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5947         VT == N1.getOperand(0).getValueType()) {
5948       unsigned Factor = VT.getVectorMinNumElements();
5949       return N1.getOperand(N2C->getZExtValue() / Factor);
5950     }
5951 
5952     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5953     // during shuffle legalization.
5954     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5955         VT == N1.getOperand(1).getValueType())
5956       return N1.getOperand(1);
5957     break;
5958   }
5959   }
5960 
5961   // Perform trivial constant folding.
5962   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5963     return SV;
5964 
5965   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5966     return V;
5967 
5968   // Canonicalize an UNDEF to the RHS, even over a constant.
5969   if (N1.isUndef()) {
5970     if (TLI->isCommutativeBinOp(Opcode)) {
5971       std::swap(N1, N2);
5972     } else {
5973       switch (Opcode) {
5974       case ISD::SIGN_EXTEND_INREG:
5975       case ISD::SUB:
5976         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5977       case ISD::UDIV:
5978       case ISD::SDIV:
5979       case ISD::UREM:
5980       case ISD::SREM:
5981       case ISD::SSUBSAT:
5982       case ISD::USUBSAT:
5983         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5984       }
5985     }
5986   }
5987 
5988   // Fold a bunch of operators when the RHS is undef.
5989   if (N2.isUndef()) {
5990     switch (Opcode) {
5991     case ISD::XOR:
5992       if (N1.isUndef())
5993         // Handle undef ^ undef -> 0 special case. This is a common
5994         // idiom (misuse).
5995         return getConstant(0, DL, VT);
5996       LLVM_FALLTHROUGH;
5997     case ISD::ADD:
5998     case ISD::SUB:
5999     case ISD::UDIV:
6000     case ISD::SDIV:
6001     case ISD::UREM:
6002     case ISD::SREM:
6003       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6004     case ISD::MUL:
6005     case ISD::AND:
6006     case ISD::SSUBSAT:
6007     case ISD::USUBSAT:
6008       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6009     case ISD::OR:
6010     case ISD::SADDSAT:
6011     case ISD::UADDSAT:
6012       return getAllOnesConstant(DL, VT);
6013     }
6014   }
6015 
6016   // Memoize this node if possible.
6017   SDNode *N;
6018   SDVTList VTs = getVTList(VT);
6019   SDValue Ops[] = {N1, N2};
6020   if (VT != MVT::Glue) {
6021     FoldingSetNodeID ID;
6022     AddNodeIDNode(ID, Opcode, VTs, Ops);
6023     void *IP = nullptr;
6024     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6025       E->intersectFlagsWith(Flags);
6026       return SDValue(E, 0);
6027     }
6028 
6029     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6030     N->setFlags(Flags);
6031     createOperands(N, Ops);
6032     CSEMap.InsertNode(N, IP);
6033   } else {
6034     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6035     createOperands(N, Ops);
6036   }
6037 
6038   InsertNode(N);
6039   SDValue V = SDValue(N, 0);
6040   NewSDValueDbgMsg(V, "Creating new node: ", this);
6041   return V;
6042 }
6043 
6044 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6045                               SDValue N1, SDValue N2, SDValue N3) {
6046   SDNodeFlags Flags;
6047   if (Inserter)
6048     Flags = Inserter->getFlags();
6049   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6050 }
6051 
6052 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6053                               SDValue N1, SDValue N2, SDValue N3,
6054                               const SDNodeFlags Flags) {
6055   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6056          N2.getOpcode() != ISD::DELETED_NODE &&
6057          N3.getOpcode() != ISD::DELETED_NODE &&
6058          "Operand is DELETED_NODE!");
6059   // Perform various simplifications.
6060   switch (Opcode) {
6061   case ISD::FMA: {
6062     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6063     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6064            N3.getValueType() == VT && "FMA types must match!");
6065     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6066     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6067     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6068     if (N1CFP && N2CFP && N3CFP) {
6069       APFloat  V1 = N1CFP->getValueAPF();
6070       const APFloat &V2 = N2CFP->getValueAPF();
6071       const APFloat &V3 = N3CFP->getValueAPF();
6072       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6073       return getConstantFP(V1, DL, VT);
6074     }
6075     break;
6076   }
6077   case ISD::BUILD_VECTOR: {
6078     // Attempt to simplify BUILD_VECTOR.
6079     SDValue Ops[] = {N1, N2, N3};
6080     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6081       return V;
6082     break;
6083   }
6084   case ISD::CONCAT_VECTORS: {
6085     SDValue Ops[] = {N1, N2, N3};
6086     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6087       return V;
6088     break;
6089   }
6090   case ISD::SETCC: {
6091     assert(VT.isInteger() && "SETCC result type must be an integer!");
6092     assert(N1.getValueType() == N2.getValueType() &&
6093            "SETCC operands must have the same type!");
6094     assert(VT.isVector() == N1.getValueType().isVector() &&
6095            "SETCC type should be vector iff the operand type is vector!");
6096     assert((!VT.isVector() || VT.getVectorElementCount() ==
6097                                   N1.getValueType().getVectorElementCount()) &&
6098            "SETCC vector element counts must match!");
6099     // Use FoldSetCC to simplify SETCC's.
6100     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6101       return V;
6102     // Vector constant folding.
6103     SDValue Ops[] = {N1, N2, N3};
6104     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6105       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6106       return V;
6107     }
6108     break;
6109   }
6110   case ISD::SELECT:
6111   case ISD::VSELECT:
6112     if (SDValue V = simplifySelect(N1, N2, N3))
6113       return V;
6114     break;
6115   case ISD::VECTOR_SHUFFLE:
6116     llvm_unreachable("should use getVectorShuffle constructor!");
6117   case ISD::VECTOR_SPLICE: {
6118     if (cast<ConstantSDNode>(N3)->isNullValue())
6119       return N1;
6120     break;
6121   }
6122   case ISD::INSERT_VECTOR_ELT: {
6123     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6124     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6125     // for scalable vectors where we will generate appropriate code to
6126     // deal with out-of-bounds cases correctly.
6127     if (N3C && N1.getValueType().isFixedLengthVector() &&
6128         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6129       return getUNDEF(VT);
6130 
6131     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6132     if (N3.isUndef())
6133       return getUNDEF(VT);
6134 
6135     // If the inserted element is an UNDEF, just use the input vector.
6136     if (N2.isUndef())
6137       return N1;
6138 
6139     break;
6140   }
6141   case ISD::INSERT_SUBVECTOR: {
6142     // Inserting undef into undef is still undef.
6143     if (N1.isUndef() && N2.isUndef())
6144       return getUNDEF(VT);
6145 
6146     EVT N2VT = N2.getValueType();
6147     assert(VT == N1.getValueType() &&
6148            "Dest and insert subvector source types must match!");
6149     assert(VT.isVector() && N2VT.isVector() &&
6150            "Insert subvector VTs must be vectors!");
6151     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6152            "Cannot insert a scalable vector into a fixed length vector!");
6153     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6154             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6155            "Insert subvector must be from smaller vector to larger vector!");
6156     assert(isa<ConstantSDNode>(N3) &&
6157            "Insert subvector index must be constant");
6158     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6159             (N2VT.getVectorMinNumElements() +
6160              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6161                 VT.getVectorMinNumElements()) &&
6162            "Insert subvector overflow!");
6163     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6164                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6165            "Constant index for INSERT_SUBVECTOR has an invalid size");
6166 
6167     // Trivial insertion.
6168     if (VT == N2VT)
6169       return N2;
6170 
6171     // If this is an insert of an extracted vector into an undef vector, we
6172     // can just use the input to the extract.
6173     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6174         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6175       return N2.getOperand(0);
6176     break;
6177   }
6178   case ISD::BITCAST:
6179     // Fold bit_convert nodes from a type to themselves.
6180     if (N1.getValueType() == VT)
6181       return N1;
6182     break;
6183   }
6184 
6185   // Memoize node if it doesn't produce a flag.
6186   SDNode *N;
6187   SDVTList VTs = getVTList(VT);
6188   SDValue Ops[] = {N1, N2, N3};
6189   if (VT != MVT::Glue) {
6190     FoldingSetNodeID ID;
6191     AddNodeIDNode(ID, Opcode, VTs, Ops);
6192     void *IP = nullptr;
6193     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6194       E->intersectFlagsWith(Flags);
6195       return SDValue(E, 0);
6196     }
6197 
6198     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6199     N->setFlags(Flags);
6200     createOperands(N, Ops);
6201     CSEMap.InsertNode(N, IP);
6202   } else {
6203     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6204     createOperands(N, Ops);
6205   }
6206 
6207   InsertNode(N);
6208   SDValue V = SDValue(N, 0);
6209   NewSDValueDbgMsg(V, "Creating new node: ", this);
6210   return V;
6211 }
6212 
6213 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6214                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6215   SDValue Ops[] = { N1, N2, N3, N4 };
6216   return getNode(Opcode, DL, VT, Ops);
6217 }
6218 
6219 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6220                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6221                               SDValue N5) {
6222   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6223   return getNode(Opcode, DL, VT, Ops);
6224 }
6225 
6226 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6227 /// the incoming stack arguments to be loaded from the stack.
6228 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6229   SmallVector<SDValue, 8> ArgChains;
6230 
6231   // Include the original chain at the beginning of the list. When this is
6232   // used by target LowerCall hooks, this helps legalize find the
6233   // CALLSEQ_BEGIN node.
6234   ArgChains.push_back(Chain);
6235 
6236   // Add a chain value for each stack argument.
6237   for (SDNode *U : getEntryNode().getNode()->uses())
6238     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6239       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6240         if (FI->getIndex() < 0)
6241           ArgChains.push_back(SDValue(L, 1));
6242 
6243   // Build a tokenfactor for all the chains.
6244   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6245 }
6246 
6247 /// getMemsetValue - Vectorized representation of the memset value
6248 /// operand.
6249 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6250                               const SDLoc &dl) {
6251   assert(!Value.isUndef());
6252 
6253   unsigned NumBits = VT.getScalarSizeInBits();
6254   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6255     assert(C->getAPIntValue().getBitWidth() == 8);
6256     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6257     if (VT.isInteger()) {
6258       bool IsOpaque = VT.getSizeInBits() > 64 ||
6259           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6260       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6261     }
6262     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6263                              VT);
6264   }
6265 
6266   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6267   EVT IntVT = VT.getScalarType();
6268   if (!IntVT.isInteger())
6269     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6270 
6271   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6272   if (NumBits > 8) {
6273     // Use a multiplication with 0x010101... to extend the input to the
6274     // required length.
6275     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6276     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6277                         DAG.getConstant(Magic, dl, IntVT));
6278   }
6279 
6280   if (VT != Value.getValueType() && !VT.isInteger())
6281     Value = DAG.getBitcast(VT.getScalarType(), Value);
6282   if (VT != Value.getValueType())
6283     Value = DAG.getSplatBuildVector(VT, dl, Value);
6284 
6285   return Value;
6286 }
6287 
6288 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6289 /// used when a memcpy is turned into a memset when the source is a constant
6290 /// string ptr.
6291 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6292                                   const TargetLowering &TLI,
6293                                   const ConstantDataArraySlice &Slice) {
6294   // Handle vector with all elements zero.
6295   if (Slice.Array == nullptr) {
6296     if (VT.isInteger())
6297       return DAG.getConstant(0, dl, VT);
6298     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6299       return DAG.getConstantFP(0.0, dl, VT);
6300     if (VT.isVector()) {
6301       unsigned NumElts = VT.getVectorNumElements();
6302       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6303       return DAG.getNode(ISD::BITCAST, dl, VT,
6304                          DAG.getConstant(0, dl,
6305                                          EVT::getVectorVT(*DAG.getContext(),
6306                                                           EltVT, NumElts)));
6307     }
6308     llvm_unreachable("Expected type!");
6309   }
6310 
6311   assert(!VT.isVector() && "Can't handle vector type here!");
6312   unsigned NumVTBits = VT.getSizeInBits();
6313   unsigned NumVTBytes = NumVTBits / 8;
6314   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6315 
6316   APInt Val(NumVTBits, 0);
6317   if (DAG.getDataLayout().isLittleEndian()) {
6318     for (unsigned i = 0; i != NumBytes; ++i)
6319       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6320   } else {
6321     for (unsigned i = 0; i != NumBytes; ++i)
6322       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6323   }
6324 
6325   // If the "cost" of materializing the integer immediate is less than the cost
6326   // of a load, then it is cost effective to turn the load into the immediate.
6327   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6328   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6329     return DAG.getConstant(Val, dl, VT);
6330   return SDValue(nullptr, 0);
6331 }
6332 
6333 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6334                                            const SDLoc &DL,
6335                                            const SDNodeFlags Flags) {
6336   EVT VT = Base.getValueType();
6337   SDValue Index;
6338 
6339   if (Offset.isScalable())
6340     Index = getVScale(DL, Base.getValueType(),
6341                       APInt(Base.getValueSizeInBits().getFixedSize(),
6342                             Offset.getKnownMinSize()));
6343   else
6344     Index = getConstant(Offset.getFixedSize(), DL, VT);
6345 
6346   return getMemBasePlusOffset(Base, Index, DL, Flags);
6347 }
6348 
6349 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6350                                            const SDLoc &DL,
6351                                            const SDNodeFlags Flags) {
6352   assert(Offset.getValueType().isInteger());
6353   EVT BasePtrVT = Ptr.getValueType();
6354   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6355 }
6356 
6357 /// Returns true if memcpy source is constant data.
6358 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6359   uint64_t SrcDelta = 0;
6360   GlobalAddressSDNode *G = nullptr;
6361   if (Src.getOpcode() == ISD::GlobalAddress)
6362     G = cast<GlobalAddressSDNode>(Src);
6363   else if (Src.getOpcode() == ISD::ADD &&
6364            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6365            Src.getOperand(1).getOpcode() == ISD::Constant) {
6366     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6367     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6368   }
6369   if (!G)
6370     return false;
6371 
6372   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6373                                   SrcDelta + G->getOffset());
6374 }
6375 
6376 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6377                                       SelectionDAG &DAG) {
6378   // On Darwin, -Os means optimize for size without hurting performance, so
6379   // only really optimize for size when -Oz (MinSize) is used.
6380   if (MF.getTarget().getTargetTriple().isOSDarwin())
6381     return MF.getFunction().hasMinSize();
6382   return DAG.shouldOptForSize();
6383 }
6384 
6385 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6386                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6387                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6388                           SmallVector<SDValue, 16> &OutStoreChains) {
6389   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6390   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6391   SmallVector<SDValue, 16> GluedLoadChains;
6392   for (unsigned i = From; i < To; ++i) {
6393     OutChains.push_back(OutLoadChains[i]);
6394     GluedLoadChains.push_back(OutLoadChains[i]);
6395   }
6396 
6397   // Chain for all loads.
6398   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6399                                   GluedLoadChains);
6400 
6401   for (unsigned i = From; i < To; ++i) {
6402     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6403     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6404                                   ST->getBasePtr(), ST->getMemoryVT(),
6405                                   ST->getMemOperand());
6406     OutChains.push_back(NewStore);
6407   }
6408 }
6409 
6410 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6411                                        SDValue Chain, SDValue Dst, SDValue Src,
6412                                        uint64_t Size, Align Alignment,
6413                                        bool isVol, bool AlwaysInline,
6414                                        MachinePointerInfo DstPtrInfo,
6415                                        MachinePointerInfo SrcPtrInfo,
6416                                        const AAMDNodes &AAInfo) {
6417   // Turn a memcpy of undef to nop.
6418   // FIXME: We need to honor volatile even is Src is undef.
6419   if (Src.isUndef())
6420     return Chain;
6421 
6422   // Expand memcpy to a series of load and store ops if the size operand falls
6423   // below a certain threshold.
6424   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6425   // rather than maybe a humongous number of loads and stores.
6426   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6427   const DataLayout &DL = DAG.getDataLayout();
6428   LLVMContext &C = *DAG.getContext();
6429   std::vector<EVT> MemOps;
6430   bool DstAlignCanChange = false;
6431   MachineFunction &MF = DAG.getMachineFunction();
6432   MachineFrameInfo &MFI = MF.getFrameInfo();
6433   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6434   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6435   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6436     DstAlignCanChange = true;
6437   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6438   if (!SrcAlign || Alignment > *SrcAlign)
6439     SrcAlign = Alignment;
6440   assert(SrcAlign && "SrcAlign must be set");
6441   ConstantDataArraySlice Slice;
6442   // If marked as volatile, perform a copy even when marked as constant.
6443   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6444   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6445   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6446   const MemOp Op = isZeroConstant
6447                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6448                                     /*IsZeroMemset*/ true, isVol)
6449                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6450                                      *SrcAlign, isVol, CopyFromConstant);
6451   if (!TLI.findOptimalMemOpLowering(
6452           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6453           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6454     return SDValue();
6455 
6456   if (DstAlignCanChange) {
6457     Type *Ty = MemOps[0].getTypeForEVT(C);
6458     Align NewAlign = DL.getABITypeAlign(Ty);
6459 
6460     // Don't promote to an alignment that would require dynamic stack
6461     // realignment.
6462     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6463     if (!TRI->hasStackRealignment(MF))
6464       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6465         NewAlign = NewAlign / 2;
6466 
6467     if (NewAlign > Alignment) {
6468       // Give the stack frame object a larger alignment if needed.
6469       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6470         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6471       Alignment = NewAlign;
6472     }
6473   }
6474 
6475   // Prepare AAInfo for loads/stores after lowering this memcpy.
6476   AAMDNodes NewAAInfo = AAInfo;
6477   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6478 
6479   MachineMemOperand::Flags MMOFlags =
6480       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6481   SmallVector<SDValue, 16> OutLoadChains;
6482   SmallVector<SDValue, 16> OutStoreChains;
6483   SmallVector<SDValue, 32> OutChains;
6484   unsigned NumMemOps = MemOps.size();
6485   uint64_t SrcOff = 0, DstOff = 0;
6486   for (unsigned i = 0; i != NumMemOps; ++i) {
6487     EVT VT = MemOps[i];
6488     unsigned VTSize = VT.getSizeInBits() / 8;
6489     SDValue Value, Store;
6490 
6491     if (VTSize > Size) {
6492       // Issuing an unaligned load / store pair  that overlaps with the previous
6493       // pair. Adjust the offset accordingly.
6494       assert(i == NumMemOps-1 && i != 0);
6495       SrcOff -= VTSize - Size;
6496       DstOff -= VTSize - Size;
6497     }
6498 
6499     if (CopyFromConstant &&
6500         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6501       // It's unlikely a store of a vector immediate can be done in a single
6502       // instruction. It would require a load from a constantpool first.
6503       // We only handle zero vectors here.
6504       // FIXME: Handle other cases where store of vector immediate is done in
6505       // a single instruction.
6506       ConstantDataArraySlice SubSlice;
6507       if (SrcOff < Slice.Length) {
6508         SubSlice = Slice;
6509         SubSlice.move(SrcOff);
6510       } else {
6511         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6512         SubSlice.Array = nullptr;
6513         SubSlice.Offset = 0;
6514         SubSlice.Length = VTSize;
6515       }
6516       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6517       if (Value.getNode()) {
6518         Store = DAG.getStore(
6519             Chain, dl, Value,
6520             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6521             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6522         OutChains.push_back(Store);
6523       }
6524     }
6525 
6526     if (!Store.getNode()) {
6527       // The type might not be legal for the target.  This should only happen
6528       // if the type is smaller than a legal type, as on PPC, so the right
6529       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6530       // to Load/Store if NVT==VT.
6531       // FIXME does the case above also need this?
6532       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6533       assert(NVT.bitsGE(VT));
6534 
6535       bool isDereferenceable =
6536         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6537       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6538       if (isDereferenceable)
6539         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6540 
6541       Value = DAG.getExtLoad(
6542           ISD::EXTLOAD, dl, NVT, Chain,
6543           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6544           SrcPtrInfo.getWithOffset(SrcOff), VT,
6545           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6546       OutLoadChains.push_back(Value.getValue(1));
6547 
6548       Store = DAG.getTruncStore(
6549           Chain, dl, Value,
6550           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6551           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6552       OutStoreChains.push_back(Store);
6553     }
6554     SrcOff += VTSize;
6555     DstOff += VTSize;
6556     Size -= VTSize;
6557   }
6558 
6559   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6560                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6561   unsigned NumLdStInMemcpy = OutStoreChains.size();
6562 
6563   if (NumLdStInMemcpy) {
6564     // It may be that memcpy might be converted to memset if it's memcpy
6565     // of constants. In such a case, we won't have loads and stores, but
6566     // just stores. In the absence of loads, there is nothing to gang up.
6567     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6568       // If target does not care, just leave as it.
6569       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6570         OutChains.push_back(OutLoadChains[i]);
6571         OutChains.push_back(OutStoreChains[i]);
6572       }
6573     } else {
6574       // Ld/St less than/equal limit set by target.
6575       if (NumLdStInMemcpy <= GluedLdStLimit) {
6576           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6577                                         NumLdStInMemcpy, OutLoadChains,
6578                                         OutStoreChains);
6579       } else {
6580         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6581         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6582         unsigned GlueIter = 0;
6583 
6584         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6585           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6586           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6587 
6588           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6589                                        OutLoadChains, OutStoreChains);
6590           GlueIter += GluedLdStLimit;
6591         }
6592 
6593         // Residual ld/st.
6594         if (RemainingLdStInMemcpy) {
6595           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6596                                         RemainingLdStInMemcpy, OutLoadChains,
6597                                         OutStoreChains);
6598         }
6599       }
6600     }
6601   }
6602   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6603 }
6604 
6605 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6606                                         SDValue Chain, SDValue Dst, SDValue Src,
6607                                         uint64_t Size, Align Alignment,
6608                                         bool isVol, bool AlwaysInline,
6609                                         MachinePointerInfo DstPtrInfo,
6610                                         MachinePointerInfo SrcPtrInfo,
6611                                         const AAMDNodes &AAInfo) {
6612   // Turn a memmove of undef to nop.
6613   // FIXME: We need to honor volatile even is Src is undef.
6614   if (Src.isUndef())
6615     return Chain;
6616 
6617   // Expand memmove to a series of load and store ops if the size operand falls
6618   // below a certain threshold.
6619   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6620   const DataLayout &DL = DAG.getDataLayout();
6621   LLVMContext &C = *DAG.getContext();
6622   std::vector<EVT> MemOps;
6623   bool DstAlignCanChange = false;
6624   MachineFunction &MF = DAG.getMachineFunction();
6625   MachineFrameInfo &MFI = MF.getFrameInfo();
6626   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6627   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6628   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6629     DstAlignCanChange = true;
6630   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6631   if (!SrcAlign || Alignment > *SrcAlign)
6632     SrcAlign = Alignment;
6633   assert(SrcAlign && "SrcAlign must be set");
6634   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6635   if (!TLI.findOptimalMemOpLowering(
6636           MemOps, Limit,
6637           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6638                       /*IsVolatile*/ true),
6639           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6640           MF.getFunction().getAttributes()))
6641     return SDValue();
6642 
6643   if (DstAlignCanChange) {
6644     Type *Ty = MemOps[0].getTypeForEVT(C);
6645     Align NewAlign = DL.getABITypeAlign(Ty);
6646     if (NewAlign > Alignment) {
6647       // Give the stack frame object a larger alignment if needed.
6648       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6649         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6650       Alignment = NewAlign;
6651     }
6652   }
6653 
6654   // Prepare AAInfo for loads/stores after lowering this memmove.
6655   AAMDNodes NewAAInfo = AAInfo;
6656   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6657 
6658   MachineMemOperand::Flags MMOFlags =
6659       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6660   uint64_t SrcOff = 0, DstOff = 0;
6661   SmallVector<SDValue, 8> LoadValues;
6662   SmallVector<SDValue, 8> LoadChains;
6663   SmallVector<SDValue, 8> OutChains;
6664   unsigned NumMemOps = MemOps.size();
6665   for (unsigned i = 0; i < NumMemOps; i++) {
6666     EVT VT = MemOps[i];
6667     unsigned VTSize = VT.getSizeInBits() / 8;
6668     SDValue Value;
6669 
6670     bool isDereferenceable =
6671       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6672     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6673     if (isDereferenceable)
6674       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6675 
6676     Value = DAG.getLoad(
6677         VT, dl, Chain,
6678         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6679         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6680     LoadValues.push_back(Value);
6681     LoadChains.push_back(Value.getValue(1));
6682     SrcOff += VTSize;
6683   }
6684   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6685   OutChains.clear();
6686   for (unsigned i = 0; i < NumMemOps; i++) {
6687     EVT VT = MemOps[i];
6688     unsigned VTSize = VT.getSizeInBits() / 8;
6689     SDValue Store;
6690 
6691     Store = DAG.getStore(
6692         Chain, dl, LoadValues[i],
6693         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6694         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6695     OutChains.push_back(Store);
6696     DstOff += VTSize;
6697   }
6698 
6699   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6700 }
6701 
6702 /// Lower the call to 'memset' intrinsic function into a series of store
6703 /// operations.
6704 ///
6705 /// \param DAG Selection DAG where lowered code is placed.
6706 /// \param dl Link to corresponding IR location.
6707 /// \param Chain Control flow dependency.
6708 /// \param Dst Pointer to destination memory location.
6709 /// \param Src Value of byte to write into the memory.
6710 /// \param Size Number of bytes to write.
6711 /// \param Alignment Alignment of the destination in bytes.
6712 /// \param isVol True if destination is volatile.
6713 /// \param DstPtrInfo IR information on the memory pointer.
6714 /// \returns New head in the control flow, if lowering was successful, empty
6715 /// SDValue otherwise.
6716 ///
6717 /// The function tries to replace 'llvm.memset' intrinsic with several store
6718 /// operations and value calculation code. This is usually profitable for small
6719 /// memory size.
6720 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6721                                SDValue Chain, SDValue Dst, SDValue Src,
6722                                uint64_t Size, Align Alignment, bool isVol,
6723                                MachinePointerInfo DstPtrInfo,
6724                                const AAMDNodes &AAInfo) {
6725   // Turn a memset of undef to nop.
6726   // FIXME: We need to honor volatile even is Src is undef.
6727   if (Src.isUndef())
6728     return Chain;
6729 
6730   // Expand memset to a series of load/store ops if the size operand
6731   // falls below a certain threshold.
6732   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6733   std::vector<EVT> MemOps;
6734   bool DstAlignCanChange = false;
6735   MachineFunction &MF = DAG.getMachineFunction();
6736   MachineFrameInfo &MFI = MF.getFrameInfo();
6737   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6738   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6739   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6740     DstAlignCanChange = true;
6741   bool IsZeroVal =
6742       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6743   if (!TLI.findOptimalMemOpLowering(
6744           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6745           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6746           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6747     return SDValue();
6748 
6749   if (DstAlignCanChange) {
6750     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6751     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6752     if (NewAlign > Alignment) {
6753       // Give the stack frame object a larger alignment if needed.
6754       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6755         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6756       Alignment = NewAlign;
6757     }
6758   }
6759 
6760   SmallVector<SDValue, 8> OutChains;
6761   uint64_t DstOff = 0;
6762   unsigned NumMemOps = MemOps.size();
6763 
6764   // Find the largest store and generate the bit pattern for it.
6765   EVT LargestVT = MemOps[0];
6766   for (unsigned i = 1; i < NumMemOps; i++)
6767     if (MemOps[i].bitsGT(LargestVT))
6768       LargestVT = MemOps[i];
6769   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6770 
6771   // Prepare AAInfo for loads/stores after lowering this memset.
6772   AAMDNodes NewAAInfo = AAInfo;
6773   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6774 
6775   for (unsigned i = 0; i < NumMemOps; i++) {
6776     EVT VT = MemOps[i];
6777     unsigned VTSize = VT.getSizeInBits() / 8;
6778     if (VTSize > Size) {
6779       // Issuing an unaligned load / store pair  that overlaps with the previous
6780       // pair. Adjust the offset accordingly.
6781       assert(i == NumMemOps-1 && i != 0);
6782       DstOff -= VTSize - Size;
6783     }
6784 
6785     // If this store is smaller than the largest store see whether we can get
6786     // the smaller value for free with a truncate.
6787     SDValue Value = MemSetValue;
6788     if (VT.bitsLT(LargestVT)) {
6789       if (!LargestVT.isVector() && !VT.isVector() &&
6790           TLI.isTruncateFree(LargestVT, VT))
6791         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6792       else
6793         Value = getMemsetValue(Src, VT, DAG, dl);
6794     }
6795     assert(Value.getValueType() == VT && "Value with wrong type.");
6796     SDValue Store = DAG.getStore(
6797         Chain, dl, Value,
6798         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6799         DstPtrInfo.getWithOffset(DstOff), Alignment,
6800         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6801         NewAAInfo);
6802     OutChains.push_back(Store);
6803     DstOff += VT.getSizeInBits() / 8;
6804     Size -= VTSize;
6805   }
6806 
6807   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6808 }
6809 
6810 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6811                                             unsigned AS) {
6812   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6813   // pointer operands can be losslessly bitcasted to pointers of address space 0
6814   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6815     report_fatal_error("cannot lower memory intrinsic in address space " +
6816                        Twine(AS));
6817   }
6818 }
6819 
6820 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6821                                 SDValue Src, SDValue Size, Align Alignment,
6822                                 bool isVol, bool AlwaysInline, bool isTailCall,
6823                                 MachinePointerInfo DstPtrInfo,
6824                                 MachinePointerInfo SrcPtrInfo,
6825                                 const AAMDNodes &AAInfo) {
6826   // Check to see if we should lower the memcpy to loads and stores first.
6827   // For cases within the target-specified limits, this is the best choice.
6828   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6829   if (ConstantSize) {
6830     // Memcpy with size zero? Just return the original chain.
6831     if (ConstantSize->isZero())
6832       return Chain;
6833 
6834     SDValue Result = getMemcpyLoadsAndStores(
6835         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6836         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6837     if (Result.getNode())
6838       return Result;
6839   }
6840 
6841   // Then check to see if we should lower the memcpy with target-specific
6842   // code. If the target chooses to do this, this is the next best.
6843   if (TSI) {
6844     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6845         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6846         DstPtrInfo, SrcPtrInfo);
6847     if (Result.getNode())
6848       return Result;
6849   }
6850 
6851   // If we really need inline code and the target declined to provide it,
6852   // use a (potentially long) sequence of loads and stores.
6853   if (AlwaysInline) {
6854     assert(ConstantSize && "AlwaysInline requires a constant size!");
6855     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6856                                    ConstantSize->getZExtValue(), Alignment,
6857                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6858   }
6859 
6860   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6861   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6862 
6863   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6864   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6865   // respect volatile, so they may do things like read or write memory
6866   // beyond the given memory regions. But fixing this isn't easy, and most
6867   // people don't care.
6868 
6869   // Emit a library call.
6870   TargetLowering::ArgListTy Args;
6871   TargetLowering::ArgListEntry Entry;
6872   Entry.Ty = Type::getInt8PtrTy(*getContext());
6873   Entry.Node = Dst; Args.push_back(Entry);
6874   Entry.Node = Src; Args.push_back(Entry);
6875 
6876   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6877   Entry.Node = Size; Args.push_back(Entry);
6878   // FIXME: pass in SDLoc
6879   TargetLowering::CallLoweringInfo CLI(*this);
6880   CLI.setDebugLoc(dl)
6881       .setChain(Chain)
6882       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6883                     Dst.getValueType().getTypeForEVT(*getContext()),
6884                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6885                                       TLI->getPointerTy(getDataLayout())),
6886                     std::move(Args))
6887       .setDiscardResult()
6888       .setTailCall(isTailCall);
6889 
6890   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6891   return CallResult.second;
6892 }
6893 
6894 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6895                                       SDValue Dst, unsigned DstAlign,
6896                                       SDValue Src, unsigned SrcAlign,
6897                                       SDValue Size, Type *SizeTy,
6898                                       unsigned ElemSz, bool isTailCall,
6899                                       MachinePointerInfo DstPtrInfo,
6900                                       MachinePointerInfo SrcPtrInfo) {
6901   // Emit a library call.
6902   TargetLowering::ArgListTy Args;
6903   TargetLowering::ArgListEntry Entry;
6904   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6905   Entry.Node = Dst;
6906   Args.push_back(Entry);
6907 
6908   Entry.Node = Src;
6909   Args.push_back(Entry);
6910 
6911   Entry.Ty = SizeTy;
6912   Entry.Node = Size;
6913   Args.push_back(Entry);
6914 
6915   RTLIB::Libcall LibraryCall =
6916       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6917   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6918     report_fatal_error("Unsupported element size");
6919 
6920   TargetLowering::CallLoweringInfo CLI(*this);
6921   CLI.setDebugLoc(dl)
6922       .setChain(Chain)
6923       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6924                     Type::getVoidTy(*getContext()),
6925                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6926                                       TLI->getPointerTy(getDataLayout())),
6927                     std::move(Args))
6928       .setDiscardResult()
6929       .setTailCall(isTailCall);
6930 
6931   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6932   return CallResult.second;
6933 }
6934 
6935 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6936                                  SDValue Src, SDValue Size, Align Alignment,
6937                                  bool isVol, bool isTailCall,
6938                                  MachinePointerInfo DstPtrInfo,
6939                                  MachinePointerInfo SrcPtrInfo,
6940                                  const AAMDNodes &AAInfo) {
6941   // Check to see if we should lower the memmove to loads and stores first.
6942   // For cases within the target-specified limits, this is the best choice.
6943   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6944   if (ConstantSize) {
6945     // Memmove with size zero? Just return the original chain.
6946     if (ConstantSize->isZero())
6947       return Chain;
6948 
6949     SDValue Result = getMemmoveLoadsAndStores(
6950         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6951         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6952     if (Result.getNode())
6953       return Result;
6954   }
6955 
6956   // Then check to see if we should lower the memmove with target-specific
6957   // code. If the target chooses to do this, this is the next best.
6958   if (TSI) {
6959     SDValue Result =
6960         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6961                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6962     if (Result.getNode())
6963       return Result;
6964   }
6965 
6966   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6967   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6968 
6969   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6970   // not be safe.  See memcpy above for more details.
6971 
6972   // Emit a library call.
6973   TargetLowering::ArgListTy Args;
6974   TargetLowering::ArgListEntry Entry;
6975   Entry.Ty = Type::getInt8PtrTy(*getContext());
6976   Entry.Node = Dst; Args.push_back(Entry);
6977   Entry.Node = Src; Args.push_back(Entry);
6978 
6979   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6980   Entry.Node = Size; Args.push_back(Entry);
6981   // FIXME:  pass in SDLoc
6982   TargetLowering::CallLoweringInfo CLI(*this);
6983   CLI.setDebugLoc(dl)
6984       .setChain(Chain)
6985       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6986                     Dst.getValueType().getTypeForEVT(*getContext()),
6987                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6988                                       TLI->getPointerTy(getDataLayout())),
6989                     std::move(Args))
6990       .setDiscardResult()
6991       .setTailCall(isTailCall);
6992 
6993   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6994   return CallResult.second;
6995 }
6996 
6997 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6998                                        SDValue Dst, unsigned DstAlign,
6999                                        SDValue Src, unsigned SrcAlign,
7000                                        SDValue Size, Type *SizeTy,
7001                                        unsigned ElemSz, bool isTailCall,
7002                                        MachinePointerInfo DstPtrInfo,
7003                                        MachinePointerInfo SrcPtrInfo) {
7004   // Emit a library call.
7005   TargetLowering::ArgListTy Args;
7006   TargetLowering::ArgListEntry Entry;
7007   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7008   Entry.Node = Dst;
7009   Args.push_back(Entry);
7010 
7011   Entry.Node = Src;
7012   Args.push_back(Entry);
7013 
7014   Entry.Ty = SizeTy;
7015   Entry.Node = Size;
7016   Args.push_back(Entry);
7017 
7018   RTLIB::Libcall LibraryCall =
7019       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7020   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7021     report_fatal_error("Unsupported element size");
7022 
7023   TargetLowering::CallLoweringInfo CLI(*this);
7024   CLI.setDebugLoc(dl)
7025       .setChain(Chain)
7026       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7027                     Type::getVoidTy(*getContext()),
7028                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7029                                       TLI->getPointerTy(getDataLayout())),
7030                     std::move(Args))
7031       .setDiscardResult()
7032       .setTailCall(isTailCall);
7033 
7034   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7035   return CallResult.second;
7036 }
7037 
7038 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7039                                 SDValue Src, SDValue Size, Align Alignment,
7040                                 bool isVol, bool isTailCall,
7041                                 MachinePointerInfo DstPtrInfo,
7042                                 const AAMDNodes &AAInfo) {
7043   // Check to see if we should lower the memset to stores first.
7044   // For cases within the target-specified limits, this is the best choice.
7045   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7046   if (ConstantSize) {
7047     // Memset with size zero? Just return the original chain.
7048     if (ConstantSize->isZero())
7049       return Chain;
7050 
7051     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7052                                      ConstantSize->getZExtValue(), Alignment,
7053                                      isVol, DstPtrInfo, AAInfo);
7054 
7055     if (Result.getNode())
7056       return Result;
7057   }
7058 
7059   // Then check to see if we should lower the memset with target-specific
7060   // code. If the target chooses to do this, this is the next best.
7061   if (TSI) {
7062     SDValue Result = TSI->EmitTargetCodeForMemset(
7063         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7064     if (Result.getNode())
7065       return Result;
7066   }
7067 
7068   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7069 
7070   // Emit a library call.
7071   TargetLowering::ArgListTy Args;
7072   TargetLowering::ArgListEntry Entry;
7073   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7074   Args.push_back(Entry);
7075   Entry.Node = Src;
7076   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7077   Args.push_back(Entry);
7078   Entry.Node = Size;
7079   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7080   Args.push_back(Entry);
7081 
7082   // FIXME: pass in SDLoc
7083   TargetLowering::CallLoweringInfo CLI(*this);
7084   CLI.setDebugLoc(dl)
7085       .setChain(Chain)
7086       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7087                     Dst.getValueType().getTypeForEVT(*getContext()),
7088                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7089                                       TLI->getPointerTy(getDataLayout())),
7090                     std::move(Args))
7091       .setDiscardResult()
7092       .setTailCall(isTailCall);
7093 
7094   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7095   return CallResult.second;
7096 }
7097 
7098 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7099                                       SDValue Dst, unsigned DstAlign,
7100                                       SDValue Value, SDValue Size, Type *SizeTy,
7101                                       unsigned ElemSz, bool isTailCall,
7102                                       MachinePointerInfo DstPtrInfo) {
7103   // Emit a library call.
7104   TargetLowering::ArgListTy Args;
7105   TargetLowering::ArgListEntry Entry;
7106   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7107   Entry.Node = Dst;
7108   Args.push_back(Entry);
7109 
7110   Entry.Ty = Type::getInt8Ty(*getContext());
7111   Entry.Node = Value;
7112   Args.push_back(Entry);
7113 
7114   Entry.Ty = SizeTy;
7115   Entry.Node = Size;
7116   Args.push_back(Entry);
7117 
7118   RTLIB::Libcall LibraryCall =
7119       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7120   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7121     report_fatal_error("Unsupported element size");
7122 
7123   TargetLowering::CallLoweringInfo CLI(*this);
7124   CLI.setDebugLoc(dl)
7125       .setChain(Chain)
7126       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7127                     Type::getVoidTy(*getContext()),
7128                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7129                                       TLI->getPointerTy(getDataLayout())),
7130                     std::move(Args))
7131       .setDiscardResult()
7132       .setTailCall(isTailCall);
7133 
7134   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7135   return CallResult.second;
7136 }
7137 
7138 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7139                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7140                                 MachineMemOperand *MMO) {
7141   FoldingSetNodeID ID;
7142   ID.AddInteger(MemVT.getRawBits());
7143   AddNodeIDNode(ID, Opcode, VTList, Ops);
7144   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7145   void* IP = nullptr;
7146   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7147     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7148     return SDValue(E, 0);
7149   }
7150 
7151   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7152                                     VTList, MemVT, MMO);
7153   createOperands(N, Ops);
7154 
7155   CSEMap.InsertNode(N, IP);
7156   InsertNode(N);
7157   return SDValue(N, 0);
7158 }
7159 
7160 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7161                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7162                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7163                                        MachineMemOperand *MMO) {
7164   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7165          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7166   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7167 
7168   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7169   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7170 }
7171 
7172 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7173                                 SDValue Chain, SDValue Ptr, SDValue Val,
7174                                 MachineMemOperand *MMO) {
7175   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7176           Opcode == ISD::ATOMIC_LOAD_SUB ||
7177           Opcode == ISD::ATOMIC_LOAD_AND ||
7178           Opcode == ISD::ATOMIC_LOAD_CLR ||
7179           Opcode == ISD::ATOMIC_LOAD_OR ||
7180           Opcode == ISD::ATOMIC_LOAD_XOR ||
7181           Opcode == ISD::ATOMIC_LOAD_NAND ||
7182           Opcode == ISD::ATOMIC_LOAD_MIN ||
7183           Opcode == ISD::ATOMIC_LOAD_MAX ||
7184           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7185           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7186           Opcode == ISD::ATOMIC_LOAD_FADD ||
7187           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7188           Opcode == ISD::ATOMIC_SWAP ||
7189           Opcode == ISD::ATOMIC_STORE) &&
7190          "Invalid Atomic Op");
7191 
7192   EVT VT = Val.getValueType();
7193 
7194   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7195                                                getVTList(VT, MVT::Other);
7196   SDValue Ops[] = {Chain, Ptr, Val};
7197   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7198 }
7199 
7200 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7201                                 EVT VT, SDValue Chain, SDValue Ptr,
7202                                 MachineMemOperand *MMO) {
7203   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7204 
7205   SDVTList VTs = getVTList(VT, MVT::Other);
7206   SDValue Ops[] = {Chain, Ptr};
7207   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7208 }
7209 
7210 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7211 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7212   if (Ops.size() == 1)
7213     return Ops[0];
7214 
7215   SmallVector<EVT, 4> VTs;
7216   VTs.reserve(Ops.size());
7217   for (const SDValue &Op : Ops)
7218     VTs.push_back(Op.getValueType());
7219   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7220 }
7221 
7222 SDValue SelectionDAG::getMemIntrinsicNode(
7223     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7224     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7225     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7226   if (!Size && MemVT.isScalableVector())
7227     Size = MemoryLocation::UnknownSize;
7228   else if (!Size)
7229     Size = MemVT.getStoreSize();
7230 
7231   MachineFunction &MF = getMachineFunction();
7232   MachineMemOperand *MMO =
7233       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7234 
7235   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7236 }
7237 
7238 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7239                                           SDVTList VTList,
7240                                           ArrayRef<SDValue> Ops, EVT MemVT,
7241                                           MachineMemOperand *MMO) {
7242   assert((Opcode == ISD::INTRINSIC_VOID ||
7243           Opcode == ISD::INTRINSIC_W_CHAIN ||
7244           Opcode == ISD::PREFETCH ||
7245           ((int)Opcode <= std::numeric_limits<int>::max() &&
7246            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7247          "Opcode is not a memory-accessing opcode!");
7248 
7249   // Memoize the node unless it returns a flag.
7250   MemIntrinsicSDNode *N;
7251   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7252     FoldingSetNodeID ID;
7253     AddNodeIDNode(ID, Opcode, VTList, Ops);
7254     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7255         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7256     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7257     void *IP = nullptr;
7258     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7259       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7260       return SDValue(E, 0);
7261     }
7262 
7263     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7264                                       VTList, MemVT, MMO);
7265     createOperands(N, Ops);
7266 
7267   CSEMap.InsertNode(N, IP);
7268   } else {
7269     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7270                                       VTList, MemVT, MMO);
7271     createOperands(N, Ops);
7272   }
7273   InsertNode(N);
7274   SDValue V(N, 0);
7275   NewSDValueDbgMsg(V, "Creating new node: ", this);
7276   return V;
7277 }
7278 
7279 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7280                                       SDValue Chain, int FrameIndex,
7281                                       int64_t Size, int64_t Offset) {
7282   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7283   const auto VTs = getVTList(MVT::Other);
7284   SDValue Ops[2] = {
7285       Chain,
7286       getFrameIndex(FrameIndex,
7287                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7288                     true)};
7289 
7290   FoldingSetNodeID ID;
7291   AddNodeIDNode(ID, Opcode, VTs, Ops);
7292   ID.AddInteger(FrameIndex);
7293   ID.AddInteger(Size);
7294   ID.AddInteger(Offset);
7295   void *IP = nullptr;
7296   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7297     return SDValue(E, 0);
7298 
7299   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7300       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7301   createOperands(N, Ops);
7302   CSEMap.InsertNode(N, IP);
7303   InsertNode(N);
7304   SDValue V(N, 0);
7305   NewSDValueDbgMsg(V, "Creating new node: ", this);
7306   return V;
7307 }
7308 
7309 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7310                                          uint64_t Guid, uint64_t Index,
7311                                          uint32_t Attr) {
7312   const unsigned Opcode = ISD::PSEUDO_PROBE;
7313   const auto VTs = getVTList(MVT::Other);
7314   SDValue Ops[] = {Chain};
7315   FoldingSetNodeID ID;
7316   AddNodeIDNode(ID, Opcode, VTs, Ops);
7317   ID.AddInteger(Guid);
7318   ID.AddInteger(Index);
7319   void *IP = nullptr;
7320   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7321     return SDValue(E, 0);
7322 
7323   auto *N = newSDNode<PseudoProbeSDNode>(
7324       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7325   createOperands(N, Ops);
7326   CSEMap.InsertNode(N, IP);
7327   InsertNode(N);
7328   SDValue V(N, 0);
7329   NewSDValueDbgMsg(V, "Creating new node: ", this);
7330   return V;
7331 }
7332 
7333 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7334 /// MachinePointerInfo record from it.  This is particularly useful because the
7335 /// code generator has many cases where it doesn't bother passing in a
7336 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7337 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7338                                            SelectionDAG &DAG, SDValue Ptr,
7339                                            int64_t Offset = 0) {
7340   // If this is FI+Offset, we can model it.
7341   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7342     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7343                                              FI->getIndex(), Offset);
7344 
7345   // If this is (FI+Offset1)+Offset2, we can model it.
7346   if (Ptr.getOpcode() != ISD::ADD ||
7347       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7348       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7349     return Info;
7350 
7351   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7352   return MachinePointerInfo::getFixedStack(
7353       DAG.getMachineFunction(), FI,
7354       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7355 }
7356 
7357 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7358 /// MachinePointerInfo record from it.  This is particularly useful because the
7359 /// code generator has many cases where it doesn't bother passing in a
7360 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7361 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7362                                            SelectionDAG &DAG, SDValue Ptr,
7363                                            SDValue OffsetOp) {
7364   // If the 'Offset' value isn't a constant, we can't handle this.
7365   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7366     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7367   if (OffsetOp.isUndef())
7368     return InferPointerInfo(Info, DAG, Ptr);
7369   return Info;
7370 }
7371 
7372 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7373                               EVT VT, const SDLoc &dl, SDValue Chain,
7374                               SDValue Ptr, SDValue Offset,
7375                               MachinePointerInfo PtrInfo, EVT MemVT,
7376                               Align Alignment,
7377                               MachineMemOperand::Flags MMOFlags,
7378                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7379   assert(Chain.getValueType() == MVT::Other &&
7380         "Invalid chain type");
7381 
7382   MMOFlags |= MachineMemOperand::MOLoad;
7383   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7384   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7385   // clients.
7386   if (PtrInfo.V.isNull())
7387     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7388 
7389   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7390   MachineFunction &MF = getMachineFunction();
7391   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7392                                                    Alignment, AAInfo, Ranges);
7393   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7394 }
7395 
7396 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7397                               EVT VT, const SDLoc &dl, SDValue Chain,
7398                               SDValue Ptr, SDValue Offset, EVT MemVT,
7399                               MachineMemOperand *MMO) {
7400   if (VT == MemVT) {
7401     ExtType = ISD::NON_EXTLOAD;
7402   } else if (ExtType == ISD::NON_EXTLOAD) {
7403     assert(VT == MemVT && "Non-extending load from different memory type!");
7404   } else {
7405     // Extending load.
7406     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7407            "Should only be an extending load, not truncating!");
7408     assert(VT.isInteger() == MemVT.isInteger() &&
7409            "Cannot convert from FP to Int or Int -> FP!");
7410     assert(VT.isVector() == MemVT.isVector() &&
7411            "Cannot use an ext load to convert to or from a vector!");
7412     assert((!VT.isVector() ||
7413             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7414            "Cannot use an ext load to change the number of vector elements!");
7415   }
7416 
7417   bool Indexed = AM != ISD::UNINDEXED;
7418   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7419 
7420   SDVTList VTs = Indexed ?
7421     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7422   SDValue Ops[] = { Chain, Ptr, Offset };
7423   FoldingSetNodeID ID;
7424   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7425   ID.AddInteger(MemVT.getRawBits());
7426   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7427       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7428   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7429   void *IP = nullptr;
7430   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7431     cast<LoadSDNode>(E)->refineAlignment(MMO);
7432     return SDValue(E, 0);
7433   }
7434   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7435                                   ExtType, MemVT, MMO);
7436   createOperands(N, Ops);
7437 
7438   CSEMap.InsertNode(N, IP);
7439   InsertNode(N);
7440   SDValue V(N, 0);
7441   NewSDValueDbgMsg(V, "Creating new node: ", this);
7442   return V;
7443 }
7444 
7445 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7446                               SDValue Ptr, MachinePointerInfo PtrInfo,
7447                               MaybeAlign Alignment,
7448                               MachineMemOperand::Flags MMOFlags,
7449                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7450   SDValue Undef = getUNDEF(Ptr.getValueType());
7451   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7452                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7453 }
7454 
7455 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7456                               SDValue Ptr, MachineMemOperand *MMO) {
7457   SDValue Undef = getUNDEF(Ptr.getValueType());
7458   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7459                  VT, MMO);
7460 }
7461 
7462 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7463                                  EVT VT, SDValue Chain, SDValue Ptr,
7464                                  MachinePointerInfo PtrInfo, EVT MemVT,
7465                                  MaybeAlign Alignment,
7466                                  MachineMemOperand::Flags MMOFlags,
7467                                  const AAMDNodes &AAInfo) {
7468   SDValue Undef = getUNDEF(Ptr.getValueType());
7469   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7470                  MemVT, Alignment, MMOFlags, AAInfo);
7471 }
7472 
7473 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7474                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7475                                  MachineMemOperand *MMO) {
7476   SDValue Undef = getUNDEF(Ptr.getValueType());
7477   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7478                  MemVT, MMO);
7479 }
7480 
7481 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7482                                      SDValue Base, SDValue Offset,
7483                                      ISD::MemIndexedMode AM) {
7484   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7485   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7486   // Don't propagate the invariant or dereferenceable flags.
7487   auto MMOFlags =
7488       LD->getMemOperand()->getFlags() &
7489       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7490   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7491                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7492                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7493 }
7494 
7495 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7496                                SDValue Ptr, MachinePointerInfo PtrInfo,
7497                                Align Alignment,
7498                                MachineMemOperand::Flags MMOFlags,
7499                                const AAMDNodes &AAInfo) {
7500   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7501 
7502   MMOFlags |= MachineMemOperand::MOStore;
7503   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7504 
7505   if (PtrInfo.V.isNull())
7506     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7507 
7508   MachineFunction &MF = getMachineFunction();
7509   uint64_t Size =
7510       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7511   MachineMemOperand *MMO =
7512       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7513   return getStore(Chain, dl, Val, Ptr, MMO);
7514 }
7515 
7516 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7517                                SDValue Ptr, MachineMemOperand *MMO) {
7518   assert(Chain.getValueType() == MVT::Other &&
7519         "Invalid chain type");
7520   EVT VT = Val.getValueType();
7521   SDVTList VTs = getVTList(MVT::Other);
7522   SDValue Undef = getUNDEF(Ptr.getValueType());
7523   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7524   FoldingSetNodeID ID;
7525   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7526   ID.AddInteger(VT.getRawBits());
7527   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7528       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7529   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7530   void *IP = nullptr;
7531   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7532     cast<StoreSDNode>(E)->refineAlignment(MMO);
7533     return SDValue(E, 0);
7534   }
7535   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7536                                    ISD::UNINDEXED, false, VT, MMO);
7537   createOperands(N, Ops);
7538 
7539   CSEMap.InsertNode(N, IP);
7540   InsertNode(N);
7541   SDValue V(N, 0);
7542   NewSDValueDbgMsg(V, "Creating new node: ", this);
7543   return V;
7544 }
7545 
7546 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7547                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7548                                     EVT SVT, Align Alignment,
7549                                     MachineMemOperand::Flags MMOFlags,
7550                                     const AAMDNodes &AAInfo) {
7551   assert(Chain.getValueType() == MVT::Other &&
7552         "Invalid chain type");
7553 
7554   MMOFlags |= MachineMemOperand::MOStore;
7555   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7556 
7557   if (PtrInfo.V.isNull())
7558     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7559 
7560   MachineFunction &MF = getMachineFunction();
7561   MachineMemOperand *MMO = MF.getMachineMemOperand(
7562       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7563       Alignment, AAInfo);
7564   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7565 }
7566 
7567 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7568                                     SDValue Ptr, EVT SVT,
7569                                     MachineMemOperand *MMO) {
7570   EVT VT = Val.getValueType();
7571 
7572   assert(Chain.getValueType() == MVT::Other &&
7573         "Invalid chain type");
7574   if (VT == SVT)
7575     return getStore(Chain, dl, Val, Ptr, MMO);
7576 
7577   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7578          "Should only be a truncating store, not extending!");
7579   assert(VT.isInteger() == SVT.isInteger() &&
7580          "Can't do FP-INT conversion!");
7581   assert(VT.isVector() == SVT.isVector() &&
7582          "Cannot use trunc store to convert to or from a vector!");
7583   assert((!VT.isVector() ||
7584           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7585          "Cannot use trunc store to change the number of vector elements!");
7586 
7587   SDVTList VTs = getVTList(MVT::Other);
7588   SDValue Undef = getUNDEF(Ptr.getValueType());
7589   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7590   FoldingSetNodeID ID;
7591   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7592   ID.AddInteger(SVT.getRawBits());
7593   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7594       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7595   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7596   void *IP = nullptr;
7597   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7598     cast<StoreSDNode>(E)->refineAlignment(MMO);
7599     return SDValue(E, 0);
7600   }
7601   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7602                                    ISD::UNINDEXED, true, SVT, MMO);
7603   createOperands(N, Ops);
7604 
7605   CSEMap.InsertNode(N, IP);
7606   InsertNode(N);
7607   SDValue V(N, 0);
7608   NewSDValueDbgMsg(V, "Creating new node: ", this);
7609   return V;
7610 }
7611 
7612 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7613                                       SDValue Base, SDValue Offset,
7614                                       ISD::MemIndexedMode AM) {
7615   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7616   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7617   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7618   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7619   FoldingSetNodeID ID;
7620   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7621   ID.AddInteger(ST->getMemoryVT().getRawBits());
7622   ID.AddInteger(ST->getRawSubclassData());
7623   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7624   void *IP = nullptr;
7625   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7626     return SDValue(E, 0);
7627 
7628   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7629                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7630                                    ST->getMemOperand());
7631   createOperands(N, Ops);
7632 
7633   CSEMap.InsertNode(N, IP);
7634   InsertNode(N);
7635   SDValue V(N, 0);
7636   NewSDValueDbgMsg(V, "Creating new node: ", this);
7637   return V;
7638 }
7639 
7640 SDValue SelectionDAG::getLoadVP(
7641     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7642     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7643     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7644     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7645     const MDNode *Ranges, bool IsExpanding) {
7646   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7647 
7648   MMOFlags |= MachineMemOperand::MOLoad;
7649   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7650   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7651   // clients.
7652   if (PtrInfo.V.isNull())
7653     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7654 
7655   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7656   MachineFunction &MF = getMachineFunction();
7657   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7658                                                    Alignment, AAInfo, Ranges);
7659   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7660                    MMO, IsExpanding);
7661 }
7662 
7663 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7664                                 ISD::LoadExtType ExtType, EVT VT,
7665                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7666                                 SDValue Offset, SDValue Mask, SDValue EVL,
7667                                 EVT MemVT, MachineMemOperand *MMO,
7668                                 bool IsExpanding) {
7669   if (VT == MemVT) {
7670     ExtType = ISD::NON_EXTLOAD;
7671   } else if (ExtType == ISD::NON_EXTLOAD) {
7672     assert(VT == MemVT && "Non-extending load from different memory type!");
7673   } else {
7674     // Extending load.
7675     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7676            "Should only be an extending load, not truncating!");
7677     assert(VT.isInteger() == MemVT.isInteger() &&
7678            "Cannot convert from FP to Int or Int -> FP!");
7679     assert(VT.isVector() == MemVT.isVector() &&
7680            "Cannot use an ext load to convert to or from a vector!");
7681     assert((!VT.isVector() ||
7682             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7683            "Cannot use an ext load to change the number of vector elements!");
7684   }
7685 
7686   bool Indexed = AM != ISD::UNINDEXED;
7687   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7688 
7689   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7690                          : getVTList(VT, MVT::Other);
7691   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7692   FoldingSetNodeID ID;
7693   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7694   ID.AddInteger(VT.getRawBits());
7695   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7696       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7697   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7698   void *IP = nullptr;
7699   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7700     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7701     return SDValue(E, 0);
7702   }
7703   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7704                                     ExtType, IsExpanding, MemVT, MMO);
7705   createOperands(N, Ops);
7706 
7707   CSEMap.InsertNode(N, IP);
7708   InsertNode(N);
7709   SDValue V(N, 0);
7710   NewSDValueDbgMsg(V, "Creating new node: ", this);
7711   return V;
7712 }
7713 
7714 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7715                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7716                                 MachinePointerInfo PtrInfo,
7717                                 MaybeAlign Alignment,
7718                                 MachineMemOperand::Flags MMOFlags,
7719                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7720                                 bool IsExpanding) {
7721   SDValue Undef = getUNDEF(Ptr.getValueType());
7722   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7723                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7724                    IsExpanding);
7725 }
7726 
7727 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7728                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7729                                 MachineMemOperand *MMO, bool IsExpanding) {
7730   SDValue Undef = getUNDEF(Ptr.getValueType());
7731   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7732                    Mask, EVL, VT, MMO, IsExpanding);
7733 }
7734 
7735 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7736                                    EVT VT, SDValue Chain, SDValue Ptr,
7737                                    SDValue Mask, SDValue EVL,
7738                                    MachinePointerInfo PtrInfo, EVT MemVT,
7739                                    MaybeAlign Alignment,
7740                                    MachineMemOperand::Flags MMOFlags,
7741                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7742   SDValue Undef = getUNDEF(Ptr.getValueType());
7743   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7744                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7745                    IsExpanding);
7746 }
7747 
7748 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7749                                    EVT VT, SDValue Chain, SDValue Ptr,
7750                                    SDValue Mask, SDValue EVL, EVT MemVT,
7751                                    MachineMemOperand *MMO, bool IsExpanding) {
7752   SDValue Undef = getUNDEF(Ptr.getValueType());
7753   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7754                    EVL, MemVT, MMO, IsExpanding);
7755 }
7756 
7757 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7758                                        SDValue Base, SDValue Offset,
7759                                        ISD::MemIndexedMode AM) {
7760   auto *LD = cast<VPLoadSDNode>(OrigLoad);
7761   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7762   // Don't propagate the invariant or dereferenceable flags.
7763   auto MMOFlags =
7764       LD->getMemOperand()->getFlags() &
7765       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7766   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7767                    LD->getChain(), Base, Offset, LD->getMask(),
7768                    LD->getVectorLength(), LD->getPointerInfo(),
7769                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7770                    nullptr, LD->isExpandingLoad());
7771 }
7772 
7773 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7774                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7775                                  MachinePointerInfo PtrInfo, Align Alignment,
7776                                  MachineMemOperand::Flags MMOFlags,
7777                                  const AAMDNodes &AAInfo, bool IsCompressing) {
7778   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7779 
7780   MMOFlags |= MachineMemOperand::MOStore;
7781   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7782 
7783   if (PtrInfo.V.isNull())
7784     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7785 
7786   MachineFunction &MF = getMachineFunction();
7787   uint64_t Size =
7788       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7789   MachineMemOperand *MMO =
7790       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7791   return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7792 }
7793 
7794 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7795                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7796                                  MachineMemOperand *MMO, bool IsCompressing) {
7797   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7798   EVT VT = Val.getValueType();
7799   SDVTList VTs = getVTList(MVT::Other);
7800   SDValue Undef = getUNDEF(Ptr.getValueType());
7801   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7802   FoldingSetNodeID ID;
7803   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7804   ID.AddInteger(VT.getRawBits());
7805   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7806       dl.getIROrder(), VTs, ISD::UNINDEXED, false, IsCompressing, VT, MMO));
7807   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7808   void *IP = nullptr;
7809   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7810     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7811     return SDValue(E, 0);
7812   }
7813   auto *N =
7814       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7815                                ISD::UNINDEXED, false, IsCompressing, VT, MMO);
7816   createOperands(N, Ops);
7817 
7818   CSEMap.InsertNode(N, IP);
7819   InsertNode(N);
7820   SDValue V(N, 0);
7821   NewSDValueDbgMsg(V, "Creating new node: ", this);
7822   return V;
7823 }
7824 
7825 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7826                                       SDValue Val, SDValue Ptr, SDValue Mask,
7827                                       SDValue EVL, MachinePointerInfo PtrInfo,
7828                                       EVT SVT, Align Alignment,
7829                                       MachineMemOperand::Flags MMOFlags,
7830                                       const AAMDNodes &AAInfo,
7831                                       bool IsCompressing) {
7832   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7833 
7834   MMOFlags |= MachineMemOperand::MOStore;
7835   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7836 
7837   if (PtrInfo.V.isNull())
7838     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7839 
7840   MachineFunction &MF = getMachineFunction();
7841   MachineMemOperand *MMO = MF.getMachineMemOperand(
7842       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7843       Alignment, AAInfo);
7844   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7845                          IsCompressing);
7846 }
7847 
7848 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7849                                       SDValue Val, SDValue Ptr, SDValue Mask,
7850                                       SDValue EVL, EVT SVT,
7851                                       MachineMemOperand *MMO,
7852                                       bool IsCompressing) {
7853   EVT VT = Val.getValueType();
7854 
7855   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7856   if (VT == SVT)
7857     return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7858 
7859   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7860          "Should only be a truncating store, not extending!");
7861   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
7862   assert(VT.isVector() == SVT.isVector() &&
7863          "Cannot use trunc store to convert to or from a vector!");
7864   assert((!VT.isVector() ||
7865           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7866          "Cannot use trunc store to change the number of vector elements!");
7867 
7868   SDVTList VTs = getVTList(MVT::Other);
7869   SDValue Undef = getUNDEF(Ptr.getValueType());
7870   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7871   FoldingSetNodeID ID;
7872   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7873   ID.AddInteger(SVT.getRawBits());
7874   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7875       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
7876   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7877   void *IP = nullptr;
7878   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7879     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7880     return SDValue(E, 0);
7881   }
7882   auto *N =
7883       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7884                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
7885   createOperands(N, Ops);
7886 
7887   CSEMap.InsertNode(N, IP);
7888   InsertNode(N);
7889   SDValue V(N, 0);
7890   NewSDValueDbgMsg(V, "Creating new node: ", this);
7891   return V;
7892 }
7893 
7894 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
7895                                         SDValue Base, SDValue Offset,
7896                                         ISD::MemIndexedMode AM) {
7897   auto *ST = cast<VPStoreSDNode>(OrigStore);
7898   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
7899   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7900   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
7901                    Offset,         ST->getMask(),  ST->getVectorLength()};
7902   FoldingSetNodeID ID;
7903   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7904   ID.AddInteger(ST->getMemoryVT().getRawBits());
7905   ID.AddInteger(ST->getRawSubclassData());
7906   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7907   void *IP = nullptr;
7908   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7909     return SDValue(E, 0);
7910 
7911   auto *N = newSDNode<VPStoreSDNode>(
7912       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
7913       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
7914   createOperands(N, Ops);
7915 
7916   CSEMap.InsertNode(N, IP);
7917   InsertNode(N);
7918   SDValue V(N, 0);
7919   NewSDValueDbgMsg(V, "Creating new node: ", this);
7920   return V;
7921 }
7922 
7923 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7924                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
7925                                   ISD::MemIndexType IndexType) {
7926   assert(Ops.size() == 6 && "Incompatible number of operands");
7927 
7928   FoldingSetNodeID ID;
7929   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
7930   ID.AddInteger(VT.getRawBits());
7931   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
7932       dl.getIROrder(), VTs, VT, MMO, IndexType));
7933   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7934   void *IP = nullptr;
7935   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7936     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
7937     return SDValue(E, 0);
7938   }
7939 
7940   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7941                                       VT, MMO, IndexType);
7942   createOperands(N, Ops);
7943 
7944   assert(N->getMask().getValueType().getVectorElementCount() ==
7945              N->getValueType(0).getVectorElementCount() &&
7946          "Vector width mismatch between mask and data");
7947   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7948              N->getValueType(0).getVectorElementCount().isScalable() &&
7949          "Scalable flags of index and data do not match");
7950   assert(ElementCount::isKnownGE(
7951              N->getIndex().getValueType().getVectorElementCount(),
7952              N->getValueType(0).getVectorElementCount()) &&
7953          "Vector width mismatch between index and data");
7954   assert(isa<ConstantSDNode>(N->getScale()) &&
7955          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7956          "Scale should be a constant power of 2");
7957 
7958   CSEMap.InsertNode(N, IP);
7959   InsertNode(N);
7960   SDValue V(N, 0);
7961   NewSDValueDbgMsg(V, "Creating new node: ", this);
7962   return V;
7963 }
7964 
7965 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7966                                    ArrayRef<SDValue> Ops,
7967                                    MachineMemOperand *MMO,
7968                                    ISD::MemIndexType IndexType) {
7969   assert(Ops.size() == 7 && "Incompatible number of operands");
7970 
7971   FoldingSetNodeID ID;
7972   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
7973   ID.AddInteger(VT.getRawBits());
7974   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
7975       dl.getIROrder(), VTs, VT, MMO, IndexType));
7976   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7977   void *IP = nullptr;
7978   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7979     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
7980     return SDValue(E, 0);
7981   }
7982   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7983                                        VT, MMO, IndexType);
7984   createOperands(N, Ops);
7985 
7986   assert(N->getMask().getValueType().getVectorElementCount() ==
7987              N->getValue().getValueType().getVectorElementCount() &&
7988          "Vector width mismatch between mask and data");
7989   assert(
7990       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7991           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7992       "Scalable flags of index and data do not match");
7993   assert(ElementCount::isKnownGE(
7994              N->getIndex().getValueType().getVectorElementCount(),
7995              N->getValue().getValueType().getVectorElementCount()) &&
7996          "Vector width mismatch between index and data");
7997   assert(isa<ConstantSDNode>(N->getScale()) &&
7998          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7999          "Scale should be a constant power of 2");
8000 
8001   CSEMap.InsertNode(N, IP);
8002   InsertNode(N);
8003   SDValue V(N, 0);
8004   NewSDValueDbgMsg(V, "Creating new node: ", this);
8005   return V;
8006 }
8007 
8008 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8009                                     SDValue Base, SDValue Offset, SDValue Mask,
8010                                     SDValue PassThru, EVT MemVT,
8011                                     MachineMemOperand *MMO,
8012                                     ISD::MemIndexedMode AM,
8013                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8014   bool Indexed = AM != ISD::UNINDEXED;
8015   assert((Indexed || Offset.isUndef()) &&
8016          "Unindexed masked load with an offset!");
8017   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8018                          : getVTList(VT, MVT::Other);
8019   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8020   FoldingSetNodeID ID;
8021   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8022   ID.AddInteger(MemVT.getRawBits());
8023   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8024       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8025   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8026   void *IP = nullptr;
8027   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8028     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8029     return SDValue(E, 0);
8030   }
8031   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8032                                         AM, ExtTy, isExpanding, MemVT, MMO);
8033   createOperands(N, Ops);
8034 
8035   CSEMap.InsertNode(N, IP);
8036   InsertNode(N);
8037   SDValue V(N, 0);
8038   NewSDValueDbgMsg(V, "Creating new node: ", this);
8039   return V;
8040 }
8041 
8042 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8043                                            SDValue Base, SDValue Offset,
8044                                            ISD::MemIndexedMode AM) {
8045   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8046   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8047   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8048                        Offset, LD->getMask(), LD->getPassThru(),
8049                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8050                        LD->getExtensionType(), LD->isExpandingLoad());
8051 }
8052 
8053 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8054                                      SDValue Val, SDValue Base, SDValue Offset,
8055                                      SDValue Mask, EVT MemVT,
8056                                      MachineMemOperand *MMO,
8057                                      ISD::MemIndexedMode AM, bool IsTruncating,
8058                                      bool IsCompressing) {
8059   assert(Chain.getValueType() == MVT::Other &&
8060         "Invalid chain type");
8061   bool Indexed = AM != ISD::UNINDEXED;
8062   assert((Indexed || Offset.isUndef()) &&
8063          "Unindexed masked store with an offset!");
8064   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8065                          : getVTList(MVT::Other);
8066   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8067   FoldingSetNodeID ID;
8068   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8069   ID.AddInteger(MemVT.getRawBits());
8070   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8071       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8072   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8073   void *IP = nullptr;
8074   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8075     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8076     return SDValue(E, 0);
8077   }
8078   auto *N =
8079       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8080                                    IsTruncating, IsCompressing, MemVT, MMO);
8081   createOperands(N, Ops);
8082 
8083   CSEMap.InsertNode(N, IP);
8084   InsertNode(N);
8085   SDValue V(N, 0);
8086   NewSDValueDbgMsg(V, "Creating new node: ", this);
8087   return V;
8088 }
8089 
8090 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8091                                             SDValue Base, SDValue Offset,
8092                                             ISD::MemIndexedMode AM) {
8093   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8094   assert(ST->getOffset().isUndef() &&
8095          "Masked store is already a indexed store!");
8096   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8097                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8098                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8099 }
8100 
8101 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8102                                       ArrayRef<SDValue> Ops,
8103                                       MachineMemOperand *MMO,
8104                                       ISD::MemIndexType IndexType,
8105                                       ISD::LoadExtType ExtTy) {
8106   assert(Ops.size() == 6 && "Incompatible number of operands");
8107 
8108   FoldingSetNodeID ID;
8109   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8110   ID.AddInteger(MemVT.getRawBits());
8111   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8112       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8113   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8114   void *IP = nullptr;
8115   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8116     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8117     return SDValue(E, 0);
8118   }
8119 
8120   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8121   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8122                                           VTs, MemVT, MMO, IndexType, ExtTy);
8123   createOperands(N, Ops);
8124 
8125   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8126          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8127   assert(N->getMask().getValueType().getVectorElementCount() ==
8128              N->getValueType(0).getVectorElementCount() &&
8129          "Vector width mismatch between mask and data");
8130   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8131              N->getValueType(0).getVectorElementCount().isScalable() &&
8132          "Scalable flags of index and data do not match");
8133   assert(ElementCount::isKnownGE(
8134              N->getIndex().getValueType().getVectorElementCount(),
8135              N->getValueType(0).getVectorElementCount()) &&
8136          "Vector width mismatch between index and data");
8137   assert(isa<ConstantSDNode>(N->getScale()) &&
8138          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8139          "Scale should be a constant power of 2");
8140 
8141   CSEMap.InsertNode(N, IP);
8142   InsertNode(N);
8143   SDValue V(N, 0);
8144   NewSDValueDbgMsg(V, "Creating new node: ", this);
8145   return V;
8146 }
8147 
8148 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8149                                        ArrayRef<SDValue> Ops,
8150                                        MachineMemOperand *MMO,
8151                                        ISD::MemIndexType IndexType,
8152                                        bool IsTrunc) {
8153   assert(Ops.size() == 6 && "Incompatible number of operands");
8154 
8155   FoldingSetNodeID ID;
8156   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8157   ID.AddInteger(MemVT.getRawBits());
8158   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8159       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8160   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8161   void *IP = nullptr;
8162   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8163     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8164     return SDValue(E, 0);
8165   }
8166 
8167   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8168   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8169                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8170   createOperands(N, Ops);
8171 
8172   assert(N->getMask().getValueType().getVectorElementCount() ==
8173              N->getValue().getValueType().getVectorElementCount() &&
8174          "Vector width mismatch between mask and data");
8175   assert(
8176       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8177           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8178       "Scalable flags of index and data do not match");
8179   assert(ElementCount::isKnownGE(
8180              N->getIndex().getValueType().getVectorElementCount(),
8181              N->getValue().getValueType().getVectorElementCount()) &&
8182          "Vector width mismatch between index and data");
8183   assert(isa<ConstantSDNode>(N->getScale()) &&
8184          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8185          "Scale should be a constant power of 2");
8186 
8187   CSEMap.InsertNode(N, IP);
8188   InsertNode(N);
8189   SDValue V(N, 0);
8190   NewSDValueDbgMsg(V, "Creating new node: ", this);
8191   return V;
8192 }
8193 
8194 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8195   // select undef, T, F --> T (if T is a constant), otherwise F
8196   // select, ?, undef, F --> F
8197   // select, ?, T, undef --> T
8198   if (Cond.isUndef())
8199     return isConstantValueOfAnyType(T) ? T : F;
8200   if (T.isUndef())
8201     return F;
8202   if (F.isUndef())
8203     return T;
8204 
8205   // select true, T, F --> T
8206   // select false, T, F --> F
8207   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8208     return CondC->isZero() ? F : T;
8209 
8210   // TODO: This should simplify VSELECT with constant condition using something
8211   // like this (but check boolean contents to be complete?):
8212   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8213   //    return T;
8214   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8215   //    return F;
8216 
8217   // select ?, T, T --> T
8218   if (T == F)
8219     return T;
8220 
8221   return SDValue();
8222 }
8223 
8224 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8225   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8226   if (X.isUndef())
8227     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8228   // shift X, undef --> undef (because it may shift by the bitwidth)
8229   if (Y.isUndef())
8230     return getUNDEF(X.getValueType());
8231 
8232   // shift 0, Y --> 0
8233   // shift X, 0 --> X
8234   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8235     return X;
8236 
8237   // shift X, C >= bitwidth(X) --> undef
8238   // All vector elements must be too big (or undef) to avoid partial undefs.
8239   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8240     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8241   };
8242   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8243     return getUNDEF(X.getValueType());
8244 
8245   return SDValue();
8246 }
8247 
8248 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8249                                       SDNodeFlags Flags) {
8250   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8251   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8252   // operation is poison. That result can be relaxed to undef.
8253   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8254   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8255   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8256                 (YC && YC->getValueAPF().isNaN());
8257   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8258                 (YC && YC->getValueAPF().isInfinity());
8259 
8260   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8261     return getUNDEF(X.getValueType());
8262 
8263   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8264     return getUNDEF(X.getValueType());
8265 
8266   if (!YC)
8267     return SDValue();
8268 
8269   // X + -0.0 --> X
8270   if (Opcode == ISD::FADD)
8271     if (YC->getValueAPF().isNegZero())
8272       return X;
8273 
8274   // X - +0.0 --> X
8275   if (Opcode == ISD::FSUB)
8276     if (YC->getValueAPF().isPosZero())
8277       return X;
8278 
8279   // X * 1.0 --> X
8280   // X / 1.0 --> X
8281   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8282     if (YC->getValueAPF().isExactlyValue(1.0))
8283       return X;
8284 
8285   // X * 0.0 --> 0.0
8286   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8287     if (YC->getValueAPF().isZero())
8288       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8289 
8290   return SDValue();
8291 }
8292 
8293 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8294                                SDValue Ptr, SDValue SV, unsigned Align) {
8295   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8296   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8297 }
8298 
8299 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8300                               ArrayRef<SDUse> Ops) {
8301   switch (Ops.size()) {
8302   case 0: return getNode(Opcode, DL, VT);
8303   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8304   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8305   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8306   default: break;
8307   }
8308 
8309   // Copy from an SDUse array into an SDValue array for use with
8310   // the regular getNode logic.
8311   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8312   return getNode(Opcode, DL, VT, NewOps);
8313 }
8314 
8315 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8316                               ArrayRef<SDValue> Ops) {
8317   SDNodeFlags Flags;
8318   if (Inserter)
8319     Flags = Inserter->getFlags();
8320   return getNode(Opcode, DL, VT, Ops, Flags);
8321 }
8322 
8323 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8324                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8325   unsigned NumOps = Ops.size();
8326   switch (NumOps) {
8327   case 0: return getNode(Opcode, DL, VT);
8328   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8329   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8330   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8331   default: break;
8332   }
8333 
8334 #ifndef NDEBUG
8335   for (auto &Op : Ops)
8336     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8337            "Operand is DELETED_NODE!");
8338 #endif
8339 
8340   switch (Opcode) {
8341   default: break;
8342   case ISD::BUILD_VECTOR:
8343     // Attempt to simplify BUILD_VECTOR.
8344     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8345       return V;
8346     break;
8347   case ISD::CONCAT_VECTORS:
8348     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8349       return V;
8350     break;
8351   case ISD::SELECT_CC:
8352     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8353     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8354            "LHS and RHS of condition must have same type!");
8355     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8356            "True and False arms of SelectCC must have same type!");
8357     assert(Ops[2].getValueType() == VT &&
8358            "select_cc node must be of same type as true and false value!");
8359     break;
8360   case ISD::BR_CC:
8361     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8362     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8363            "LHS/RHS of comparison should match types!");
8364     break;
8365   }
8366 
8367   // Memoize nodes.
8368   SDNode *N;
8369   SDVTList VTs = getVTList(VT);
8370 
8371   if (VT != MVT::Glue) {
8372     FoldingSetNodeID ID;
8373     AddNodeIDNode(ID, Opcode, VTs, Ops);
8374     void *IP = nullptr;
8375 
8376     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8377       return SDValue(E, 0);
8378 
8379     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8380     createOperands(N, Ops);
8381 
8382     CSEMap.InsertNode(N, IP);
8383   } else {
8384     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8385     createOperands(N, Ops);
8386   }
8387 
8388   N->setFlags(Flags);
8389   InsertNode(N);
8390   SDValue V(N, 0);
8391   NewSDValueDbgMsg(V, "Creating new node: ", this);
8392   return V;
8393 }
8394 
8395 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8396                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8397   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8398 }
8399 
8400 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8401                               ArrayRef<SDValue> Ops) {
8402   SDNodeFlags Flags;
8403   if (Inserter)
8404     Flags = Inserter->getFlags();
8405   return getNode(Opcode, DL, VTList, Ops, Flags);
8406 }
8407 
8408 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8409                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8410   if (VTList.NumVTs == 1)
8411     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8412 
8413 #ifndef NDEBUG
8414   for (auto &Op : Ops)
8415     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8416            "Operand is DELETED_NODE!");
8417 #endif
8418 
8419   switch (Opcode) {
8420   case ISD::STRICT_FP_EXTEND:
8421     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8422            "Invalid STRICT_FP_EXTEND!");
8423     assert(VTList.VTs[0].isFloatingPoint() &&
8424            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8425     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8426            "STRICT_FP_EXTEND result type should be vector iff the operand "
8427            "type is vector!");
8428     assert((!VTList.VTs[0].isVector() ||
8429             VTList.VTs[0].getVectorNumElements() ==
8430             Ops[1].getValueType().getVectorNumElements()) &&
8431            "Vector element count mismatch!");
8432     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8433            "Invalid fpext node, dst <= src!");
8434     break;
8435   case ISD::STRICT_FP_ROUND:
8436     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8437     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8438            "STRICT_FP_ROUND result type should be vector iff the operand "
8439            "type is vector!");
8440     assert((!VTList.VTs[0].isVector() ||
8441             VTList.VTs[0].getVectorNumElements() ==
8442             Ops[1].getValueType().getVectorNumElements()) &&
8443            "Vector element count mismatch!");
8444     assert(VTList.VTs[0].isFloatingPoint() &&
8445            Ops[1].getValueType().isFloatingPoint() &&
8446            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8447            isa<ConstantSDNode>(Ops[2]) &&
8448            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8449             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8450            "Invalid STRICT_FP_ROUND!");
8451     break;
8452 #if 0
8453   // FIXME: figure out how to safely handle things like
8454   // int foo(int x) { return 1 << (x & 255); }
8455   // int bar() { return foo(256); }
8456   case ISD::SRA_PARTS:
8457   case ISD::SRL_PARTS:
8458   case ISD::SHL_PARTS:
8459     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8460         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8461       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8462     else if (N3.getOpcode() == ISD::AND)
8463       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8464         // If the and is only masking out bits that cannot effect the shift,
8465         // eliminate the and.
8466         unsigned NumBits = VT.getScalarSizeInBits()*2;
8467         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8468           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8469       }
8470     break;
8471 #endif
8472   }
8473 
8474   // Memoize the node unless it returns a flag.
8475   SDNode *N;
8476   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8477     FoldingSetNodeID ID;
8478     AddNodeIDNode(ID, Opcode, VTList, Ops);
8479     void *IP = nullptr;
8480     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8481       return SDValue(E, 0);
8482 
8483     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8484     createOperands(N, Ops);
8485     CSEMap.InsertNode(N, IP);
8486   } else {
8487     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8488     createOperands(N, Ops);
8489   }
8490 
8491   N->setFlags(Flags);
8492   InsertNode(N);
8493   SDValue V(N, 0);
8494   NewSDValueDbgMsg(V, "Creating new node: ", this);
8495   return V;
8496 }
8497 
8498 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8499                               SDVTList VTList) {
8500   return getNode(Opcode, DL, VTList, None);
8501 }
8502 
8503 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8504                               SDValue N1) {
8505   SDValue Ops[] = { N1 };
8506   return getNode(Opcode, DL, VTList, Ops);
8507 }
8508 
8509 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8510                               SDValue N1, SDValue N2) {
8511   SDValue Ops[] = { N1, N2 };
8512   return getNode(Opcode, DL, VTList, Ops);
8513 }
8514 
8515 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8516                               SDValue N1, SDValue N2, SDValue N3) {
8517   SDValue Ops[] = { N1, N2, N3 };
8518   return getNode(Opcode, DL, VTList, Ops);
8519 }
8520 
8521 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8522                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8523   SDValue Ops[] = { N1, N2, N3, N4 };
8524   return getNode(Opcode, DL, VTList, Ops);
8525 }
8526 
8527 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8528                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8529                               SDValue N5) {
8530   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8531   return getNode(Opcode, DL, VTList, Ops);
8532 }
8533 
8534 SDVTList SelectionDAG::getVTList(EVT VT) {
8535   return makeVTList(SDNode::getValueTypeList(VT), 1);
8536 }
8537 
8538 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8539   FoldingSetNodeID ID;
8540   ID.AddInteger(2U);
8541   ID.AddInteger(VT1.getRawBits());
8542   ID.AddInteger(VT2.getRawBits());
8543 
8544   void *IP = nullptr;
8545   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8546   if (!Result) {
8547     EVT *Array = Allocator.Allocate<EVT>(2);
8548     Array[0] = VT1;
8549     Array[1] = VT2;
8550     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8551     VTListMap.InsertNode(Result, IP);
8552   }
8553   return Result->getSDVTList();
8554 }
8555 
8556 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8557   FoldingSetNodeID ID;
8558   ID.AddInteger(3U);
8559   ID.AddInteger(VT1.getRawBits());
8560   ID.AddInteger(VT2.getRawBits());
8561   ID.AddInteger(VT3.getRawBits());
8562 
8563   void *IP = nullptr;
8564   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8565   if (!Result) {
8566     EVT *Array = Allocator.Allocate<EVT>(3);
8567     Array[0] = VT1;
8568     Array[1] = VT2;
8569     Array[2] = VT3;
8570     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8571     VTListMap.InsertNode(Result, IP);
8572   }
8573   return Result->getSDVTList();
8574 }
8575 
8576 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8577   FoldingSetNodeID ID;
8578   ID.AddInteger(4U);
8579   ID.AddInteger(VT1.getRawBits());
8580   ID.AddInteger(VT2.getRawBits());
8581   ID.AddInteger(VT3.getRawBits());
8582   ID.AddInteger(VT4.getRawBits());
8583 
8584   void *IP = nullptr;
8585   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8586   if (!Result) {
8587     EVT *Array = Allocator.Allocate<EVT>(4);
8588     Array[0] = VT1;
8589     Array[1] = VT2;
8590     Array[2] = VT3;
8591     Array[3] = VT4;
8592     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8593     VTListMap.InsertNode(Result, IP);
8594   }
8595   return Result->getSDVTList();
8596 }
8597 
8598 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8599   unsigned NumVTs = VTs.size();
8600   FoldingSetNodeID ID;
8601   ID.AddInteger(NumVTs);
8602   for (unsigned index = 0; index < NumVTs; index++) {
8603     ID.AddInteger(VTs[index].getRawBits());
8604   }
8605 
8606   void *IP = nullptr;
8607   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8608   if (!Result) {
8609     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8610     llvm::copy(VTs, Array);
8611     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8612     VTListMap.InsertNode(Result, IP);
8613   }
8614   return Result->getSDVTList();
8615 }
8616 
8617 
8618 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8619 /// specified operands.  If the resultant node already exists in the DAG,
8620 /// this does not modify the specified node, instead it returns the node that
8621 /// already exists.  If the resultant node does not exist in the DAG, the
8622 /// input node is returned.  As a degenerate case, if you specify the same
8623 /// input operands as the node already has, the input node is returned.
8624 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8625   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8626 
8627   // Check to see if there is no change.
8628   if (Op == N->getOperand(0)) return N;
8629 
8630   // See if the modified node already exists.
8631   void *InsertPos = nullptr;
8632   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8633     return Existing;
8634 
8635   // Nope it doesn't.  Remove the node from its current place in the maps.
8636   if (InsertPos)
8637     if (!RemoveNodeFromCSEMaps(N))
8638       InsertPos = nullptr;
8639 
8640   // Now we update the operands.
8641   N->OperandList[0].set(Op);
8642 
8643   updateDivergence(N);
8644   // If this gets put into a CSE map, add it.
8645   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8646   return N;
8647 }
8648 
8649 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8650   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8651 
8652   // Check to see if there is no change.
8653   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8654     return N;   // No operands changed, just return the input node.
8655 
8656   // See if the modified node already exists.
8657   void *InsertPos = nullptr;
8658   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8659     return Existing;
8660 
8661   // Nope it doesn't.  Remove the node from its current place in the maps.
8662   if (InsertPos)
8663     if (!RemoveNodeFromCSEMaps(N))
8664       InsertPos = nullptr;
8665 
8666   // Now we update the operands.
8667   if (N->OperandList[0] != Op1)
8668     N->OperandList[0].set(Op1);
8669   if (N->OperandList[1] != Op2)
8670     N->OperandList[1].set(Op2);
8671 
8672   updateDivergence(N);
8673   // If this gets put into a CSE map, add it.
8674   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8675   return N;
8676 }
8677 
8678 SDNode *SelectionDAG::
8679 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8680   SDValue Ops[] = { Op1, Op2, Op3 };
8681   return UpdateNodeOperands(N, Ops);
8682 }
8683 
8684 SDNode *SelectionDAG::
8685 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8686                    SDValue Op3, SDValue Op4) {
8687   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8688   return UpdateNodeOperands(N, Ops);
8689 }
8690 
8691 SDNode *SelectionDAG::
8692 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8693                    SDValue Op3, SDValue Op4, SDValue Op5) {
8694   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8695   return UpdateNodeOperands(N, Ops);
8696 }
8697 
8698 SDNode *SelectionDAG::
8699 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8700   unsigned NumOps = Ops.size();
8701   assert(N->getNumOperands() == NumOps &&
8702          "Update with wrong number of operands");
8703 
8704   // If no operands changed just return the input node.
8705   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8706     return N;
8707 
8708   // See if the modified node already exists.
8709   void *InsertPos = nullptr;
8710   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8711     return Existing;
8712 
8713   // Nope it doesn't.  Remove the node from its current place in the maps.
8714   if (InsertPos)
8715     if (!RemoveNodeFromCSEMaps(N))
8716       InsertPos = nullptr;
8717 
8718   // Now we update the operands.
8719   for (unsigned i = 0; i != NumOps; ++i)
8720     if (N->OperandList[i] != Ops[i])
8721       N->OperandList[i].set(Ops[i]);
8722 
8723   updateDivergence(N);
8724   // If this gets put into a CSE map, add it.
8725   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8726   return N;
8727 }
8728 
8729 /// DropOperands - Release the operands and set this node to have
8730 /// zero operands.
8731 void SDNode::DropOperands() {
8732   // Unlike the code in MorphNodeTo that does this, we don't need to
8733   // watch for dead nodes here.
8734   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8735     SDUse &Use = *I++;
8736     Use.set(SDValue());
8737   }
8738 }
8739 
8740 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8741                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8742   if (NewMemRefs.empty()) {
8743     N->clearMemRefs();
8744     return;
8745   }
8746 
8747   // Check if we can avoid allocating by storing a single reference directly.
8748   if (NewMemRefs.size() == 1) {
8749     N->MemRefs = NewMemRefs[0];
8750     N->NumMemRefs = 1;
8751     return;
8752   }
8753 
8754   MachineMemOperand **MemRefsBuffer =
8755       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8756   llvm::copy(NewMemRefs, MemRefsBuffer);
8757   N->MemRefs = MemRefsBuffer;
8758   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8759 }
8760 
8761 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8762 /// machine opcode.
8763 ///
8764 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8765                                    EVT VT) {
8766   SDVTList VTs = getVTList(VT);
8767   return SelectNodeTo(N, MachineOpc, VTs, None);
8768 }
8769 
8770 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8771                                    EVT VT, SDValue Op1) {
8772   SDVTList VTs = getVTList(VT);
8773   SDValue Ops[] = { Op1 };
8774   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8775 }
8776 
8777 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8778                                    EVT VT, SDValue Op1,
8779                                    SDValue Op2) {
8780   SDVTList VTs = getVTList(VT);
8781   SDValue Ops[] = { Op1, Op2 };
8782   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8783 }
8784 
8785 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8786                                    EVT VT, SDValue Op1,
8787                                    SDValue Op2, SDValue Op3) {
8788   SDVTList VTs = getVTList(VT);
8789   SDValue Ops[] = { Op1, Op2, Op3 };
8790   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8791 }
8792 
8793 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8794                                    EVT VT, ArrayRef<SDValue> Ops) {
8795   SDVTList VTs = getVTList(VT);
8796   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8797 }
8798 
8799 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8800                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8801   SDVTList VTs = getVTList(VT1, VT2);
8802   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8803 }
8804 
8805 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8806                                    EVT VT1, EVT VT2) {
8807   SDVTList VTs = getVTList(VT1, VT2);
8808   return SelectNodeTo(N, MachineOpc, VTs, None);
8809 }
8810 
8811 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8812                                    EVT VT1, EVT VT2, EVT VT3,
8813                                    ArrayRef<SDValue> Ops) {
8814   SDVTList VTs = getVTList(VT1, VT2, VT3);
8815   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8816 }
8817 
8818 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8819                                    EVT VT1, EVT VT2,
8820                                    SDValue Op1, SDValue Op2) {
8821   SDVTList VTs = getVTList(VT1, VT2);
8822   SDValue Ops[] = { Op1, Op2 };
8823   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8824 }
8825 
8826 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8827                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8828   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8829   // Reset the NodeID to -1.
8830   New->setNodeId(-1);
8831   if (New != N) {
8832     ReplaceAllUsesWith(N, New);
8833     RemoveDeadNode(N);
8834   }
8835   return New;
8836 }
8837 
8838 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8839 /// the line number information on the merged node since it is not possible to
8840 /// preserve the information that operation is associated with multiple lines.
8841 /// This will make the debugger working better at -O0, were there is a higher
8842 /// probability having other instructions associated with that line.
8843 ///
8844 /// For IROrder, we keep the smaller of the two
8845 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8846   DebugLoc NLoc = N->getDebugLoc();
8847   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8848     N->setDebugLoc(DebugLoc());
8849   }
8850   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8851   N->setIROrder(Order);
8852   return N;
8853 }
8854 
8855 /// MorphNodeTo - This *mutates* the specified node to have the specified
8856 /// return type, opcode, and operands.
8857 ///
8858 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8859 /// node of the specified opcode and operands, it returns that node instead of
8860 /// the current one.  Note that the SDLoc need not be the same.
8861 ///
8862 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8863 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8864 /// node, and because it doesn't require CSE recalculation for any of
8865 /// the node's users.
8866 ///
8867 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8868 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8869 /// the legalizer which maintain worklists that would need to be updated when
8870 /// deleting things.
8871 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8872                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8873   // If an identical node already exists, use it.
8874   void *IP = nullptr;
8875   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8876     FoldingSetNodeID ID;
8877     AddNodeIDNode(ID, Opc, VTs, Ops);
8878     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8879       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8880   }
8881 
8882   if (!RemoveNodeFromCSEMaps(N))
8883     IP = nullptr;
8884 
8885   // Start the morphing.
8886   N->NodeType = Opc;
8887   N->ValueList = VTs.VTs;
8888   N->NumValues = VTs.NumVTs;
8889 
8890   // Clear the operands list, updating used nodes to remove this from their
8891   // use list.  Keep track of any operands that become dead as a result.
8892   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8893   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8894     SDUse &Use = *I++;
8895     SDNode *Used = Use.getNode();
8896     Use.set(SDValue());
8897     if (Used->use_empty())
8898       DeadNodeSet.insert(Used);
8899   }
8900 
8901   // For MachineNode, initialize the memory references information.
8902   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8903     MN->clearMemRefs();
8904 
8905   // Swap for an appropriately sized array from the recycler.
8906   removeOperands(N);
8907   createOperands(N, Ops);
8908 
8909   // Delete any nodes that are still dead after adding the uses for the
8910   // new operands.
8911   if (!DeadNodeSet.empty()) {
8912     SmallVector<SDNode *, 16> DeadNodes;
8913     for (SDNode *N : DeadNodeSet)
8914       if (N->use_empty())
8915         DeadNodes.push_back(N);
8916     RemoveDeadNodes(DeadNodes);
8917   }
8918 
8919   if (IP)
8920     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8921   return N;
8922 }
8923 
8924 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8925   unsigned OrigOpc = Node->getOpcode();
8926   unsigned NewOpc;
8927   switch (OrigOpc) {
8928   default:
8929     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8930 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8931   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8932 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8933   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8934 #include "llvm/IR/ConstrainedOps.def"
8935   }
8936 
8937   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8938 
8939   // We're taking this node out of the chain, so we need to re-link things.
8940   SDValue InputChain = Node->getOperand(0);
8941   SDValue OutputChain = SDValue(Node, 1);
8942   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8943 
8944   SmallVector<SDValue, 3> Ops;
8945   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8946     Ops.push_back(Node->getOperand(i));
8947 
8948   SDVTList VTs = getVTList(Node->getValueType(0));
8949   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8950 
8951   // MorphNodeTo can operate in two ways: if an existing node with the
8952   // specified operands exists, it can just return it.  Otherwise, it
8953   // updates the node in place to have the requested operands.
8954   if (Res == Node) {
8955     // If we updated the node in place, reset the node ID.  To the isel,
8956     // this should be just like a newly allocated machine node.
8957     Res->setNodeId(-1);
8958   } else {
8959     ReplaceAllUsesWith(Node, Res);
8960     RemoveDeadNode(Node);
8961   }
8962 
8963   return Res;
8964 }
8965 
8966 /// getMachineNode - These are used for target selectors to create a new node
8967 /// with specified return type(s), MachineInstr opcode, and operands.
8968 ///
8969 /// Note that getMachineNode returns the resultant node.  If there is already a
8970 /// node of the specified opcode and operands, it returns that node instead of
8971 /// the current one.
8972 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8973                                             EVT VT) {
8974   SDVTList VTs = getVTList(VT);
8975   return getMachineNode(Opcode, dl, VTs, None);
8976 }
8977 
8978 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8979                                             EVT VT, SDValue Op1) {
8980   SDVTList VTs = getVTList(VT);
8981   SDValue Ops[] = { Op1 };
8982   return getMachineNode(Opcode, dl, VTs, Ops);
8983 }
8984 
8985 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8986                                             EVT VT, SDValue Op1, SDValue Op2) {
8987   SDVTList VTs = getVTList(VT);
8988   SDValue Ops[] = { Op1, Op2 };
8989   return getMachineNode(Opcode, dl, VTs, Ops);
8990 }
8991 
8992 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8993                                             EVT VT, SDValue Op1, SDValue Op2,
8994                                             SDValue Op3) {
8995   SDVTList VTs = getVTList(VT);
8996   SDValue Ops[] = { Op1, Op2, Op3 };
8997   return getMachineNode(Opcode, dl, VTs, Ops);
8998 }
8999 
9000 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9001                                             EVT VT, ArrayRef<SDValue> Ops) {
9002   SDVTList VTs = getVTList(VT);
9003   return getMachineNode(Opcode, dl, VTs, Ops);
9004 }
9005 
9006 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9007                                             EVT VT1, EVT VT2, SDValue Op1,
9008                                             SDValue Op2) {
9009   SDVTList VTs = getVTList(VT1, VT2);
9010   SDValue Ops[] = { Op1, Op2 };
9011   return getMachineNode(Opcode, dl, VTs, Ops);
9012 }
9013 
9014 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9015                                             EVT VT1, EVT VT2, SDValue Op1,
9016                                             SDValue Op2, SDValue Op3) {
9017   SDVTList VTs = getVTList(VT1, VT2);
9018   SDValue Ops[] = { Op1, Op2, Op3 };
9019   return getMachineNode(Opcode, dl, VTs, Ops);
9020 }
9021 
9022 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9023                                             EVT VT1, EVT VT2,
9024                                             ArrayRef<SDValue> Ops) {
9025   SDVTList VTs = getVTList(VT1, VT2);
9026   return getMachineNode(Opcode, dl, VTs, Ops);
9027 }
9028 
9029 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9030                                             EVT VT1, EVT VT2, EVT VT3,
9031                                             SDValue Op1, SDValue Op2) {
9032   SDVTList VTs = getVTList(VT1, VT2, VT3);
9033   SDValue Ops[] = { Op1, Op2 };
9034   return getMachineNode(Opcode, dl, VTs, Ops);
9035 }
9036 
9037 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9038                                             EVT VT1, EVT VT2, EVT VT3,
9039                                             SDValue Op1, SDValue Op2,
9040                                             SDValue Op3) {
9041   SDVTList VTs = getVTList(VT1, VT2, VT3);
9042   SDValue Ops[] = { Op1, Op2, Op3 };
9043   return getMachineNode(Opcode, dl, VTs, Ops);
9044 }
9045 
9046 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9047                                             EVT VT1, EVT VT2, EVT VT3,
9048                                             ArrayRef<SDValue> Ops) {
9049   SDVTList VTs = getVTList(VT1, VT2, VT3);
9050   return getMachineNode(Opcode, dl, VTs, Ops);
9051 }
9052 
9053 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9054                                             ArrayRef<EVT> ResultTys,
9055                                             ArrayRef<SDValue> Ops) {
9056   SDVTList VTs = getVTList(ResultTys);
9057   return getMachineNode(Opcode, dl, VTs, Ops);
9058 }
9059 
9060 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9061                                             SDVTList VTs,
9062                                             ArrayRef<SDValue> Ops) {
9063   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9064   MachineSDNode *N;
9065   void *IP = nullptr;
9066 
9067   if (DoCSE) {
9068     FoldingSetNodeID ID;
9069     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9070     IP = nullptr;
9071     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9072       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9073     }
9074   }
9075 
9076   // Allocate a new MachineSDNode.
9077   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9078   createOperands(N, Ops);
9079 
9080   if (DoCSE)
9081     CSEMap.InsertNode(N, IP);
9082 
9083   InsertNode(N);
9084   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9085   return N;
9086 }
9087 
9088 /// getTargetExtractSubreg - A convenience function for creating
9089 /// TargetOpcode::EXTRACT_SUBREG nodes.
9090 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9091                                              SDValue Operand) {
9092   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9093   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9094                                   VT, Operand, SRIdxVal);
9095   return SDValue(Subreg, 0);
9096 }
9097 
9098 /// getTargetInsertSubreg - A convenience function for creating
9099 /// TargetOpcode::INSERT_SUBREG nodes.
9100 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9101                                             SDValue Operand, SDValue Subreg) {
9102   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9103   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9104                                   VT, Operand, Subreg, SRIdxVal);
9105   return SDValue(Result, 0);
9106 }
9107 
9108 /// getNodeIfExists - Get the specified node if it's already available, or
9109 /// else return NULL.
9110 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9111                                       ArrayRef<SDValue> Ops) {
9112   SDNodeFlags Flags;
9113   if (Inserter)
9114     Flags = Inserter->getFlags();
9115   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9116 }
9117 
9118 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9119                                       ArrayRef<SDValue> Ops,
9120                                       const SDNodeFlags Flags) {
9121   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9122     FoldingSetNodeID ID;
9123     AddNodeIDNode(ID, Opcode, VTList, Ops);
9124     void *IP = nullptr;
9125     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9126       E->intersectFlagsWith(Flags);
9127       return E;
9128     }
9129   }
9130   return nullptr;
9131 }
9132 
9133 /// doesNodeExist - Check if a node exists without modifying its flags.
9134 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9135                                  ArrayRef<SDValue> Ops) {
9136   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9137     FoldingSetNodeID ID;
9138     AddNodeIDNode(ID, Opcode, VTList, Ops);
9139     void *IP = nullptr;
9140     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9141       return true;
9142   }
9143   return false;
9144 }
9145 
9146 /// getDbgValue - Creates a SDDbgValue node.
9147 ///
9148 /// SDNode
9149 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9150                                       SDNode *N, unsigned R, bool IsIndirect,
9151                                       const DebugLoc &DL, unsigned O) {
9152   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9153          "Expected inlined-at fields to agree");
9154   return new (DbgInfo->getAlloc())
9155       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9156                  {}, IsIndirect, DL, O,
9157                  /*IsVariadic=*/false);
9158 }
9159 
9160 /// Constant
9161 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9162                                               DIExpression *Expr,
9163                                               const Value *C,
9164                                               const DebugLoc &DL, unsigned O) {
9165   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9166          "Expected inlined-at fields to agree");
9167   return new (DbgInfo->getAlloc())
9168       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9169                  /*IsIndirect=*/false, DL, O,
9170                  /*IsVariadic=*/false);
9171 }
9172 
9173 /// FrameIndex
9174 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9175                                                 DIExpression *Expr, unsigned FI,
9176                                                 bool IsIndirect,
9177                                                 const DebugLoc &DL,
9178                                                 unsigned O) {
9179   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9180          "Expected inlined-at fields to agree");
9181   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9182 }
9183 
9184 /// FrameIndex with dependencies
9185 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9186                                                 DIExpression *Expr, unsigned FI,
9187                                                 ArrayRef<SDNode *> Dependencies,
9188                                                 bool IsIndirect,
9189                                                 const DebugLoc &DL,
9190                                                 unsigned O) {
9191   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9192          "Expected inlined-at fields to agree");
9193   return new (DbgInfo->getAlloc())
9194       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9195                  Dependencies, IsIndirect, DL, O,
9196                  /*IsVariadic=*/false);
9197 }
9198 
9199 /// VReg
9200 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9201                                           unsigned VReg, bool IsIndirect,
9202                                           const DebugLoc &DL, unsigned O) {
9203   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9204          "Expected inlined-at fields to agree");
9205   return new (DbgInfo->getAlloc())
9206       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9207                  {}, IsIndirect, DL, O,
9208                  /*IsVariadic=*/false);
9209 }
9210 
9211 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9212                                           ArrayRef<SDDbgOperand> Locs,
9213                                           ArrayRef<SDNode *> Dependencies,
9214                                           bool IsIndirect, const DebugLoc &DL,
9215                                           unsigned O, bool IsVariadic) {
9216   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9217          "Expected inlined-at fields to agree");
9218   return new (DbgInfo->getAlloc())
9219       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9220                  DL, O, IsVariadic);
9221 }
9222 
9223 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9224                                      unsigned OffsetInBits, unsigned SizeInBits,
9225                                      bool InvalidateDbg) {
9226   SDNode *FromNode = From.getNode();
9227   SDNode *ToNode = To.getNode();
9228   assert(FromNode && ToNode && "Can't modify dbg values");
9229 
9230   // PR35338
9231   // TODO: assert(From != To && "Redundant dbg value transfer");
9232   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9233   if (From == To || FromNode == ToNode)
9234     return;
9235 
9236   if (!FromNode->getHasDebugValue())
9237     return;
9238 
9239   SDDbgOperand FromLocOp =
9240       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9241   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9242 
9243   SmallVector<SDDbgValue *, 2> ClonedDVs;
9244   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9245     if (Dbg->isInvalidated())
9246       continue;
9247 
9248     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9249 
9250     // Create a new location ops vector that is equal to the old vector, but
9251     // with each instance of FromLocOp replaced with ToLocOp.
9252     bool Changed = false;
9253     auto NewLocOps = Dbg->copyLocationOps();
9254     std::replace_if(
9255         NewLocOps.begin(), NewLocOps.end(),
9256         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9257           bool Match = Op == FromLocOp;
9258           Changed |= Match;
9259           return Match;
9260         },
9261         ToLocOp);
9262     // Ignore this SDDbgValue if we didn't find a matching location.
9263     if (!Changed)
9264       continue;
9265 
9266     DIVariable *Var = Dbg->getVariable();
9267     auto *Expr = Dbg->getExpression();
9268     // If a fragment is requested, update the expression.
9269     if (SizeInBits) {
9270       // When splitting a larger (e.g., sign-extended) value whose
9271       // lower bits are described with an SDDbgValue, do not attempt
9272       // to transfer the SDDbgValue to the upper bits.
9273       if (auto FI = Expr->getFragmentInfo())
9274         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9275           continue;
9276       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9277                                                              SizeInBits);
9278       if (!Fragment)
9279         continue;
9280       Expr = *Fragment;
9281     }
9282 
9283     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9284     // Clone the SDDbgValue and move it to To.
9285     SDDbgValue *Clone = getDbgValueList(
9286         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9287         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9288         Dbg->isVariadic());
9289     ClonedDVs.push_back(Clone);
9290 
9291     if (InvalidateDbg) {
9292       // Invalidate value and indicate the SDDbgValue should not be emitted.
9293       Dbg->setIsInvalidated();
9294       Dbg->setIsEmitted();
9295     }
9296   }
9297 
9298   for (SDDbgValue *Dbg : ClonedDVs) {
9299     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9300            "Transferred DbgValues should depend on the new SDNode");
9301     AddDbgValue(Dbg, false);
9302   }
9303 }
9304 
9305 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9306   if (!N.getHasDebugValue())
9307     return;
9308 
9309   SmallVector<SDDbgValue *, 2> ClonedDVs;
9310   for (auto DV : GetDbgValues(&N)) {
9311     if (DV->isInvalidated())
9312       continue;
9313     switch (N.getOpcode()) {
9314     default:
9315       break;
9316     case ISD::ADD:
9317       SDValue N0 = N.getOperand(0);
9318       SDValue N1 = N.getOperand(1);
9319       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9320           isConstantIntBuildVectorOrConstantInt(N1)) {
9321         uint64_t Offset = N.getConstantOperandVal(1);
9322 
9323         // Rewrite an ADD constant node into a DIExpression. Since we are
9324         // performing arithmetic to compute the variable's *value* in the
9325         // DIExpression, we need to mark the expression with a
9326         // DW_OP_stack_value.
9327         auto *DIExpr = DV->getExpression();
9328         auto NewLocOps = DV->copyLocationOps();
9329         bool Changed = false;
9330         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9331           // We're not given a ResNo to compare against because the whole
9332           // node is going away. We know that any ISD::ADD only has one
9333           // result, so we can assume any node match is using the result.
9334           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9335               NewLocOps[i].getSDNode() != &N)
9336             continue;
9337           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9338           SmallVector<uint64_t, 3> ExprOps;
9339           DIExpression::appendOffset(ExprOps, Offset);
9340           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9341           Changed = true;
9342         }
9343         (void)Changed;
9344         assert(Changed && "Salvage target doesn't use N");
9345 
9346         auto AdditionalDependencies = DV->getAdditionalDependencies();
9347         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9348                                             NewLocOps, AdditionalDependencies,
9349                                             DV->isIndirect(), DV->getDebugLoc(),
9350                                             DV->getOrder(), DV->isVariadic());
9351         ClonedDVs.push_back(Clone);
9352         DV->setIsInvalidated();
9353         DV->setIsEmitted();
9354         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9355                    N0.getNode()->dumprFull(this);
9356                    dbgs() << " into " << *DIExpr << '\n');
9357       }
9358     }
9359   }
9360 
9361   for (SDDbgValue *Dbg : ClonedDVs) {
9362     assert(!Dbg->getSDNodes().empty() &&
9363            "Salvaged DbgValue should depend on a new SDNode");
9364     AddDbgValue(Dbg, false);
9365   }
9366 }
9367 
9368 /// Creates a SDDbgLabel node.
9369 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9370                                       const DebugLoc &DL, unsigned O) {
9371   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9372          "Expected inlined-at fields to agree");
9373   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9374 }
9375 
9376 namespace {
9377 
9378 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9379 /// pointed to by a use iterator is deleted, increment the use iterator
9380 /// so that it doesn't dangle.
9381 ///
9382 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9383   SDNode::use_iterator &UI;
9384   SDNode::use_iterator &UE;
9385 
9386   void NodeDeleted(SDNode *N, SDNode *E) override {
9387     // Increment the iterator as needed.
9388     while (UI != UE && N == *UI)
9389       ++UI;
9390   }
9391 
9392 public:
9393   RAUWUpdateListener(SelectionDAG &d,
9394                      SDNode::use_iterator &ui,
9395                      SDNode::use_iterator &ue)
9396     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9397 };
9398 
9399 } // end anonymous namespace
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 From has a single result value.
9405 ///
9406 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9407   SDNode *From = FromN.getNode();
9408   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9409          "Cannot replace with this method!");
9410   assert(From != To.getNode() && "Cannot replace uses of with self");
9411 
9412   // Preserve Debug Values
9413   transferDbgValues(FromN, To);
9414 
9415   // Iterate over all the existing uses of From. New uses will be added
9416   // to the beginning of the use list, which we avoid visiting.
9417   // This specifically avoids visiting uses of From that arise while the
9418   // replacement is happening, because any such uses would be the result
9419   // of CSE: If an existing node looks like From after one of its operands
9420   // is replaced by To, we don't want to replace of all its users with To
9421   // too. See PR3018 for more info.
9422   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9423   RAUWUpdateListener Listener(*this, UI, UE);
9424   while (UI != UE) {
9425     SDNode *User = *UI;
9426 
9427     // This node is about to morph, remove its old self from the CSE maps.
9428     RemoveNodeFromCSEMaps(User);
9429 
9430     // A user can appear in a use list multiple times, and when this
9431     // happens the uses are usually next to each other in the list.
9432     // To help reduce the number of CSE recomputations, process all
9433     // the uses of this user that we can find this way.
9434     do {
9435       SDUse &Use = UI.getUse();
9436       ++UI;
9437       Use.set(To);
9438       if (To->isDivergent() != From->isDivergent())
9439         updateDivergence(User);
9440     } while (UI != UE && *UI == User);
9441     // Now that we have modified User, add it back to the CSE maps.  If it
9442     // already exists there, recursively merge the results together.
9443     AddModifiedNodeToCSEMaps(User);
9444   }
9445 
9446   // If we just RAUW'd the root, take note.
9447   if (FromN == getRoot())
9448     setRoot(To);
9449 }
9450 
9451 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9452 /// This can cause recursive merging of nodes in the DAG.
9453 ///
9454 /// This version assumes that for each value of From, there is a
9455 /// corresponding value in To in the same position with the same type.
9456 ///
9457 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9458 #ifndef NDEBUG
9459   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9460     assert((!From->hasAnyUseOfValue(i) ||
9461             From->getValueType(i) == To->getValueType(i)) &&
9462            "Cannot use this version of ReplaceAllUsesWith!");
9463 #endif
9464 
9465   // Handle the trivial case.
9466   if (From == To)
9467     return;
9468 
9469   // Preserve Debug Info. Only do this if there's a use.
9470   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9471     if (From->hasAnyUseOfValue(i)) {
9472       assert((i < To->getNumValues()) && "Invalid To location");
9473       transferDbgValues(SDValue(From, i), SDValue(To, i));
9474     }
9475 
9476   // Iterate over just the existing users of From. See the comments in
9477   // the ReplaceAllUsesWith above.
9478   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9479   RAUWUpdateListener Listener(*this, UI, UE);
9480   while (UI != UE) {
9481     SDNode *User = *UI;
9482 
9483     // This node is about to morph, remove its old self from the CSE maps.
9484     RemoveNodeFromCSEMaps(User);
9485 
9486     // A user can appear in a use list multiple times, and when this
9487     // happens the uses are usually next to each other in the list.
9488     // To help reduce the number of CSE recomputations, process all
9489     // the uses of this user that we can find this way.
9490     do {
9491       SDUse &Use = UI.getUse();
9492       ++UI;
9493       Use.setNode(To);
9494       if (To->isDivergent() != From->isDivergent())
9495         updateDivergence(User);
9496     } while (UI != UE && *UI == User);
9497 
9498     // Now that we have modified User, add it back to the CSE maps.  If it
9499     // already exists there, recursively merge the results together.
9500     AddModifiedNodeToCSEMaps(User);
9501   }
9502 
9503   // If we just RAUW'd the root, take note.
9504   if (From == getRoot().getNode())
9505     setRoot(SDValue(To, getRoot().getResNo()));
9506 }
9507 
9508 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9509 /// This can cause recursive merging of nodes in the DAG.
9510 ///
9511 /// This version can replace From with any result values.  To must match the
9512 /// number and types of values returned by From.
9513 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9514   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9515     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9516 
9517   // Preserve Debug Info.
9518   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9519     transferDbgValues(SDValue(From, i), To[i]);
9520 
9521   // Iterate over just the existing users of From. See the comments in
9522   // the ReplaceAllUsesWith above.
9523   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9524   RAUWUpdateListener Listener(*this, UI, UE);
9525   while (UI != UE) {
9526     SDNode *User = *UI;
9527 
9528     // This node is about to morph, remove its old self from the CSE maps.
9529     RemoveNodeFromCSEMaps(User);
9530 
9531     // A user can appear in a use list multiple times, and when this happens the
9532     // uses are usually next to each other in the list.  To help reduce the
9533     // number of CSE and divergence recomputations, process all the uses of this
9534     // user that we can find this way.
9535     bool To_IsDivergent = false;
9536     do {
9537       SDUse &Use = UI.getUse();
9538       const SDValue &ToOp = To[Use.getResNo()];
9539       ++UI;
9540       Use.set(ToOp);
9541       To_IsDivergent |= ToOp->isDivergent();
9542     } while (UI != UE && *UI == User);
9543 
9544     if (To_IsDivergent != From->isDivergent())
9545       updateDivergence(User);
9546 
9547     // Now that we have modified User, add it back to the CSE maps.  If it
9548     // already exists there, recursively merge the results together.
9549     AddModifiedNodeToCSEMaps(User);
9550   }
9551 
9552   // If we just RAUW'd the root, take note.
9553   if (From == getRoot().getNode())
9554     setRoot(SDValue(To[getRoot().getResNo()]));
9555 }
9556 
9557 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9558 /// uses of other values produced by From.getNode() alone.  The Deleted
9559 /// vector is handled the same way as for ReplaceAllUsesWith.
9560 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9561   // Handle the really simple, really trivial case efficiently.
9562   if (From == To) return;
9563 
9564   // Handle the simple, trivial, case efficiently.
9565   if (From.getNode()->getNumValues() == 1) {
9566     ReplaceAllUsesWith(From, To);
9567     return;
9568   }
9569 
9570   // Preserve Debug Info.
9571   transferDbgValues(From, To);
9572 
9573   // Iterate over just the existing users of From. See the comments in
9574   // the ReplaceAllUsesWith above.
9575   SDNode::use_iterator UI = From.getNode()->use_begin(),
9576                        UE = From.getNode()->use_end();
9577   RAUWUpdateListener Listener(*this, UI, UE);
9578   while (UI != UE) {
9579     SDNode *User = *UI;
9580     bool UserRemovedFromCSEMaps = false;
9581 
9582     // A user can appear in a use list multiple times, and when this
9583     // happens the uses are usually next to each other in the list.
9584     // To help reduce the number of CSE recomputations, process all
9585     // the uses of this user that we can find this way.
9586     do {
9587       SDUse &Use = UI.getUse();
9588 
9589       // Skip uses of different values from the same node.
9590       if (Use.getResNo() != From.getResNo()) {
9591         ++UI;
9592         continue;
9593       }
9594 
9595       // If this node hasn't been modified yet, it's still in the CSE maps,
9596       // so remove its old self from the CSE maps.
9597       if (!UserRemovedFromCSEMaps) {
9598         RemoveNodeFromCSEMaps(User);
9599         UserRemovedFromCSEMaps = true;
9600       }
9601 
9602       ++UI;
9603       Use.set(To);
9604       if (To->isDivergent() != From->isDivergent())
9605         updateDivergence(User);
9606     } while (UI != UE && *UI == User);
9607     // We are iterating over all uses of the From node, so if a use
9608     // doesn't use the specific value, no changes are made.
9609     if (!UserRemovedFromCSEMaps)
9610       continue;
9611 
9612     // Now that we have modified User, add it back to the CSE maps.  If it
9613     // already exists there, recursively merge the results together.
9614     AddModifiedNodeToCSEMaps(User);
9615   }
9616 
9617   // If we just RAUW'd the root, take note.
9618   if (From == getRoot())
9619     setRoot(To);
9620 }
9621 
9622 namespace {
9623 
9624   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9625   /// to record information about a use.
9626   struct UseMemo {
9627     SDNode *User;
9628     unsigned Index;
9629     SDUse *Use;
9630   };
9631 
9632   /// operator< - Sort Memos by User.
9633   bool operator<(const UseMemo &L, const UseMemo &R) {
9634     return (intptr_t)L.User < (intptr_t)R.User;
9635   }
9636 
9637 } // end anonymous namespace
9638 
9639 bool SelectionDAG::calculateDivergence(SDNode *N) {
9640   if (TLI->isSDNodeAlwaysUniform(N)) {
9641     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9642            "Conflicting divergence information!");
9643     return false;
9644   }
9645   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9646     return true;
9647   for (auto &Op : N->ops()) {
9648     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9649       return true;
9650   }
9651   return false;
9652 }
9653 
9654 void SelectionDAG::updateDivergence(SDNode *N) {
9655   SmallVector<SDNode *, 16> Worklist(1, N);
9656   do {
9657     N = Worklist.pop_back_val();
9658     bool IsDivergent = calculateDivergence(N);
9659     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9660       N->SDNodeBits.IsDivergent = IsDivergent;
9661       llvm::append_range(Worklist, N->uses());
9662     }
9663   } while (!Worklist.empty());
9664 }
9665 
9666 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9667   DenseMap<SDNode *, unsigned> Degree;
9668   Order.reserve(AllNodes.size());
9669   for (auto &N : allnodes()) {
9670     unsigned NOps = N.getNumOperands();
9671     Degree[&N] = NOps;
9672     if (0 == NOps)
9673       Order.push_back(&N);
9674   }
9675   for (size_t I = 0; I != Order.size(); ++I) {
9676     SDNode *N = Order[I];
9677     for (auto U : N->uses()) {
9678       unsigned &UnsortedOps = Degree[U];
9679       if (0 == --UnsortedOps)
9680         Order.push_back(U);
9681     }
9682   }
9683 }
9684 
9685 #ifndef NDEBUG
9686 void SelectionDAG::VerifyDAGDivergence() {
9687   std::vector<SDNode *> TopoOrder;
9688   CreateTopologicalOrder(TopoOrder);
9689   for (auto *N : TopoOrder) {
9690     assert(calculateDivergence(N) == N->isDivergent() &&
9691            "Divergence bit inconsistency detected");
9692   }
9693 }
9694 #endif
9695 
9696 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9697 /// uses of other values produced by From.getNode() alone.  The same value
9698 /// may appear in both the From and To list.  The Deleted vector is
9699 /// handled the same way as for ReplaceAllUsesWith.
9700 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9701                                               const SDValue *To,
9702                                               unsigned Num){
9703   // Handle the simple, trivial case efficiently.
9704   if (Num == 1)
9705     return ReplaceAllUsesOfValueWith(*From, *To);
9706 
9707   transferDbgValues(*From, *To);
9708 
9709   // Read up all the uses and make records of them. This helps
9710   // processing new uses that are introduced during the
9711   // replacement process.
9712   SmallVector<UseMemo, 4> Uses;
9713   for (unsigned i = 0; i != Num; ++i) {
9714     unsigned FromResNo = From[i].getResNo();
9715     SDNode *FromNode = From[i].getNode();
9716     for (SDNode::use_iterator UI = FromNode->use_begin(),
9717          E = FromNode->use_end(); UI != E; ++UI) {
9718       SDUse &Use = UI.getUse();
9719       if (Use.getResNo() == FromResNo) {
9720         UseMemo Memo = { *UI, i, &Use };
9721         Uses.push_back(Memo);
9722       }
9723     }
9724   }
9725 
9726   // Sort the uses, so that all the uses from a given User are together.
9727   llvm::sort(Uses);
9728 
9729   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9730        UseIndex != UseIndexEnd; ) {
9731     // We know that this user uses some value of From.  If it is the right
9732     // value, update it.
9733     SDNode *User = Uses[UseIndex].User;
9734 
9735     // This node is about to morph, remove its old self from the CSE maps.
9736     RemoveNodeFromCSEMaps(User);
9737 
9738     // The Uses array is sorted, so all the uses for a given User
9739     // are next to each other in the list.
9740     // To help reduce the number of CSE recomputations, process all
9741     // the uses of this user that we can find this way.
9742     do {
9743       unsigned i = Uses[UseIndex].Index;
9744       SDUse &Use = *Uses[UseIndex].Use;
9745       ++UseIndex;
9746 
9747       Use.set(To[i]);
9748     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9749 
9750     // Now that we have modified User, add it back to the CSE maps.  If it
9751     // already exists there, recursively merge the results together.
9752     AddModifiedNodeToCSEMaps(User);
9753   }
9754 }
9755 
9756 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9757 /// based on their topological order. It returns the maximum id and a vector
9758 /// of the SDNodes* in assigned order by reference.
9759 unsigned SelectionDAG::AssignTopologicalOrder() {
9760   unsigned DAGSize = 0;
9761 
9762   // SortedPos tracks the progress of the algorithm. Nodes before it are
9763   // sorted, nodes after it are unsorted. When the algorithm completes
9764   // it is at the end of the list.
9765   allnodes_iterator SortedPos = allnodes_begin();
9766 
9767   // Visit all the nodes. Move nodes with no operands to the front of
9768   // the list immediately. Annotate nodes that do have operands with their
9769   // operand count. Before we do this, the Node Id fields of the nodes
9770   // may contain arbitrary values. After, the Node Id fields for nodes
9771   // before SortedPos will contain the topological sort index, and the
9772   // Node Id fields for nodes At SortedPos and after will contain the
9773   // count of outstanding operands.
9774   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
9775     checkForCycles(&N, this);
9776     unsigned Degree = N.getNumOperands();
9777     if (Degree == 0) {
9778       // A node with no uses, add it to the result array immediately.
9779       N.setNodeId(DAGSize++);
9780       allnodes_iterator Q(&N);
9781       if (Q != SortedPos)
9782         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9783       assert(SortedPos != AllNodes.end() && "Overran node list");
9784       ++SortedPos;
9785     } else {
9786       // Temporarily use the Node Id as scratch space for the degree count.
9787       N.setNodeId(Degree);
9788     }
9789   }
9790 
9791   // Visit all the nodes. As we iterate, move nodes into sorted order,
9792   // such that by the time the end is reached all nodes will be sorted.
9793   for (SDNode &Node : allnodes()) {
9794     SDNode *N = &Node;
9795     checkForCycles(N, this);
9796     // N is in sorted position, so all its uses have one less operand
9797     // that needs to be sorted.
9798     for (SDNode *P : N->uses()) {
9799       unsigned Degree = P->getNodeId();
9800       assert(Degree != 0 && "Invalid node degree");
9801       --Degree;
9802       if (Degree == 0) {
9803         // All of P's operands are sorted, so P may sorted now.
9804         P->setNodeId(DAGSize++);
9805         if (P->getIterator() != SortedPos)
9806           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9807         assert(SortedPos != AllNodes.end() && "Overran node list");
9808         ++SortedPos;
9809       } else {
9810         // Update P's outstanding operand count.
9811         P->setNodeId(Degree);
9812       }
9813     }
9814     if (Node.getIterator() == SortedPos) {
9815 #ifndef NDEBUG
9816       allnodes_iterator I(N);
9817       SDNode *S = &*++I;
9818       dbgs() << "Overran sorted position:\n";
9819       S->dumprFull(this); dbgs() << "\n";
9820       dbgs() << "Checking if this is due to cycles\n";
9821       checkForCycles(this, true);
9822 #endif
9823       llvm_unreachable(nullptr);
9824     }
9825   }
9826 
9827   assert(SortedPos == AllNodes.end() &&
9828          "Topological sort incomplete!");
9829   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9830          "First node in topological sort is not the entry token!");
9831   assert(AllNodes.front().getNodeId() == 0 &&
9832          "First node in topological sort has non-zero id!");
9833   assert(AllNodes.front().getNumOperands() == 0 &&
9834          "First node in topological sort has operands!");
9835   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9836          "Last node in topologic sort has unexpected id!");
9837   assert(AllNodes.back().use_empty() &&
9838          "Last node in topologic sort has users!");
9839   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9840   return DAGSize;
9841 }
9842 
9843 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9844 /// value is produced by SD.
9845 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9846   for (SDNode *SD : DB->getSDNodes()) {
9847     if (!SD)
9848       continue;
9849     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9850     SD->setHasDebugValue(true);
9851   }
9852   DbgInfo->add(DB, isParameter);
9853 }
9854 
9855 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9856 
9857 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9858                                                    SDValue NewMemOpChain) {
9859   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9860   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9861   // The new memory operation must have the same position as the old load in
9862   // terms of memory dependency. Create a TokenFactor for the old load and new
9863   // memory operation and update uses of the old load's output chain to use that
9864   // TokenFactor.
9865   if (OldChain == NewMemOpChain || OldChain.use_empty())
9866     return NewMemOpChain;
9867 
9868   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9869                                 OldChain, NewMemOpChain);
9870   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9871   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9872   return TokenFactor;
9873 }
9874 
9875 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9876                                                    SDValue NewMemOp) {
9877   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9878   SDValue OldChain = SDValue(OldLoad, 1);
9879   SDValue NewMemOpChain = NewMemOp.getValue(1);
9880   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9881 }
9882 
9883 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9884                                                      Function **OutFunction) {
9885   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9886 
9887   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9888   auto *Module = MF->getFunction().getParent();
9889   auto *Function = Module->getFunction(Symbol);
9890 
9891   if (OutFunction != nullptr)
9892       *OutFunction = Function;
9893 
9894   if (Function != nullptr) {
9895     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9896     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9897   }
9898 
9899   std::string ErrorStr;
9900   raw_string_ostream ErrorFormatter(ErrorStr);
9901   ErrorFormatter << "Undefined external symbol ";
9902   ErrorFormatter << '"' << Symbol << '"';
9903   report_fatal_error(Twine(ErrorFormatter.str()));
9904 }
9905 
9906 //===----------------------------------------------------------------------===//
9907 //                              SDNode Class
9908 //===----------------------------------------------------------------------===//
9909 
9910 bool llvm::isNullConstant(SDValue V) {
9911   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9912   return Const != nullptr && Const->isZero();
9913 }
9914 
9915 bool llvm::isNullFPConstant(SDValue V) {
9916   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9917   return Const != nullptr && Const->isZero() && !Const->isNegative();
9918 }
9919 
9920 bool llvm::isAllOnesConstant(SDValue V) {
9921   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9922   return Const != nullptr && Const->isAllOnes();
9923 }
9924 
9925 bool llvm::isOneConstant(SDValue V) {
9926   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9927   return Const != nullptr && Const->isOne();
9928 }
9929 
9930 SDValue llvm::peekThroughBitcasts(SDValue V) {
9931   while (V.getOpcode() == ISD::BITCAST)
9932     V = V.getOperand(0);
9933   return V;
9934 }
9935 
9936 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9937   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9938     V = V.getOperand(0);
9939   return V;
9940 }
9941 
9942 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9943   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9944     V = V.getOperand(0);
9945   return V;
9946 }
9947 
9948 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9949   if (V.getOpcode() != ISD::XOR)
9950     return false;
9951   V = peekThroughBitcasts(V.getOperand(1));
9952   unsigned NumBits = V.getScalarValueSizeInBits();
9953   ConstantSDNode *C =
9954       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9955   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9956 }
9957 
9958 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9959                                           bool AllowTruncation) {
9960   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9961     return CN;
9962 
9963   // SplatVectors can truncate their operands. Ignore that case here unless
9964   // AllowTruncation is set.
9965   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9966     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9967     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9968       EVT CVT = CN->getValueType(0);
9969       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9970       if (AllowTruncation || CVT == VecEltVT)
9971         return CN;
9972     }
9973   }
9974 
9975   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9976     BitVector UndefElements;
9977     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9978 
9979     // BuildVectors can truncate their operands. Ignore that case here unless
9980     // AllowTruncation is set.
9981     if (CN && (UndefElements.none() || AllowUndefs)) {
9982       EVT CVT = CN->getValueType(0);
9983       EVT NSVT = N.getValueType().getScalarType();
9984       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9985       if (AllowTruncation || (CVT == NSVT))
9986         return CN;
9987     }
9988   }
9989 
9990   return nullptr;
9991 }
9992 
9993 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9994                                           bool AllowUndefs,
9995                                           bool AllowTruncation) {
9996   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9997     return CN;
9998 
9999   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10000     BitVector UndefElements;
10001     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10002 
10003     // BuildVectors can truncate their operands. Ignore that case here unless
10004     // AllowTruncation is set.
10005     if (CN && (UndefElements.none() || AllowUndefs)) {
10006       EVT CVT = CN->getValueType(0);
10007       EVT NSVT = N.getValueType().getScalarType();
10008       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10009       if (AllowTruncation || (CVT == NSVT))
10010         return CN;
10011     }
10012   }
10013 
10014   return nullptr;
10015 }
10016 
10017 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10018   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10019     return CN;
10020 
10021   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10022     BitVector UndefElements;
10023     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10024     if (CN && (UndefElements.none() || AllowUndefs))
10025       return CN;
10026   }
10027 
10028   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10029     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10030       return CN;
10031 
10032   return nullptr;
10033 }
10034 
10035 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10036                                               const APInt &DemandedElts,
10037                                               bool AllowUndefs) {
10038   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10039     return CN;
10040 
10041   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10042     BitVector UndefElements;
10043     ConstantFPSDNode *CN =
10044         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10045     if (CN && (UndefElements.none() || AllowUndefs))
10046       return CN;
10047   }
10048 
10049   return nullptr;
10050 }
10051 
10052 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10053   // TODO: may want to use peekThroughBitcast() here.
10054   ConstantSDNode *C =
10055       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10056   return C && C->isZero();
10057 }
10058 
10059 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10060   // TODO: may want to use peekThroughBitcast() here.
10061   unsigned BitWidth = N.getScalarValueSizeInBits();
10062   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10063   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10064 }
10065 
10066 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10067   N = peekThroughBitcasts(N);
10068   unsigned BitWidth = N.getScalarValueSizeInBits();
10069   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10070   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10071 }
10072 
10073 HandleSDNode::~HandleSDNode() {
10074   DropOperands();
10075 }
10076 
10077 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10078                                          const DebugLoc &DL,
10079                                          const GlobalValue *GA, EVT VT,
10080                                          int64_t o, unsigned TF)
10081     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10082   TheGlobal = GA;
10083 }
10084 
10085 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10086                                          EVT VT, unsigned SrcAS,
10087                                          unsigned DestAS)
10088     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10089       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10090 
10091 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10092                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10093     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10094   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10095   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10096   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10097   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10098 
10099   // We check here that the size of the memory operand fits within the size of
10100   // the MMO. This is because the MMO might indicate only a possible address
10101   // range instead of specifying the affected memory addresses precisely.
10102   // TODO: Make MachineMemOperands aware of scalable vectors.
10103   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10104          "Size mismatch!");
10105 }
10106 
10107 /// Profile - Gather unique data for the node.
10108 ///
10109 void SDNode::Profile(FoldingSetNodeID &ID) const {
10110   AddNodeIDNode(ID, this);
10111 }
10112 
10113 namespace {
10114 
10115   struct EVTArray {
10116     std::vector<EVT> VTs;
10117 
10118     EVTArray() {
10119       VTs.reserve(MVT::VALUETYPE_SIZE);
10120       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10121         VTs.push_back(MVT((MVT::SimpleValueType)i));
10122     }
10123   };
10124 
10125 } // end anonymous namespace
10126 
10127 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10128 static ManagedStatic<EVTArray> SimpleVTArray;
10129 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10130 
10131 /// getValueTypeList - Return a pointer to the specified value type.
10132 ///
10133 const EVT *SDNode::getValueTypeList(EVT VT) {
10134   if (VT.isExtended()) {
10135     sys::SmartScopedLock<true> Lock(*VTMutex);
10136     return &(*EVTs->insert(VT).first);
10137   }
10138   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10139   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10140 }
10141 
10142 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10143 /// indicated value.  This method ignores uses of other values defined by this
10144 /// operation.
10145 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10146   assert(Value < getNumValues() && "Bad value!");
10147 
10148   // TODO: Only iterate over uses of a given value of the node
10149   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10150     if (UI.getUse().getResNo() == Value) {
10151       if (NUses == 0)
10152         return false;
10153       --NUses;
10154     }
10155   }
10156 
10157   // Found exactly the right number of uses?
10158   return NUses == 0;
10159 }
10160 
10161 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10162 /// value. This method ignores uses of other values defined by this operation.
10163 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10164   assert(Value < getNumValues() && "Bad value!");
10165 
10166   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10167     if (UI.getUse().getResNo() == Value)
10168       return true;
10169 
10170   return false;
10171 }
10172 
10173 /// isOnlyUserOf - Return true if this node is the only use of N.
10174 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10175   bool Seen = false;
10176   for (const SDNode *User : N->uses()) {
10177     if (User == this)
10178       Seen = true;
10179     else
10180       return false;
10181   }
10182 
10183   return Seen;
10184 }
10185 
10186 /// Return true if the only users of N are contained in Nodes.
10187 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10188   bool Seen = false;
10189   for (const SDNode *User : N->uses()) {
10190     if (llvm::is_contained(Nodes, User))
10191       Seen = true;
10192     else
10193       return false;
10194   }
10195 
10196   return Seen;
10197 }
10198 
10199 /// isOperand - Return true if this node is an operand of N.
10200 bool SDValue::isOperandOf(const SDNode *N) const {
10201   return is_contained(N->op_values(), *this);
10202 }
10203 
10204 bool SDNode::isOperandOf(const SDNode *N) const {
10205   return any_of(N->op_values(),
10206                 [this](SDValue Op) { return this == Op.getNode(); });
10207 }
10208 
10209 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10210 /// be a chain) reaches the specified operand without crossing any
10211 /// side-effecting instructions on any chain path.  In practice, this looks
10212 /// through token factors and non-volatile loads.  In order to remain efficient,
10213 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10214 ///
10215 /// Note that we only need to examine chains when we're searching for
10216 /// side-effects; SelectionDAG requires that all side-effects are represented
10217 /// by chains, even if another operand would force a specific ordering. This
10218 /// constraint is necessary to allow transformations like splitting loads.
10219 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10220                                              unsigned Depth) const {
10221   if (*this == Dest) return true;
10222 
10223   // Don't search too deeply, we just want to be able to see through
10224   // TokenFactor's etc.
10225   if (Depth == 0) return false;
10226 
10227   // If this is a token factor, all inputs to the TF happen in parallel.
10228   if (getOpcode() == ISD::TokenFactor) {
10229     // First, try a shallow search.
10230     if (is_contained((*this)->ops(), Dest)) {
10231       // We found the chain we want as an operand of this TokenFactor.
10232       // Essentially, we reach the chain without side-effects if we could
10233       // serialize the TokenFactor into a simple chain of operations with
10234       // Dest as the last operation. This is automatically true if the
10235       // chain has one use: there are no other ordering constraints.
10236       // If the chain has more than one use, we give up: some other
10237       // use of Dest might force a side-effect between Dest and the current
10238       // node.
10239       if (Dest.hasOneUse())
10240         return true;
10241     }
10242     // Next, try a deep search: check whether every operand of the TokenFactor
10243     // reaches Dest.
10244     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10245       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10246     });
10247   }
10248 
10249   // Loads don't have side effects, look through them.
10250   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10251     if (Ld->isUnordered())
10252       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10253   }
10254   return false;
10255 }
10256 
10257 bool SDNode::hasPredecessor(const SDNode *N) const {
10258   SmallPtrSet<const SDNode *, 32> Visited;
10259   SmallVector<const SDNode *, 16> Worklist;
10260   Worklist.push_back(this);
10261   return hasPredecessorHelper(N, Visited, Worklist);
10262 }
10263 
10264 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10265   this->Flags.intersectWith(Flags);
10266 }
10267 
10268 SDValue
10269 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10270                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10271                                   bool AllowPartials) {
10272   // The pattern must end in an extract from index 0.
10273   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10274       !isNullConstant(Extract->getOperand(1)))
10275     return SDValue();
10276 
10277   // Match against one of the candidate binary ops.
10278   SDValue Op = Extract->getOperand(0);
10279   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10280         return Op.getOpcode() == unsigned(BinOp);
10281       }))
10282     return SDValue();
10283 
10284   // Floating-point reductions may require relaxed constraints on the final step
10285   // of the reduction because they may reorder intermediate operations.
10286   unsigned CandidateBinOp = Op.getOpcode();
10287   if (Op.getValueType().isFloatingPoint()) {
10288     SDNodeFlags Flags = Op->getFlags();
10289     switch (CandidateBinOp) {
10290     case ISD::FADD:
10291       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10292         return SDValue();
10293       break;
10294     default:
10295       llvm_unreachable("Unhandled FP opcode for binop reduction");
10296     }
10297   }
10298 
10299   // Matching failed - attempt to see if we did enough stages that a partial
10300   // reduction from a subvector is possible.
10301   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10302     if (!AllowPartials || !Op)
10303       return SDValue();
10304     EVT OpVT = Op.getValueType();
10305     EVT OpSVT = OpVT.getScalarType();
10306     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10307     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10308       return SDValue();
10309     BinOp = (ISD::NodeType)CandidateBinOp;
10310     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10311                    getVectorIdxConstant(0, SDLoc(Op)));
10312   };
10313 
10314   // At each stage, we're looking for something that looks like:
10315   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10316   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10317   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10318   // %a = binop <8 x i32> %op, %s
10319   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10320   // we expect something like:
10321   // <4,5,6,7,u,u,u,u>
10322   // <2,3,u,u,u,u,u,u>
10323   // <1,u,u,u,u,u,u,u>
10324   // While a partial reduction match would be:
10325   // <2,3,u,u,u,u,u,u>
10326   // <1,u,u,u,u,u,u,u>
10327   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10328   SDValue PrevOp;
10329   for (unsigned i = 0; i < Stages; ++i) {
10330     unsigned MaskEnd = (1 << i);
10331 
10332     if (Op.getOpcode() != CandidateBinOp)
10333       return PartialReduction(PrevOp, MaskEnd);
10334 
10335     SDValue Op0 = Op.getOperand(0);
10336     SDValue Op1 = Op.getOperand(1);
10337 
10338     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10339     if (Shuffle) {
10340       Op = Op1;
10341     } else {
10342       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10343       Op = Op0;
10344     }
10345 
10346     // The first operand of the shuffle should be the same as the other operand
10347     // of the binop.
10348     if (!Shuffle || Shuffle->getOperand(0) != Op)
10349       return PartialReduction(PrevOp, MaskEnd);
10350 
10351     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10352     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10353       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10354         return PartialReduction(PrevOp, MaskEnd);
10355 
10356     PrevOp = Op;
10357   }
10358 
10359   // Handle subvector reductions, which tend to appear after the shuffle
10360   // reduction stages.
10361   while (Op.getOpcode() == CandidateBinOp) {
10362     unsigned NumElts = Op.getValueType().getVectorNumElements();
10363     SDValue Op0 = Op.getOperand(0);
10364     SDValue Op1 = Op.getOperand(1);
10365     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10366         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10367         Op0.getOperand(0) != Op1.getOperand(0))
10368       break;
10369     SDValue Src = Op0.getOperand(0);
10370     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10371     if (NumSrcElts != (2 * NumElts))
10372       break;
10373     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10374           Op1.getConstantOperandAPInt(1) == NumElts) &&
10375         !(Op1.getConstantOperandAPInt(1) == 0 &&
10376           Op0.getConstantOperandAPInt(1) == NumElts))
10377       break;
10378     Op = Src;
10379   }
10380 
10381   BinOp = (ISD::NodeType)CandidateBinOp;
10382   return Op;
10383 }
10384 
10385 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10386   assert(N->getNumValues() == 1 &&
10387          "Can't unroll a vector with multiple results!");
10388 
10389   EVT VT = N->getValueType(0);
10390   unsigned NE = VT.getVectorNumElements();
10391   EVT EltVT = VT.getVectorElementType();
10392   SDLoc dl(N);
10393 
10394   SmallVector<SDValue, 8> Scalars;
10395   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10396 
10397   // If ResNE is 0, fully unroll the vector op.
10398   if (ResNE == 0)
10399     ResNE = NE;
10400   else if (NE > ResNE)
10401     NE = ResNE;
10402 
10403   unsigned i;
10404   for (i= 0; i != NE; ++i) {
10405     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10406       SDValue Operand = N->getOperand(j);
10407       EVT OperandVT = Operand.getValueType();
10408       if (OperandVT.isVector()) {
10409         // A vector operand; extract a single element.
10410         EVT OperandEltVT = OperandVT.getVectorElementType();
10411         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10412                               Operand, getVectorIdxConstant(i, dl));
10413       } else {
10414         // A scalar operand; just use it as is.
10415         Operands[j] = Operand;
10416       }
10417     }
10418 
10419     switch (N->getOpcode()) {
10420     default: {
10421       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10422                                 N->getFlags()));
10423       break;
10424     }
10425     case ISD::VSELECT:
10426       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10427       break;
10428     case ISD::SHL:
10429     case ISD::SRA:
10430     case ISD::SRL:
10431     case ISD::ROTL:
10432     case ISD::ROTR:
10433       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10434                                getShiftAmountOperand(Operands[0].getValueType(),
10435                                                      Operands[1])));
10436       break;
10437     case ISD::SIGN_EXTEND_INREG: {
10438       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10439       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10440                                 Operands[0],
10441                                 getValueType(ExtVT)));
10442     }
10443     }
10444   }
10445 
10446   for (; i < ResNE; ++i)
10447     Scalars.push_back(getUNDEF(EltVT));
10448 
10449   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10450   return getBuildVector(VecVT, dl, Scalars);
10451 }
10452 
10453 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10454     SDNode *N, unsigned ResNE) {
10455   unsigned Opcode = N->getOpcode();
10456   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10457           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10458           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10459          "Expected an overflow opcode");
10460 
10461   EVT ResVT = N->getValueType(0);
10462   EVT OvVT = N->getValueType(1);
10463   EVT ResEltVT = ResVT.getVectorElementType();
10464   EVT OvEltVT = OvVT.getVectorElementType();
10465   SDLoc dl(N);
10466 
10467   // If ResNE is 0, fully unroll the vector op.
10468   unsigned NE = ResVT.getVectorNumElements();
10469   if (ResNE == 0)
10470     ResNE = NE;
10471   else if (NE > ResNE)
10472     NE = ResNE;
10473 
10474   SmallVector<SDValue, 8> LHSScalars;
10475   SmallVector<SDValue, 8> RHSScalars;
10476   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10477   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10478 
10479   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10480   SDVTList VTs = getVTList(ResEltVT, SVT);
10481   SmallVector<SDValue, 8> ResScalars;
10482   SmallVector<SDValue, 8> OvScalars;
10483   for (unsigned i = 0; i < NE; ++i) {
10484     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10485     SDValue Ov =
10486         getSelect(dl, OvEltVT, Res.getValue(1),
10487                   getBoolConstant(true, dl, OvEltVT, ResVT),
10488                   getConstant(0, dl, OvEltVT));
10489 
10490     ResScalars.push_back(Res);
10491     OvScalars.push_back(Ov);
10492   }
10493 
10494   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10495   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10496 
10497   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10498   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10499   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10500                         getBuildVector(NewOvVT, dl, OvScalars));
10501 }
10502 
10503 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10504                                                   LoadSDNode *Base,
10505                                                   unsigned Bytes,
10506                                                   int Dist) const {
10507   if (LD->isVolatile() || Base->isVolatile())
10508     return false;
10509   // TODO: probably too restrictive for atomics, revisit
10510   if (!LD->isSimple())
10511     return false;
10512   if (LD->isIndexed() || Base->isIndexed())
10513     return false;
10514   if (LD->getChain() != Base->getChain())
10515     return false;
10516   EVT VT = LD->getValueType(0);
10517   if (VT.getSizeInBits() / 8 != Bytes)
10518     return false;
10519 
10520   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10521   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10522 
10523   int64_t Offset = 0;
10524   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10525     return (Dist * Bytes == Offset);
10526   return false;
10527 }
10528 
10529 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10530 /// if it cannot be inferred.
10531 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10532   // If this is a GlobalAddress + cst, return the alignment.
10533   const GlobalValue *GV = nullptr;
10534   int64_t GVOffset = 0;
10535   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10536     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10537     KnownBits Known(PtrWidth);
10538     llvm::computeKnownBits(GV, Known, getDataLayout());
10539     unsigned AlignBits = Known.countMinTrailingZeros();
10540     if (AlignBits)
10541       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10542   }
10543 
10544   // If this is a direct reference to a stack slot, use information about the
10545   // stack slot's alignment.
10546   int FrameIdx = INT_MIN;
10547   int64_t FrameOffset = 0;
10548   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10549     FrameIdx = FI->getIndex();
10550   } else if (isBaseWithConstantOffset(Ptr) &&
10551              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10552     // Handle FI+Cst
10553     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10554     FrameOffset = Ptr.getConstantOperandVal(1);
10555   }
10556 
10557   if (FrameIdx != INT_MIN) {
10558     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10559     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10560   }
10561 
10562   return None;
10563 }
10564 
10565 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10566 /// which is split (or expanded) into two not necessarily identical pieces.
10567 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10568   // Currently all types are split in half.
10569   EVT LoVT, HiVT;
10570   if (!VT.isVector())
10571     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10572   else
10573     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10574 
10575   return std::make_pair(LoVT, HiVT);
10576 }
10577 
10578 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10579 /// type, dependent on an enveloping VT that has been split into two identical
10580 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10581 std::pair<EVT, EVT>
10582 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10583                                        bool *HiIsEmpty) const {
10584   EVT EltTp = VT.getVectorElementType();
10585   // Examples:
10586   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10587   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10588   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10589   //   etc.
10590   ElementCount VTNumElts = VT.getVectorElementCount();
10591   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10592   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10593          "Mixing fixed width and scalable vectors when enveloping a type");
10594   EVT LoVT, HiVT;
10595   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10596     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10597     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10598     *HiIsEmpty = false;
10599   } else {
10600     // Flag that hi type has zero storage size, but return split envelop type
10601     // (this would be easier if vector types with zero elements were allowed).
10602     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10603     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10604     *HiIsEmpty = true;
10605   }
10606   return std::make_pair(LoVT, HiVT);
10607 }
10608 
10609 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10610 /// low/high part.
10611 std::pair<SDValue, SDValue>
10612 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10613                           const EVT &HiVT) {
10614   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10615          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10616          "Splitting vector with an invalid mixture of fixed and scalable "
10617          "vector types");
10618   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10619              N.getValueType().getVectorMinNumElements() &&
10620          "More vector elements requested than available!");
10621   SDValue Lo, Hi;
10622   Lo =
10623       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10624   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10625   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10626   // IDX with the runtime scaling factor of the result vector type. For
10627   // fixed-width result vectors, that runtime scaling factor is 1.
10628   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10629                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10630   return std::make_pair(Lo, Hi);
10631 }
10632 
10633 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10634 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10635   EVT VT = N.getValueType();
10636   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10637                                 NextPowerOf2(VT.getVectorNumElements()));
10638   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10639                  getVectorIdxConstant(0, DL));
10640 }
10641 
10642 void SelectionDAG::ExtractVectorElements(SDValue Op,
10643                                          SmallVectorImpl<SDValue> &Args,
10644                                          unsigned Start, unsigned Count,
10645                                          EVT EltVT) {
10646   EVT VT = Op.getValueType();
10647   if (Count == 0)
10648     Count = VT.getVectorNumElements();
10649   if (EltVT == EVT())
10650     EltVT = VT.getVectorElementType();
10651   SDLoc SL(Op);
10652   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10653     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10654                            getVectorIdxConstant(i, SL)));
10655   }
10656 }
10657 
10658 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10659 unsigned GlobalAddressSDNode::getAddressSpace() const {
10660   return getGlobal()->getType()->getAddressSpace();
10661 }
10662 
10663 Type *ConstantPoolSDNode::getType() const {
10664   if (isMachineConstantPoolEntry())
10665     return Val.MachineCPVal->getType();
10666   return Val.ConstVal->getType();
10667 }
10668 
10669 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10670                                         unsigned &SplatBitSize,
10671                                         bool &HasAnyUndefs,
10672                                         unsigned MinSplatBits,
10673                                         bool IsBigEndian) const {
10674   EVT VT = getValueType(0);
10675   assert(VT.isVector() && "Expected a vector type");
10676   unsigned VecWidth = VT.getSizeInBits();
10677   if (MinSplatBits > VecWidth)
10678     return false;
10679 
10680   // FIXME: The widths are based on this node's type, but build vectors can
10681   // truncate their operands.
10682   SplatValue = APInt(VecWidth, 0);
10683   SplatUndef = APInt(VecWidth, 0);
10684 
10685   // Get the bits. Bits with undefined values (when the corresponding element
10686   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10687   // in SplatValue. If any of the values are not constant, give up and return
10688   // false.
10689   unsigned int NumOps = getNumOperands();
10690   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10691   unsigned EltWidth = VT.getScalarSizeInBits();
10692 
10693   for (unsigned j = 0; j < NumOps; ++j) {
10694     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10695     SDValue OpVal = getOperand(i);
10696     unsigned BitPos = j * EltWidth;
10697 
10698     if (OpVal.isUndef())
10699       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10700     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10701       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10702     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10703       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10704     else
10705       return false;
10706   }
10707 
10708   // The build_vector is all constants or undefs. Find the smallest element
10709   // size that splats the vector.
10710   HasAnyUndefs = (SplatUndef != 0);
10711 
10712   // FIXME: This does not work for vectors with elements less than 8 bits.
10713   while (VecWidth > 8) {
10714     unsigned HalfSize = VecWidth / 2;
10715     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10716     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10717     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10718     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10719 
10720     // If the two halves do not match (ignoring undef bits), stop here.
10721     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10722         MinSplatBits > HalfSize)
10723       break;
10724 
10725     SplatValue = HighValue | LowValue;
10726     SplatUndef = HighUndef & LowUndef;
10727 
10728     VecWidth = HalfSize;
10729   }
10730 
10731   SplatBitSize = VecWidth;
10732   return true;
10733 }
10734 
10735 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10736                                          BitVector *UndefElements) const {
10737   unsigned NumOps = getNumOperands();
10738   if (UndefElements) {
10739     UndefElements->clear();
10740     UndefElements->resize(NumOps);
10741   }
10742   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10743   if (!DemandedElts)
10744     return SDValue();
10745   SDValue Splatted;
10746   for (unsigned i = 0; i != NumOps; ++i) {
10747     if (!DemandedElts[i])
10748       continue;
10749     SDValue Op = getOperand(i);
10750     if (Op.isUndef()) {
10751       if (UndefElements)
10752         (*UndefElements)[i] = true;
10753     } else if (!Splatted) {
10754       Splatted = Op;
10755     } else if (Splatted != Op) {
10756       return SDValue();
10757     }
10758   }
10759 
10760   if (!Splatted) {
10761     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10762     assert(getOperand(FirstDemandedIdx).isUndef() &&
10763            "Can only have a splat without a constant for all undefs.");
10764     return getOperand(FirstDemandedIdx);
10765   }
10766 
10767   return Splatted;
10768 }
10769 
10770 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10771   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10772   return getSplatValue(DemandedElts, UndefElements);
10773 }
10774 
10775 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10776                                             SmallVectorImpl<SDValue> &Sequence,
10777                                             BitVector *UndefElements) const {
10778   unsigned NumOps = getNumOperands();
10779   Sequence.clear();
10780   if (UndefElements) {
10781     UndefElements->clear();
10782     UndefElements->resize(NumOps);
10783   }
10784   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10785   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10786     return false;
10787 
10788   // Set the undefs even if we don't find a sequence (like getSplatValue).
10789   if (UndefElements)
10790     for (unsigned I = 0; I != NumOps; ++I)
10791       if (DemandedElts[I] && getOperand(I).isUndef())
10792         (*UndefElements)[I] = true;
10793 
10794   // Iteratively widen the sequence length looking for repetitions.
10795   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10796     Sequence.append(SeqLen, SDValue());
10797     for (unsigned I = 0; I != NumOps; ++I) {
10798       if (!DemandedElts[I])
10799         continue;
10800       SDValue &SeqOp = Sequence[I % SeqLen];
10801       SDValue Op = getOperand(I);
10802       if (Op.isUndef()) {
10803         if (!SeqOp)
10804           SeqOp = Op;
10805         continue;
10806       }
10807       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10808         Sequence.clear();
10809         break;
10810       }
10811       SeqOp = Op;
10812     }
10813     if (!Sequence.empty())
10814       return true;
10815   }
10816 
10817   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10818   return false;
10819 }
10820 
10821 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10822                                             BitVector *UndefElements) const {
10823   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10824   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10825 }
10826 
10827 ConstantSDNode *
10828 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10829                                         BitVector *UndefElements) const {
10830   return dyn_cast_or_null<ConstantSDNode>(
10831       getSplatValue(DemandedElts, UndefElements));
10832 }
10833 
10834 ConstantSDNode *
10835 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10836   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10837 }
10838 
10839 ConstantFPSDNode *
10840 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10841                                           BitVector *UndefElements) const {
10842   return dyn_cast_or_null<ConstantFPSDNode>(
10843       getSplatValue(DemandedElts, UndefElements));
10844 }
10845 
10846 ConstantFPSDNode *
10847 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10848   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10849 }
10850 
10851 int32_t
10852 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10853                                                    uint32_t BitWidth) const {
10854   if (ConstantFPSDNode *CN =
10855           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10856     bool IsExact;
10857     APSInt IntVal(BitWidth);
10858     const APFloat &APF = CN->getValueAPF();
10859     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10860             APFloat::opOK ||
10861         !IsExact)
10862       return -1;
10863 
10864     return IntVal.exactLogBase2();
10865   }
10866   return -1;
10867 }
10868 
10869 bool BuildVectorSDNode::getConstantRawBits(
10870     bool IsLittleEndian, unsigned DstEltSizeInBits,
10871     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
10872   // Early-out if this contains anything but Undef/Constant/ConstantFP.
10873   if (!isConstant())
10874     return false;
10875 
10876   unsigned NumSrcOps = getNumOperands();
10877   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
10878   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10879          "Invalid bitcast scale");
10880 
10881   // Extract raw src bits.
10882   SmallVector<APInt> SrcBitElements(NumSrcOps,
10883                                     APInt::getNullValue(SrcEltSizeInBits));
10884   BitVector SrcUndeElements(NumSrcOps, false);
10885 
10886   for (unsigned I = 0; I != NumSrcOps; ++I) {
10887     SDValue Op = getOperand(I);
10888     if (Op.isUndef()) {
10889       SrcUndeElements.set(I);
10890       continue;
10891     }
10892     auto *CInt = dyn_cast<ConstantSDNode>(Op);
10893     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
10894     assert((CInt || CFP) && "Unknown constant");
10895     SrcBitElements[I] =
10896         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
10897              : CFP->getValueAPF().bitcastToAPInt();
10898   }
10899 
10900   // Recast to dst width.
10901   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
10902                 SrcBitElements, UndefElements, SrcUndeElements);
10903   return true;
10904 }
10905 
10906 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
10907                                       unsigned DstEltSizeInBits,
10908                                       SmallVectorImpl<APInt> &DstBitElements,
10909                                       ArrayRef<APInt> SrcBitElements,
10910                                       BitVector &DstUndefElements,
10911                                       const BitVector &SrcUndefElements) {
10912   unsigned NumSrcOps = SrcBitElements.size();
10913   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
10914   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10915          "Invalid bitcast scale");
10916   assert(NumSrcOps == SrcUndefElements.size() &&
10917          "Vector size mismatch");
10918 
10919   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
10920   DstUndefElements.clear();
10921   DstUndefElements.resize(NumDstOps, false);
10922   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
10923 
10924   // Concatenate src elements constant bits together into dst element.
10925   if (SrcEltSizeInBits <= DstEltSizeInBits) {
10926     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
10927     for (unsigned I = 0; I != NumDstOps; ++I) {
10928       DstUndefElements.set(I);
10929       APInt &DstBits = DstBitElements[I];
10930       for (unsigned J = 0; J != Scale; ++J) {
10931         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10932         if (SrcUndefElements[Idx])
10933           continue;
10934         DstUndefElements.reset(I);
10935         const APInt &SrcBits = SrcBitElements[Idx];
10936         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
10937                "Illegal constant bitwidths");
10938         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
10939       }
10940     }
10941     return;
10942   }
10943 
10944   // Split src element constant bits into dst elements.
10945   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
10946   for (unsigned I = 0; I != NumSrcOps; ++I) {
10947     if (SrcUndefElements[I]) {
10948       DstUndefElements.set(I * Scale, (I + 1) * Scale);
10949       continue;
10950     }
10951     const APInt &SrcBits = SrcBitElements[I];
10952     for (unsigned J = 0; J != Scale; ++J) {
10953       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10954       APInt &DstBits = DstBitElements[Idx];
10955       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
10956     }
10957   }
10958 }
10959 
10960 bool BuildVectorSDNode::isConstant() const {
10961   for (const SDValue &Op : op_values()) {
10962     unsigned Opc = Op.getOpcode();
10963     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10964       return false;
10965   }
10966   return true;
10967 }
10968 
10969 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10970   // Find the first non-undef value in the shuffle mask.
10971   unsigned i, e;
10972   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10973     /* search */;
10974 
10975   // If all elements are undefined, this shuffle can be considered a splat
10976   // (although it should eventually get simplified away completely).
10977   if (i == e)
10978     return true;
10979 
10980   // Make sure all remaining elements are either undef or the same as the first
10981   // non-undef value.
10982   for (int Idx = Mask[i]; i != e; ++i)
10983     if (Mask[i] >= 0 && Mask[i] != Idx)
10984       return false;
10985   return true;
10986 }
10987 
10988 // Returns the SDNode if it is a constant integer BuildVector
10989 // or constant integer.
10990 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10991   if (isa<ConstantSDNode>(N))
10992     return N.getNode();
10993   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10994     return N.getNode();
10995   // Treat a GlobalAddress supporting constant offset folding as a
10996   // constant integer.
10997   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10998     if (GA->getOpcode() == ISD::GlobalAddress &&
10999         TLI->isOffsetFoldingLegal(GA))
11000       return GA;
11001   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11002       isa<ConstantSDNode>(N.getOperand(0)))
11003     return N.getNode();
11004   return nullptr;
11005 }
11006 
11007 // Returns the SDNode if it is a constant float BuildVector
11008 // or constant float.
11009 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11010   if (isa<ConstantFPSDNode>(N))
11011     return N.getNode();
11012 
11013   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11014     return N.getNode();
11015 
11016   return nullptr;
11017 }
11018 
11019 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11020   assert(!Node->OperandList && "Node already has operands");
11021   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11022          "too many operands to fit into SDNode");
11023   SDUse *Ops = OperandRecycler.allocate(
11024       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11025 
11026   bool IsDivergent = false;
11027   for (unsigned I = 0; I != Vals.size(); ++I) {
11028     Ops[I].setUser(Node);
11029     Ops[I].setInitial(Vals[I]);
11030     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11031       IsDivergent |= Ops[I].getNode()->isDivergent();
11032   }
11033   Node->NumOperands = Vals.size();
11034   Node->OperandList = Ops;
11035   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11036     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11037     Node->SDNodeBits.IsDivergent = IsDivergent;
11038   }
11039   checkForCycles(Node);
11040 }
11041 
11042 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11043                                      SmallVectorImpl<SDValue> &Vals) {
11044   size_t Limit = SDNode::getMaxNumOperands();
11045   while (Vals.size() > Limit) {
11046     unsigned SliceIdx = Vals.size() - Limit;
11047     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11048     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11049     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11050     Vals.emplace_back(NewTF);
11051   }
11052   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11053 }
11054 
11055 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11056                                         EVT VT, SDNodeFlags Flags) {
11057   switch (Opcode) {
11058   default:
11059     return SDValue();
11060   case ISD::ADD:
11061   case ISD::OR:
11062   case ISD::XOR:
11063   case ISD::UMAX:
11064     return getConstant(0, DL, VT);
11065   case ISD::MUL:
11066     return getConstant(1, DL, VT);
11067   case ISD::AND:
11068   case ISD::UMIN:
11069     return getAllOnesConstant(DL, VT);
11070   case ISD::SMAX:
11071     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11072   case ISD::SMIN:
11073     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11074   case ISD::FADD:
11075     return getConstantFP(-0.0, DL, VT);
11076   case ISD::FMUL:
11077     return getConstantFP(1.0, DL, VT);
11078   case ISD::FMINNUM:
11079   case ISD::FMAXNUM: {
11080     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11081     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11082     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11083                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11084                         APFloat::getLargest(Semantics);
11085     if (Opcode == ISD::FMAXNUM)
11086       NeutralAF.changeSign();
11087 
11088     return getConstantFP(NeutralAF, DL, VT);
11089   }
11090   }
11091 }
11092 
11093 #ifndef NDEBUG
11094 static void checkForCyclesHelper(const SDNode *N,
11095                                  SmallPtrSetImpl<const SDNode*> &Visited,
11096                                  SmallPtrSetImpl<const SDNode*> &Checked,
11097                                  const llvm::SelectionDAG *DAG) {
11098   // If this node has already been checked, don't check it again.
11099   if (Checked.count(N))
11100     return;
11101 
11102   // If a node has already been visited on this depth-first walk, reject it as
11103   // a cycle.
11104   if (!Visited.insert(N).second) {
11105     errs() << "Detected cycle in SelectionDAG\n";
11106     dbgs() << "Offending node:\n";
11107     N->dumprFull(DAG); dbgs() << "\n";
11108     abort();
11109   }
11110 
11111   for (const SDValue &Op : N->op_values())
11112     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11113 
11114   Checked.insert(N);
11115   Visited.erase(N);
11116 }
11117 #endif
11118 
11119 void llvm::checkForCycles(const llvm::SDNode *N,
11120                           const llvm::SelectionDAG *DAG,
11121                           bool force) {
11122 #ifndef NDEBUG
11123   bool check = force;
11124 #ifdef EXPENSIVE_CHECKS
11125   check = true;
11126 #endif  // EXPENSIVE_CHECKS
11127   if (check) {
11128     assert(N && "Checking nonexistent SDNode");
11129     SmallPtrSet<const SDNode*, 32> visited;
11130     SmallPtrSet<const SDNode*, 32> checked;
11131     checkForCyclesHelper(N, visited, checked, DAG);
11132   }
11133 #endif  // !NDEBUG
11134 }
11135 
11136 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11137   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11138 }
11139