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