xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp (revision 5956d97f4b3204318ceb6aa9c77bd0bc6ea87a41)
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   case ISD::VP_REDUCE_FADD:
377   case ISD::VP_REDUCE_SEQ_FADD:
378     return ISD::FADD;
379   case ISD::VECREDUCE_FMUL:
380   case ISD::VECREDUCE_SEQ_FMUL:
381   case ISD::VP_REDUCE_FMUL:
382   case ISD::VP_REDUCE_SEQ_FMUL:
383     return ISD::FMUL;
384   case ISD::VECREDUCE_ADD:
385   case ISD::VP_REDUCE_ADD:
386     return ISD::ADD;
387   case ISD::VECREDUCE_MUL:
388   case ISD::VP_REDUCE_MUL:
389     return ISD::MUL;
390   case ISD::VECREDUCE_AND:
391   case ISD::VP_REDUCE_AND:
392     return ISD::AND;
393   case ISD::VECREDUCE_OR:
394   case ISD::VP_REDUCE_OR:
395     return ISD::OR;
396   case ISD::VECREDUCE_XOR:
397   case ISD::VP_REDUCE_XOR:
398     return ISD::XOR;
399   case ISD::VECREDUCE_SMAX:
400   case ISD::VP_REDUCE_SMAX:
401     return ISD::SMAX;
402   case ISD::VECREDUCE_SMIN:
403   case ISD::VP_REDUCE_SMIN:
404     return ISD::SMIN;
405   case ISD::VECREDUCE_UMAX:
406   case ISD::VP_REDUCE_UMAX:
407     return ISD::UMAX;
408   case ISD::VECREDUCE_UMIN:
409   case ISD::VP_REDUCE_UMIN:
410     return ISD::UMIN;
411   case ISD::VECREDUCE_FMAX:
412   case ISD::VP_REDUCE_FMAX:
413     return ISD::FMAXNUM;
414   case ISD::VECREDUCE_FMIN:
415   case ISD::VP_REDUCE_FMIN:
416     return ISD::FMINNUM;
417   }
418 }
419 
420 bool ISD::isVPOpcode(unsigned Opcode) {
421   switch (Opcode) {
422   default:
423     return false;
424 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
425   case ISD::VPSD:                                                              \
426     return true;
427 #include "llvm/IR/VPIntrinsics.def"
428   }
429 }
430 
431 bool ISD::isVPBinaryOp(unsigned Opcode) {
432   switch (Opcode) {
433   default:
434     break;
435 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
436 #define VP_PROPERTY_BINARYOP return true;
437 #define END_REGISTER_VP_SDNODE(VPSD) break;
438 #include "llvm/IR/VPIntrinsics.def"
439   }
440   return false;
441 }
442 
443 bool ISD::isVPReduction(unsigned Opcode) {
444   switch (Opcode) {
445   default:
446     break;
447 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
448 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
449 #define END_REGISTER_VP_SDNODE(VPSD) break;
450 #include "llvm/IR/VPIntrinsics.def"
451   }
452   return false;
453 }
454 
455 /// The operand position of the vector mask.
456 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
457   switch (Opcode) {
458   default:
459     return None;
460 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
461   case ISD::VPSD:                                                              \
462     return MASKPOS;
463 #include "llvm/IR/VPIntrinsics.def"
464   }
465 }
466 
467 /// The operand position of the explicit vector length parameter.
468 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
469   switch (Opcode) {
470   default:
471     return None;
472 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
473   case ISD::VPSD:                                                              \
474     return EVLPOS;
475 #include "llvm/IR/VPIntrinsics.def"
476   }
477 }
478 
479 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
480   switch (ExtType) {
481   case ISD::EXTLOAD:
482     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
483   case ISD::SEXTLOAD:
484     return ISD::SIGN_EXTEND;
485   case ISD::ZEXTLOAD:
486     return ISD::ZERO_EXTEND;
487   default:
488     break;
489   }
490 
491   llvm_unreachable("Invalid LoadExtType");
492 }
493 
494 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
495   // To perform this operation, we just need to swap the L and G bits of the
496   // operation.
497   unsigned OldL = (Operation >> 2) & 1;
498   unsigned OldG = (Operation >> 1) & 1;
499   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
500                        (OldL << 1) |       // New G bit
501                        (OldG << 2));       // New L bit.
502 }
503 
504 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
505   unsigned Operation = Op;
506   if (isIntegerLike)
507     Operation ^= 7;   // Flip L, G, E bits, but not U.
508   else
509     Operation ^= 15;  // Flip all of the condition bits.
510 
511   if (Operation > ISD::SETTRUE2)
512     Operation &= ~8;  // Don't let N and U bits get set.
513 
514   return ISD::CondCode(Operation);
515 }
516 
517 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
518   return getSetCCInverseImpl(Op, Type.isInteger());
519 }
520 
521 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
522                                                bool isIntegerLike) {
523   return getSetCCInverseImpl(Op, isIntegerLike);
524 }
525 
526 /// For an integer comparison, return 1 if the comparison is a signed operation
527 /// and 2 if the result is an unsigned comparison. Return zero if the operation
528 /// does not depend on the sign of the input (setne and seteq).
529 static int isSignedOp(ISD::CondCode Opcode) {
530   switch (Opcode) {
531   default: llvm_unreachable("Illegal integer setcc operation!");
532   case ISD::SETEQ:
533   case ISD::SETNE: return 0;
534   case ISD::SETLT:
535   case ISD::SETLE:
536   case ISD::SETGT:
537   case ISD::SETGE: return 1;
538   case ISD::SETULT:
539   case ISD::SETULE:
540   case ISD::SETUGT:
541   case ISD::SETUGE: return 2;
542   }
543 }
544 
545 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
546                                        EVT Type) {
547   bool IsInteger = Type.isInteger();
548   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
549     // Cannot fold a signed integer setcc with an unsigned integer setcc.
550     return ISD::SETCC_INVALID;
551 
552   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
553 
554   // If the N and U bits get set, then the resultant comparison DOES suddenly
555   // care about orderedness, and it is true when ordered.
556   if (Op > ISD::SETTRUE2)
557     Op &= ~16;     // Clear the U bit if the N bit is set.
558 
559   // Canonicalize illegal integer setcc's.
560   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
561     Op = ISD::SETNE;
562 
563   return ISD::CondCode(Op);
564 }
565 
566 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
567                                         EVT Type) {
568   bool IsInteger = Type.isInteger();
569   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
570     // Cannot fold a signed setcc with an unsigned setcc.
571     return ISD::SETCC_INVALID;
572 
573   // Combine all of the condition bits.
574   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
575 
576   // Canonicalize illegal integer setcc's.
577   if (IsInteger) {
578     switch (Result) {
579     default: break;
580     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
581     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
582     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
583     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
584     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
585     }
586   }
587 
588   return Result;
589 }
590 
591 //===----------------------------------------------------------------------===//
592 //                           SDNode Profile Support
593 //===----------------------------------------------------------------------===//
594 
595 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
596 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
597   ID.AddInteger(OpC);
598 }
599 
600 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
601 /// solely with their pointer.
602 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
603   ID.AddPointer(VTList.VTs);
604 }
605 
606 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
607 static void AddNodeIDOperands(FoldingSetNodeID &ID,
608                               ArrayRef<SDValue> Ops) {
609   for (auto& Op : Ops) {
610     ID.AddPointer(Op.getNode());
611     ID.AddInteger(Op.getResNo());
612   }
613 }
614 
615 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
616 static void AddNodeIDOperands(FoldingSetNodeID &ID,
617                               ArrayRef<SDUse> Ops) {
618   for (auto& Op : Ops) {
619     ID.AddPointer(Op.getNode());
620     ID.AddInteger(Op.getResNo());
621   }
622 }
623 
624 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
625                           SDVTList VTList, ArrayRef<SDValue> OpList) {
626   AddNodeIDOpcode(ID, OpC);
627   AddNodeIDValueTypes(ID, VTList);
628   AddNodeIDOperands(ID, OpList);
629 }
630 
631 /// If this is an SDNode with special info, add this info to the NodeID data.
632 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
633   switch (N->getOpcode()) {
634   case ISD::TargetExternalSymbol:
635   case ISD::ExternalSymbol:
636   case ISD::MCSymbol:
637     llvm_unreachable("Should only be used on nodes with operands");
638   default: break;  // Normal nodes don't need extra info.
639   case ISD::TargetConstant:
640   case ISD::Constant: {
641     const ConstantSDNode *C = cast<ConstantSDNode>(N);
642     ID.AddPointer(C->getConstantIntValue());
643     ID.AddBoolean(C->isOpaque());
644     break;
645   }
646   case ISD::TargetConstantFP:
647   case ISD::ConstantFP:
648     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
649     break;
650   case ISD::TargetGlobalAddress:
651   case ISD::GlobalAddress:
652   case ISD::TargetGlobalTLSAddress:
653   case ISD::GlobalTLSAddress: {
654     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
655     ID.AddPointer(GA->getGlobal());
656     ID.AddInteger(GA->getOffset());
657     ID.AddInteger(GA->getTargetFlags());
658     break;
659   }
660   case ISD::BasicBlock:
661     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
662     break;
663   case ISD::Register:
664     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
665     break;
666   case ISD::RegisterMask:
667     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
668     break;
669   case ISD::SRCVALUE:
670     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
671     break;
672   case ISD::FrameIndex:
673   case ISD::TargetFrameIndex:
674     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
675     break;
676   case ISD::LIFETIME_START:
677   case ISD::LIFETIME_END:
678     if (cast<LifetimeSDNode>(N)->hasOffset()) {
679       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
680       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
681     }
682     break;
683   case ISD::PSEUDO_PROBE:
684     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
685     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
686     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
687     break;
688   case ISD::JumpTable:
689   case ISD::TargetJumpTable:
690     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
691     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
692     break;
693   case ISD::ConstantPool:
694   case ISD::TargetConstantPool: {
695     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
696     ID.AddInteger(CP->getAlign().value());
697     ID.AddInteger(CP->getOffset());
698     if (CP->isMachineConstantPoolEntry())
699       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
700     else
701       ID.AddPointer(CP->getConstVal());
702     ID.AddInteger(CP->getTargetFlags());
703     break;
704   }
705   case ISD::TargetIndex: {
706     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
707     ID.AddInteger(TI->getIndex());
708     ID.AddInteger(TI->getOffset());
709     ID.AddInteger(TI->getTargetFlags());
710     break;
711   }
712   case ISD::LOAD: {
713     const LoadSDNode *LD = cast<LoadSDNode>(N);
714     ID.AddInteger(LD->getMemoryVT().getRawBits());
715     ID.AddInteger(LD->getRawSubclassData());
716     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
717     break;
718   }
719   case ISD::STORE: {
720     const StoreSDNode *ST = cast<StoreSDNode>(N);
721     ID.AddInteger(ST->getMemoryVT().getRawBits());
722     ID.AddInteger(ST->getRawSubclassData());
723     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
724     break;
725   }
726   case ISD::VP_LOAD: {
727     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
728     ID.AddInteger(ELD->getMemoryVT().getRawBits());
729     ID.AddInteger(ELD->getRawSubclassData());
730     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
731     break;
732   }
733   case ISD::VP_STORE: {
734     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735     ID.AddInteger(EST->getMemoryVT().getRawBits());
736     ID.AddInteger(EST->getRawSubclassData());
737     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738     break;
739   }
740   case ISD::VP_GATHER: {
741     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
742     ID.AddInteger(EG->getMemoryVT().getRawBits());
743     ID.AddInteger(EG->getRawSubclassData());
744     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
745     break;
746   }
747   case ISD::VP_SCATTER: {
748     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
749     ID.AddInteger(ES->getMemoryVT().getRawBits());
750     ID.AddInteger(ES->getRawSubclassData());
751     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
752     break;
753   }
754   case ISD::MLOAD: {
755     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
756     ID.AddInteger(MLD->getMemoryVT().getRawBits());
757     ID.AddInteger(MLD->getRawSubclassData());
758     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
759     break;
760   }
761   case ISD::MSTORE: {
762     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
763     ID.AddInteger(MST->getMemoryVT().getRawBits());
764     ID.AddInteger(MST->getRawSubclassData());
765     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
766     break;
767   }
768   case ISD::MGATHER: {
769     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
770     ID.AddInteger(MG->getMemoryVT().getRawBits());
771     ID.AddInteger(MG->getRawSubclassData());
772     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
773     break;
774   }
775   case ISD::MSCATTER: {
776     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
777     ID.AddInteger(MS->getMemoryVT().getRawBits());
778     ID.AddInteger(MS->getRawSubclassData());
779     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
780     break;
781   }
782   case ISD::ATOMIC_CMP_SWAP:
783   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
784   case ISD::ATOMIC_SWAP:
785   case ISD::ATOMIC_LOAD_ADD:
786   case ISD::ATOMIC_LOAD_SUB:
787   case ISD::ATOMIC_LOAD_AND:
788   case ISD::ATOMIC_LOAD_CLR:
789   case ISD::ATOMIC_LOAD_OR:
790   case ISD::ATOMIC_LOAD_XOR:
791   case ISD::ATOMIC_LOAD_NAND:
792   case ISD::ATOMIC_LOAD_MIN:
793   case ISD::ATOMIC_LOAD_MAX:
794   case ISD::ATOMIC_LOAD_UMIN:
795   case ISD::ATOMIC_LOAD_UMAX:
796   case ISD::ATOMIC_LOAD:
797   case ISD::ATOMIC_STORE: {
798     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
799     ID.AddInteger(AT->getMemoryVT().getRawBits());
800     ID.AddInteger(AT->getRawSubclassData());
801     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
802     break;
803   }
804   case ISD::PREFETCH: {
805     const MemSDNode *PF = cast<MemSDNode>(N);
806     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
807     break;
808   }
809   case ISD::VECTOR_SHUFFLE: {
810     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
811     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
812          i != e; ++i)
813       ID.AddInteger(SVN->getMaskElt(i));
814     break;
815   }
816   case ISD::TargetBlockAddress:
817   case ISD::BlockAddress: {
818     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
819     ID.AddPointer(BA->getBlockAddress());
820     ID.AddInteger(BA->getOffset());
821     ID.AddInteger(BA->getTargetFlags());
822     break;
823   }
824   } // end switch (N->getOpcode())
825 
826   // Target specific memory nodes could also have address spaces to check.
827   if (N->isTargetMemoryOpcode())
828     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
829 }
830 
831 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
832 /// data.
833 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
834   AddNodeIDOpcode(ID, N->getOpcode());
835   // Add the return value info.
836   AddNodeIDValueTypes(ID, N->getVTList());
837   // Add the operand info.
838   AddNodeIDOperands(ID, N->ops());
839 
840   // Handle SDNode leafs with special info.
841   AddNodeIDCustom(ID, N);
842 }
843 
844 //===----------------------------------------------------------------------===//
845 //                              SelectionDAG Class
846 //===----------------------------------------------------------------------===//
847 
848 /// doNotCSE - Return true if CSE should not be performed for this node.
849 static bool doNotCSE(SDNode *N) {
850   if (N->getValueType(0) == MVT::Glue)
851     return true; // Never CSE anything that produces a flag.
852 
853   switch (N->getOpcode()) {
854   default: break;
855   case ISD::HANDLENODE:
856   case ISD::EH_LABEL:
857     return true;   // Never CSE these nodes.
858   }
859 
860   // Check that remaining values produced are not flags.
861   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
862     if (N->getValueType(i) == MVT::Glue)
863       return true; // Never CSE anything that produces a flag.
864 
865   return false;
866 }
867 
868 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
869 /// SelectionDAG.
870 void SelectionDAG::RemoveDeadNodes() {
871   // Create a dummy node (which is not added to allnodes), that adds a reference
872   // to the root node, preventing it from being deleted.
873   HandleSDNode Dummy(getRoot());
874 
875   SmallVector<SDNode*, 128> DeadNodes;
876 
877   // Add all obviously-dead nodes to the DeadNodes worklist.
878   for (SDNode &Node : allnodes())
879     if (Node.use_empty())
880       DeadNodes.push_back(&Node);
881 
882   RemoveDeadNodes(DeadNodes);
883 
884   // If the root changed (e.g. it was a dead load, update the root).
885   setRoot(Dummy.getValue());
886 }
887 
888 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
889 /// given list, and any nodes that become unreachable as a result.
890 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
891 
892   // Process the worklist, deleting the nodes and adding their uses to the
893   // worklist.
894   while (!DeadNodes.empty()) {
895     SDNode *N = DeadNodes.pop_back_val();
896     // Skip to next node if we've already managed to delete the node. This could
897     // happen if replacing a node causes a node previously added to the node to
898     // be deleted.
899     if (N->getOpcode() == ISD::DELETED_NODE)
900       continue;
901 
902     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
903       DUL->NodeDeleted(N, nullptr);
904 
905     // Take the node out of the appropriate CSE map.
906     RemoveNodeFromCSEMaps(N);
907 
908     // Next, brutally remove the operand list.  This is safe to do, as there are
909     // no cycles in the graph.
910     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
911       SDUse &Use = *I++;
912       SDNode *Operand = Use.getNode();
913       Use.set(SDValue());
914 
915       // Now that we removed this operand, see if there are no uses of it left.
916       if (Operand->use_empty())
917         DeadNodes.push_back(Operand);
918     }
919 
920     DeallocateNode(N);
921   }
922 }
923 
924 void SelectionDAG::RemoveDeadNode(SDNode *N){
925   SmallVector<SDNode*, 16> DeadNodes(1, N);
926 
927   // Create a dummy node that adds a reference to the root node, preventing
928   // it from being deleted.  (This matters if the root is an operand of the
929   // dead node.)
930   HandleSDNode Dummy(getRoot());
931 
932   RemoveDeadNodes(DeadNodes);
933 }
934 
935 void SelectionDAG::DeleteNode(SDNode *N) {
936   // First take this out of the appropriate CSE map.
937   RemoveNodeFromCSEMaps(N);
938 
939   // Finally, remove uses due to operands of this node, remove from the
940   // AllNodes list, and delete the node.
941   DeleteNodeNotInCSEMaps(N);
942 }
943 
944 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
945   assert(N->getIterator() != AllNodes.begin() &&
946          "Cannot delete the entry node!");
947   assert(N->use_empty() && "Cannot delete a node that is not dead!");
948 
949   // Drop all of the operands and decrement used node's use counts.
950   N->DropOperands();
951 
952   DeallocateNode(N);
953 }
954 
955 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
956   assert(!(V->isVariadic() && isParameter));
957   if (isParameter)
958     ByvalParmDbgValues.push_back(V);
959   else
960     DbgValues.push_back(V);
961   for (const SDNode *Node : V->getSDNodes())
962     if (Node)
963       DbgValMap[Node].push_back(V);
964 }
965 
966 void SDDbgInfo::erase(const SDNode *Node) {
967   DbgValMapType::iterator I = DbgValMap.find(Node);
968   if (I == DbgValMap.end())
969     return;
970   for (auto &Val: I->second)
971     Val->setIsInvalidated();
972   DbgValMap.erase(I);
973 }
974 
975 void SelectionDAG::DeallocateNode(SDNode *N) {
976   // If we have operands, deallocate them.
977   removeOperands(N);
978 
979   NodeAllocator.Deallocate(AllNodes.remove(N));
980 
981   // Set the opcode to DELETED_NODE to help catch bugs when node
982   // memory is reallocated.
983   // FIXME: There are places in SDag that have grown a dependency on the opcode
984   // value in the released node.
985   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
986   N->NodeType = ISD::DELETED_NODE;
987 
988   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
989   // them and forget about that node.
990   DbgInfo->erase(N);
991 }
992 
993 #ifndef NDEBUG
994 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
995 static void VerifySDNode(SDNode *N) {
996   switch (N->getOpcode()) {
997   default:
998     break;
999   case ISD::BUILD_PAIR: {
1000     EVT VT = N->getValueType(0);
1001     assert(N->getNumValues() == 1 && "Too many results!");
1002     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1003            "Wrong return type!");
1004     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1005     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1006            "Mismatched operand types!");
1007     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1008            "Wrong operand type!");
1009     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1010            "Wrong return type size");
1011     break;
1012   }
1013   case ISD::BUILD_VECTOR: {
1014     assert(N->getNumValues() == 1 && "Too many results!");
1015     assert(N->getValueType(0).isVector() && "Wrong return type!");
1016     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1017            "Wrong number of operands!");
1018     EVT EltVT = N->getValueType(0).getVectorElementType();
1019     for (const SDUse &Op : N->ops()) {
1020       assert((Op.getValueType() == EltVT ||
1021               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1022                EltVT.bitsLE(Op.getValueType()))) &&
1023              "Wrong operand type!");
1024       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1025              "Operands must all have the same type");
1026     }
1027     break;
1028   }
1029   }
1030 }
1031 #endif // NDEBUG
1032 
1033 /// Insert a newly allocated node into the DAG.
1034 ///
1035 /// Handles insertion into the all nodes list and CSE map, as well as
1036 /// verification and other common operations when a new node is allocated.
1037 void SelectionDAG::InsertNode(SDNode *N) {
1038   AllNodes.push_back(N);
1039 #ifndef NDEBUG
1040   N->PersistentId = NextPersistentId++;
1041   VerifySDNode(N);
1042 #endif
1043   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1044     DUL->NodeInserted(N);
1045 }
1046 
1047 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1048 /// correspond to it.  This is useful when we're about to delete or repurpose
1049 /// the node.  We don't want future request for structurally identical nodes
1050 /// to return N anymore.
1051 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1052   bool Erased = false;
1053   switch (N->getOpcode()) {
1054   case ISD::HANDLENODE: return false;  // noop.
1055   case ISD::CONDCODE:
1056     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1057            "Cond code doesn't exist!");
1058     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1059     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1060     break;
1061   case ISD::ExternalSymbol:
1062     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1063     break;
1064   case ISD::TargetExternalSymbol: {
1065     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1066     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1067         ESN->getSymbol(), ESN->getTargetFlags()));
1068     break;
1069   }
1070   case ISD::MCSymbol: {
1071     auto *MCSN = cast<MCSymbolSDNode>(N);
1072     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1073     break;
1074   }
1075   case ISD::VALUETYPE: {
1076     EVT VT = cast<VTSDNode>(N)->getVT();
1077     if (VT.isExtended()) {
1078       Erased = ExtendedValueTypeNodes.erase(VT);
1079     } else {
1080       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1081       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1082     }
1083     break;
1084   }
1085   default:
1086     // Remove it from the CSE Map.
1087     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1088     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1089     Erased = CSEMap.RemoveNode(N);
1090     break;
1091   }
1092 #ifndef NDEBUG
1093   // Verify that the node was actually in one of the CSE maps, unless it has a
1094   // flag result (which cannot be CSE'd) or is one of the special cases that are
1095   // not subject to CSE.
1096   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1097       !N->isMachineOpcode() && !doNotCSE(N)) {
1098     N->dump(this);
1099     dbgs() << "\n";
1100     llvm_unreachable("Node is not in map!");
1101   }
1102 #endif
1103   return Erased;
1104 }
1105 
1106 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1107 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1108 /// node already exists, in which case transfer all its users to the existing
1109 /// node. This transfer can potentially trigger recursive merging.
1110 void
1111 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1112   // For node types that aren't CSE'd, just act as if no identical node
1113   // already exists.
1114   if (!doNotCSE(N)) {
1115     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1116     if (Existing != N) {
1117       // If there was already an existing matching node, use ReplaceAllUsesWith
1118       // to replace the dead one with the existing one.  This can cause
1119       // recursive merging of other unrelated nodes down the line.
1120       ReplaceAllUsesWith(N, Existing);
1121 
1122       // N is now dead. Inform the listeners and delete it.
1123       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1124         DUL->NodeDeleted(N, Existing);
1125       DeleteNodeNotInCSEMaps(N);
1126       return;
1127     }
1128   }
1129 
1130   // If the node doesn't already exist, we updated it.  Inform listeners.
1131   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1132     DUL->NodeUpdated(N);
1133 }
1134 
1135 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1136 /// were replaced with those specified.  If this node is never memoized,
1137 /// return null, otherwise return a pointer to the slot it would take.  If a
1138 /// node already exists with these operands, the slot will be non-null.
1139 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1140                                            void *&InsertPos) {
1141   if (doNotCSE(N))
1142     return nullptr;
1143 
1144   SDValue Ops[] = { Op };
1145   FoldingSetNodeID ID;
1146   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1147   AddNodeIDCustom(ID, N);
1148   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1149   if (Node)
1150     Node->intersectFlagsWith(N->getFlags());
1151   return Node;
1152 }
1153 
1154 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1155 /// were replaced with those specified.  If this node is never memoized,
1156 /// return null, otherwise return a pointer to the slot it would take.  If a
1157 /// node already exists with these operands, the slot will be non-null.
1158 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1159                                            SDValue Op1, SDValue Op2,
1160                                            void *&InsertPos) {
1161   if (doNotCSE(N))
1162     return nullptr;
1163 
1164   SDValue Ops[] = { Op1, Op2 };
1165   FoldingSetNodeID ID;
1166   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1167   AddNodeIDCustom(ID, N);
1168   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1169   if (Node)
1170     Node->intersectFlagsWith(N->getFlags());
1171   return Node;
1172 }
1173 
1174 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1175 /// were replaced with those specified.  If this node is never memoized,
1176 /// return null, otherwise return a pointer to the slot it would take.  If a
1177 /// node already exists with these operands, the slot will be non-null.
1178 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1179                                            void *&InsertPos) {
1180   if (doNotCSE(N))
1181     return nullptr;
1182 
1183   FoldingSetNodeID ID;
1184   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1185   AddNodeIDCustom(ID, N);
1186   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1187   if (Node)
1188     Node->intersectFlagsWith(N->getFlags());
1189   return Node;
1190 }
1191 
1192 Align SelectionDAG::getEVTAlign(EVT VT) const {
1193   Type *Ty = VT == MVT::iPTR ?
1194                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1195                    VT.getTypeForEVT(*getContext());
1196 
1197   return getDataLayout().getABITypeAlign(Ty);
1198 }
1199 
1200 // EntryNode could meaningfully have debug info if we can find it...
1201 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1202     : TM(tm), OptLevel(OL),
1203       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1204       Root(getEntryNode()) {
1205   InsertNode(&EntryNode);
1206   DbgInfo = new SDDbgInfo();
1207 }
1208 
1209 void SelectionDAG::init(MachineFunction &NewMF,
1210                         OptimizationRemarkEmitter &NewORE,
1211                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1212                         LegacyDivergenceAnalysis * Divergence,
1213                         ProfileSummaryInfo *PSIin,
1214                         BlockFrequencyInfo *BFIin) {
1215   MF = &NewMF;
1216   SDAGISelPass = PassPtr;
1217   ORE = &NewORE;
1218   TLI = getSubtarget().getTargetLowering();
1219   TSI = getSubtarget().getSelectionDAGInfo();
1220   LibInfo = LibraryInfo;
1221   Context = &MF->getFunction().getContext();
1222   DA = Divergence;
1223   PSI = PSIin;
1224   BFI = BFIin;
1225 }
1226 
1227 SelectionDAG::~SelectionDAG() {
1228   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1229   allnodes_clear();
1230   OperandRecycler.clear(OperandAllocator);
1231   delete DbgInfo;
1232 }
1233 
1234 bool SelectionDAG::shouldOptForSize() const {
1235   return MF->getFunction().hasOptSize() ||
1236       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1237 }
1238 
1239 void SelectionDAG::allnodes_clear() {
1240   assert(&*AllNodes.begin() == &EntryNode);
1241   AllNodes.remove(AllNodes.begin());
1242   while (!AllNodes.empty())
1243     DeallocateNode(&AllNodes.front());
1244 #ifndef NDEBUG
1245   NextPersistentId = 0;
1246 #endif
1247 }
1248 
1249 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1250                                           void *&InsertPos) {
1251   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1252   if (N) {
1253     switch (N->getOpcode()) {
1254     default: break;
1255     case ISD::Constant:
1256     case ISD::ConstantFP:
1257       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1258                        "debug location.  Use another overload.");
1259     }
1260   }
1261   return N;
1262 }
1263 
1264 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1265                                           const SDLoc &DL, void *&InsertPos) {
1266   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1267   if (N) {
1268     switch (N->getOpcode()) {
1269     case ISD::Constant:
1270     case ISD::ConstantFP:
1271       // Erase debug location from the node if the node is used at several
1272       // different places. Do not propagate one location to all uses as it
1273       // will cause a worse single stepping debugging experience.
1274       if (N->getDebugLoc() != DL.getDebugLoc())
1275         N->setDebugLoc(DebugLoc());
1276       break;
1277     default:
1278       // When the node's point of use is located earlier in the instruction
1279       // sequence than its prior point of use, update its debug info to the
1280       // earlier location.
1281       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1282         N->setDebugLoc(DL.getDebugLoc());
1283       break;
1284     }
1285   }
1286   return N;
1287 }
1288 
1289 void SelectionDAG::clear() {
1290   allnodes_clear();
1291   OperandRecycler.clear(OperandAllocator);
1292   OperandAllocator.Reset();
1293   CSEMap.clear();
1294 
1295   ExtendedValueTypeNodes.clear();
1296   ExternalSymbols.clear();
1297   TargetExternalSymbols.clear();
1298   MCSymbols.clear();
1299   SDCallSiteDbgInfo.clear();
1300   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1301             static_cast<CondCodeSDNode*>(nullptr));
1302   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1303             static_cast<SDNode*>(nullptr));
1304 
1305   EntryNode.UseList = nullptr;
1306   InsertNode(&EntryNode);
1307   Root = getEntryNode();
1308   DbgInfo->clear();
1309 }
1310 
1311 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1312   return VT.bitsGT(Op.getValueType())
1313              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1314              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1315 }
1316 
1317 std::pair<SDValue, SDValue>
1318 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1319                                        const SDLoc &DL, EVT VT) {
1320   assert(!VT.bitsEq(Op.getValueType()) &&
1321          "Strict no-op FP extend/round not allowed.");
1322   SDValue Res =
1323       VT.bitsGT(Op.getValueType())
1324           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1325           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1326                     {Chain, Op, getIntPtrConstant(0, DL)});
1327 
1328   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1329 }
1330 
1331 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1332   return VT.bitsGT(Op.getValueType()) ?
1333     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1334     getNode(ISD::TRUNCATE, DL, VT, Op);
1335 }
1336 
1337 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1338   return VT.bitsGT(Op.getValueType()) ?
1339     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1340     getNode(ISD::TRUNCATE, DL, VT, Op);
1341 }
1342 
1343 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1344   return VT.bitsGT(Op.getValueType()) ?
1345     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1346     getNode(ISD::TRUNCATE, DL, VT, Op);
1347 }
1348 
1349 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1350                                         EVT OpVT) {
1351   if (VT.bitsLE(Op.getValueType()))
1352     return getNode(ISD::TRUNCATE, SL, VT, Op);
1353 
1354   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1355   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1356 }
1357 
1358 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1359   EVT OpVT = Op.getValueType();
1360   assert(VT.isInteger() && OpVT.isInteger() &&
1361          "Cannot getZeroExtendInReg FP types");
1362   assert(VT.isVector() == OpVT.isVector() &&
1363          "getZeroExtendInReg type should be vector iff the operand "
1364          "type is vector!");
1365   assert((!VT.isVector() ||
1366           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1367          "Vector element counts must match in getZeroExtendInReg");
1368   assert(VT.bitsLE(OpVT) && "Not extending!");
1369   if (OpVT == VT)
1370     return Op;
1371   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1372                                    VT.getScalarSizeInBits());
1373   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1374 }
1375 
1376 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1377   // Only unsigned pointer semantics are supported right now. In the future this
1378   // might delegate to TLI to check pointer signedness.
1379   return getZExtOrTrunc(Op, DL, VT);
1380 }
1381 
1382 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1383   // Only unsigned pointer semantics are supported right now. In the future this
1384   // might delegate to TLI to check pointer signedness.
1385   return getZeroExtendInReg(Op, DL, VT);
1386 }
1387 
1388 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1389 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1390   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1391 }
1392 
1393 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1394   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1395   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1396 }
1397 
1398 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1399                                       EVT OpVT) {
1400   if (!V)
1401     return getConstant(0, DL, VT);
1402 
1403   switch (TLI->getBooleanContents(OpVT)) {
1404   case TargetLowering::ZeroOrOneBooleanContent:
1405   case TargetLowering::UndefinedBooleanContent:
1406     return getConstant(1, DL, VT);
1407   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1408     return getAllOnesConstant(DL, VT);
1409   }
1410   llvm_unreachable("Unexpected boolean content enum!");
1411 }
1412 
1413 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1414                                   bool isT, bool isO) {
1415   EVT EltVT = VT.getScalarType();
1416   assert((EltVT.getSizeInBits() >= 64 ||
1417           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1418          "getConstant with a uint64_t value that doesn't fit in the type!");
1419   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1420 }
1421 
1422 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1423                                   bool isT, bool isO) {
1424   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1425 }
1426 
1427 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1428                                   EVT VT, bool isT, bool isO) {
1429   assert(VT.isInteger() && "Cannot create FP integer constant!");
1430 
1431   EVT EltVT = VT.getScalarType();
1432   const ConstantInt *Elt = &Val;
1433 
1434   // In some cases the vector type is legal but the element type is illegal and
1435   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1436   // inserted value (the type does not need to match the vector element type).
1437   // Any extra bits introduced will be truncated away.
1438   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1439                            TargetLowering::TypePromoteInteger) {
1440     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1441     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1442     Elt = ConstantInt::get(*getContext(), NewVal);
1443   }
1444   // In other cases the element type is illegal and needs to be expanded, for
1445   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1446   // the value into n parts and use a vector type with n-times the elements.
1447   // Then bitcast to the type requested.
1448   // Legalizing constants too early makes the DAGCombiner's job harder so we
1449   // only legalize if the DAG tells us we must produce legal types.
1450   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1451            TLI->getTypeAction(*getContext(), EltVT) ==
1452                TargetLowering::TypeExpandInteger) {
1453     const APInt &NewVal = Elt->getValue();
1454     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1455     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1456 
1457     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1458     if (VT.isScalableVector()) {
1459       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1460              "Can only handle an even split!");
1461       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1462 
1463       SmallVector<SDValue, 2> ScalarParts;
1464       for (unsigned i = 0; i != Parts; ++i)
1465         ScalarParts.push_back(getConstant(
1466             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1467             ViaEltVT, isT, isO));
1468 
1469       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1470     }
1471 
1472     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1473     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1474 
1475     // Check the temporary vector is the correct size. If this fails then
1476     // getTypeToTransformTo() probably returned a type whose size (in bits)
1477     // isn't a power-of-2 factor of the requested type size.
1478     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1479 
1480     SmallVector<SDValue, 2> EltParts;
1481     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1482       EltParts.push_back(getConstant(
1483           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1484           ViaEltVT, isT, isO));
1485 
1486     // EltParts is currently in little endian order. If we actually want
1487     // big-endian order then reverse it now.
1488     if (getDataLayout().isBigEndian())
1489       std::reverse(EltParts.begin(), EltParts.end());
1490 
1491     // The elements must be reversed when the element order is different
1492     // to the endianness of the elements (because the BITCAST is itself a
1493     // vector shuffle in this situation). However, we do not need any code to
1494     // perform this reversal because getConstant() is producing a vector
1495     // splat.
1496     // This situation occurs in MIPS MSA.
1497 
1498     SmallVector<SDValue, 8> Ops;
1499     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1500       llvm::append_range(Ops, EltParts);
1501 
1502     SDValue V =
1503         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1504     return V;
1505   }
1506 
1507   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1508          "APInt size does not match type size!");
1509   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1510   FoldingSetNodeID ID;
1511   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1512   ID.AddPointer(Elt);
1513   ID.AddBoolean(isO);
1514   void *IP = nullptr;
1515   SDNode *N = nullptr;
1516   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1517     if (!VT.isVector())
1518       return SDValue(N, 0);
1519 
1520   if (!N) {
1521     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1522     CSEMap.InsertNode(N, IP);
1523     InsertNode(N);
1524     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1525   }
1526 
1527   SDValue Result(N, 0);
1528   if (VT.isScalableVector())
1529     Result = getSplatVector(VT, DL, Result);
1530   else if (VT.isVector())
1531     Result = getSplatBuildVector(VT, DL, Result);
1532 
1533   return Result;
1534 }
1535 
1536 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1537                                         bool isTarget) {
1538   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1539 }
1540 
1541 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1542                                              const SDLoc &DL, bool LegalTypes) {
1543   assert(VT.isInteger() && "Shift amount is not an integer type!");
1544   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1545   return getConstant(Val, DL, ShiftVT);
1546 }
1547 
1548 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1549                                            bool isTarget) {
1550   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1551 }
1552 
1553 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1554                                     bool isTarget) {
1555   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1556 }
1557 
1558 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1559                                     EVT VT, bool isTarget) {
1560   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1561 
1562   EVT EltVT = VT.getScalarType();
1563 
1564   // Do the map lookup using the actual bit pattern for the floating point
1565   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1566   // we don't have issues with SNANs.
1567   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1568   FoldingSetNodeID ID;
1569   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1570   ID.AddPointer(&V);
1571   void *IP = nullptr;
1572   SDNode *N = nullptr;
1573   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1574     if (!VT.isVector())
1575       return SDValue(N, 0);
1576 
1577   if (!N) {
1578     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1579     CSEMap.InsertNode(N, IP);
1580     InsertNode(N);
1581   }
1582 
1583   SDValue Result(N, 0);
1584   if (VT.isScalableVector())
1585     Result = getSplatVector(VT, DL, Result);
1586   else if (VT.isVector())
1587     Result = getSplatBuildVector(VT, DL, Result);
1588   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1589   return Result;
1590 }
1591 
1592 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1593                                     bool isTarget) {
1594   EVT EltVT = VT.getScalarType();
1595   if (EltVT == MVT::f32)
1596     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1597   if (EltVT == MVT::f64)
1598     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1599   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1600       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1601     bool Ignored;
1602     APFloat APF = APFloat(Val);
1603     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1604                 &Ignored);
1605     return getConstantFP(APF, DL, VT, isTarget);
1606   }
1607   llvm_unreachable("Unsupported type in getConstantFP");
1608 }
1609 
1610 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1611                                        EVT VT, int64_t Offset, bool isTargetGA,
1612                                        unsigned TargetFlags) {
1613   assert((TargetFlags == 0 || isTargetGA) &&
1614          "Cannot set target flags on target-independent globals");
1615 
1616   // Truncate (with sign-extension) the offset value to the pointer size.
1617   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1618   if (BitWidth < 64)
1619     Offset = SignExtend64(Offset, BitWidth);
1620 
1621   unsigned Opc;
1622   if (GV->isThreadLocal())
1623     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1624   else
1625     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1626 
1627   FoldingSetNodeID ID;
1628   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1629   ID.AddPointer(GV);
1630   ID.AddInteger(Offset);
1631   ID.AddInteger(TargetFlags);
1632   void *IP = nullptr;
1633   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1634     return SDValue(E, 0);
1635 
1636   auto *N = newSDNode<GlobalAddressSDNode>(
1637       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1638   CSEMap.InsertNode(N, IP);
1639     InsertNode(N);
1640   return SDValue(N, 0);
1641 }
1642 
1643 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1644   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1645   FoldingSetNodeID ID;
1646   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1647   ID.AddInteger(FI);
1648   void *IP = nullptr;
1649   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1650     return SDValue(E, 0);
1651 
1652   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1653   CSEMap.InsertNode(N, IP);
1654   InsertNode(N);
1655   return SDValue(N, 0);
1656 }
1657 
1658 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1659                                    unsigned TargetFlags) {
1660   assert((TargetFlags == 0 || isTarget) &&
1661          "Cannot set target flags on target-independent jump tables");
1662   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1663   FoldingSetNodeID ID;
1664   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1665   ID.AddInteger(JTI);
1666   ID.AddInteger(TargetFlags);
1667   void *IP = nullptr;
1668   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1669     return SDValue(E, 0);
1670 
1671   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1672   CSEMap.InsertNode(N, IP);
1673   InsertNode(N);
1674   return SDValue(N, 0);
1675 }
1676 
1677 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1678                                       MaybeAlign Alignment, int Offset,
1679                                       bool isTarget, unsigned TargetFlags) {
1680   assert((TargetFlags == 0 || isTarget) &&
1681          "Cannot set target flags on target-independent globals");
1682   if (!Alignment)
1683     Alignment = shouldOptForSize()
1684                     ? getDataLayout().getABITypeAlign(C->getType())
1685                     : getDataLayout().getPrefTypeAlign(C->getType());
1686   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1687   FoldingSetNodeID ID;
1688   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1689   ID.AddInteger(Alignment->value());
1690   ID.AddInteger(Offset);
1691   ID.AddPointer(C);
1692   ID.AddInteger(TargetFlags);
1693   void *IP = nullptr;
1694   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1695     return SDValue(E, 0);
1696 
1697   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1698                                           TargetFlags);
1699   CSEMap.InsertNode(N, IP);
1700   InsertNode(N);
1701   SDValue V = SDValue(N, 0);
1702   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1703   return V;
1704 }
1705 
1706 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1707                                       MaybeAlign Alignment, int Offset,
1708                                       bool isTarget, unsigned TargetFlags) {
1709   assert((TargetFlags == 0 || isTarget) &&
1710          "Cannot set target flags on target-independent globals");
1711   if (!Alignment)
1712     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1713   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1714   FoldingSetNodeID ID;
1715   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1716   ID.AddInteger(Alignment->value());
1717   ID.AddInteger(Offset);
1718   C->addSelectionDAGCSEId(ID);
1719   ID.AddInteger(TargetFlags);
1720   void *IP = nullptr;
1721   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1722     return SDValue(E, 0);
1723 
1724   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1725                                           TargetFlags);
1726   CSEMap.InsertNode(N, IP);
1727   InsertNode(N);
1728   return SDValue(N, 0);
1729 }
1730 
1731 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1732                                      unsigned TargetFlags) {
1733   FoldingSetNodeID ID;
1734   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1735   ID.AddInteger(Index);
1736   ID.AddInteger(Offset);
1737   ID.AddInteger(TargetFlags);
1738   void *IP = nullptr;
1739   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1740     return SDValue(E, 0);
1741 
1742   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1743   CSEMap.InsertNode(N, IP);
1744   InsertNode(N);
1745   return SDValue(N, 0);
1746 }
1747 
1748 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1749   FoldingSetNodeID ID;
1750   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1751   ID.AddPointer(MBB);
1752   void *IP = nullptr;
1753   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1754     return SDValue(E, 0);
1755 
1756   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1757   CSEMap.InsertNode(N, IP);
1758   InsertNode(N);
1759   return SDValue(N, 0);
1760 }
1761 
1762 SDValue SelectionDAG::getValueType(EVT VT) {
1763   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1764       ValueTypeNodes.size())
1765     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1766 
1767   SDNode *&N = VT.isExtended() ?
1768     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1769 
1770   if (N) return SDValue(N, 0);
1771   N = newSDNode<VTSDNode>(VT);
1772   InsertNode(N);
1773   return SDValue(N, 0);
1774 }
1775 
1776 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1777   SDNode *&N = ExternalSymbols[Sym];
1778   if (N) return SDValue(N, 0);
1779   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1780   InsertNode(N);
1781   return SDValue(N, 0);
1782 }
1783 
1784 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1785   SDNode *&N = MCSymbols[Sym];
1786   if (N)
1787     return SDValue(N, 0);
1788   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1789   InsertNode(N);
1790   return SDValue(N, 0);
1791 }
1792 
1793 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1794                                               unsigned TargetFlags) {
1795   SDNode *&N =
1796       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1797   if (N) return SDValue(N, 0);
1798   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1799   InsertNode(N);
1800   return SDValue(N, 0);
1801 }
1802 
1803 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1804   if ((unsigned)Cond >= CondCodeNodes.size())
1805     CondCodeNodes.resize(Cond+1);
1806 
1807   if (!CondCodeNodes[Cond]) {
1808     auto *N = newSDNode<CondCodeSDNode>(Cond);
1809     CondCodeNodes[Cond] = N;
1810     InsertNode(N);
1811   }
1812 
1813   return SDValue(CondCodeNodes[Cond], 0);
1814 }
1815 
1816 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1817   APInt One(ResVT.getScalarSizeInBits(), 1);
1818   return getStepVector(DL, ResVT, One);
1819 }
1820 
1821 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1822   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1823   if (ResVT.isScalableVector())
1824     return getNode(
1825         ISD::STEP_VECTOR, DL, ResVT,
1826         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1827 
1828   SmallVector<SDValue, 16> OpsStepConstants;
1829   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1830     OpsStepConstants.push_back(
1831         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1832   return getBuildVector(ResVT, DL, OpsStepConstants);
1833 }
1834 
1835 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1836 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1837 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1838   std::swap(N1, N2);
1839   ShuffleVectorSDNode::commuteMask(M);
1840 }
1841 
1842 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1843                                        SDValue N2, ArrayRef<int> Mask) {
1844   assert(VT.getVectorNumElements() == Mask.size() &&
1845          "Must have the same number of vector elements as mask elements!");
1846   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1847          "Invalid VECTOR_SHUFFLE");
1848 
1849   // Canonicalize shuffle undef, undef -> undef
1850   if (N1.isUndef() && N2.isUndef())
1851     return getUNDEF(VT);
1852 
1853   // Validate that all indices in Mask are within the range of the elements
1854   // input to the shuffle.
1855   int NElts = Mask.size();
1856   assert(llvm::all_of(Mask,
1857                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1858          "Index out of range");
1859 
1860   // Copy the mask so we can do any needed cleanup.
1861   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1862 
1863   // Canonicalize shuffle v, v -> v, undef
1864   if (N1 == N2) {
1865     N2 = getUNDEF(VT);
1866     for (int i = 0; i != NElts; ++i)
1867       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1868   }
1869 
1870   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1871   if (N1.isUndef())
1872     commuteShuffle(N1, N2, MaskVec);
1873 
1874   if (TLI->hasVectorBlend()) {
1875     // If shuffling a splat, try to blend the splat instead. We do this here so
1876     // that even when this arises during lowering we don't have to re-handle it.
1877     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1878       BitVector UndefElements;
1879       SDValue Splat = BV->getSplatValue(&UndefElements);
1880       if (!Splat)
1881         return;
1882 
1883       for (int i = 0; i < NElts; ++i) {
1884         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1885           continue;
1886 
1887         // If this input comes from undef, mark it as such.
1888         if (UndefElements[MaskVec[i] - Offset]) {
1889           MaskVec[i] = -1;
1890           continue;
1891         }
1892 
1893         // If we can blend a non-undef lane, use that instead.
1894         if (!UndefElements[i])
1895           MaskVec[i] = i + Offset;
1896       }
1897     };
1898     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1899       BlendSplat(N1BV, 0);
1900     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1901       BlendSplat(N2BV, NElts);
1902   }
1903 
1904   // Canonicalize all index into lhs, -> shuffle lhs, undef
1905   // Canonicalize all index into rhs, -> shuffle rhs, undef
1906   bool AllLHS = true, AllRHS = true;
1907   bool N2Undef = N2.isUndef();
1908   for (int i = 0; i != NElts; ++i) {
1909     if (MaskVec[i] >= NElts) {
1910       if (N2Undef)
1911         MaskVec[i] = -1;
1912       else
1913         AllLHS = false;
1914     } else if (MaskVec[i] >= 0) {
1915       AllRHS = false;
1916     }
1917   }
1918   if (AllLHS && AllRHS)
1919     return getUNDEF(VT);
1920   if (AllLHS && !N2Undef)
1921     N2 = getUNDEF(VT);
1922   if (AllRHS) {
1923     N1 = getUNDEF(VT);
1924     commuteShuffle(N1, N2, MaskVec);
1925   }
1926   // Reset our undef status after accounting for the mask.
1927   N2Undef = N2.isUndef();
1928   // Re-check whether both sides ended up undef.
1929   if (N1.isUndef() && N2Undef)
1930     return getUNDEF(VT);
1931 
1932   // If Identity shuffle return that node.
1933   bool Identity = true, AllSame = true;
1934   for (int i = 0; i != NElts; ++i) {
1935     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1936     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1937   }
1938   if (Identity && NElts)
1939     return N1;
1940 
1941   // Shuffling a constant splat doesn't change the result.
1942   if (N2Undef) {
1943     SDValue V = N1;
1944 
1945     // Look through any bitcasts. We check that these don't change the number
1946     // (and size) of elements and just changes their types.
1947     while (V.getOpcode() == ISD::BITCAST)
1948       V = V->getOperand(0);
1949 
1950     // A splat should always show up as a build vector node.
1951     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1952       BitVector UndefElements;
1953       SDValue Splat = BV->getSplatValue(&UndefElements);
1954       // If this is a splat of an undef, shuffling it is also undef.
1955       if (Splat && Splat.isUndef())
1956         return getUNDEF(VT);
1957 
1958       bool SameNumElts =
1959           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1960 
1961       // We only have a splat which can skip shuffles if there is a splatted
1962       // value and no undef lanes rearranged by the shuffle.
1963       if (Splat && UndefElements.none()) {
1964         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1965         // number of elements match or the value splatted is a zero constant.
1966         if (SameNumElts)
1967           return N1;
1968         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1969           if (C->isZero())
1970             return N1;
1971       }
1972 
1973       // If the shuffle itself creates a splat, build the vector directly.
1974       if (AllSame && SameNumElts) {
1975         EVT BuildVT = BV->getValueType(0);
1976         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1977         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1978 
1979         // We may have jumped through bitcasts, so the type of the
1980         // BUILD_VECTOR may not match the type of the shuffle.
1981         if (BuildVT != VT)
1982           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1983         return NewBV;
1984       }
1985     }
1986   }
1987 
1988   FoldingSetNodeID ID;
1989   SDValue Ops[2] = { N1, N2 };
1990   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1991   for (int i = 0; i != NElts; ++i)
1992     ID.AddInteger(MaskVec[i]);
1993 
1994   void* IP = nullptr;
1995   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1996     return SDValue(E, 0);
1997 
1998   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1999   // SDNode doesn't have access to it.  This memory will be "leaked" when
2000   // the node is deallocated, but recovered when the NodeAllocator is released.
2001   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2002   llvm::copy(MaskVec, MaskAlloc);
2003 
2004   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2005                                            dl.getDebugLoc(), MaskAlloc);
2006   createOperands(N, Ops);
2007 
2008   CSEMap.InsertNode(N, IP);
2009   InsertNode(N);
2010   SDValue V = SDValue(N, 0);
2011   NewSDValueDbgMsg(V, "Creating new node: ", this);
2012   return V;
2013 }
2014 
2015 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2016   EVT VT = SV.getValueType(0);
2017   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2018   ShuffleVectorSDNode::commuteMask(MaskVec);
2019 
2020   SDValue Op0 = SV.getOperand(0);
2021   SDValue Op1 = SV.getOperand(1);
2022   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2023 }
2024 
2025 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2026   FoldingSetNodeID ID;
2027   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2028   ID.AddInteger(RegNo);
2029   void *IP = nullptr;
2030   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2031     return SDValue(E, 0);
2032 
2033   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2034   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2035   CSEMap.InsertNode(N, IP);
2036   InsertNode(N);
2037   return SDValue(N, 0);
2038 }
2039 
2040 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2041   FoldingSetNodeID ID;
2042   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2043   ID.AddPointer(RegMask);
2044   void *IP = nullptr;
2045   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2046     return SDValue(E, 0);
2047 
2048   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2049   CSEMap.InsertNode(N, IP);
2050   InsertNode(N);
2051   return SDValue(N, 0);
2052 }
2053 
2054 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2055                                  MCSymbol *Label) {
2056   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2057 }
2058 
2059 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2060                                    SDValue Root, MCSymbol *Label) {
2061   FoldingSetNodeID ID;
2062   SDValue Ops[] = { Root };
2063   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2064   ID.AddPointer(Label);
2065   void *IP = nullptr;
2066   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067     return SDValue(E, 0);
2068 
2069   auto *N =
2070       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2071   createOperands(N, Ops);
2072 
2073   CSEMap.InsertNode(N, IP);
2074   InsertNode(N);
2075   return SDValue(N, 0);
2076 }
2077 
2078 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2079                                       int64_t Offset, bool isTarget,
2080                                       unsigned TargetFlags) {
2081   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2082 
2083   FoldingSetNodeID ID;
2084   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2085   ID.AddPointer(BA);
2086   ID.AddInteger(Offset);
2087   ID.AddInteger(TargetFlags);
2088   void *IP = nullptr;
2089   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2090     return SDValue(E, 0);
2091 
2092   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2093   CSEMap.InsertNode(N, IP);
2094   InsertNode(N);
2095   return SDValue(N, 0);
2096 }
2097 
2098 SDValue SelectionDAG::getSrcValue(const Value *V) {
2099   FoldingSetNodeID ID;
2100   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2101   ID.AddPointer(V);
2102 
2103   void *IP = nullptr;
2104   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2105     return SDValue(E, 0);
2106 
2107   auto *N = newSDNode<SrcValueSDNode>(V);
2108   CSEMap.InsertNode(N, IP);
2109   InsertNode(N);
2110   return SDValue(N, 0);
2111 }
2112 
2113 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2114   FoldingSetNodeID ID;
2115   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2116   ID.AddPointer(MD);
2117 
2118   void *IP = nullptr;
2119   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2120     return SDValue(E, 0);
2121 
2122   auto *N = newSDNode<MDNodeSDNode>(MD);
2123   CSEMap.InsertNode(N, IP);
2124   InsertNode(N);
2125   return SDValue(N, 0);
2126 }
2127 
2128 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2129   if (VT == V.getValueType())
2130     return V;
2131 
2132   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2133 }
2134 
2135 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2136                                        unsigned SrcAS, unsigned DestAS) {
2137   SDValue Ops[] = {Ptr};
2138   FoldingSetNodeID ID;
2139   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2140   ID.AddInteger(SrcAS);
2141   ID.AddInteger(DestAS);
2142 
2143   void *IP = nullptr;
2144   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2145     return SDValue(E, 0);
2146 
2147   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2148                                            VT, SrcAS, DestAS);
2149   createOperands(N, Ops);
2150 
2151   CSEMap.InsertNode(N, IP);
2152   InsertNode(N);
2153   return SDValue(N, 0);
2154 }
2155 
2156 SDValue SelectionDAG::getFreeze(SDValue V) {
2157   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2158 }
2159 
2160 /// getShiftAmountOperand - Return the specified value casted to
2161 /// the target's desired shift amount type.
2162 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2163   EVT OpTy = Op.getValueType();
2164   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2165   if (OpTy == ShTy || OpTy.isVector()) return Op;
2166 
2167   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2168 }
2169 
2170 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2171   SDLoc dl(Node);
2172   const TargetLowering &TLI = getTargetLoweringInfo();
2173   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2174   EVT VT = Node->getValueType(0);
2175   SDValue Tmp1 = Node->getOperand(0);
2176   SDValue Tmp2 = Node->getOperand(1);
2177   const MaybeAlign MA(Node->getConstantOperandVal(3));
2178 
2179   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2180                                Tmp2, MachinePointerInfo(V));
2181   SDValue VAList = VAListLoad;
2182 
2183   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2184     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2185                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2186 
2187     VAList =
2188         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2189                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2190   }
2191 
2192   // Increment the pointer, VAList, to the next vaarg
2193   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2194                  getConstant(getDataLayout().getTypeAllocSize(
2195                                                VT.getTypeForEVT(*getContext())),
2196                              dl, VAList.getValueType()));
2197   // Store the incremented VAList to the legalized pointer
2198   Tmp1 =
2199       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2200   // Load the actual argument out of the pointer VAList
2201   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2202 }
2203 
2204 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2205   SDLoc dl(Node);
2206   const TargetLowering &TLI = getTargetLoweringInfo();
2207   // This defaults to loading a pointer from the input and storing it to the
2208   // output, returning the chain.
2209   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2210   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2211   SDValue Tmp1 =
2212       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2213               Node->getOperand(2), MachinePointerInfo(VS));
2214   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2215                   MachinePointerInfo(VD));
2216 }
2217 
2218 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2219   const DataLayout &DL = getDataLayout();
2220   Type *Ty = VT.getTypeForEVT(*getContext());
2221   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2222 
2223   if (TLI->isTypeLegal(VT) || !VT.isVector())
2224     return RedAlign;
2225 
2226   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2227   const Align StackAlign = TFI->getStackAlign();
2228 
2229   // See if we can choose a smaller ABI alignment in cases where it's an
2230   // illegal vector type that will get broken down.
2231   if (RedAlign > StackAlign) {
2232     EVT IntermediateVT;
2233     MVT RegisterVT;
2234     unsigned NumIntermediates;
2235     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2236                                 NumIntermediates, RegisterVT);
2237     Ty = IntermediateVT.getTypeForEVT(*getContext());
2238     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2239     if (RedAlign2 < RedAlign)
2240       RedAlign = RedAlign2;
2241   }
2242 
2243   return RedAlign;
2244 }
2245 
2246 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2247   MachineFrameInfo &MFI = MF->getFrameInfo();
2248   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2249   int StackID = 0;
2250   if (Bytes.isScalable())
2251     StackID = TFI->getStackIDForScalableVectors();
2252   // The stack id gives an indication of whether the object is scalable or
2253   // not, so it's safe to pass in the minimum size here.
2254   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2255                                        false, nullptr, StackID);
2256   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2257 }
2258 
2259 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2260   Type *Ty = VT.getTypeForEVT(*getContext());
2261   Align StackAlign =
2262       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2263   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2264 }
2265 
2266 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2267   TypeSize VT1Size = VT1.getStoreSize();
2268   TypeSize VT2Size = VT2.getStoreSize();
2269   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2270          "Don't know how to choose the maximum size when creating a stack "
2271          "temporary");
2272   TypeSize Bytes =
2273       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2274 
2275   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2276   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2277   const DataLayout &DL = getDataLayout();
2278   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2279   return CreateStackTemporary(Bytes, Align);
2280 }
2281 
2282 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2283                                 ISD::CondCode Cond, const SDLoc &dl) {
2284   EVT OpVT = N1.getValueType();
2285 
2286   // These setcc operations always fold.
2287   switch (Cond) {
2288   default: break;
2289   case ISD::SETFALSE:
2290   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2291   case ISD::SETTRUE:
2292   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2293 
2294   case ISD::SETOEQ:
2295   case ISD::SETOGT:
2296   case ISD::SETOGE:
2297   case ISD::SETOLT:
2298   case ISD::SETOLE:
2299   case ISD::SETONE:
2300   case ISD::SETO:
2301   case ISD::SETUO:
2302   case ISD::SETUEQ:
2303   case ISD::SETUNE:
2304     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2305     break;
2306   }
2307 
2308   if (OpVT.isInteger()) {
2309     // For EQ and NE, we can always pick a value for the undef to make the
2310     // predicate pass or fail, so we can return undef.
2311     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2312     // icmp eq/ne X, undef -> undef.
2313     if ((N1.isUndef() || N2.isUndef()) &&
2314         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2315       return getUNDEF(VT);
2316 
2317     // If both operands are undef, we can return undef for int comparison.
2318     // icmp undef, undef -> undef.
2319     if (N1.isUndef() && N2.isUndef())
2320       return getUNDEF(VT);
2321 
2322     // icmp X, X -> true/false
2323     // icmp X, undef -> true/false because undef could be X.
2324     if (N1 == N2)
2325       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2326   }
2327 
2328   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2329     const APInt &C2 = N2C->getAPIntValue();
2330     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2331       const APInt &C1 = N1C->getAPIntValue();
2332 
2333       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2334                              dl, VT, OpVT);
2335     }
2336   }
2337 
2338   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2339   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2340 
2341   if (N1CFP && N2CFP) {
2342     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2343     switch (Cond) {
2344     default: break;
2345     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2346                         return getUNDEF(VT);
2347                       LLVM_FALLTHROUGH;
2348     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2349                                              OpVT);
2350     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2351                         return getUNDEF(VT);
2352                       LLVM_FALLTHROUGH;
2353     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2354                                              R==APFloat::cmpLessThan, dl, VT,
2355                                              OpVT);
2356     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2357                         return getUNDEF(VT);
2358                       LLVM_FALLTHROUGH;
2359     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2360                                              OpVT);
2361     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2362                         return getUNDEF(VT);
2363                       LLVM_FALLTHROUGH;
2364     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2365                                              VT, OpVT);
2366     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2367                         return getUNDEF(VT);
2368                       LLVM_FALLTHROUGH;
2369     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2370                                              R==APFloat::cmpEqual, dl, VT,
2371                                              OpVT);
2372     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2373                         return getUNDEF(VT);
2374                       LLVM_FALLTHROUGH;
2375     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2376                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2377     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2378                                              OpVT);
2379     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2380                                              OpVT);
2381     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2382                                              R==APFloat::cmpEqual, dl, VT,
2383                                              OpVT);
2384     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2385                                              OpVT);
2386     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2387                                              R==APFloat::cmpLessThan, dl, VT,
2388                                              OpVT);
2389     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390                                              R==APFloat::cmpUnordered, dl, VT,
2391                                              OpVT);
2392     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2393                                              VT, OpVT);
2394     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2395                                              OpVT);
2396     }
2397   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2398     // Ensure that the constant occurs on the RHS.
2399     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2400     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2401       return SDValue();
2402     return getSetCC(dl, VT, N2, N1, SwappedCond);
2403   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2404              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2405     // If an operand is known to be a nan (or undef that could be a nan), we can
2406     // fold it.
2407     // Choosing NaN for the undef will always make unordered comparison succeed
2408     // and ordered comparison fails.
2409     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2410     switch (ISD::getUnorderedFlavor(Cond)) {
2411     default:
2412       llvm_unreachable("Unknown flavor!");
2413     case 0: // Known false.
2414       return getBoolConstant(false, dl, VT, OpVT);
2415     case 1: // Known true.
2416       return getBoolConstant(true, dl, VT, OpVT);
2417     case 2: // Undefined.
2418       return getUNDEF(VT);
2419     }
2420   }
2421 
2422   // Could not fold it.
2423   return SDValue();
2424 }
2425 
2426 /// See if the specified operand can be simplified with the knowledge that only
2427 /// the bits specified by DemandedBits are used.
2428 /// TODO: really we should be making this into the DAG equivalent of
2429 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2430 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2431   EVT VT = V.getValueType();
2432 
2433   if (VT.isScalableVector())
2434     return SDValue();
2435 
2436   APInt DemandedElts = VT.isVector()
2437                            ? APInt::getAllOnes(VT.getVectorNumElements())
2438                            : APInt(1, 1);
2439   return GetDemandedBits(V, DemandedBits, DemandedElts);
2440 }
2441 
2442 /// See if the specified operand can be simplified with the knowledge that only
2443 /// the bits specified by DemandedBits are used in the elements specified by
2444 /// DemandedElts.
2445 /// TODO: really we should be making this into the DAG equivalent of
2446 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2447 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2448                                       const APInt &DemandedElts) {
2449   switch (V.getOpcode()) {
2450   default:
2451     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2452                                                 *this);
2453   case ISD::Constant: {
2454     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2455     APInt NewVal = CVal & DemandedBits;
2456     if (NewVal != CVal)
2457       return getConstant(NewVal, SDLoc(V), V.getValueType());
2458     break;
2459   }
2460   case ISD::SRL:
2461     // Only look at single-use SRLs.
2462     if (!V.getNode()->hasOneUse())
2463       break;
2464     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2465       // See if we can recursively simplify the LHS.
2466       unsigned Amt = RHSC->getZExtValue();
2467 
2468       // Watch out for shift count overflow though.
2469       if (Amt >= DemandedBits.getBitWidth())
2470         break;
2471       APInt SrcDemandedBits = DemandedBits << Amt;
2472       if (SDValue SimplifyLHS =
2473               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2474         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2475                        V.getOperand(1));
2476     }
2477     break;
2478   }
2479   return SDValue();
2480 }
2481 
2482 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2483 /// use this predicate to simplify operations downstream.
2484 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2485   unsigned BitWidth = Op.getScalarValueSizeInBits();
2486   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2487 }
2488 
2489 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2490 /// this predicate to simplify operations downstream.  Mask is known to be zero
2491 /// for bits that V cannot have.
2492 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2493                                      unsigned Depth) const {
2494   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2495 }
2496 
2497 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2498 /// DemandedElts.  We use this predicate to simplify operations downstream.
2499 /// Mask is known to be zero for bits that V cannot have.
2500 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2501                                      const APInt &DemandedElts,
2502                                      unsigned Depth) const {
2503   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2504 }
2505 
2506 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2507 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2508                                         unsigned Depth) const {
2509   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2510 }
2511 
2512 /// isSplatValue - Return true if the vector V has the same value
2513 /// across all DemandedElts. For scalable vectors it does not make
2514 /// sense to specify which elements are demanded or undefined, therefore
2515 /// they are simply ignored.
2516 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2517                                 APInt &UndefElts, unsigned Depth) const {
2518   unsigned Opcode = V.getOpcode();
2519   EVT VT = V.getValueType();
2520   assert(VT.isVector() && "Vector type expected");
2521 
2522   if (!VT.isScalableVector() && !DemandedElts)
2523     return false; // No demanded elts, better to assume we don't know anything.
2524 
2525   if (Depth >= MaxRecursionDepth)
2526     return false; // Limit search depth.
2527 
2528   // Deal with some common cases here that work for both fixed and scalable
2529   // vector types.
2530   switch (Opcode) {
2531   case ISD::SPLAT_VECTOR:
2532     UndefElts = V.getOperand(0).isUndef()
2533                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2534                     : APInt(DemandedElts.getBitWidth(), 0);
2535     return true;
2536   case ISD::ADD:
2537   case ISD::SUB:
2538   case ISD::AND:
2539   case ISD::XOR:
2540   case ISD::OR: {
2541     APInt UndefLHS, UndefRHS;
2542     SDValue LHS = V.getOperand(0);
2543     SDValue RHS = V.getOperand(1);
2544     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2545         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2546       UndefElts = UndefLHS | UndefRHS;
2547       return true;
2548     }
2549     return false;
2550   }
2551   case ISD::ABS:
2552   case ISD::TRUNCATE:
2553   case ISD::SIGN_EXTEND:
2554   case ISD::ZERO_EXTEND:
2555     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2556   default:
2557     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2558         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2559       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2560     break;
2561 }
2562 
2563   // We don't support other cases than those above for scalable vectors at
2564   // the moment.
2565   if (VT.isScalableVector())
2566     return false;
2567 
2568   unsigned NumElts = VT.getVectorNumElements();
2569   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2570   UndefElts = APInt::getZero(NumElts);
2571 
2572   switch (Opcode) {
2573   case ISD::BUILD_VECTOR: {
2574     SDValue Scl;
2575     for (unsigned i = 0; i != NumElts; ++i) {
2576       SDValue Op = V.getOperand(i);
2577       if (Op.isUndef()) {
2578         UndefElts.setBit(i);
2579         continue;
2580       }
2581       if (!DemandedElts[i])
2582         continue;
2583       if (Scl && Scl != Op)
2584         return false;
2585       Scl = Op;
2586     }
2587     return true;
2588   }
2589   case ISD::VECTOR_SHUFFLE: {
2590     // Check if this is a shuffle node doing a splat.
2591     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2592     int SplatIndex = -1;
2593     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2594     for (int i = 0; i != (int)NumElts; ++i) {
2595       int M = Mask[i];
2596       if (M < 0) {
2597         UndefElts.setBit(i);
2598         continue;
2599       }
2600       if (!DemandedElts[i])
2601         continue;
2602       if (0 <= SplatIndex && SplatIndex != M)
2603         return false;
2604       SplatIndex = M;
2605     }
2606     return true;
2607   }
2608   case ISD::EXTRACT_SUBVECTOR: {
2609     // Offset the demanded elts by the subvector index.
2610     SDValue Src = V.getOperand(0);
2611     // We don't support scalable vectors at the moment.
2612     if (Src.getValueType().isScalableVector())
2613       return false;
2614     uint64_t Idx = V.getConstantOperandVal(1);
2615     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2616     APInt UndefSrcElts;
2617     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2618     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2619       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2620       return true;
2621     }
2622     break;
2623   }
2624   case ISD::ANY_EXTEND_VECTOR_INREG:
2625   case ISD::SIGN_EXTEND_VECTOR_INREG:
2626   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2627     // Widen the demanded elts by the src element count.
2628     SDValue Src = V.getOperand(0);
2629     // We don't support scalable vectors at the moment.
2630     if (Src.getValueType().isScalableVector())
2631       return false;
2632     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2633     APInt UndefSrcElts;
2634     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2635     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2636       UndefElts = UndefSrcElts.truncOrSelf(NumElts);
2637       return true;
2638     }
2639     break;
2640   }
2641   }
2642 
2643   return false;
2644 }
2645 
2646 /// Helper wrapper to main isSplatValue function.
2647 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2648   EVT VT = V.getValueType();
2649   assert(VT.isVector() && "Vector type expected");
2650 
2651   APInt UndefElts;
2652   APInt DemandedElts;
2653 
2654   // For now we don't support this with scalable vectors.
2655   if (!VT.isScalableVector())
2656     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2657   return isSplatValue(V, DemandedElts, UndefElts) &&
2658          (AllowUndefs || !UndefElts);
2659 }
2660 
2661 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2662   V = peekThroughExtractSubvectors(V);
2663 
2664   EVT VT = V.getValueType();
2665   unsigned Opcode = V.getOpcode();
2666   switch (Opcode) {
2667   default: {
2668     APInt UndefElts;
2669     APInt DemandedElts;
2670 
2671     if (!VT.isScalableVector())
2672       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2673 
2674     if (isSplatValue(V, DemandedElts, UndefElts)) {
2675       if (VT.isScalableVector()) {
2676         // DemandedElts and UndefElts are ignored for scalable vectors, since
2677         // the only supported cases are SPLAT_VECTOR nodes.
2678         SplatIdx = 0;
2679       } else {
2680         // Handle case where all demanded elements are UNDEF.
2681         if (DemandedElts.isSubsetOf(UndefElts)) {
2682           SplatIdx = 0;
2683           return getUNDEF(VT);
2684         }
2685         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2686       }
2687       return V;
2688     }
2689     break;
2690   }
2691   case ISD::SPLAT_VECTOR:
2692     SplatIdx = 0;
2693     return V;
2694   case ISD::VECTOR_SHUFFLE: {
2695     if (VT.isScalableVector())
2696       return SDValue();
2697 
2698     // Check if this is a shuffle node doing a splat.
2699     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2700     // getTargetVShiftNode currently struggles without the splat source.
2701     auto *SVN = cast<ShuffleVectorSDNode>(V);
2702     if (!SVN->isSplat())
2703       break;
2704     int Idx = SVN->getSplatIndex();
2705     int NumElts = V.getValueType().getVectorNumElements();
2706     SplatIdx = Idx % NumElts;
2707     return V.getOperand(Idx / NumElts);
2708   }
2709   }
2710 
2711   return SDValue();
2712 }
2713 
2714 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2715   int SplatIdx;
2716   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2717     EVT SVT = SrcVector.getValueType().getScalarType();
2718     EVT LegalSVT = SVT;
2719     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2720       if (!SVT.isInteger())
2721         return SDValue();
2722       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2723       if (LegalSVT.bitsLT(SVT))
2724         return SDValue();
2725     }
2726     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2727                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2728   }
2729   return SDValue();
2730 }
2731 
2732 const APInt *
2733 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2734                                           const APInt &DemandedElts) const {
2735   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2736           V.getOpcode() == ISD::SRA) &&
2737          "Unknown shift node");
2738   unsigned BitWidth = V.getScalarValueSizeInBits();
2739   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2740     // Shifting more than the bitwidth is not valid.
2741     const APInt &ShAmt = SA->getAPIntValue();
2742     if (ShAmt.ult(BitWidth))
2743       return &ShAmt;
2744   }
2745   return nullptr;
2746 }
2747 
2748 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2749     SDValue V, const APInt &DemandedElts) const {
2750   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2751           V.getOpcode() == ISD::SRA) &&
2752          "Unknown shift node");
2753   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2754     return ValidAmt;
2755   unsigned BitWidth = V.getScalarValueSizeInBits();
2756   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2757   if (!BV)
2758     return nullptr;
2759   const APInt *MinShAmt = nullptr;
2760   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2761     if (!DemandedElts[i])
2762       continue;
2763     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2764     if (!SA)
2765       return nullptr;
2766     // Shifting more than the bitwidth is not valid.
2767     const APInt &ShAmt = SA->getAPIntValue();
2768     if (ShAmt.uge(BitWidth))
2769       return nullptr;
2770     if (MinShAmt && MinShAmt->ule(ShAmt))
2771       continue;
2772     MinShAmt = &ShAmt;
2773   }
2774   return MinShAmt;
2775 }
2776 
2777 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2778     SDValue V, const APInt &DemandedElts) const {
2779   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2780           V.getOpcode() == ISD::SRA) &&
2781          "Unknown shift node");
2782   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2783     return ValidAmt;
2784   unsigned BitWidth = V.getScalarValueSizeInBits();
2785   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2786   if (!BV)
2787     return nullptr;
2788   const APInt *MaxShAmt = nullptr;
2789   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2790     if (!DemandedElts[i])
2791       continue;
2792     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2793     if (!SA)
2794       return nullptr;
2795     // Shifting more than the bitwidth is not valid.
2796     const APInt &ShAmt = SA->getAPIntValue();
2797     if (ShAmt.uge(BitWidth))
2798       return nullptr;
2799     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2800       continue;
2801     MaxShAmt = &ShAmt;
2802   }
2803   return MaxShAmt;
2804 }
2805 
2806 /// Determine which bits of Op are known to be either zero or one and return
2807 /// them in Known. For vectors, the known bits are those that are shared by
2808 /// every vector element.
2809 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2810   EVT VT = Op.getValueType();
2811 
2812   // TOOD: Until we have a plan for how to represent demanded elements for
2813   // scalable vectors, we can just bail out for now.
2814   if (Op.getValueType().isScalableVector()) {
2815     unsigned BitWidth = Op.getScalarValueSizeInBits();
2816     return KnownBits(BitWidth);
2817   }
2818 
2819   APInt DemandedElts = VT.isVector()
2820                            ? APInt::getAllOnes(VT.getVectorNumElements())
2821                            : APInt(1, 1);
2822   return computeKnownBits(Op, DemandedElts, Depth);
2823 }
2824 
2825 /// Determine which bits of Op are known to be either zero or one and return
2826 /// them in Known. The DemandedElts argument allows us to only collect the known
2827 /// bits that are shared by the requested vector elements.
2828 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2829                                          unsigned Depth) const {
2830   unsigned BitWidth = Op.getScalarValueSizeInBits();
2831 
2832   KnownBits Known(BitWidth);   // Don't know anything.
2833 
2834   // TOOD: Until we have a plan for how to represent demanded elements for
2835   // scalable vectors, we can just bail out for now.
2836   if (Op.getValueType().isScalableVector())
2837     return Known;
2838 
2839   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2840     // We know all of the bits for a constant!
2841     return KnownBits::makeConstant(C->getAPIntValue());
2842   }
2843   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2844     // We know all of the bits for a constant fp!
2845     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2846   }
2847 
2848   if (Depth >= MaxRecursionDepth)
2849     return Known;  // Limit search depth.
2850 
2851   KnownBits Known2;
2852   unsigned NumElts = DemandedElts.getBitWidth();
2853   assert((!Op.getValueType().isVector() ||
2854           NumElts == Op.getValueType().getVectorNumElements()) &&
2855          "Unexpected vector size");
2856 
2857   if (!DemandedElts)
2858     return Known;  // No demanded elts, better to assume we don't know anything.
2859 
2860   unsigned Opcode = Op.getOpcode();
2861   switch (Opcode) {
2862   case ISD::BUILD_VECTOR:
2863     // Collect the known bits that are shared by every demanded vector element.
2864     Known.Zero.setAllBits(); Known.One.setAllBits();
2865     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2866       if (!DemandedElts[i])
2867         continue;
2868 
2869       SDValue SrcOp = Op.getOperand(i);
2870       Known2 = computeKnownBits(SrcOp, Depth + 1);
2871 
2872       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2873       if (SrcOp.getValueSizeInBits() != BitWidth) {
2874         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2875                "Expected BUILD_VECTOR implicit truncation");
2876         Known2 = Known2.trunc(BitWidth);
2877       }
2878 
2879       // Known bits are the values that are shared by every demanded element.
2880       Known = KnownBits::commonBits(Known, Known2);
2881 
2882       // If we don't know any bits, early out.
2883       if (Known.isUnknown())
2884         break;
2885     }
2886     break;
2887   case ISD::VECTOR_SHUFFLE: {
2888     // Collect the known bits that are shared by every vector element referenced
2889     // by the shuffle.
2890     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2891     Known.Zero.setAllBits(); Known.One.setAllBits();
2892     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2893     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2894     for (unsigned i = 0; i != NumElts; ++i) {
2895       if (!DemandedElts[i])
2896         continue;
2897 
2898       int M = SVN->getMaskElt(i);
2899       if (M < 0) {
2900         // For UNDEF elements, we don't know anything about the common state of
2901         // the shuffle result.
2902         Known.resetAll();
2903         DemandedLHS.clearAllBits();
2904         DemandedRHS.clearAllBits();
2905         break;
2906       }
2907 
2908       if ((unsigned)M < NumElts)
2909         DemandedLHS.setBit((unsigned)M % NumElts);
2910       else
2911         DemandedRHS.setBit((unsigned)M % NumElts);
2912     }
2913     // Known bits are the values that are shared by every demanded element.
2914     if (!!DemandedLHS) {
2915       SDValue LHS = Op.getOperand(0);
2916       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2917       Known = KnownBits::commonBits(Known, Known2);
2918     }
2919     // If we don't know any bits, early out.
2920     if (Known.isUnknown())
2921       break;
2922     if (!!DemandedRHS) {
2923       SDValue RHS = Op.getOperand(1);
2924       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2925       Known = KnownBits::commonBits(Known, Known2);
2926     }
2927     break;
2928   }
2929   case ISD::CONCAT_VECTORS: {
2930     // Split DemandedElts and test each of the demanded subvectors.
2931     Known.Zero.setAllBits(); Known.One.setAllBits();
2932     EVT SubVectorVT = Op.getOperand(0).getValueType();
2933     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2934     unsigned NumSubVectors = Op.getNumOperands();
2935     for (unsigned i = 0; i != NumSubVectors; ++i) {
2936       APInt DemandedSub =
2937           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2938       if (!!DemandedSub) {
2939         SDValue Sub = Op.getOperand(i);
2940         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2941         Known = KnownBits::commonBits(Known, Known2);
2942       }
2943       // If we don't know any bits, early out.
2944       if (Known.isUnknown())
2945         break;
2946     }
2947     break;
2948   }
2949   case ISD::INSERT_SUBVECTOR: {
2950     // Demand any elements from the subvector and the remainder from the src its
2951     // inserted into.
2952     SDValue Src = Op.getOperand(0);
2953     SDValue Sub = Op.getOperand(1);
2954     uint64_t Idx = Op.getConstantOperandVal(2);
2955     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2956     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2957     APInt DemandedSrcElts = DemandedElts;
2958     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2959 
2960     Known.One.setAllBits();
2961     Known.Zero.setAllBits();
2962     if (!!DemandedSubElts) {
2963       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2964       if (Known.isUnknown())
2965         break; // early-out.
2966     }
2967     if (!!DemandedSrcElts) {
2968       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2969       Known = KnownBits::commonBits(Known, Known2);
2970     }
2971     break;
2972   }
2973   case ISD::EXTRACT_SUBVECTOR: {
2974     // Offset the demanded elts by the subvector index.
2975     SDValue Src = Op.getOperand(0);
2976     // Bail until we can represent demanded elements for scalable vectors.
2977     if (Src.getValueType().isScalableVector())
2978       break;
2979     uint64_t Idx = Op.getConstantOperandVal(1);
2980     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2981     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2982     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2983     break;
2984   }
2985   case ISD::SCALAR_TO_VECTOR: {
2986     // We know about scalar_to_vector as much as we know about it source,
2987     // which becomes the first element of otherwise unknown vector.
2988     if (DemandedElts != 1)
2989       break;
2990 
2991     SDValue N0 = Op.getOperand(0);
2992     Known = computeKnownBits(N0, Depth + 1);
2993     if (N0.getValueSizeInBits() != BitWidth)
2994       Known = Known.trunc(BitWidth);
2995 
2996     break;
2997   }
2998   case ISD::BITCAST: {
2999     SDValue N0 = Op.getOperand(0);
3000     EVT SubVT = N0.getValueType();
3001     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3002 
3003     // Ignore bitcasts from unsupported types.
3004     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3005       break;
3006 
3007     // Fast handling of 'identity' bitcasts.
3008     if (BitWidth == SubBitWidth) {
3009       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3010       break;
3011     }
3012 
3013     bool IsLE = getDataLayout().isLittleEndian();
3014 
3015     // Bitcast 'small element' vector to 'large element' scalar/vector.
3016     if ((BitWidth % SubBitWidth) == 0) {
3017       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3018 
3019       // Collect known bits for the (larger) output by collecting the known
3020       // bits from each set of sub elements and shift these into place.
3021       // We need to separately call computeKnownBits for each set of
3022       // sub elements as the knownbits for each is likely to be different.
3023       unsigned SubScale = BitWidth / SubBitWidth;
3024       APInt SubDemandedElts(NumElts * SubScale, 0);
3025       for (unsigned i = 0; i != NumElts; ++i)
3026         if (DemandedElts[i])
3027           SubDemandedElts.setBit(i * SubScale);
3028 
3029       for (unsigned i = 0; i != SubScale; ++i) {
3030         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3031                          Depth + 1);
3032         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3033         Known.insertBits(Known2, SubBitWidth * Shifts);
3034       }
3035     }
3036 
3037     // Bitcast 'large element' scalar/vector to 'small element' vector.
3038     if ((SubBitWidth % BitWidth) == 0) {
3039       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3040 
3041       // Collect known bits for the (smaller) output by collecting the known
3042       // bits from the overlapping larger input elements and extracting the
3043       // sub sections we actually care about.
3044       unsigned SubScale = SubBitWidth / BitWidth;
3045       APInt SubDemandedElts =
3046           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3047       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3048 
3049       Known.Zero.setAllBits(); Known.One.setAllBits();
3050       for (unsigned i = 0; i != NumElts; ++i)
3051         if (DemandedElts[i]) {
3052           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3053           unsigned Offset = (Shifts % SubScale) * BitWidth;
3054           Known = KnownBits::commonBits(Known,
3055                                         Known2.extractBits(BitWidth, Offset));
3056           // If we don't know any bits, early out.
3057           if (Known.isUnknown())
3058             break;
3059         }
3060     }
3061     break;
3062   }
3063   case ISD::AND:
3064     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3065     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3066 
3067     Known &= Known2;
3068     break;
3069   case ISD::OR:
3070     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3071     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3072 
3073     Known |= Known2;
3074     break;
3075   case ISD::XOR:
3076     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3077     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3078 
3079     Known ^= Known2;
3080     break;
3081   case ISD::MUL: {
3082     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3083     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3084     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3085     // TODO: SelfMultiply can be poison, but not undef.
3086     SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3087         Op.getOperand(0), DemandedElts, false, Depth + 1);
3088     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3089     break;
3090   }
3091   case ISD::MULHU: {
3092     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3093     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3094     Known = KnownBits::mulhu(Known, Known2);
3095     break;
3096   }
3097   case ISD::MULHS: {
3098     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3099     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3100     Known = KnownBits::mulhs(Known, Known2);
3101     break;
3102   }
3103   case ISD::UMUL_LOHI: {
3104     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3105     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3106     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3107     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3108     if (Op.getResNo() == 0)
3109       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3110     else
3111       Known = KnownBits::mulhu(Known, Known2);
3112     break;
3113   }
3114   case ISD::SMUL_LOHI: {
3115     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3116     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3117     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3118     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3119     if (Op.getResNo() == 0)
3120       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3121     else
3122       Known = KnownBits::mulhs(Known, Known2);
3123     break;
3124   }
3125   case ISD::UDIV: {
3126     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3127     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3128     Known = KnownBits::udiv(Known, Known2);
3129     break;
3130   }
3131   case ISD::SELECT:
3132   case ISD::VSELECT:
3133     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3134     // If we don't know any bits, early out.
3135     if (Known.isUnknown())
3136       break;
3137     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3138 
3139     // Only known if known in both the LHS and RHS.
3140     Known = KnownBits::commonBits(Known, Known2);
3141     break;
3142   case ISD::SELECT_CC:
3143     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3144     // If we don't know any bits, early out.
3145     if (Known.isUnknown())
3146       break;
3147     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3148 
3149     // Only known if known in both the LHS and RHS.
3150     Known = KnownBits::commonBits(Known, Known2);
3151     break;
3152   case ISD::SMULO:
3153   case ISD::UMULO:
3154     if (Op.getResNo() != 1)
3155       break;
3156     // The boolean result conforms to getBooleanContents.
3157     // If we know the result of a setcc has the top bits zero, use this info.
3158     // We know that we have an integer-based boolean since these operations
3159     // are only available for integer.
3160     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3161             TargetLowering::ZeroOrOneBooleanContent &&
3162         BitWidth > 1)
3163       Known.Zero.setBitsFrom(1);
3164     break;
3165   case ISD::SETCC:
3166   case ISD::STRICT_FSETCC:
3167   case ISD::STRICT_FSETCCS: {
3168     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3169     // If we know the result of a setcc has the top bits zero, use this info.
3170     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3171             TargetLowering::ZeroOrOneBooleanContent &&
3172         BitWidth > 1)
3173       Known.Zero.setBitsFrom(1);
3174     break;
3175   }
3176   case ISD::SHL:
3177     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3178     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3179     Known = KnownBits::shl(Known, Known2);
3180 
3181     // Minimum shift low bits are known zero.
3182     if (const APInt *ShMinAmt =
3183             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3184       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3185     break;
3186   case ISD::SRL:
3187     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3188     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3189     Known = KnownBits::lshr(Known, Known2);
3190 
3191     // Minimum shift high bits are known zero.
3192     if (const APInt *ShMinAmt =
3193             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3194       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3195     break;
3196   case ISD::SRA:
3197     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3198     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3199     Known = KnownBits::ashr(Known, Known2);
3200     // TODO: Add minimum shift high known sign bits.
3201     break;
3202   case ISD::FSHL:
3203   case ISD::FSHR:
3204     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3205       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3206 
3207       // For fshl, 0-shift returns the 1st arg.
3208       // For fshr, 0-shift returns the 2nd arg.
3209       if (Amt == 0) {
3210         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3211                                  DemandedElts, Depth + 1);
3212         break;
3213       }
3214 
3215       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3216       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3217       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3218       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3219       if (Opcode == ISD::FSHL) {
3220         Known.One <<= Amt;
3221         Known.Zero <<= Amt;
3222         Known2.One.lshrInPlace(BitWidth - Amt);
3223         Known2.Zero.lshrInPlace(BitWidth - Amt);
3224       } else {
3225         Known.One <<= BitWidth - Amt;
3226         Known.Zero <<= BitWidth - Amt;
3227         Known2.One.lshrInPlace(Amt);
3228         Known2.Zero.lshrInPlace(Amt);
3229       }
3230       Known.One |= Known2.One;
3231       Known.Zero |= Known2.Zero;
3232     }
3233     break;
3234   case ISD::SIGN_EXTEND_INREG: {
3235     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3236     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3237     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3238     break;
3239   }
3240   case ISD::CTTZ:
3241   case ISD::CTTZ_ZERO_UNDEF: {
3242     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3243     // If we have a known 1, its position is our upper bound.
3244     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3245     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3246     Known.Zero.setBitsFrom(LowBits);
3247     break;
3248   }
3249   case ISD::CTLZ:
3250   case ISD::CTLZ_ZERO_UNDEF: {
3251     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3252     // If we have a known 1, its position is our upper bound.
3253     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3254     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3255     Known.Zero.setBitsFrom(LowBits);
3256     break;
3257   }
3258   case ISD::CTPOP: {
3259     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3260     // If we know some of the bits are zero, they can't be one.
3261     unsigned PossibleOnes = Known2.countMaxPopulation();
3262     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3263     break;
3264   }
3265   case ISD::PARITY: {
3266     // Parity returns 0 everywhere but the LSB.
3267     Known.Zero.setBitsFrom(1);
3268     break;
3269   }
3270   case ISD::LOAD: {
3271     LoadSDNode *LD = cast<LoadSDNode>(Op);
3272     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3273     if (ISD::isNON_EXTLoad(LD) && Cst) {
3274       // Determine any common known bits from the loaded constant pool value.
3275       Type *CstTy = Cst->getType();
3276       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3277         // If its a vector splat, then we can (quickly) reuse the scalar path.
3278         // NOTE: We assume all elements match and none are UNDEF.
3279         if (CstTy->isVectorTy()) {
3280           if (const Constant *Splat = Cst->getSplatValue()) {
3281             Cst = Splat;
3282             CstTy = Cst->getType();
3283           }
3284         }
3285         // TODO - do we need to handle different bitwidths?
3286         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3287           // Iterate across all vector elements finding common known bits.
3288           Known.One.setAllBits();
3289           Known.Zero.setAllBits();
3290           for (unsigned i = 0; i != NumElts; ++i) {
3291             if (!DemandedElts[i])
3292               continue;
3293             if (Constant *Elt = Cst->getAggregateElement(i)) {
3294               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3295                 const APInt &Value = CInt->getValue();
3296                 Known.One &= Value;
3297                 Known.Zero &= ~Value;
3298                 continue;
3299               }
3300               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3301                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3302                 Known.One &= Value;
3303                 Known.Zero &= ~Value;
3304                 continue;
3305               }
3306             }
3307             Known.One.clearAllBits();
3308             Known.Zero.clearAllBits();
3309             break;
3310           }
3311         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3312           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3313             Known = KnownBits::makeConstant(CInt->getValue());
3314           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3315             Known =
3316                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3317           }
3318         }
3319       }
3320     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3321       // If this is a ZEXTLoad and we are looking at the loaded value.
3322       EVT VT = LD->getMemoryVT();
3323       unsigned MemBits = VT.getScalarSizeInBits();
3324       Known.Zero.setBitsFrom(MemBits);
3325     } else if (const MDNode *Ranges = LD->getRanges()) {
3326       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3327         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3328     }
3329     break;
3330   }
3331   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3332     EVT InVT = Op.getOperand(0).getValueType();
3333     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3334     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3335     Known = Known.zext(BitWidth);
3336     break;
3337   }
3338   case ISD::ZERO_EXTEND: {
3339     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3340     Known = Known.zext(BitWidth);
3341     break;
3342   }
3343   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3344     EVT InVT = Op.getOperand(0).getValueType();
3345     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3346     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3347     // If the sign bit is known to be zero or one, then sext will extend
3348     // it to the top bits, else it will just zext.
3349     Known = Known.sext(BitWidth);
3350     break;
3351   }
3352   case ISD::SIGN_EXTEND: {
3353     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3354     // If the sign bit is known to be zero or one, then sext will extend
3355     // it to the top bits, else it will just zext.
3356     Known = Known.sext(BitWidth);
3357     break;
3358   }
3359   case ISD::ANY_EXTEND_VECTOR_INREG: {
3360     EVT InVT = Op.getOperand(0).getValueType();
3361     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3362     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3363     Known = Known.anyext(BitWidth);
3364     break;
3365   }
3366   case ISD::ANY_EXTEND: {
3367     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3368     Known = Known.anyext(BitWidth);
3369     break;
3370   }
3371   case ISD::TRUNCATE: {
3372     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3373     Known = Known.trunc(BitWidth);
3374     break;
3375   }
3376   case ISD::AssertZext: {
3377     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3378     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3379     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3380     Known.Zero |= (~InMask);
3381     Known.One  &= (~Known.Zero);
3382     break;
3383   }
3384   case ISD::AssertAlign: {
3385     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3386     assert(LogOfAlign != 0);
3387 
3388     // TODO: Should use maximum with source
3389     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3390     // well as clearing one bits.
3391     Known.Zero.setLowBits(LogOfAlign);
3392     Known.One.clearLowBits(LogOfAlign);
3393     break;
3394   }
3395   case ISD::FGETSIGN:
3396     // All bits are zero except the low bit.
3397     Known.Zero.setBitsFrom(1);
3398     break;
3399   case ISD::USUBO:
3400   case ISD::SSUBO:
3401     if (Op.getResNo() == 1) {
3402       // If we know the result of a setcc has the top bits zero, use this info.
3403       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3404               TargetLowering::ZeroOrOneBooleanContent &&
3405           BitWidth > 1)
3406         Known.Zero.setBitsFrom(1);
3407       break;
3408     }
3409     LLVM_FALLTHROUGH;
3410   case ISD::SUB:
3411   case ISD::SUBC: {
3412     assert(Op.getResNo() == 0 &&
3413            "We only compute knownbits for the difference here.");
3414 
3415     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3416     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3417     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3418                                         Known, Known2);
3419     break;
3420   }
3421   case ISD::UADDO:
3422   case ISD::SADDO:
3423   case ISD::ADDCARRY:
3424     if (Op.getResNo() == 1) {
3425       // If we know the result of a setcc has the top bits zero, use this info.
3426       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3427               TargetLowering::ZeroOrOneBooleanContent &&
3428           BitWidth > 1)
3429         Known.Zero.setBitsFrom(1);
3430       break;
3431     }
3432     LLVM_FALLTHROUGH;
3433   case ISD::ADD:
3434   case ISD::ADDC:
3435   case ISD::ADDE: {
3436     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3437 
3438     // With ADDE and ADDCARRY, a carry bit may be added in.
3439     KnownBits Carry(1);
3440     if (Opcode == ISD::ADDE)
3441       // Can't track carry from glue, set carry to unknown.
3442       Carry.resetAll();
3443     else if (Opcode == ISD::ADDCARRY)
3444       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3445       // the trouble (how often will we find a known carry bit). And I haven't
3446       // tested this very much yet, but something like this might work:
3447       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3448       //   Carry = Carry.zextOrTrunc(1, false);
3449       Carry.resetAll();
3450     else
3451       Carry.setAllZero();
3452 
3453     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3454     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3455     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3456     break;
3457   }
3458   case ISD::SREM: {
3459     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3460     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3461     Known = KnownBits::srem(Known, Known2);
3462     break;
3463   }
3464   case ISD::UREM: {
3465     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3466     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3467     Known = KnownBits::urem(Known, Known2);
3468     break;
3469   }
3470   case ISD::EXTRACT_ELEMENT: {
3471     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3472     const unsigned Index = Op.getConstantOperandVal(1);
3473     const unsigned EltBitWidth = Op.getValueSizeInBits();
3474 
3475     // Remove low part of known bits mask
3476     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3477     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3478 
3479     // Remove high part of known bit mask
3480     Known = Known.trunc(EltBitWidth);
3481     break;
3482   }
3483   case ISD::EXTRACT_VECTOR_ELT: {
3484     SDValue InVec = Op.getOperand(0);
3485     SDValue EltNo = Op.getOperand(1);
3486     EVT VecVT = InVec.getValueType();
3487     // computeKnownBits not yet implemented for scalable vectors.
3488     if (VecVT.isScalableVector())
3489       break;
3490     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3491     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3492 
3493     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3494     // anything about the extended bits.
3495     if (BitWidth > EltBitWidth)
3496       Known = Known.trunc(EltBitWidth);
3497 
3498     // If we know the element index, just demand that vector element, else for
3499     // an unknown element index, ignore DemandedElts and demand them all.
3500     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3501     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3502     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3503       DemandedSrcElts =
3504           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3505 
3506     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3507     if (BitWidth > EltBitWidth)
3508       Known = Known.anyext(BitWidth);
3509     break;
3510   }
3511   case ISD::INSERT_VECTOR_ELT: {
3512     // If we know the element index, split the demand between the
3513     // source vector and the inserted element, otherwise assume we need
3514     // the original demanded vector elements and the value.
3515     SDValue InVec = Op.getOperand(0);
3516     SDValue InVal = Op.getOperand(1);
3517     SDValue EltNo = Op.getOperand(2);
3518     bool DemandedVal = true;
3519     APInt DemandedVecElts = DemandedElts;
3520     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3521     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3522       unsigned EltIdx = CEltNo->getZExtValue();
3523       DemandedVal = !!DemandedElts[EltIdx];
3524       DemandedVecElts.clearBit(EltIdx);
3525     }
3526     Known.One.setAllBits();
3527     Known.Zero.setAllBits();
3528     if (DemandedVal) {
3529       Known2 = computeKnownBits(InVal, Depth + 1);
3530       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3531     }
3532     if (!!DemandedVecElts) {
3533       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3534       Known = KnownBits::commonBits(Known, Known2);
3535     }
3536     break;
3537   }
3538   case ISD::BITREVERSE: {
3539     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3540     Known = Known2.reverseBits();
3541     break;
3542   }
3543   case ISD::BSWAP: {
3544     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3545     Known = Known2.byteSwap();
3546     break;
3547   }
3548   case ISD::ABS: {
3549     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3550     Known = Known2.abs();
3551     break;
3552   }
3553   case ISD::USUBSAT: {
3554     // The result of usubsat will never be larger than the LHS.
3555     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3556     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3557     break;
3558   }
3559   case ISD::UMIN: {
3560     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3561     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3562     Known = KnownBits::umin(Known, Known2);
3563     break;
3564   }
3565   case ISD::UMAX: {
3566     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3567     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3568     Known = KnownBits::umax(Known, Known2);
3569     break;
3570   }
3571   case ISD::SMIN:
3572   case ISD::SMAX: {
3573     // If we have a clamp pattern, we know that the number of sign bits will be
3574     // the minimum of the clamp min/max range.
3575     bool IsMax = (Opcode == ISD::SMAX);
3576     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3577     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3578       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3579         CstHigh =
3580             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3581     if (CstLow && CstHigh) {
3582       if (!IsMax)
3583         std::swap(CstLow, CstHigh);
3584 
3585       const APInt &ValueLow = CstLow->getAPIntValue();
3586       const APInt &ValueHigh = CstHigh->getAPIntValue();
3587       if (ValueLow.sle(ValueHigh)) {
3588         unsigned LowSignBits = ValueLow.getNumSignBits();
3589         unsigned HighSignBits = ValueHigh.getNumSignBits();
3590         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3591         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3592           Known.One.setHighBits(MinSignBits);
3593           break;
3594         }
3595         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3596           Known.Zero.setHighBits(MinSignBits);
3597           break;
3598         }
3599       }
3600     }
3601 
3602     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3603     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3604     if (IsMax)
3605       Known = KnownBits::smax(Known, Known2);
3606     else
3607       Known = KnownBits::smin(Known, Known2);
3608     break;
3609   }
3610   case ISD::FP_TO_UINT_SAT: {
3611     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3612     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3613     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3614     break;
3615   }
3616   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3617     if (Op.getResNo() == 1) {
3618       // The boolean result conforms to getBooleanContents.
3619       // If we know the result of a setcc has the top bits zero, use this info.
3620       // We know that we have an integer-based boolean since these operations
3621       // are only available for integer.
3622       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3623               TargetLowering::ZeroOrOneBooleanContent &&
3624           BitWidth > 1)
3625         Known.Zero.setBitsFrom(1);
3626       break;
3627     }
3628     LLVM_FALLTHROUGH;
3629   case ISD::ATOMIC_CMP_SWAP:
3630   case ISD::ATOMIC_SWAP:
3631   case ISD::ATOMIC_LOAD_ADD:
3632   case ISD::ATOMIC_LOAD_SUB:
3633   case ISD::ATOMIC_LOAD_AND:
3634   case ISD::ATOMIC_LOAD_CLR:
3635   case ISD::ATOMIC_LOAD_OR:
3636   case ISD::ATOMIC_LOAD_XOR:
3637   case ISD::ATOMIC_LOAD_NAND:
3638   case ISD::ATOMIC_LOAD_MIN:
3639   case ISD::ATOMIC_LOAD_MAX:
3640   case ISD::ATOMIC_LOAD_UMIN:
3641   case ISD::ATOMIC_LOAD_UMAX:
3642   case ISD::ATOMIC_LOAD: {
3643     unsigned MemBits =
3644         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3645     // If we are looking at the loaded value.
3646     if (Op.getResNo() == 0) {
3647       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3648         Known.Zero.setBitsFrom(MemBits);
3649     }
3650     break;
3651   }
3652   case ISD::FrameIndex:
3653   case ISD::TargetFrameIndex:
3654     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3655                                        Known, getMachineFunction());
3656     break;
3657 
3658   default:
3659     if (Opcode < ISD::BUILTIN_OP_END)
3660       break;
3661     LLVM_FALLTHROUGH;
3662   case ISD::INTRINSIC_WO_CHAIN:
3663   case ISD::INTRINSIC_W_CHAIN:
3664   case ISD::INTRINSIC_VOID:
3665     // Allow the target to implement this method for its nodes.
3666     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3667     break;
3668   }
3669 
3670   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3671   return Known;
3672 }
3673 
3674 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3675                                                              SDValue N1) const {
3676   // X + 0 never overflow
3677   if (isNullConstant(N1))
3678     return OFK_Never;
3679 
3680   KnownBits N1Known = computeKnownBits(N1);
3681   if (N1Known.Zero.getBoolValue()) {
3682     KnownBits N0Known = computeKnownBits(N0);
3683 
3684     bool overflow;
3685     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3686     if (!overflow)
3687       return OFK_Never;
3688   }
3689 
3690   // mulhi + 1 never overflow
3691   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3692       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3693     return OFK_Never;
3694 
3695   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3696     KnownBits N0Known = computeKnownBits(N0);
3697 
3698     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3699       return OFK_Never;
3700   }
3701 
3702   return OFK_Sometime;
3703 }
3704 
3705 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3706   EVT OpVT = Val.getValueType();
3707   unsigned BitWidth = OpVT.getScalarSizeInBits();
3708 
3709   // Is the constant a known power of 2?
3710   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3711     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3712 
3713   // A left-shift of a constant one will have exactly one bit set because
3714   // shifting the bit off the end is undefined.
3715   if (Val.getOpcode() == ISD::SHL) {
3716     auto *C = isConstOrConstSplat(Val.getOperand(0));
3717     if (C && C->getAPIntValue() == 1)
3718       return true;
3719   }
3720 
3721   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3722   // one bit set.
3723   if (Val.getOpcode() == ISD::SRL) {
3724     auto *C = isConstOrConstSplat(Val.getOperand(0));
3725     if (C && C->getAPIntValue().isSignMask())
3726       return true;
3727   }
3728 
3729   // Are all operands of a build vector constant powers of two?
3730   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3731     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3732           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3733             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3734           return false;
3735         }))
3736       return true;
3737 
3738   // Is the operand of a splat vector a constant power of two?
3739   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3740     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3741       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3742         return true;
3743 
3744   // More could be done here, though the above checks are enough
3745   // to handle some common cases.
3746 
3747   // Fall back to computeKnownBits to catch other known cases.
3748   KnownBits Known = computeKnownBits(Val);
3749   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3750 }
3751 
3752 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3753   EVT VT = Op.getValueType();
3754 
3755   // TODO: Assume we don't know anything for now.
3756   if (VT.isScalableVector())
3757     return 1;
3758 
3759   APInt DemandedElts = VT.isVector()
3760                            ? APInt::getAllOnes(VT.getVectorNumElements())
3761                            : APInt(1, 1);
3762   return ComputeNumSignBits(Op, DemandedElts, Depth);
3763 }
3764 
3765 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3766                                           unsigned Depth) const {
3767   EVT VT = Op.getValueType();
3768   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3769   unsigned VTBits = VT.getScalarSizeInBits();
3770   unsigned NumElts = DemandedElts.getBitWidth();
3771   unsigned Tmp, Tmp2;
3772   unsigned FirstAnswer = 1;
3773 
3774   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3775     const APInt &Val = C->getAPIntValue();
3776     return Val.getNumSignBits();
3777   }
3778 
3779   if (Depth >= MaxRecursionDepth)
3780     return 1;  // Limit search depth.
3781 
3782   if (!DemandedElts || VT.isScalableVector())
3783     return 1;  // No demanded elts, better to assume we don't know anything.
3784 
3785   unsigned Opcode = Op.getOpcode();
3786   switch (Opcode) {
3787   default: break;
3788   case ISD::AssertSext:
3789     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3790     return VTBits-Tmp+1;
3791   case ISD::AssertZext:
3792     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3793     return VTBits-Tmp;
3794 
3795   case ISD::BUILD_VECTOR:
3796     Tmp = VTBits;
3797     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3798       if (!DemandedElts[i])
3799         continue;
3800 
3801       SDValue SrcOp = Op.getOperand(i);
3802       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3803 
3804       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3805       if (SrcOp.getValueSizeInBits() != VTBits) {
3806         assert(SrcOp.getValueSizeInBits() > VTBits &&
3807                "Expected BUILD_VECTOR implicit truncation");
3808         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3809         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3810       }
3811       Tmp = std::min(Tmp, Tmp2);
3812     }
3813     return Tmp;
3814 
3815   case ISD::VECTOR_SHUFFLE: {
3816     // Collect the minimum number of sign bits that are shared by every vector
3817     // element referenced by the shuffle.
3818     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3819     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3820     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3821     for (unsigned i = 0; i != NumElts; ++i) {
3822       int M = SVN->getMaskElt(i);
3823       if (!DemandedElts[i])
3824         continue;
3825       // For UNDEF elements, we don't know anything about the common state of
3826       // the shuffle result.
3827       if (M < 0)
3828         return 1;
3829       if ((unsigned)M < NumElts)
3830         DemandedLHS.setBit((unsigned)M % NumElts);
3831       else
3832         DemandedRHS.setBit((unsigned)M % NumElts);
3833     }
3834     Tmp = std::numeric_limits<unsigned>::max();
3835     if (!!DemandedLHS)
3836       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3837     if (!!DemandedRHS) {
3838       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3839       Tmp = std::min(Tmp, Tmp2);
3840     }
3841     // If we don't know anything, early out and try computeKnownBits fall-back.
3842     if (Tmp == 1)
3843       break;
3844     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3845     return Tmp;
3846   }
3847 
3848   case ISD::BITCAST: {
3849     SDValue N0 = Op.getOperand(0);
3850     EVT SrcVT = N0.getValueType();
3851     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3852 
3853     // Ignore bitcasts from unsupported types..
3854     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3855       break;
3856 
3857     // Fast handling of 'identity' bitcasts.
3858     if (VTBits == SrcBits)
3859       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3860 
3861     bool IsLE = getDataLayout().isLittleEndian();
3862 
3863     // Bitcast 'large element' scalar/vector to 'small element' vector.
3864     if ((SrcBits % VTBits) == 0) {
3865       assert(VT.isVector() && "Expected bitcast to vector");
3866 
3867       unsigned Scale = SrcBits / VTBits;
3868       APInt SrcDemandedElts =
3869           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3870 
3871       // Fast case - sign splat can be simply split across the small elements.
3872       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3873       if (Tmp == SrcBits)
3874         return VTBits;
3875 
3876       // Slow case - determine how far the sign extends into each sub-element.
3877       Tmp2 = VTBits;
3878       for (unsigned i = 0; i != NumElts; ++i)
3879         if (DemandedElts[i]) {
3880           unsigned SubOffset = i % Scale;
3881           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3882           SubOffset = SubOffset * VTBits;
3883           if (Tmp <= SubOffset)
3884             return 1;
3885           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3886         }
3887       return Tmp2;
3888     }
3889     break;
3890   }
3891 
3892   case ISD::FP_TO_SINT_SAT:
3893     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
3894     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3895     return VTBits - Tmp + 1;
3896   case ISD::SIGN_EXTEND:
3897     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3898     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3899   case ISD::SIGN_EXTEND_INREG:
3900     // Max of the input and what this extends.
3901     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3902     Tmp = VTBits-Tmp+1;
3903     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3904     return std::max(Tmp, Tmp2);
3905   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3906     SDValue Src = Op.getOperand(0);
3907     EVT SrcVT = Src.getValueType();
3908     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3909     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3910     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3911   }
3912   case ISD::SRA:
3913     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3914     // SRA X, C -> adds C sign bits.
3915     if (const APInt *ShAmt =
3916             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3917       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3918     return Tmp;
3919   case ISD::SHL:
3920     if (const APInt *ShAmt =
3921             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3922       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3923       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3924       if (ShAmt->ult(Tmp))
3925         return Tmp - ShAmt->getZExtValue();
3926     }
3927     break;
3928   case ISD::AND:
3929   case ISD::OR:
3930   case ISD::XOR:    // NOT is handled here.
3931     // Logical binary ops preserve the number of sign bits at the worst.
3932     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3933     if (Tmp != 1) {
3934       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3935       FirstAnswer = std::min(Tmp, Tmp2);
3936       // We computed what we know about the sign bits as our first
3937       // answer. Now proceed to the generic code that uses
3938       // computeKnownBits, and pick whichever answer is better.
3939     }
3940     break;
3941 
3942   case ISD::SELECT:
3943   case ISD::VSELECT:
3944     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3945     if (Tmp == 1) return 1;  // Early out.
3946     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3947     return std::min(Tmp, Tmp2);
3948   case ISD::SELECT_CC:
3949     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3950     if (Tmp == 1) return 1;  // Early out.
3951     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3952     return std::min(Tmp, Tmp2);
3953 
3954   case ISD::SMIN:
3955   case ISD::SMAX: {
3956     // If we have a clamp pattern, we know that the number of sign bits will be
3957     // the minimum of the clamp min/max range.
3958     bool IsMax = (Opcode == ISD::SMAX);
3959     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3960     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3961       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3962         CstHigh =
3963             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3964     if (CstLow && CstHigh) {
3965       if (!IsMax)
3966         std::swap(CstLow, CstHigh);
3967       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3968         Tmp = CstLow->getAPIntValue().getNumSignBits();
3969         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3970         return std::min(Tmp, Tmp2);
3971       }
3972     }
3973 
3974     // Fallback - just get the minimum number of sign bits of the operands.
3975     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3976     if (Tmp == 1)
3977       return 1;  // Early out.
3978     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3979     return std::min(Tmp, Tmp2);
3980   }
3981   case ISD::UMIN:
3982   case ISD::UMAX:
3983     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3984     if (Tmp == 1)
3985       return 1;  // Early out.
3986     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3987     return std::min(Tmp, Tmp2);
3988   case ISD::SADDO:
3989   case ISD::UADDO:
3990   case ISD::SSUBO:
3991   case ISD::USUBO:
3992   case ISD::SMULO:
3993   case ISD::UMULO:
3994     if (Op.getResNo() != 1)
3995       break;
3996     // The boolean result conforms to getBooleanContents.  Fall through.
3997     // If setcc returns 0/-1, all bits are sign bits.
3998     // We know that we have an integer-based boolean since these operations
3999     // are only available for integer.
4000     if (TLI->getBooleanContents(VT.isVector(), false) ==
4001         TargetLowering::ZeroOrNegativeOneBooleanContent)
4002       return VTBits;
4003     break;
4004   case ISD::SETCC:
4005   case ISD::STRICT_FSETCC:
4006   case ISD::STRICT_FSETCCS: {
4007     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4008     // If setcc returns 0/-1, all bits are sign bits.
4009     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4010         TargetLowering::ZeroOrNegativeOneBooleanContent)
4011       return VTBits;
4012     break;
4013   }
4014   case ISD::ROTL:
4015   case ISD::ROTR:
4016     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4017 
4018     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4019     if (Tmp == VTBits)
4020       return VTBits;
4021 
4022     if (ConstantSDNode *C =
4023             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4024       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4025 
4026       // Handle rotate right by N like a rotate left by 32-N.
4027       if (Opcode == ISD::ROTR)
4028         RotAmt = (VTBits - RotAmt) % VTBits;
4029 
4030       // If we aren't rotating out all of the known-in sign bits, return the
4031       // number that are left.  This handles rotl(sext(x), 1) for example.
4032       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4033     }
4034     break;
4035   case ISD::ADD:
4036   case ISD::ADDC:
4037     // Add can have at most one carry bit.  Thus we know that the output
4038     // is, at worst, one more bit than the inputs.
4039     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4040     if (Tmp == 1) return 1; // Early out.
4041 
4042     // Special case decrementing a value (ADD X, -1):
4043     if (ConstantSDNode *CRHS =
4044             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4045       if (CRHS->isAllOnes()) {
4046         KnownBits Known =
4047             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4048 
4049         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4050         // sign bits set.
4051         if ((Known.Zero | 1).isAllOnes())
4052           return VTBits;
4053 
4054         // If we are subtracting one from a positive number, there is no carry
4055         // out of the result.
4056         if (Known.isNonNegative())
4057           return Tmp;
4058       }
4059 
4060     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4061     if (Tmp2 == 1) return 1; // Early out.
4062     return std::min(Tmp, Tmp2) - 1;
4063   case ISD::SUB:
4064     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4065     if (Tmp2 == 1) return 1; // Early out.
4066 
4067     // Handle NEG.
4068     if (ConstantSDNode *CLHS =
4069             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4070       if (CLHS->isZero()) {
4071         KnownBits Known =
4072             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4073         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4074         // sign bits set.
4075         if ((Known.Zero | 1).isAllOnes())
4076           return VTBits;
4077 
4078         // If the input is known to be positive (the sign bit is known clear),
4079         // the output of the NEG has the same number of sign bits as the input.
4080         if (Known.isNonNegative())
4081           return Tmp2;
4082 
4083         // Otherwise, we treat this like a SUB.
4084       }
4085 
4086     // Sub can have at most one carry bit.  Thus we know that the output
4087     // is, at worst, one more bit than the inputs.
4088     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4089     if (Tmp == 1) return 1; // Early out.
4090     return std::min(Tmp, Tmp2) - 1;
4091   case ISD::MUL: {
4092     // The output of the Mul can be at most twice the valid bits in the inputs.
4093     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4094     if (SignBitsOp0 == 1)
4095       break;
4096     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4097     if (SignBitsOp1 == 1)
4098       break;
4099     unsigned OutValidBits =
4100         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4101     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4102   }
4103   case ISD::SREM:
4104     // The sign bit is the LHS's sign bit, except when the result of the
4105     // remainder is zero. The magnitude of the result should be less than or
4106     // equal to the magnitude of the LHS. Therefore, the result should have
4107     // at least as many sign bits as the left hand side.
4108     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4109   case ISD::TRUNCATE: {
4110     // Check if the sign bits of source go down as far as the truncated value.
4111     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4112     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4113     if (NumSrcSignBits > (NumSrcBits - VTBits))
4114       return NumSrcSignBits - (NumSrcBits - VTBits);
4115     break;
4116   }
4117   case ISD::EXTRACT_ELEMENT: {
4118     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4119     const int BitWidth = Op.getValueSizeInBits();
4120     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4121 
4122     // Get reverse index (starting from 1), Op1 value indexes elements from
4123     // little end. Sign starts at big end.
4124     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4125 
4126     // If the sign portion ends in our element the subtraction gives correct
4127     // result. Otherwise it gives either negative or > bitwidth result
4128     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4129   }
4130   case ISD::INSERT_VECTOR_ELT: {
4131     // If we know the element index, split the demand between the
4132     // source vector and the inserted element, otherwise assume we need
4133     // the original demanded vector elements and the value.
4134     SDValue InVec = Op.getOperand(0);
4135     SDValue InVal = Op.getOperand(1);
4136     SDValue EltNo = Op.getOperand(2);
4137     bool DemandedVal = true;
4138     APInt DemandedVecElts = DemandedElts;
4139     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4140     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4141       unsigned EltIdx = CEltNo->getZExtValue();
4142       DemandedVal = !!DemandedElts[EltIdx];
4143       DemandedVecElts.clearBit(EltIdx);
4144     }
4145     Tmp = std::numeric_limits<unsigned>::max();
4146     if (DemandedVal) {
4147       // TODO - handle implicit truncation of inserted elements.
4148       if (InVal.getScalarValueSizeInBits() != VTBits)
4149         break;
4150       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4151       Tmp = std::min(Tmp, Tmp2);
4152     }
4153     if (!!DemandedVecElts) {
4154       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4155       Tmp = std::min(Tmp, Tmp2);
4156     }
4157     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4158     return Tmp;
4159   }
4160   case ISD::EXTRACT_VECTOR_ELT: {
4161     SDValue InVec = Op.getOperand(0);
4162     SDValue EltNo = Op.getOperand(1);
4163     EVT VecVT = InVec.getValueType();
4164     // ComputeNumSignBits not yet implemented for scalable vectors.
4165     if (VecVT.isScalableVector())
4166       break;
4167     const unsigned BitWidth = Op.getValueSizeInBits();
4168     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4169     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4170 
4171     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4172     // anything about sign bits. But if the sizes match we can derive knowledge
4173     // about sign bits from the vector operand.
4174     if (BitWidth != EltBitWidth)
4175       break;
4176 
4177     // If we know the element index, just demand that vector element, else for
4178     // an unknown element index, ignore DemandedElts and demand them all.
4179     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4180     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4181     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4182       DemandedSrcElts =
4183           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4184 
4185     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4186   }
4187   case ISD::EXTRACT_SUBVECTOR: {
4188     // Offset the demanded elts by the subvector index.
4189     SDValue Src = Op.getOperand(0);
4190     // Bail until we can represent demanded elements for scalable vectors.
4191     if (Src.getValueType().isScalableVector())
4192       break;
4193     uint64_t Idx = Op.getConstantOperandVal(1);
4194     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4195     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4196     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4197   }
4198   case ISD::CONCAT_VECTORS: {
4199     // Determine the minimum number of sign bits across all demanded
4200     // elts of the input vectors. Early out if the result is already 1.
4201     Tmp = std::numeric_limits<unsigned>::max();
4202     EVT SubVectorVT = Op.getOperand(0).getValueType();
4203     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4204     unsigned NumSubVectors = Op.getNumOperands();
4205     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4206       APInt DemandedSub =
4207           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4208       if (!DemandedSub)
4209         continue;
4210       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4211       Tmp = std::min(Tmp, Tmp2);
4212     }
4213     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4214     return Tmp;
4215   }
4216   case ISD::INSERT_SUBVECTOR: {
4217     // Demand any elements from the subvector and the remainder from the src its
4218     // inserted into.
4219     SDValue Src = Op.getOperand(0);
4220     SDValue Sub = Op.getOperand(1);
4221     uint64_t Idx = Op.getConstantOperandVal(2);
4222     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4223     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4224     APInt DemandedSrcElts = DemandedElts;
4225     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4226 
4227     Tmp = std::numeric_limits<unsigned>::max();
4228     if (!!DemandedSubElts) {
4229       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4230       if (Tmp == 1)
4231         return 1; // early-out
4232     }
4233     if (!!DemandedSrcElts) {
4234       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4235       Tmp = std::min(Tmp, Tmp2);
4236     }
4237     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4238     return Tmp;
4239   }
4240   case ISD::ATOMIC_CMP_SWAP:
4241   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4242   case ISD::ATOMIC_SWAP:
4243   case ISD::ATOMIC_LOAD_ADD:
4244   case ISD::ATOMIC_LOAD_SUB:
4245   case ISD::ATOMIC_LOAD_AND:
4246   case ISD::ATOMIC_LOAD_CLR:
4247   case ISD::ATOMIC_LOAD_OR:
4248   case ISD::ATOMIC_LOAD_XOR:
4249   case ISD::ATOMIC_LOAD_NAND:
4250   case ISD::ATOMIC_LOAD_MIN:
4251   case ISD::ATOMIC_LOAD_MAX:
4252   case ISD::ATOMIC_LOAD_UMIN:
4253   case ISD::ATOMIC_LOAD_UMAX:
4254   case ISD::ATOMIC_LOAD: {
4255     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4256     // If we are looking at the loaded value.
4257     if (Op.getResNo() == 0) {
4258       if (Tmp == VTBits)
4259         return 1; // early-out
4260       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4261         return VTBits - Tmp + 1;
4262       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4263         return VTBits - Tmp;
4264     }
4265     break;
4266   }
4267   }
4268 
4269   // If we are looking at the loaded value of the SDNode.
4270   if (Op.getResNo() == 0) {
4271     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4272     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4273       unsigned ExtType = LD->getExtensionType();
4274       switch (ExtType) {
4275       default: break;
4276       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4277         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4278         return VTBits - Tmp + 1;
4279       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4280         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4281         return VTBits - Tmp;
4282       case ISD::NON_EXTLOAD:
4283         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4284           // We only need to handle vectors - computeKnownBits should handle
4285           // scalar cases.
4286           Type *CstTy = Cst->getType();
4287           if (CstTy->isVectorTy() &&
4288               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4289               VTBits == CstTy->getScalarSizeInBits()) {
4290             Tmp = VTBits;
4291             for (unsigned i = 0; i != NumElts; ++i) {
4292               if (!DemandedElts[i])
4293                 continue;
4294               if (Constant *Elt = Cst->getAggregateElement(i)) {
4295                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4296                   const APInt &Value = CInt->getValue();
4297                   Tmp = std::min(Tmp, Value.getNumSignBits());
4298                   continue;
4299                 }
4300                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4301                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4302                   Tmp = std::min(Tmp, Value.getNumSignBits());
4303                   continue;
4304                 }
4305               }
4306               // Unknown type. Conservatively assume no bits match sign bit.
4307               return 1;
4308             }
4309             return Tmp;
4310           }
4311         }
4312         break;
4313       }
4314     }
4315   }
4316 
4317   // Allow the target to implement this method for its nodes.
4318   if (Opcode >= ISD::BUILTIN_OP_END ||
4319       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4320       Opcode == ISD::INTRINSIC_W_CHAIN ||
4321       Opcode == ISD::INTRINSIC_VOID) {
4322     unsigned NumBits =
4323         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4324     if (NumBits > 1)
4325       FirstAnswer = std::max(FirstAnswer, NumBits);
4326   }
4327 
4328   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4329   // use this information.
4330   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4331   return std::max(FirstAnswer, Known.countMinSignBits());
4332 }
4333 
4334 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4335                                                  unsigned Depth) const {
4336   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4337   return Op.getScalarValueSizeInBits() - SignBits + 1;
4338 }
4339 
4340 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4341                                                  const APInt &DemandedElts,
4342                                                  unsigned Depth) const {
4343   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4344   return Op.getScalarValueSizeInBits() - SignBits + 1;
4345 }
4346 
4347 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4348                                                     unsigned Depth) const {
4349   // Early out for FREEZE.
4350   if (Op.getOpcode() == ISD::FREEZE)
4351     return true;
4352 
4353   // TODO: Assume we don't know anything for now.
4354   EVT VT = Op.getValueType();
4355   if (VT.isScalableVector())
4356     return false;
4357 
4358   APInt DemandedElts = VT.isVector()
4359                            ? APInt::getAllOnes(VT.getVectorNumElements())
4360                            : APInt(1, 1);
4361   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4362 }
4363 
4364 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4365                                                     const APInt &DemandedElts,
4366                                                     bool PoisonOnly,
4367                                                     unsigned Depth) const {
4368   unsigned Opcode = Op.getOpcode();
4369 
4370   // Early out for FREEZE.
4371   if (Opcode == ISD::FREEZE)
4372     return true;
4373 
4374   if (Depth >= MaxRecursionDepth)
4375     return false; // Limit search depth.
4376 
4377   if (isIntOrFPConstant(Op))
4378     return true;
4379 
4380   switch (Opcode) {
4381   case ISD::UNDEF:
4382     return PoisonOnly;
4383 
4384   case ISD::BUILD_VECTOR:
4385     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4386     // this shouldn't affect the result.
4387     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4388       if (!DemandedElts[i])
4389         continue;
4390       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4391                                             Depth + 1))
4392         return false;
4393     }
4394     return true;
4395 
4396   // TODO: Search for noundef attributes from library functions.
4397 
4398   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4399 
4400   default:
4401     // Allow the target to implement this method for its nodes.
4402     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4403         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4404       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4405           Op, DemandedElts, *this, PoisonOnly, Depth);
4406     break;
4407   }
4408 
4409   return false;
4410 }
4411 
4412 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4413   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4414       !isa<ConstantSDNode>(Op.getOperand(1)))
4415     return false;
4416 
4417   if (Op.getOpcode() == ISD::OR &&
4418       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4419     return false;
4420 
4421   return true;
4422 }
4423 
4424 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4425   // If we're told that NaNs won't happen, assume they won't.
4426   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4427     return true;
4428 
4429   if (Depth >= MaxRecursionDepth)
4430     return false; // Limit search depth.
4431 
4432   // TODO: Handle vectors.
4433   // If the value is a constant, we can obviously see if it is a NaN or not.
4434   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4435     return !C->getValueAPF().isNaN() ||
4436            (SNaN && !C->getValueAPF().isSignaling());
4437   }
4438 
4439   unsigned Opcode = Op.getOpcode();
4440   switch (Opcode) {
4441   case ISD::FADD:
4442   case ISD::FSUB:
4443   case ISD::FMUL:
4444   case ISD::FDIV:
4445   case ISD::FREM:
4446   case ISD::FSIN:
4447   case ISD::FCOS: {
4448     if (SNaN)
4449       return true;
4450     // TODO: Need isKnownNeverInfinity
4451     return false;
4452   }
4453   case ISD::FCANONICALIZE:
4454   case ISD::FEXP:
4455   case ISD::FEXP2:
4456   case ISD::FTRUNC:
4457   case ISD::FFLOOR:
4458   case ISD::FCEIL:
4459   case ISD::FROUND:
4460   case ISD::FROUNDEVEN:
4461   case ISD::FRINT:
4462   case ISD::FNEARBYINT: {
4463     if (SNaN)
4464       return true;
4465     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4466   }
4467   case ISD::FABS:
4468   case ISD::FNEG:
4469   case ISD::FCOPYSIGN: {
4470     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4471   }
4472   case ISD::SELECT:
4473     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4474            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4475   case ISD::FP_EXTEND:
4476   case ISD::FP_ROUND: {
4477     if (SNaN)
4478       return true;
4479     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4480   }
4481   case ISD::SINT_TO_FP:
4482   case ISD::UINT_TO_FP:
4483     return true;
4484   case ISD::FMA:
4485   case ISD::FMAD: {
4486     if (SNaN)
4487       return true;
4488     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4489            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4490            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4491   }
4492   case ISD::FSQRT: // Need is known positive
4493   case ISD::FLOG:
4494   case ISD::FLOG2:
4495   case ISD::FLOG10:
4496   case ISD::FPOWI:
4497   case ISD::FPOW: {
4498     if (SNaN)
4499       return true;
4500     // TODO: Refine on operand
4501     return false;
4502   }
4503   case ISD::FMINNUM:
4504   case ISD::FMAXNUM: {
4505     // Only one needs to be known not-nan, since it will be returned if the
4506     // other ends up being one.
4507     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4508            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4509   }
4510   case ISD::FMINNUM_IEEE:
4511   case ISD::FMAXNUM_IEEE: {
4512     if (SNaN)
4513       return true;
4514     // This can return a NaN if either operand is an sNaN, or if both operands
4515     // are NaN.
4516     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4517             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4518            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4519             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4520   }
4521   case ISD::FMINIMUM:
4522   case ISD::FMAXIMUM: {
4523     // TODO: Does this quiet or return the origina NaN as-is?
4524     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4525            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4526   }
4527   case ISD::EXTRACT_VECTOR_ELT: {
4528     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4529   }
4530   default:
4531     if (Opcode >= ISD::BUILTIN_OP_END ||
4532         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4533         Opcode == ISD::INTRINSIC_W_CHAIN ||
4534         Opcode == ISD::INTRINSIC_VOID) {
4535       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4536     }
4537 
4538     return false;
4539   }
4540 }
4541 
4542 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4543   assert(Op.getValueType().isFloatingPoint() &&
4544          "Floating point type expected");
4545 
4546   // If the value is a constant, we can obviously see if it is a zero or not.
4547   // TODO: Add BuildVector support.
4548   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4549     return !C->isZero();
4550   return false;
4551 }
4552 
4553 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4554   assert(!Op.getValueType().isFloatingPoint() &&
4555          "Floating point types unsupported - use isKnownNeverZeroFloat");
4556 
4557   // If the value is a constant, we can obviously see if it is a zero or not.
4558   if (ISD::matchUnaryPredicate(Op,
4559                                [](ConstantSDNode *C) { return !C->isZero(); }))
4560     return true;
4561 
4562   // TODO: Recognize more cases here.
4563   switch (Op.getOpcode()) {
4564   default: break;
4565   case ISD::OR:
4566     if (isKnownNeverZero(Op.getOperand(1)) ||
4567         isKnownNeverZero(Op.getOperand(0)))
4568       return true;
4569     break;
4570   }
4571 
4572   return false;
4573 }
4574 
4575 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4576   // Check the obvious case.
4577   if (A == B) return true;
4578 
4579   // For for negative and positive zero.
4580   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4581     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4582       if (CA->isZero() && CB->isZero()) return true;
4583 
4584   // Otherwise they may not be equal.
4585   return false;
4586 }
4587 
4588 // FIXME: unify with llvm::haveNoCommonBitsSet.
4589 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4590   assert(A.getValueType() == B.getValueType() &&
4591          "Values must have the same type");
4592   // Match masked merge pattern (X & ~M) op (Y & M)
4593   if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) {
4594     auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) {
4595       if (isBitwiseNot(NotM, true)) {
4596         SDValue NotOperand = NotM->getOperand(0);
4597         return NotOperand == And->getOperand(0) ||
4598                NotOperand == And->getOperand(1);
4599       }
4600       return false;
4601     };
4602     if (MatchNoCommonBitsPattern(A->getOperand(0), B) ||
4603         MatchNoCommonBitsPattern(A->getOperand(1), B) ||
4604         MatchNoCommonBitsPattern(B->getOperand(0), A) ||
4605         MatchNoCommonBitsPattern(B->getOperand(1), A))
4606       return true;
4607   }
4608   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4609                                         computeKnownBits(B));
4610 }
4611 
4612 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4613                                SelectionDAG &DAG) {
4614   if (cast<ConstantSDNode>(Step)->isZero())
4615     return DAG.getConstant(0, DL, VT);
4616 
4617   return SDValue();
4618 }
4619 
4620 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4621                                 ArrayRef<SDValue> Ops,
4622                                 SelectionDAG &DAG) {
4623   int NumOps = Ops.size();
4624   assert(NumOps != 0 && "Can't build an empty vector!");
4625   assert(!VT.isScalableVector() &&
4626          "BUILD_VECTOR cannot be used with scalable types");
4627   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4628          "Incorrect element count in BUILD_VECTOR!");
4629 
4630   // BUILD_VECTOR of UNDEFs is UNDEF.
4631   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4632     return DAG.getUNDEF(VT);
4633 
4634   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4635   SDValue IdentitySrc;
4636   bool IsIdentity = true;
4637   for (int i = 0; i != NumOps; ++i) {
4638     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4639         Ops[i].getOperand(0).getValueType() != VT ||
4640         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4641         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4642         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4643       IsIdentity = false;
4644       break;
4645     }
4646     IdentitySrc = Ops[i].getOperand(0);
4647   }
4648   if (IsIdentity)
4649     return IdentitySrc;
4650 
4651   return SDValue();
4652 }
4653 
4654 /// Try to simplify vector concatenation to an input value, undef, or build
4655 /// vector.
4656 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4657                                   ArrayRef<SDValue> Ops,
4658                                   SelectionDAG &DAG) {
4659   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4660   assert(llvm::all_of(Ops,
4661                       [Ops](SDValue Op) {
4662                         return Ops[0].getValueType() == Op.getValueType();
4663                       }) &&
4664          "Concatenation of vectors with inconsistent value types!");
4665   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4666              VT.getVectorElementCount() &&
4667          "Incorrect element count in vector concatenation!");
4668 
4669   if (Ops.size() == 1)
4670     return Ops[0];
4671 
4672   // Concat of UNDEFs is UNDEF.
4673   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4674     return DAG.getUNDEF(VT);
4675 
4676   // Scan the operands and look for extract operations from a single source
4677   // that correspond to insertion at the same location via this concatenation:
4678   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4679   SDValue IdentitySrc;
4680   bool IsIdentity = true;
4681   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4682     SDValue Op = Ops[i];
4683     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4684     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4685         Op.getOperand(0).getValueType() != VT ||
4686         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4687         Op.getConstantOperandVal(1) != IdentityIndex) {
4688       IsIdentity = false;
4689       break;
4690     }
4691     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4692            "Unexpected identity source vector for concat of extracts");
4693     IdentitySrc = Op.getOperand(0);
4694   }
4695   if (IsIdentity) {
4696     assert(IdentitySrc && "Failed to set source vector of extracts");
4697     return IdentitySrc;
4698   }
4699 
4700   // The code below this point is only designed to work for fixed width
4701   // vectors, so we bail out for now.
4702   if (VT.isScalableVector())
4703     return SDValue();
4704 
4705   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4706   // simplified to one big BUILD_VECTOR.
4707   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4708   EVT SVT = VT.getScalarType();
4709   SmallVector<SDValue, 16> Elts;
4710   for (SDValue Op : Ops) {
4711     EVT OpVT = Op.getValueType();
4712     if (Op.isUndef())
4713       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4714     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4715       Elts.append(Op->op_begin(), Op->op_end());
4716     else
4717       return SDValue();
4718   }
4719 
4720   // BUILD_VECTOR requires all inputs to be of the same type, find the
4721   // maximum type and extend them all.
4722   for (SDValue Op : Elts)
4723     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4724 
4725   if (SVT.bitsGT(VT.getScalarType())) {
4726     for (SDValue &Op : Elts) {
4727       if (Op.isUndef())
4728         Op = DAG.getUNDEF(SVT);
4729       else
4730         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4731                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4732                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4733     }
4734   }
4735 
4736   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4737   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4738   return V;
4739 }
4740 
4741 /// Gets or creates the specified node.
4742 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4743   FoldingSetNodeID ID;
4744   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4745   void *IP = nullptr;
4746   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4747     return SDValue(E, 0);
4748 
4749   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4750                               getVTList(VT));
4751   CSEMap.InsertNode(N, IP);
4752 
4753   InsertNode(N);
4754   SDValue V = SDValue(N, 0);
4755   NewSDValueDbgMsg(V, "Creating new node: ", this);
4756   return V;
4757 }
4758 
4759 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4760                               SDValue Operand) {
4761   SDNodeFlags Flags;
4762   if (Inserter)
4763     Flags = Inserter->getFlags();
4764   return getNode(Opcode, DL, VT, Operand, Flags);
4765 }
4766 
4767 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4768                               SDValue Operand, const SDNodeFlags Flags) {
4769   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4770          "Operand is DELETED_NODE!");
4771   // Constant fold unary operations with an integer constant operand. Even
4772   // opaque constant will be folded, because the folding of unary operations
4773   // doesn't create new constants with different values. Nevertheless, the
4774   // opaque flag is preserved during folding to prevent future folding with
4775   // other constants.
4776   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4777     const APInt &Val = C->getAPIntValue();
4778     switch (Opcode) {
4779     default: break;
4780     case ISD::SIGN_EXTEND:
4781       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4782                          C->isTargetOpcode(), C->isOpaque());
4783     case ISD::TRUNCATE:
4784       if (C->isOpaque())
4785         break;
4786       LLVM_FALLTHROUGH;
4787     case ISD::ZERO_EXTEND:
4788       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4789                          C->isTargetOpcode(), C->isOpaque());
4790     case ISD::ANY_EXTEND:
4791       // Some targets like RISCV prefer to sign extend some types.
4792       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4793         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4794                            C->isTargetOpcode(), C->isOpaque());
4795       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4796                          C->isTargetOpcode(), C->isOpaque());
4797     case ISD::UINT_TO_FP:
4798     case ISD::SINT_TO_FP: {
4799       APFloat apf(EVTToAPFloatSemantics(VT),
4800                   APInt::getZero(VT.getSizeInBits()));
4801       (void)apf.convertFromAPInt(Val,
4802                                  Opcode==ISD::SINT_TO_FP,
4803                                  APFloat::rmNearestTiesToEven);
4804       return getConstantFP(apf, DL, VT);
4805     }
4806     case ISD::BITCAST:
4807       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4808         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4809       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4810         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4811       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4812         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4813       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4814         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4815       break;
4816     case ISD::ABS:
4817       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4818                          C->isOpaque());
4819     case ISD::BITREVERSE:
4820       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4821                          C->isOpaque());
4822     case ISD::BSWAP:
4823       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4824                          C->isOpaque());
4825     case ISD::CTPOP:
4826       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4827                          C->isOpaque());
4828     case ISD::CTLZ:
4829     case ISD::CTLZ_ZERO_UNDEF:
4830       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4831                          C->isOpaque());
4832     case ISD::CTTZ:
4833     case ISD::CTTZ_ZERO_UNDEF:
4834       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4835                          C->isOpaque());
4836     case ISD::FP16_TO_FP: {
4837       bool Ignored;
4838       APFloat FPV(APFloat::IEEEhalf(),
4839                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4840 
4841       // This can return overflow, underflow, or inexact; we don't care.
4842       // FIXME need to be more flexible about rounding mode.
4843       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4844                         APFloat::rmNearestTiesToEven, &Ignored);
4845       return getConstantFP(FPV, DL, VT);
4846     }
4847     case ISD::STEP_VECTOR: {
4848       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4849         return V;
4850       break;
4851     }
4852     }
4853   }
4854 
4855   // Constant fold unary operations with a floating point constant operand.
4856   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4857     APFloat V = C->getValueAPF();    // make copy
4858     switch (Opcode) {
4859     case ISD::FNEG:
4860       V.changeSign();
4861       return getConstantFP(V, DL, VT);
4862     case ISD::FABS:
4863       V.clearSign();
4864       return getConstantFP(V, DL, VT);
4865     case ISD::FCEIL: {
4866       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4867       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4868         return getConstantFP(V, DL, VT);
4869       break;
4870     }
4871     case ISD::FTRUNC: {
4872       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4873       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4874         return getConstantFP(V, DL, VT);
4875       break;
4876     }
4877     case ISD::FFLOOR: {
4878       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4879       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4880         return getConstantFP(V, DL, VT);
4881       break;
4882     }
4883     case ISD::FP_EXTEND: {
4884       bool ignored;
4885       // This can return overflow, underflow, or inexact; we don't care.
4886       // FIXME need to be more flexible about rounding mode.
4887       (void)V.convert(EVTToAPFloatSemantics(VT),
4888                       APFloat::rmNearestTiesToEven, &ignored);
4889       return getConstantFP(V, DL, VT);
4890     }
4891     case ISD::FP_TO_SINT:
4892     case ISD::FP_TO_UINT: {
4893       bool ignored;
4894       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4895       // FIXME need to be more flexible about rounding mode.
4896       APFloat::opStatus s =
4897           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4898       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4899         break;
4900       return getConstant(IntVal, DL, VT);
4901     }
4902     case ISD::BITCAST:
4903       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4904         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4905       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4906         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4907       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4908         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4909       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4910         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4911       break;
4912     case ISD::FP_TO_FP16: {
4913       bool Ignored;
4914       // This can return overflow, underflow, or inexact; we don't care.
4915       // FIXME need to be more flexible about rounding mode.
4916       (void)V.convert(APFloat::IEEEhalf(),
4917                       APFloat::rmNearestTiesToEven, &Ignored);
4918       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4919     }
4920     }
4921   }
4922 
4923   // Constant fold unary operations with a vector integer or float operand.
4924   switch (Opcode) {
4925   default:
4926     // FIXME: Entirely reasonable to perform folding of other unary
4927     // operations here as the need arises.
4928     break;
4929   case ISD::FNEG:
4930   case ISD::FABS:
4931   case ISD::FCEIL:
4932   case ISD::FTRUNC:
4933   case ISD::FFLOOR:
4934   case ISD::FP_EXTEND:
4935   case ISD::FP_TO_SINT:
4936   case ISD::FP_TO_UINT:
4937   case ISD::TRUNCATE:
4938   case ISD::ANY_EXTEND:
4939   case ISD::ZERO_EXTEND:
4940   case ISD::SIGN_EXTEND:
4941   case ISD::UINT_TO_FP:
4942   case ISD::SINT_TO_FP:
4943   case ISD::ABS:
4944   case ISD::BITREVERSE:
4945   case ISD::BSWAP:
4946   case ISD::CTLZ:
4947   case ISD::CTLZ_ZERO_UNDEF:
4948   case ISD::CTTZ:
4949   case ISD::CTTZ_ZERO_UNDEF:
4950   case ISD::CTPOP: {
4951     SDValue Ops = {Operand};
4952     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
4953       return Fold;
4954   }
4955   }
4956 
4957   unsigned OpOpcode = Operand.getNode()->getOpcode();
4958   switch (Opcode) {
4959   case ISD::STEP_VECTOR:
4960     assert(VT.isScalableVector() &&
4961            "STEP_VECTOR can only be used with scalable types");
4962     assert(OpOpcode == ISD::TargetConstant &&
4963            VT.getVectorElementType() == Operand.getValueType() &&
4964            "Unexpected step operand");
4965     break;
4966   case ISD::FREEZE:
4967     assert(VT == Operand.getValueType() && "Unexpected VT!");
4968     break;
4969   case ISD::TokenFactor:
4970   case ISD::MERGE_VALUES:
4971   case ISD::CONCAT_VECTORS:
4972     return Operand;         // Factor, merge or concat of one node?  No need.
4973   case ISD::BUILD_VECTOR: {
4974     // Attempt to simplify BUILD_VECTOR.
4975     SDValue Ops[] = {Operand};
4976     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4977       return V;
4978     break;
4979   }
4980   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4981   case ISD::FP_EXTEND:
4982     assert(VT.isFloatingPoint() &&
4983            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4984     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4985     assert((!VT.isVector() ||
4986             VT.getVectorElementCount() ==
4987             Operand.getValueType().getVectorElementCount()) &&
4988            "Vector element count mismatch!");
4989     assert(Operand.getValueType().bitsLT(VT) &&
4990            "Invalid fpext node, dst < src!");
4991     if (Operand.isUndef())
4992       return getUNDEF(VT);
4993     break;
4994   case ISD::FP_TO_SINT:
4995   case ISD::FP_TO_UINT:
4996     if (Operand.isUndef())
4997       return getUNDEF(VT);
4998     break;
4999   case ISD::SINT_TO_FP:
5000   case ISD::UINT_TO_FP:
5001     // [us]itofp(undef) = 0, because the result value is bounded.
5002     if (Operand.isUndef())
5003       return getConstantFP(0.0, DL, VT);
5004     break;
5005   case ISD::SIGN_EXTEND:
5006     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5007            "Invalid SIGN_EXTEND!");
5008     assert(VT.isVector() == Operand.getValueType().isVector() &&
5009            "SIGN_EXTEND result type type should be vector iff the operand "
5010            "type is vector!");
5011     if (Operand.getValueType() == VT) return Operand;   // noop extension
5012     assert((!VT.isVector() ||
5013             VT.getVectorElementCount() ==
5014                 Operand.getValueType().getVectorElementCount()) &&
5015            "Vector element count mismatch!");
5016     assert(Operand.getValueType().bitsLT(VT) &&
5017            "Invalid sext node, dst < src!");
5018     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5019       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5020     if (OpOpcode == ISD::UNDEF)
5021       // sext(undef) = 0, because the top bits will all be the same.
5022       return getConstant(0, DL, VT);
5023     break;
5024   case ISD::ZERO_EXTEND:
5025     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5026            "Invalid ZERO_EXTEND!");
5027     assert(VT.isVector() == Operand.getValueType().isVector() &&
5028            "ZERO_EXTEND result type type should be vector iff the operand "
5029            "type is vector!");
5030     if (Operand.getValueType() == VT) return Operand;   // noop extension
5031     assert((!VT.isVector() ||
5032             VT.getVectorElementCount() ==
5033                 Operand.getValueType().getVectorElementCount()) &&
5034            "Vector element count mismatch!");
5035     assert(Operand.getValueType().bitsLT(VT) &&
5036            "Invalid zext node, dst < src!");
5037     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5038       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5039     if (OpOpcode == ISD::UNDEF)
5040       // zext(undef) = 0, because the top bits will be zero.
5041       return getConstant(0, DL, VT);
5042     break;
5043   case ISD::ANY_EXTEND:
5044     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5045            "Invalid ANY_EXTEND!");
5046     assert(VT.isVector() == Operand.getValueType().isVector() &&
5047            "ANY_EXTEND result type type should be vector iff the operand "
5048            "type is vector!");
5049     if (Operand.getValueType() == VT) return Operand;   // noop extension
5050     assert((!VT.isVector() ||
5051             VT.getVectorElementCount() ==
5052                 Operand.getValueType().getVectorElementCount()) &&
5053            "Vector element count mismatch!");
5054     assert(Operand.getValueType().bitsLT(VT) &&
5055            "Invalid anyext node, dst < src!");
5056 
5057     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5058         OpOpcode == ISD::ANY_EXTEND)
5059       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5060       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5061     if (OpOpcode == ISD::UNDEF)
5062       return getUNDEF(VT);
5063 
5064     // (ext (trunc x)) -> x
5065     if (OpOpcode == ISD::TRUNCATE) {
5066       SDValue OpOp = Operand.getOperand(0);
5067       if (OpOp.getValueType() == VT) {
5068         transferDbgValues(Operand, OpOp);
5069         return OpOp;
5070       }
5071     }
5072     break;
5073   case ISD::TRUNCATE:
5074     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5075            "Invalid TRUNCATE!");
5076     assert(VT.isVector() == Operand.getValueType().isVector() &&
5077            "TRUNCATE result type type should be vector iff the operand "
5078            "type is vector!");
5079     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5080     assert((!VT.isVector() ||
5081             VT.getVectorElementCount() ==
5082                 Operand.getValueType().getVectorElementCount()) &&
5083            "Vector element count mismatch!");
5084     assert(Operand.getValueType().bitsGT(VT) &&
5085            "Invalid truncate node, src < dst!");
5086     if (OpOpcode == ISD::TRUNCATE)
5087       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5088     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5089         OpOpcode == ISD::ANY_EXTEND) {
5090       // If the source is smaller than the dest, we still need an extend.
5091       if (Operand.getOperand(0).getValueType().getScalarType()
5092             .bitsLT(VT.getScalarType()))
5093         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5094       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5095         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5096       return Operand.getOperand(0);
5097     }
5098     if (OpOpcode == ISD::UNDEF)
5099       return getUNDEF(VT);
5100     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5101       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5102     break;
5103   case ISD::ANY_EXTEND_VECTOR_INREG:
5104   case ISD::ZERO_EXTEND_VECTOR_INREG:
5105   case ISD::SIGN_EXTEND_VECTOR_INREG:
5106     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5107     assert(Operand.getValueType().bitsLE(VT) &&
5108            "The input must be the same size or smaller than the result.");
5109     assert(VT.getVectorMinNumElements() <
5110                Operand.getValueType().getVectorMinNumElements() &&
5111            "The destination vector type must have fewer lanes than the input.");
5112     break;
5113   case ISD::ABS:
5114     assert(VT.isInteger() && VT == Operand.getValueType() &&
5115            "Invalid ABS!");
5116     if (OpOpcode == ISD::UNDEF)
5117       return getUNDEF(VT);
5118     break;
5119   case ISD::BSWAP:
5120     assert(VT.isInteger() && VT == Operand.getValueType() &&
5121            "Invalid BSWAP!");
5122     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5123            "BSWAP types must be a multiple of 16 bits!");
5124     if (OpOpcode == ISD::UNDEF)
5125       return getUNDEF(VT);
5126     // bswap(bswap(X)) -> X.
5127     if (OpOpcode == ISD::BSWAP)
5128       return Operand.getOperand(0);
5129     break;
5130   case ISD::BITREVERSE:
5131     assert(VT.isInteger() && VT == Operand.getValueType() &&
5132            "Invalid BITREVERSE!");
5133     if (OpOpcode == ISD::UNDEF)
5134       return getUNDEF(VT);
5135     break;
5136   case ISD::BITCAST:
5137     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5138            "Cannot BITCAST between types of different sizes!");
5139     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5140     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5141       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5142     if (OpOpcode == ISD::UNDEF)
5143       return getUNDEF(VT);
5144     break;
5145   case ISD::SCALAR_TO_VECTOR:
5146     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5147            (VT.getVectorElementType() == Operand.getValueType() ||
5148             (VT.getVectorElementType().isInteger() &&
5149              Operand.getValueType().isInteger() &&
5150              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5151            "Illegal SCALAR_TO_VECTOR node!");
5152     if (OpOpcode == ISD::UNDEF)
5153       return getUNDEF(VT);
5154     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5155     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5156         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5157         Operand.getConstantOperandVal(1) == 0 &&
5158         Operand.getOperand(0).getValueType() == VT)
5159       return Operand.getOperand(0);
5160     break;
5161   case ISD::FNEG:
5162     // Negation of an unknown bag of bits is still completely undefined.
5163     if (OpOpcode == ISD::UNDEF)
5164       return getUNDEF(VT);
5165 
5166     if (OpOpcode == ISD::FNEG)  // --X -> X
5167       return Operand.getOperand(0);
5168     break;
5169   case ISD::FABS:
5170     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5171       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5172     break;
5173   case ISD::VSCALE:
5174     assert(VT == Operand.getValueType() && "Unexpected VT!");
5175     break;
5176   case ISD::CTPOP:
5177     if (Operand.getValueType().getScalarType() == MVT::i1)
5178       return Operand;
5179     break;
5180   case ISD::CTLZ:
5181   case ISD::CTTZ:
5182     if (Operand.getValueType().getScalarType() == MVT::i1)
5183       return getNOT(DL, Operand, Operand.getValueType());
5184     break;
5185   case ISD::VECREDUCE_SMIN:
5186   case ISD::VECREDUCE_UMAX:
5187     if (Operand.getValueType().getScalarType() == MVT::i1)
5188       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5189     break;
5190   case ISD::VECREDUCE_SMAX:
5191   case ISD::VECREDUCE_UMIN:
5192     if (Operand.getValueType().getScalarType() == MVT::i1)
5193       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5194     break;
5195   }
5196 
5197   SDNode *N;
5198   SDVTList VTs = getVTList(VT);
5199   SDValue Ops[] = {Operand};
5200   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5201     FoldingSetNodeID ID;
5202     AddNodeIDNode(ID, Opcode, VTs, Ops);
5203     void *IP = nullptr;
5204     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5205       E->intersectFlagsWith(Flags);
5206       return SDValue(E, 0);
5207     }
5208 
5209     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5210     N->setFlags(Flags);
5211     createOperands(N, Ops);
5212     CSEMap.InsertNode(N, IP);
5213   } else {
5214     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5215     createOperands(N, Ops);
5216   }
5217 
5218   InsertNode(N);
5219   SDValue V = SDValue(N, 0);
5220   NewSDValueDbgMsg(V, "Creating new node: ", this);
5221   return V;
5222 }
5223 
5224 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5225                                        const APInt &C2) {
5226   switch (Opcode) {
5227   case ISD::ADD:  return C1 + C2;
5228   case ISD::SUB:  return C1 - C2;
5229   case ISD::MUL:  return C1 * C2;
5230   case ISD::AND:  return C1 & C2;
5231   case ISD::OR:   return C1 | C2;
5232   case ISD::XOR:  return C1 ^ C2;
5233   case ISD::SHL:  return C1 << C2;
5234   case ISD::SRL:  return C1.lshr(C2);
5235   case ISD::SRA:  return C1.ashr(C2);
5236   case ISD::ROTL: return C1.rotl(C2);
5237   case ISD::ROTR: return C1.rotr(C2);
5238   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5239   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5240   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5241   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5242   case ISD::SADDSAT: return C1.sadd_sat(C2);
5243   case ISD::UADDSAT: return C1.uadd_sat(C2);
5244   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5245   case ISD::USUBSAT: return C1.usub_sat(C2);
5246   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5247   case ISD::USHLSAT: return C1.ushl_sat(C2);
5248   case ISD::UDIV:
5249     if (!C2.getBoolValue())
5250       break;
5251     return C1.udiv(C2);
5252   case ISD::UREM:
5253     if (!C2.getBoolValue())
5254       break;
5255     return C1.urem(C2);
5256   case ISD::SDIV:
5257     if (!C2.getBoolValue())
5258       break;
5259     return C1.sdiv(C2);
5260   case ISD::SREM:
5261     if (!C2.getBoolValue())
5262       break;
5263     return C1.srem(C2);
5264   case ISD::MULHS: {
5265     unsigned FullWidth = C1.getBitWidth() * 2;
5266     APInt C1Ext = C1.sext(FullWidth);
5267     APInt C2Ext = C2.sext(FullWidth);
5268     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5269   }
5270   case ISD::MULHU: {
5271     unsigned FullWidth = C1.getBitWidth() * 2;
5272     APInt C1Ext = C1.zext(FullWidth);
5273     APInt C2Ext = C2.zext(FullWidth);
5274     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5275   }
5276   }
5277   return llvm::None;
5278 }
5279 
5280 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5281                                        const GlobalAddressSDNode *GA,
5282                                        const SDNode *N2) {
5283   if (GA->getOpcode() != ISD::GlobalAddress)
5284     return SDValue();
5285   if (!TLI->isOffsetFoldingLegal(GA))
5286     return SDValue();
5287   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5288   if (!C2)
5289     return SDValue();
5290   int64_t Offset = C2->getSExtValue();
5291   switch (Opcode) {
5292   case ISD::ADD: break;
5293   case ISD::SUB: Offset = -uint64_t(Offset); break;
5294   default: return SDValue();
5295   }
5296   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5297                           GA->getOffset() + uint64_t(Offset));
5298 }
5299 
5300 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5301   switch (Opcode) {
5302   case ISD::SDIV:
5303   case ISD::UDIV:
5304   case ISD::SREM:
5305   case ISD::UREM: {
5306     // If a divisor is zero/undef or any element of a divisor vector is
5307     // zero/undef, the whole op is undef.
5308     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5309     SDValue Divisor = Ops[1];
5310     if (Divisor.isUndef() || isNullConstant(Divisor))
5311       return true;
5312 
5313     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5314            llvm::any_of(Divisor->op_values(),
5315                         [](SDValue V) { return V.isUndef() ||
5316                                         isNullConstant(V); });
5317     // TODO: Handle signed overflow.
5318   }
5319   // TODO: Handle oversized shifts.
5320   default:
5321     return false;
5322   }
5323 }
5324 
5325 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5326                                              EVT VT, ArrayRef<SDValue> Ops) {
5327   // If the opcode is a target-specific ISD node, there's nothing we can
5328   // do here and the operand rules may not line up with the below, so
5329   // bail early.
5330   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5331   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5332   // foldCONCAT_VECTORS in getNode before this is called.
5333   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5334     return SDValue();
5335 
5336   unsigned NumOps = Ops.size();
5337   if (NumOps == 0)
5338     return SDValue();
5339 
5340   if (isUndef(Opcode, Ops))
5341     return getUNDEF(VT);
5342 
5343   // Handle binops special cases.
5344   if (NumOps == 2) {
5345     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5346       return CFP;
5347 
5348     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5349       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5350         if (C1->isOpaque() || C2->isOpaque())
5351           return SDValue();
5352 
5353         Optional<APInt> FoldAttempt =
5354             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5355         if (!FoldAttempt)
5356           return SDValue();
5357 
5358         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5359         assert((!Folded || !VT.isVector()) &&
5360                "Can't fold vectors ops with scalar operands");
5361         return Folded;
5362       }
5363     }
5364 
5365     // fold (add Sym, c) -> Sym+c
5366     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5367       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5368     if (TLI->isCommutativeBinOp(Opcode))
5369       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5370         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5371   }
5372 
5373   // This is for vector folding only from here on.
5374   if (!VT.isVector())
5375     return SDValue();
5376 
5377   ElementCount NumElts = VT.getVectorElementCount();
5378 
5379   // See if we can fold through bitcasted integer ops.
5380   // TODO: Can we handle undef elements?
5381   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5382       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5383       Ops[0].getOpcode() == ISD::BITCAST &&
5384       Ops[1].getOpcode() == ISD::BITCAST) {
5385     SDValue N1 = peekThroughBitcasts(Ops[0]);
5386     SDValue N2 = peekThroughBitcasts(Ops[1]);
5387     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5388     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5389     EVT BVVT = N1.getValueType();
5390     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5391       bool IsLE = getDataLayout().isLittleEndian();
5392       unsigned EltBits = VT.getScalarSizeInBits();
5393       SmallVector<APInt> RawBits1, RawBits2;
5394       BitVector UndefElts1, UndefElts2;
5395       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5396           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5397           UndefElts1.none() && UndefElts2.none()) {
5398         SmallVector<APInt> RawBits;
5399         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5400           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5401           if (!Fold)
5402             break;
5403           RawBits.push_back(Fold.getValue());
5404         }
5405         if (RawBits.size() == NumElts.getFixedValue()) {
5406           // We have constant folded, but we need to cast this again back to
5407           // the original (possibly legalized) type.
5408           SmallVector<APInt> DstBits;
5409           BitVector DstUndefs;
5410           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5411                                            DstBits, RawBits, DstUndefs,
5412                                            BitVector(RawBits.size(), false));
5413           EVT BVEltVT = BV1->getOperand(0).getValueType();
5414           unsigned BVEltBits = BVEltVT.getSizeInBits();
5415           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5416           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5417             if (DstUndefs[I])
5418               continue;
5419             Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5420           }
5421           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5422         }
5423       }
5424     }
5425   }
5426 
5427   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5428   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5429   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5430       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5431     APInt RHSVal;
5432     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5433       APInt NewStep = Opcode == ISD::MUL
5434                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5435                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5436       return getStepVector(DL, VT, NewStep);
5437     }
5438   }
5439 
5440   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5441     return !Op.getValueType().isVector() ||
5442            Op.getValueType().getVectorElementCount() == NumElts;
5443   };
5444 
5445   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5446     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5447            Op.getOpcode() == ISD::BUILD_VECTOR ||
5448            Op.getOpcode() == ISD::SPLAT_VECTOR;
5449   };
5450 
5451   // All operands must be vector types with the same number of elements as
5452   // the result type and must be either UNDEF or a build/splat vector
5453   // or UNDEF scalars.
5454   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5455       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5456     return SDValue();
5457 
5458   // If we are comparing vectors, then the result needs to be a i1 boolean
5459   // that is then sign-extended back to the legal result type.
5460   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5461 
5462   // Find legal integer scalar type for constant promotion and
5463   // ensure that its scalar size is at least as large as source.
5464   EVT LegalSVT = VT.getScalarType();
5465   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5466     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5467     if (LegalSVT.bitsLT(VT.getScalarType()))
5468       return SDValue();
5469   }
5470 
5471   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5472   // only have one operand to check. For fixed-length vector types we may have
5473   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5474   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5475 
5476   // Constant fold each scalar lane separately.
5477   SmallVector<SDValue, 4> ScalarResults;
5478   for (unsigned I = 0; I != NumVectorElts; I++) {
5479     SmallVector<SDValue, 4> ScalarOps;
5480     for (SDValue Op : Ops) {
5481       EVT InSVT = Op.getValueType().getScalarType();
5482       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5483           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5484         if (Op.isUndef())
5485           ScalarOps.push_back(getUNDEF(InSVT));
5486         else
5487           ScalarOps.push_back(Op);
5488         continue;
5489       }
5490 
5491       SDValue ScalarOp =
5492           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5493       EVT ScalarVT = ScalarOp.getValueType();
5494 
5495       // Build vector (integer) scalar operands may need implicit
5496       // truncation - do this before constant folding.
5497       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5498         // Don't create illegally-typed nodes unless they're constants or undef
5499         // - if we fail to constant fold we can't guarantee the (dead) nodes
5500         // we're creating will be cleaned up before being visited for
5501         // legalization.
5502         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5503             !isa<ConstantSDNode>(ScalarOp) &&
5504             TLI->getTypeAction(*getContext(), InSVT) !=
5505                 TargetLowering::TypeLegal)
5506           return SDValue();
5507         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5508       }
5509 
5510       ScalarOps.push_back(ScalarOp);
5511     }
5512 
5513     // Constant fold the scalar operands.
5514     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5515 
5516     // Legalize the (integer) scalar constant if necessary.
5517     if (LegalSVT != SVT)
5518       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5519 
5520     // Scalar folding only succeeded if the result is a constant or UNDEF.
5521     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5522         ScalarResult.getOpcode() != ISD::ConstantFP)
5523       return SDValue();
5524     ScalarResults.push_back(ScalarResult);
5525   }
5526 
5527   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5528                                    : getBuildVector(VT, DL, ScalarResults);
5529   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5530   return V;
5531 }
5532 
5533 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5534                                          EVT VT, SDValue N1, SDValue N2) {
5535   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5536   //       should. That will require dealing with a potentially non-default
5537   //       rounding mode, checking the "opStatus" return value from the APFloat
5538   //       math calculations, and possibly other variations.
5539   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5540   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5541   if (N1CFP && N2CFP) {
5542     APFloat C1 = N1CFP->getValueAPF(); // make copy
5543     const APFloat &C2 = N2CFP->getValueAPF();
5544     switch (Opcode) {
5545     case ISD::FADD:
5546       C1.add(C2, APFloat::rmNearestTiesToEven);
5547       return getConstantFP(C1, DL, VT);
5548     case ISD::FSUB:
5549       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5550       return getConstantFP(C1, DL, VT);
5551     case ISD::FMUL:
5552       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5553       return getConstantFP(C1, DL, VT);
5554     case ISD::FDIV:
5555       C1.divide(C2, APFloat::rmNearestTiesToEven);
5556       return getConstantFP(C1, DL, VT);
5557     case ISD::FREM:
5558       C1.mod(C2);
5559       return getConstantFP(C1, DL, VT);
5560     case ISD::FCOPYSIGN:
5561       C1.copySign(C2);
5562       return getConstantFP(C1, DL, VT);
5563     case ISD::FMINNUM:
5564       return getConstantFP(minnum(C1, C2), DL, VT);
5565     case ISD::FMAXNUM:
5566       return getConstantFP(maxnum(C1, C2), DL, VT);
5567     case ISD::FMINIMUM:
5568       return getConstantFP(minimum(C1, C2), DL, VT);
5569     case ISD::FMAXIMUM:
5570       return getConstantFP(maximum(C1, C2), DL, VT);
5571     default: break;
5572     }
5573   }
5574   if (N1CFP && Opcode == ISD::FP_ROUND) {
5575     APFloat C1 = N1CFP->getValueAPF();    // make copy
5576     bool Unused;
5577     // This can return overflow, underflow, or inexact; we don't care.
5578     // FIXME need to be more flexible about rounding mode.
5579     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5580                       &Unused);
5581     return getConstantFP(C1, DL, VT);
5582   }
5583 
5584   switch (Opcode) {
5585   case ISD::FSUB:
5586     // -0.0 - undef --> undef (consistent with "fneg undef")
5587     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5588       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5589         return getUNDEF(VT);
5590     LLVM_FALLTHROUGH;
5591 
5592   case ISD::FADD:
5593   case ISD::FMUL:
5594   case ISD::FDIV:
5595   case ISD::FREM:
5596     // If both operands are undef, the result is undef. If 1 operand is undef,
5597     // the result is NaN. This should match the behavior of the IR optimizer.
5598     if (N1.isUndef() && N2.isUndef())
5599       return getUNDEF(VT);
5600     if (N1.isUndef() || N2.isUndef())
5601       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5602   }
5603   return SDValue();
5604 }
5605 
5606 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5607   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5608 
5609   // There's no need to assert on a byte-aligned pointer. All pointers are at
5610   // least byte aligned.
5611   if (A == Align(1))
5612     return Val;
5613 
5614   FoldingSetNodeID ID;
5615   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5616   ID.AddInteger(A.value());
5617 
5618   void *IP = nullptr;
5619   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5620     return SDValue(E, 0);
5621 
5622   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5623                                          Val.getValueType(), A);
5624   createOperands(N, {Val});
5625 
5626   CSEMap.InsertNode(N, IP);
5627   InsertNode(N);
5628 
5629   SDValue V(N, 0);
5630   NewSDValueDbgMsg(V, "Creating new node: ", this);
5631   return V;
5632 }
5633 
5634 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5635                               SDValue N1, SDValue N2) {
5636   SDNodeFlags Flags;
5637   if (Inserter)
5638     Flags = Inserter->getFlags();
5639   return getNode(Opcode, DL, VT, N1, N2, Flags);
5640 }
5641 
5642 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5643                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5644   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5645          N2.getOpcode() != ISD::DELETED_NODE &&
5646          "Operand is DELETED_NODE!");
5647   // Canonicalize constant to RHS if commutative.
5648   if (TLI->isCommutativeBinOp(Opcode)) {
5649     bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5650     bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5651     bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5652     bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5653     if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5654       std::swap(N1, N2);
5655   }
5656 
5657   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5658   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5659 
5660   // Don't allow undefs in vector splats - we might be returning N2 when folding
5661   // to zero etc.
5662   ConstantSDNode *N2CV =
5663       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5664 
5665   switch (Opcode) {
5666   default: break;
5667   case ISD::TokenFactor:
5668     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5669            N2.getValueType() == MVT::Other && "Invalid token factor!");
5670     // Fold trivial token factors.
5671     if (N1.getOpcode() == ISD::EntryToken) return N2;
5672     if (N2.getOpcode() == ISD::EntryToken) return N1;
5673     if (N1 == N2) return N1;
5674     break;
5675   case ISD::BUILD_VECTOR: {
5676     // Attempt to simplify BUILD_VECTOR.
5677     SDValue Ops[] = {N1, N2};
5678     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5679       return V;
5680     break;
5681   }
5682   case ISD::CONCAT_VECTORS: {
5683     SDValue Ops[] = {N1, N2};
5684     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5685       return V;
5686     break;
5687   }
5688   case ISD::AND:
5689     assert(VT.isInteger() && "This operator does not apply to FP types!");
5690     assert(N1.getValueType() == N2.getValueType() &&
5691            N1.getValueType() == VT && "Binary operator types must match!");
5692     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5693     // worth handling here.
5694     if (N2CV && N2CV->isZero())
5695       return N2;
5696     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5697       return N1;
5698     break;
5699   case ISD::OR:
5700   case ISD::XOR:
5701   case ISD::ADD:
5702   case ISD::SUB:
5703     assert(VT.isInteger() && "This operator does not apply to FP types!");
5704     assert(N1.getValueType() == N2.getValueType() &&
5705            N1.getValueType() == VT && "Binary operator types must match!");
5706     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5707     // it's worth handling here.
5708     if (N2CV && N2CV->isZero())
5709       return N1;
5710     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5711         VT.getVectorElementType() == MVT::i1)
5712       return getNode(ISD::XOR, DL, VT, N1, N2);
5713     break;
5714   case ISD::MUL:
5715     assert(VT.isInteger() && "This operator does not apply to FP types!");
5716     assert(N1.getValueType() == N2.getValueType() &&
5717            N1.getValueType() == VT && "Binary operator types must match!");
5718     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5719       return getNode(ISD::AND, DL, VT, N1, N2);
5720     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5721       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5722       const APInt &N2CImm = N2C->getAPIntValue();
5723       return getVScale(DL, VT, MulImm * N2CImm);
5724     }
5725     break;
5726   case ISD::UDIV:
5727   case ISD::UREM:
5728   case ISD::MULHU:
5729   case ISD::MULHS:
5730   case ISD::SDIV:
5731   case ISD::SREM:
5732   case ISD::SADDSAT:
5733   case ISD::SSUBSAT:
5734   case ISD::UADDSAT:
5735   case ISD::USUBSAT:
5736     assert(VT.isInteger() && "This operator does not apply to FP types!");
5737     assert(N1.getValueType() == N2.getValueType() &&
5738            N1.getValueType() == VT && "Binary operator types must match!");
5739     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5740       // fold (add_sat x, y) -> (or x, y) for bool types.
5741       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5742         return getNode(ISD::OR, DL, VT, N1, N2);
5743       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5744       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5745         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5746     }
5747     break;
5748   case ISD::SMIN:
5749   case ISD::UMAX:
5750     assert(VT.isInteger() && "This operator does not apply to FP types!");
5751     assert(N1.getValueType() == N2.getValueType() &&
5752            N1.getValueType() == VT && "Binary operator types must match!");
5753     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5754       return getNode(ISD::OR, DL, VT, N1, N2);
5755     break;
5756   case ISD::SMAX:
5757   case ISD::UMIN:
5758     assert(VT.isInteger() && "This operator does not apply to FP types!");
5759     assert(N1.getValueType() == N2.getValueType() &&
5760            N1.getValueType() == VT && "Binary operator types must match!");
5761     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5762       return getNode(ISD::AND, DL, VT, N1, N2);
5763     break;
5764   case ISD::FADD:
5765   case ISD::FSUB:
5766   case ISD::FMUL:
5767   case ISD::FDIV:
5768   case ISD::FREM:
5769     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5770     assert(N1.getValueType() == N2.getValueType() &&
5771            N1.getValueType() == VT && "Binary operator types must match!");
5772     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5773       return V;
5774     break;
5775   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5776     assert(N1.getValueType() == VT &&
5777            N1.getValueType().isFloatingPoint() &&
5778            N2.getValueType().isFloatingPoint() &&
5779            "Invalid FCOPYSIGN!");
5780     break;
5781   case ISD::SHL:
5782     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5783       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5784       const APInt &ShiftImm = N2C->getAPIntValue();
5785       return getVScale(DL, VT, MulImm << ShiftImm);
5786     }
5787     LLVM_FALLTHROUGH;
5788   case ISD::SRA:
5789   case ISD::SRL:
5790     if (SDValue V = simplifyShift(N1, N2))
5791       return V;
5792     LLVM_FALLTHROUGH;
5793   case ISD::ROTL:
5794   case ISD::ROTR:
5795     assert(VT == N1.getValueType() &&
5796            "Shift operators return type must be the same as their first arg");
5797     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5798            "Shifts only work on integers");
5799     assert((!VT.isVector() || VT == N2.getValueType()) &&
5800            "Vector shift amounts must be in the same as their first arg");
5801     // Verify that the shift amount VT is big enough to hold valid shift
5802     // amounts.  This catches things like trying to shift an i1024 value by an
5803     // i8, which is easy to fall into in generic code that uses
5804     // TLI.getShiftAmount().
5805     assert(N2.getValueType().getScalarSizeInBits() >=
5806                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5807            "Invalid use of small shift amount with oversized value!");
5808 
5809     // Always fold shifts of i1 values so the code generator doesn't need to
5810     // handle them.  Since we know the size of the shift has to be less than the
5811     // size of the value, the shift/rotate count is guaranteed to be zero.
5812     if (VT == MVT::i1)
5813       return N1;
5814     if (N2CV && N2CV->isZero())
5815       return N1;
5816     break;
5817   case ISD::FP_ROUND:
5818     assert(VT.isFloatingPoint() &&
5819            N1.getValueType().isFloatingPoint() &&
5820            VT.bitsLE(N1.getValueType()) &&
5821            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5822            "Invalid FP_ROUND!");
5823     if (N1.getValueType() == VT) return N1;  // noop conversion.
5824     break;
5825   case ISD::AssertSext:
5826   case ISD::AssertZext: {
5827     EVT EVT = cast<VTSDNode>(N2)->getVT();
5828     assert(VT == N1.getValueType() && "Not an inreg extend!");
5829     assert(VT.isInteger() && EVT.isInteger() &&
5830            "Cannot *_EXTEND_INREG FP types");
5831     assert(!EVT.isVector() &&
5832            "AssertSExt/AssertZExt type should be the vector element type "
5833            "rather than the vector type!");
5834     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5835     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5836     break;
5837   }
5838   case ISD::SIGN_EXTEND_INREG: {
5839     EVT EVT = cast<VTSDNode>(N2)->getVT();
5840     assert(VT == N1.getValueType() && "Not an inreg extend!");
5841     assert(VT.isInteger() && EVT.isInteger() &&
5842            "Cannot *_EXTEND_INREG FP types");
5843     assert(EVT.isVector() == VT.isVector() &&
5844            "SIGN_EXTEND_INREG type should be vector iff the operand "
5845            "type is vector!");
5846     assert((!EVT.isVector() ||
5847             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5848            "Vector element counts must match in SIGN_EXTEND_INREG");
5849     assert(EVT.bitsLE(VT) && "Not extending!");
5850     if (EVT == VT) return N1;  // Not actually extending
5851 
5852     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5853       unsigned FromBits = EVT.getScalarSizeInBits();
5854       Val <<= Val.getBitWidth() - FromBits;
5855       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5856       return getConstant(Val, DL, ConstantVT);
5857     };
5858 
5859     if (N1C) {
5860       const APInt &Val = N1C->getAPIntValue();
5861       return SignExtendInReg(Val, VT);
5862     }
5863 
5864     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5865       SmallVector<SDValue, 8> Ops;
5866       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5867       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5868         SDValue Op = N1.getOperand(i);
5869         if (Op.isUndef()) {
5870           Ops.push_back(getUNDEF(OpVT));
5871           continue;
5872         }
5873         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5874         APInt Val = C->getAPIntValue();
5875         Ops.push_back(SignExtendInReg(Val, OpVT));
5876       }
5877       return getBuildVector(VT, DL, Ops);
5878     }
5879     break;
5880   }
5881   case ISD::FP_TO_SINT_SAT:
5882   case ISD::FP_TO_UINT_SAT: {
5883     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5884            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5885     assert(N1.getValueType().isVector() == VT.isVector() &&
5886            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5887            "vector!");
5888     assert((!VT.isVector() || VT.getVectorNumElements() ==
5889                                   N1.getValueType().getVectorNumElements()) &&
5890            "Vector element counts must match in FP_TO_*INT_SAT");
5891     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5892            "Type to saturate to must be a scalar.");
5893     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5894            "Not extending!");
5895     break;
5896   }
5897   case ISD::EXTRACT_VECTOR_ELT:
5898     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5899            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5900              element type of the vector.");
5901 
5902     // Extract from an undefined value or using an undefined index is undefined.
5903     if (N1.isUndef() || N2.isUndef())
5904       return getUNDEF(VT);
5905 
5906     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5907     // vectors. For scalable vectors we will provide appropriate support for
5908     // dealing with arbitrary indices.
5909     if (N2C && N1.getValueType().isFixedLengthVector() &&
5910         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5911       return getUNDEF(VT);
5912 
5913     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5914     // expanding copies of large vectors from registers. This only works for
5915     // fixed length vectors, since we need to know the exact number of
5916     // elements.
5917     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5918         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5919       unsigned Factor =
5920         N1.getOperand(0).getValueType().getVectorNumElements();
5921       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5922                      N1.getOperand(N2C->getZExtValue() / Factor),
5923                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5924     }
5925 
5926     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5927     // lowering is expanding large vector constants.
5928     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5929                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5930       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5931               N1.getValueType().isFixedLengthVector()) &&
5932              "BUILD_VECTOR used for scalable vectors");
5933       unsigned Index =
5934           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5935       SDValue Elt = N1.getOperand(Index);
5936 
5937       if (VT != Elt.getValueType())
5938         // If the vector element type is not legal, the BUILD_VECTOR operands
5939         // are promoted and implicitly truncated, and the result implicitly
5940         // extended. Make that explicit here.
5941         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5942 
5943       return Elt;
5944     }
5945 
5946     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5947     // operations are lowered to scalars.
5948     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5949       // If the indices are the same, return the inserted element else
5950       // if the indices are known different, extract the element from
5951       // the original vector.
5952       SDValue N1Op2 = N1.getOperand(2);
5953       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5954 
5955       if (N1Op2C && N2C) {
5956         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5957           if (VT == N1.getOperand(1).getValueType())
5958             return N1.getOperand(1);
5959           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5960         }
5961         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5962       }
5963     }
5964 
5965     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5966     // when vector types are scalarized and v1iX is legal.
5967     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5968     // Here we are completely ignoring the extract element index (N2),
5969     // which is fine for fixed width vectors, since any index other than 0
5970     // is undefined anyway. However, this cannot be ignored for scalable
5971     // vectors - in theory we could support this, but we don't want to do this
5972     // without a profitability check.
5973     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5974         N1.getValueType().isFixedLengthVector() &&
5975         N1.getValueType().getVectorNumElements() == 1) {
5976       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5977                      N1.getOperand(1));
5978     }
5979     break;
5980   case ISD::EXTRACT_ELEMENT:
5981     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5982     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5983            (N1.getValueType().isInteger() == VT.isInteger()) &&
5984            N1.getValueType() != VT &&
5985            "Wrong types for EXTRACT_ELEMENT!");
5986 
5987     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5988     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5989     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5990     if (N1.getOpcode() == ISD::BUILD_PAIR)
5991       return N1.getOperand(N2C->getZExtValue());
5992 
5993     // EXTRACT_ELEMENT of a constant int is also very common.
5994     if (N1C) {
5995       unsigned ElementSize = VT.getSizeInBits();
5996       unsigned Shift = ElementSize * N2C->getZExtValue();
5997       const APInt &Val = N1C->getAPIntValue();
5998       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5999     }
6000     break;
6001   case ISD::EXTRACT_SUBVECTOR: {
6002     EVT N1VT = N1.getValueType();
6003     assert(VT.isVector() && N1VT.isVector() &&
6004            "Extract subvector VTs must be vectors!");
6005     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6006            "Extract subvector VTs must have the same element type!");
6007     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6008            "Cannot extract a scalable vector from a fixed length vector!");
6009     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6010             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6011            "Extract subvector must be from larger vector to smaller vector!");
6012     assert(N2C && "Extract subvector index must be a constant");
6013     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6014             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6015                 N1VT.getVectorMinNumElements()) &&
6016            "Extract subvector overflow!");
6017     assert(N2C->getAPIntValue().getBitWidth() ==
6018                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6019            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6020 
6021     // Trivial extraction.
6022     if (VT == N1VT)
6023       return N1;
6024 
6025     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6026     if (N1.isUndef())
6027       return getUNDEF(VT);
6028 
6029     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6030     // the concat have the same type as the extract.
6031     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6032         VT == N1.getOperand(0).getValueType()) {
6033       unsigned Factor = VT.getVectorMinNumElements();
6034       return N1.getOperand(N2C->getZExtValue() / Factor);
6035     }
6036 
6037     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6038     // during shuffle legalization.
6039     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6040         VT == N1.getOperand(1).getValueType())
6041       return N1.getOperand(1);
6042     break;
6043   }
6044   }
6045 
6046   // Perform trivial constant folding.
6047   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6048     return SV;
6049 
6050   // Canonicalize an UNDEF to the RHS, even over a constant.
6051   if (N1.isUndef()) {
6052     if (TLI->isCommutativeBinOp(Opcode)) {
6053       std::swap(N1, N2);
6054     } else {
6055       switch (Opcode) {
6056       case ISD::SIGN_EXTEND_INREG:
6057       case ISD::SUB:
6058         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6059       case ISD::UDIV:
6060       case ISD::SDIV:
6061       case ISD::UREM:
6062       case ISD::SREM:
6063       case ISD::SSUBSAT:
6064       case ISD::USUBSAT:
6065         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6066       }
6067     }
6068   }
6069 
6070   // Fold a bunch of operators when the RHS is undef.
6071   if (N2.isUndef()) {
6072     switch (Opcode) {
6073     case ISD::XOR:
6074       if (N1.isUndef())
6075         // Handle undef ^ undef -> 0 special case. This is a common
6076         // idiom (misuse).
6077         return getConstant(0, DL, VT);
6078       LLVM_FALLTHROUGH;
6079     case ISD::ADD:
6080     case ISD::SUB:
6081     case ISD::UDIV:
6082     case ISD::SDIV:
6083     case ISD::UREM:
6084     case ISD::SREM:
6085       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6086     case ISD::MUL:
6087     case ISD::AND:
6088     case ISD::SSUBSAT:
6089     case ISD::USUBSAT:
6090       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6091     case ISD::OR:
6092     case ISD::SADDSAT:
6093     case ISD::UADDSAT:
6094       return getAllOnesConstant(DL, VT);
6095     }
6096   }
6097 
6098   // Memoize this node if possible.
6099   SDNode *N;
6100   SDVTList VTs = getVTList(VT);
6101   SDValue Ops[] = {N1, N2};
6102   if (VT != MVT::Glue) {
6103     FoldingSetNodeID ID;
6104     AddNodeIDNode(ID, Opcode, VTs, Ops);
6105     void *IP = nullptr;
6106     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6107       E->intersectFlagsWith(Flags);
6108       return SDValue(E, 0);
6109     }
6110 
6111     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6112     N->setFlags(Flags);
6113     createOperands(N, Ops);
6114     CSEMap.InsertNode(N, IP);
6115   } else {
6116     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6117     createOperands(N, Ops);
6118   }
6119 
6120   InsertNode(N);
6121   SDValue V = SDValue(N, 0);
6122   NewSDValueDbgMsg(V, "Creating new node: ", this);
6123   return V;
6124 }
6125 
6126 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6127                               SDValue N1, SDValue N2, SDValue N3) {
6128   SDNodeFlags Flags;
6129   if (Inserter)
6130     Flags = Inserter->getFlags();
6131   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6132 }
6133 
6134 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6135                               SDValue N1, SDValue N2, SDValue N3,
6136                               const SDNodeFlags Flags) {
6137   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6138          N2.getOpcode() != ISD::DELETED_NODE &&
6139          N3.getOpcode() != ISD::DELETED_NODE &&
6140          "Operand is DELETED_NODE!");
6141   // Perform various simplifications.
6142   switch (Opcode) {
6143   case ISD::FMA: {
6144     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6145     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6146            N3.getValueType() == VT && "FMA types must match!");
6147     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6148     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6149     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6150     if (N1CFP && N2CFP && N3CFP) {
6151       APFloat  V1 = N1CFP->getValueAPF();
6152       const APFloat &V2 = N2CFP->getValueAPF();
6153       const APFloat &V3 = N3CFP->getValueAPF();
6154       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6155       return getConstantFP(V1, DL, VT);
6156     }
6157     break;
6158   }
6159   case ISD::BUILD_VECTOR: {
6160     // Attempt to simplify BUILD_VECTOR.
6161     SDValue Ops[] = {N1, N2, N3};
6162     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6163       return V;
6164     break;
6165   }
6166   case ISD::CONCAT_VECTORS: {
6167     SDValue Ops[] = {N1, N2, N3};
6168     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6169       return V;
6170     break;
6171   }
6172   case ISD::SETCC: {
6173     assert(VT.isInteger() && "SETCC result type must be an integer!");
6174     assert(N1.getValueType() == N2.getValueType() &&
6175            "SETCC operands must have the same type!");
6176     assert(VT.isVector() == N1.getValueType().isVector() &&
6177            "SETCC type should be vector iff the operand type is vector!");
6178     assert((!VT.isVector() || VT.getVectorElementCount() ==
6179                                   N1.getValueType().getVectorElementCount()) &&
6180            "SETCC vector element counts must match!");
6181     // Use FoldSetCC to simplify SETCC's.
6182     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6183       return V;
6184     // Vector constant folding.
6185     SDValue Ops[] = {N1, N2, N3};
6186     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6187       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6188       return V;
6189     }
6190     break;
6191   }
6192   case ISD::SELECT:
6193   case ISD::VSELECT:
6194     if (SDValue V = simplifySelect(N1, N2, N3))
6195       return V;
6196     break;
6197   case ISD::VECTOR_SHUFFLE:
6198     llvm_unreachable("should use getVectorShuffle constructor!");
6199   case ISD::VECTOR_SPLICE: {
6200     if (cast<ConstantSDNode>(N3)->isNullValue())
6201       return N1;
6202     break;
6203   }
6204   case ISD::INSERT_VECTOR_ELT: {
6205     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6206     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6207     // for scalable vectors where we will generate appropriate code to
6208     // deal with out-of-bounds cases correctly.
6209     if (N3C && N1.getValueType().isFixedLengthVector() &&
6210         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6211       return getUNDEF(VT);
6212 
6213     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6214     if (N3.isUndef())
6215       return getUNDEF(VT);
6216 
6217     // If the inserted element is an UNDEF, just use the input vector.
6218     if (N2.isUndef())
6219       return N1;
6220 
6221     break;
6222   }
6223   case ISD::INSERT_SUBVECTOR: {
6224     // Inserting undef into undef is still undef.
6225     if (N1.isUndef() && N2.isUndef())
6226       return getUNDEF(VT);
6227 
6228     EVT N2VT = N2.getValueType();
6229     assert(VT == N1.getValueType() &&
6230            "Dest and insert subvector source types must match!");
6231     assert(VT.isVector() && N2VT.isVector() &&
6232            "Insert subvector VTs must be vectors!");
6233     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6234            "Cannot insert a scalable vector into a fixed length vector!");
6235     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6236             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6237            "Insert subvector must be from smaller vector to larger vector!");
6238     assert(isa<ConstantSDNode>(N3) &&
6239            "Insert subvector index must be constant");
6240     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6241             (N2VT.getVectorMinNumElements() +
6242              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6243                 VT.getVectorMinNumElements()) &&
6244            "Insert subvector overflow!");
6245     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6246                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6247            "Constant index for INSERT_SUBVECTOR has an invalid size");
6248 
6249     // Trivial insertion.
6250     if (VT == N2VT)
6251       return N2;
6252 
6253     // If this is an insert of an extracted vector into an undef vector, we
6254     // can just use the input to the extract.
6255     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6256         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6257       return N2.getOperand(0);
6258     break;
6259   }
6260   case ISD::BITCAST:
6261     // Fold bit_convert nodes from a type to themselves.
6262     if (N1.getValueType() == VT)
6263       return N1;
6264     break;
6265   }
6266 
6267   // Memoize node if it doesn't produce a flag.
6268   SDNode *N;
6269   SDVTList VTs = getVTList(VT);
6270   SDValue Ops[] = {N1, N2, N3};
6271   if (VT != MVT::Glue) {
6272     FoldingSetNodeID ID;
6273     AddNodeIDNode(ID, Opcode, VTs, Ops);
6274     void *IP = nullptr;
6275     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6276       E->intersectFlagsWith(Flags);
6277       return SDValue(E, 0);
6278     }
6279 
6280     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6281     N->setFlags(Flags);
6282     createOperands(N, Ops);
6283     CSEMap.InsertNode(N, IP);
6284   } else {
6285     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6286     createOperands(N, Ops);
6287   }
6288 
6289   InsertNode(N);
6290   SDValue V = SDValue(N, 0);
6291   NewSDValueDbgMsg(V, "Creating new node: ", this);
6292   return V;
6293 }
6294 
6295 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6296                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6297   SDValue Ops[] = { N1, N2, N3, N4 };
6298   return getNode(Opcode, DL, VT, Ops);
6299 }
6300 
6301 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6302                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6303                               SDValue N5) {
6304   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6305   return getNode(Opcode, DL, VT, Ops);
6306 }
6307 
6308 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6309 /// the incoming stack arguments to be loaded from the stack.
6310 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6311   SmallVector<SDValue, 8> ArgChains;
6312 
6313   // Include the original chain at the beginning of the list. When this is
6314   // used by target LowerCall hooks, this helps legalize find the
6315   // CALLSEQ_BEGIN node.
6316   ArgChains.push_back(Chain);
6317 
6318   // Add a chain value for each stack argument.
6319   for (SDNode *U : getEntryNode().getNode()->uses())
6320     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6321       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6322         if (FI->getIndex() < 0)
6323           ArgChains.push_back(SDValue(L, 1));
6324 
6325   // Build a tokenfactor for all the chains.
6326   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6327 }
6328 
6329 /// getMemsetValue - Vectorized representation of the memset value
6330 /// operand.
6331 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6332                               const SDLoc &dl) {
6333   assert(!Value.isUndef());
6334 
6335   unsigned NumBits = VT.getScalarSizeInBits();
6336   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6337     assert(C->getAPIntValue().getBitWidth() == 8);
6338     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6339     if (VT.isInteger()) {
6340       bool IsOpaque = VT.getSizeInBits() > 64 ||
6341           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6342       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6343     }
6344     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6345                              VT);
6346   }
6347 
6348   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6349   EVT IntVT = VT.getScalarType();
6350   if (!IntVT.isInteger())
6351     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6352 
6353   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6354   if (NumBits > 8) {
6355     // Use a multiplication with 0x010101... to extend the input to the
6356     // required length.
6357     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6358     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6359                         DAG.getConstant(Magic, dl, IntVT));
6360   }
6361 
6362   if (VT != Value.getValueType() && !VT.isInteger())
6363     Value = DAG.getBitcast(VT.getScalarType(), Value);
6364   if (VT != Value.getValueType())
6365     Value = DAG.getSplatBuildVector(VT, dl, Value);
6366 
6367   return Value;
6368 }
6369 
6370 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6371 /// used when a memcpy is turned into a memset when the source is a constant
6372 /// string ptr.
6373 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6374                                   const TargetLowering &TLI,
6375                                   const ConstantDataArraySlice &Slice) {
6376   // Handle vector with all elements zero.
6377   if (Slice.Array == nullptr) {
6378     if (VT.isInteger())
6379       return DAG.getConstant(0, dl, VT);
6380     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6381       return DAG.getConstantFP(0.0, dl, VT);
6382     if (VT.isVector()) {
6383       unsigned NumElts = VT.getVectorNumElements();
6384       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6385       return DAG.getNode(ISD::BITCAST, dl, VT,
6386                          DAG.getConstant(0, dl,
6387                                          EVT::getVectorVT(*DAG.getContext(),
6388                                                           EltVT, NumElts)));
6389     }
6390     llvm_unreachable("Expected type!");
6391   }
6392 
6393   assert(!VT.isVector() && "Can't handle vector type here!");
6394   unsigned NumVTBits = VT.getSizeInBits();
6395   unsigned NumVTBytes = NumVTBits / 8;
6396   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6397 
6398   APInt Val(NumVTBits, 0);
6399   if (DAG.getDataLayout().isLittleEndian()) {
6400     for (unsigned i = 0; i != NumBytes; ++i)
6401       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6402   } else {
6403     for (unsigned i = 0; i != NumBytes; ++i)
6404       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6405   }
6406 
6407   // If the "cost" of materializing the integer immediate is less than the cost
6408   // of a load, then it is cost effective to turn the load into the immediate.
6409   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6410   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6411     return DAG.getConstant(Val, dl, VT);
6412   return SDValue();
6413 }
6414 
6415 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6416                                            const SDLoc &DL,
6417                                            const SDNodeFlags Flags) {
6418   EVT VT = Base.getValueType();
6419   SDValue Index;
6420 
6421   if (Offset.isScalable())
6422     Index = getVScale(DL, Base.getValueType(),
6423                       APInt(Base.getValueSizeInBits().getFixedSize(),
6424                             Offset.getKnownMinSize()));
6425   else
6426     Index = getConstant(Offset.getFixedSize(), DL, VT);
6427 
6428   return getMemBasePlusOffset(Base, Index, DL, Flags);
6429 }
6430 
6431 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6432                                            const SDLoc &DL,
6433                                            const SDNodeFlags Flags) {
6434   assert(Offset.getValueType().isInteger());
6435   EVT BasePtrVT = Ptr.getValueType();
6436   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6437 }
6438 
6439 /// Returns true if memcpy source is constant data.
6440 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6441   uint64_t SrcDelta = 0;
6442   GlobalAddressSDNode *G = nullptr;
6443   if (Src.getOpcode() == ISD::GlobalAddress)
6444     G = cast<GlobalAddressSDNode>(Src);
6445   else if (Src.getOpcode() == ISD::ADD &&
6446            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6447            Src.getOperand(1).getOpcode() == ISD::Constant) {
6448     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6449     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6450   }
6451   if (!G)
6452     return false;
6453 
6454   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6455                                   SrcDelta + G->getOffset());
6456 }
6457 
6458 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6459                                       SelectionDAG &DAG) {
6460   // On Darwin, -Os means optimize for size without hurting performance, so
6461   // only really optimize for size when -Oz (MinSize) is used.
6462   if (MF.getTarget().getTargetTriple().isOSDarwin())
6463     return MF.getFunction().hasMinSize();
6464   return DAG.shouldOptForSize();
6465 }
6466 
6467 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6468                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6469                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6470                           SmallVector<SDValue, 16> &OutStoreChains) {
6471   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6472   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6473   SmallVector<SDValue, 16> GluedLoadChains;
6474   for (unsigned i = From; i < To; ++i) {
6475     OutChains.push_back(OutLoadChains[i]);
6476     GluedLoadChains.push_back(OutLoadChains[i]);
6477   }
6478 
6479   // Chain for all loads.
6480   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6481                                   GluedLoadChains);
6482 
6483   for (unsigned i = From; i < To; ++i) {
6484     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6485     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6486                                   ST->getBasePtr(), ST->getMemoryVT(),
6487                                   ST->getMemOperand());
6488     OutChains.push_back(NewStore);
6489   }
6490 }
6491 
6492 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6493                                        SDValue Chain, SDValue Dst, SDValue Src,
6494                                        uint64_t Size, Align Alignment,
6495                                        bool isVol, bool AlwaysInline,
6496                                        MachinePointerInfo DstPtrInfo,
6497                                        MachinePointerInfo SrcPtrInfo,
6498                                        const AAMDNodes &AAInfo) {
6499   // Turn a memcpy of undef to nop.
6500   // FIXME: We need to honor volatile even is Src is undef.
6501   if (Src.isUndef())
6502     return Chain;
6503 
6504   // Expand memcpy to a series of load and store ops if the size operand falls
6505   // below a certain threshold.
6506   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6507   // rather than maybe a humongous number of loads and stores.
6508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6509   const DataLayout &DL = DAG.getDataLayout();
6510   LLVMContext &C = *DAG.getContext();
6511   std::vector<EVT> MemOps;
6512   bool DstAlignCanChange = false;
6513   MachineFunction &MF = DAG.getMachineFunction();
6514   MachineFrameInfo &MFI = MF.getFrameInfo();
6515   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6516   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6517   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6518     DstAlignCanChange = true;
6519   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6520   if (!SrcAlign || Alignment > *SrcAlign)
6521     SrcAlign = Alignment;
6522   assert(SrcAlign && "SrcAlign must be set");
6523   ConstantDataArraySlice Slice;
6524   // If marked as volatile, perform a copy even when marked as constant.
6525   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6526   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6527   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6528   const MemOp Op = isZeroConstant
6529                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6530                                     /*IsZeroMemset*/ true, isVol)
6531                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6532                                      *SrcAlign, isVol, CopyFromConstant);
6533   if (!TLI.findOptimalMemOpLowering(
6534           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6535           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6536     return SDValue();
6537 
6538   if (DstAlignCanChange) {
6539     Type *Ty = MemOps[0].getTypeForEVT(C);
6540     Align NewAlign = DL.getABITypeAlign(Ty);
6541 
6542     // Don't promote to an alignment that would require dynamic stack
6543     // realignment.
6544     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6545     if (!TRI->hasStackRealignment(MF))
6546       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6547         NewAlign = NewAlign / 2;
6548 
6549     if (NewAlign > Alignment) {
6550       // Give the stack frame object a larger alignment if needed.
6551       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6552         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6553       Alignment = NewAlign;
6554     }
6555   }
6556 
6557   // Prepare AAInfo for loads/stores after lowering this memcpy.
6558   AAMDNodes NewAAInfo = AAInfo;
6559   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6560 
6561   MachineMemOperand::Flags MMOFlags =
6562       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6563   SmallVector<SDValue, 16> OutLoadChains;
6564   SmallVector<SDValue, 16> OutStoreChains;
6565   SmallVector<SDValue, 32> OutChains;
6566   unsigned NumMemOps = MemOps.size();
6567   uint64_t SrcOff = 0, DstOff = 0;
6568   for (unsigned i = 0; i != NumMemOps; ++i) {
6569     EVT VT = MemOps[i];
6570     unsigned VTSize = VT.getSizeInBits() / 8;
6571     SDValue Value, Store;
6572 
6573     if (VTSize > Size) {
6574       // Issuing an unaligned load / store pair  that overlaps with the previous
6575       // pair. Adjust the offset accordingly.
6576       assert(i == NumMemOps-1 && i != 0);
6577       SrcOff -= VTSize - Size;
6578       DstOff -= VTSize - Size;
6579     }
6580 
6581     if (CopyFromConstant &&
6582         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6583       // It's unlikely a store of a vector immediate can be done in a single
6584       // instruction. It would require a load from a constantpool first.
6585       // We only handle zero vectors here.
6586       // FIXME: Handle other cases where store of vector immediate is done in
6587       // a single instruction.
6588       ConstantDataArraySlice SubSlice;
6589       if (SrcOff < Slice.Length) {
6590         SubSlice = Slice;
6591         SubSlice.move(SrcOff);
6592       } else {
6593         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6594         SubSlice.Array = nullptr;
6595         SubSlice.Offset = 0;
6596         SubSlice.Length = VTSize;
6597       }
6598       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6599       if (Value.getNode()) {
6600         Store = DAG.getStore(
6601             Chain, dl, Value,
6602             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6603             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6604         OutChains.push_back(Store);
6605       }
6606     }
6607 
6608     if (!Store.getNode()) {
6609       // The type might not be legal for the target.  This should only happen
6610       // if the type is smaller than a legal type, as on PPC, so the right
6611       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6612       // to Load/Store if NVT==VT.
6613       // FIXME does the case above also need this?
6614       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6615       assert(NVT.bitsGE(VT));
6616 
6617       bool isDereferenceable =
6618         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6619       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6620       if (isDereferenceable)
6621         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6622 
6623       Value = DAG.getExtLoad(
6624           ISD::EXTLOAD, dl, NVT, Chain,
6625           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6626           SrcPtrInfo.getWithOffset(SrcOff), VT,
6627           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6628       OutLoadChains.push_back(Value.getValue(1));
6629 
6630       Store = DAG.getTruncStore(
6631           Chain, dl, Value,
6632           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6633           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6634       OutStoreChains.push_back(Store);
6635     }
6636     SrcOff += VTSize;
6637     DstOff += VTSize;
6638     Size -= VTSize;
6639   }
6640 
6641   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6642                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6643   unsigned NumLdStInMemcpy = OutStoreChains.size();
6644 
6645   if (NumLdStInMemcpy) {
6646     // It may be that memcpy might be converted to memset if it's memcpy
6647     // of constants. In such a case, we won't have loads and stores, but
6648     // just stores. In the absence of loads, there is nothing to gang up.
6649     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6650       // If target does not care, just leave as it.
6651       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6652         OutChains.push_back(OutLoadChains[i]);
6653         OutChains.push_back(OutStoreChains[i]);
6654       }
6655     } else {
6656       // Ld/St less than/equal limit set by target.
6657       if (NumLdStInMemcpy <= GluedLdStLimit) {
6658           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6659                                         NumLdStInMemcpy, OutLoadChains,
6660                                         OutStoreChains);
6661       } else {
6662         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6663         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6664         unsigned GlueIter = 0;
6665 
6666         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6667           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6668           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6669 
6670           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6671                                        OutLoadChains, OutStoreChains);
6672           GlueIter += GluedLdStLimit;
6673         }
6674 
6675         // Residual ld/st.
6676         if (RemainingLdStInMemcpy) {
6677           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6678                                         RemainingLdStInMemcpy, OutLoadChains,
6679                                         OutStoreChains);
6680         }
6681       }
6682     }
6683   }
6684   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6685 }
6686 
6687 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6688                                         SDValue Chain, SDValue Dst, SDValue Src,
6689                                         uint64_t Size, Align Alignment,
6690                                         bool isVol, bool AlwaysInline,
6691                                         MachinePointerInfo DstPtrInfo,
6692                                         MachinePointerInfo SrcPtrInfo,
6693                                         const AAMDNodes &AAInfo) {
6694   // Turn a memmove of undef to nop.
6695   // FIXME: We need to honor volatile even is Src is undef.
6696   if (Src.isUndef())
6697     return Chain;
6698 
6699   // Expand memmove to a series of load and store ops if the size operand falls
6700   // below a certain threshold.
6701   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6702   const DataLayout &DL = DAG.getDataLayout();
6703   LLVMContext &C = *DAG.getContext();
6704   std::vector<EVT> MemOps;
6705   bool DstAlignCanChange = false;
6706   MachineFunction &MF = DAG.getMachineFunction();
6707   MachineFrameInfo &MFI = MF.getFrameInfo();
6708   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6709   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6710   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6711     DstAlignCanChange = true;
6712   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6713   if (!SrcAlign || Alignment > *SrcAlign)
6714     SrcAlign = Alignment;
6715   assert(SrcAlign && "SrcAlign must be set");
6716   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6717   if (!TLI.findOptimalMemOpLowering(
6718           MemOps, Limit,
6719           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6720                       /*IsVolatile*/ true),
6721           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6722           MF.getFunction().getAttributes()))
6723     return SDValue();
6724 
6725   if (DstAlignCanChange) {
6726     Type *Ty = MemOps[0].getTypeForEVT(C);
6727     Align NewAlign = DL.getABITypeAlign(Ty);
6728     if (NewAlign > Alignment) {
6729       // Give the stack frame object a larger alignment if needed.
6730       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6731         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6732       Alignment = NewAlign;
6733     }
6734   }
6735 
6736   // Prepare AAInfo for loads/stores after lowering this memmove.
6737   AAMDNodes NewAAInfo = AAInfo;
6738   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6739 
6740   MachineMemOperand::Flags MMOFlags =
6741       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6742   uint64_t SrcOff = 0, DstOff = 0;
6743   SmallVector<SDValue, 8> LoadValues;
6744   SmallVector<SDValue, 8> LoadChains;
6745   SmallVector<SDValue, 8> OutChains;
6746   unsigned NumMemOps = MemOps.size();
6747   for (unsigned i = 0; i < NumMemOps; i++) {
6748     EVT VT = MemOps[i];
6749     unsigned VTSize = VT.getSizeInBits() / 8;
6750     SDValue Value;
6751 
6752     bool isDereferenceable =
6753       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6754     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6755     if (isDereferenceable)
6756       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6757 
6758     Value = DAG.getLoad(
6759         VT, dl, Chain,
6760         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6761         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6762     LoadValues.push_back(Value);
6763     LoadChains.push_back(Value.getValue(1));
6764     SrcOff += VTSize;
6765   }
6766   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6767   OutChains.clear();
6768   for (unsigned i = 0; i < NumMemOps; i++) {
6769     EVT VT = MemOps[i];
6770     unsigned VTSize = VT.getSizeInBits() / 8;
6771     SDValue Store;
6772 
6773     Store = DAG.getStore(
6774         Chain, dl, LoadValues[i],
6775         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6776         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6777     OutChains.push_back(Store);
6778     DstOff += VTSize;
6779   }
6780 
6781   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6782 }
6783 
6784 /// Lower the call to 'memset' intrinsic function into a series of store
6785 /// operations.
6786 ///
6787 /// \param DAG Selection DAG where lowered code is placed.
6788 /// \param dl Link to corresponding IR location.
6789 /// \param Chain Control flow dependency.
6790 /// \param Dst Pointer to destination memory location.
6791 /// \param Src Value of byte to write into the memory.
6792 /// \param Size Number of bytes to write.
6793 /// \param Alignment Alignment of the destination in bytes.
6794 /// \param isVol True if destination is volatile.
6795 /// \param DstPtrInfo IR information on the memory pointer.
6796 /// \returns New head in the control flow, if lowering was successful, empty
6797 /// SDValue otherwise.
6798 ///
6799 /// The function tries to replace 'llvm.memset' intrinsic with several store
6800 /// operations and value calculation code. This is usually profitable for small
6801 /// memory size.
6802 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6803                                SDValue Chain, SDValue Dst, SDValue Src,
6804                                uint64_t Size, Align Alignment, bool isVol,
6805                                MachinePointerInfo DstPtrInfo,
6806                                const AAMDNodes &AAInfo) {
6807   // Turn a memset of undef to nop.
6808   // FIXME: We need to honor volatile even is Src is undef.
6809   if (Src.isUndef())
6810     return Chain;
6811 
6812   // Expand memset to a series of load/store ops if the size operand
6813   // falls below a certain threshold.
6814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6815   std::vector<EVT> MemOps;
6816   bool DstAlignCanChange = false;
6817   MachineFunction &MF = DAG.getMachineFunction();
6818   MachineFrameInfo &MFI = MF.getFrameInfo();
6819   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6820   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6821   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6822     DstAlignCanChange = true;
6823   bool IsZeroVal =
6824       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6825   if (!TLI.findOptimalMemOpLowering(
6826           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6827           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6828           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6829     return SDValue();
6830 
6831   if (DstAlignCanChange) {
6832     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6833     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6834     if (NewAlign > Alignment) {
6835       // Give the stack frame object a larger alignment if needed.
6836       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6837         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6838       Alignment = NewAlign;
6839     }
6840   }
6841 
6842   SmallVector<SDValue, 8> OutChains;
6843   uint64_t DstOff = 0;
6844   unsigned NumMemOps = MemOps.size();
6845 
6846   // Find the largest store and generate the bit pattern for it.
6847   EVT LargestVT = MemOps[0];
6848   for (unsigned i = 1; i < NumMemOps; i++)
6849     if (MemOps[i].bitsGT(LargestVT))
6850       LargestVT = MemOps[i];
6851   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6852 
6853   // Prepare AAInfo for loads/stores after lowering this memset.
6854   AAMDNodes NewAAInfo = AAInfo;
6855   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6856 
6857   for (unsigned i = 0; i < NumMemOps; i++) {
6858     EVT VT = MemOps[i];
6859     unsigned VTSize = VT.getSizeInBits() / 8;
6860     if (VTSize > Size) {
6861       // Issuing an unaligned load / store pair  that overlaps with the previous
6862       // pair. Adjust the offset accordingly.
6863       assert(i == NumMemOps-1 && i != 0);
6864       DstOff -= VTSize - Size;
6865     }
6866 
6867     // If this store is smaller than the largest store see whether we can get
6868     // the smaller value for free with a truncate.
6869     SDValue Value = MemSetValue;
6870     if (VT.bitsLT(LargestVT)) {
6871       if (!LargestVT.isVector() && !VT.isVector() &&
6872           TLI.isTruncateFree(LargestVT, VT))
6873         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6874       else
6875         Value = getMemsetValue(Src, VT, DAG, dl);
6876     }
6877     assert(Value.getValueType() == VT && "Value with wrong type.");
6878     SDValue Store = DAG.getStore(
6879         Chain, dl, Value,
6880         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6881         DstPtrInfo.getWithOffset(DstOff), Alignment,
6882         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6883         NewAAInfo);
6884     OutChains.push_back(Store);
6885     DstOff += VT.getSizeInBits() / 8;
6886     Size -= VTSize;
6887   }
6888 
6889   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6890 }
6891 
6892 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6893                                             unsigned AS) {
6894   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6895   // pointer operands can be losslessly bitcasted to pointers of address space 0
6896   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6897     report_fatal_error("cannot lower memory intrinsic in address space " +
6898                        Twine(AS));
6899   }
6900 }
6901 
6902 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6903                                 SDValue Src, SDValue Size, Align Alignment,
6904                                 bool isVol, bool AlwaysInline, bool isTailCall,
6905                                 MachinePointerInfo DstPtrInfo,
6906                                 MachinePointerInfo SrcPtrInfo,
6907                                 const AAMDNodes &AAInfo) {
6908   // Check to see if we should lower the memcpy to loads and stores first.
6909   // For cases within the target-specified limits, this is the best choice.
6910   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6911   if (ConstantSize) {
6912     // Memcpy with size zero? Just return the original chain.
6913     if (ConstantSize->isZero())
6914       return Chain;
6915 
6916     SDValue Result = getMemcpyLoadsAndStores(
6917         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6918         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6919     if (Result.getNode())
6920       return Result;
6921   }
6922 
6923   // Then check to see if we should lower the memcpy with target-specific
6924   // code. If the target chooses to do this, this is the next best.
6925   if (TSI) {
6926     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6927         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6928         DstPtrInfo, SrcPtrInfo);
6929     if (Result.getNode())
6930       return Result;
6931   }
6932 
6933   // If we really need inline code and the target declined to provide it,
6934   // use a (potentially long) sequence of loads and stores.
6935   if (AlwaysInline) {
6936     assert(ConstantSize && "AlwaysInline requires a constant size!");
6937     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6938                                    ConstantSize->getZExtValue(), Alignment,
6939                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6940   }
6941 
6942   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6943   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6944 
6945   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6946   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6947   // respect volatile, so they may do things like read or write memory
6948   // beyond the given memory regions. But fixing this isn't easy, and most
6949   // people don't care.
6950 
6951   // Emit a library call.
6952   TargetLowering::ArgListTy Args;
6953   TargetLowering::ArgListEntry Entry;
6954   Entry.Ty = Type::getInt8PtrTy(*getContext());
6955   Entry.Node = Dst; Args.push_back(Entry);
6956   Entry.Node = Src; Args.push_back(Entry);
6957 
6958   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6959   Entry.Node = Size; Args.push_back(Entry);
6960   // FIXME: pass in SDLoc
6961   TargetLowering::CallLoweringInfo CLI(*this);
6962   CLI.setDebugLoc(dl)
6963       .setChain(Chain)
6964       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6965                     Dst.getValueType().getTypeForEVT(*getContext()),
6966                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6967                                       TLI->getPointerTy(getDataLayout())),
6968                     std::move(Args))
6969       .setDiscardResult()
6970       .setTailCall(isTailCall);
6971 
6972   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6973   return CallResult.second;
6974 }
6975 
6976 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6977                                       SDValue Dst, unsigned DstAlign,
6978                                       SDValue Src, unsigned SrcAlign,
6979                                       SDValue Size, Type *SizeTy,
6980                                       unsigned ElemSz, bool isTailCall,
6981                                       MachinePointerInfo DstPtrInfo,
6982                                       MachinePointerInfo SrcPtrInfo) {
6983   // Emit a library call.
6984   TargetLowering::ArgListTy Args;
6985   TargetLowering::ArgListEntry Entry;
6986   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6987   Entry.Node = Dst;
6988   Args.push_back(Entry);
6989 
6990   Entry.Node = Src;
6991   Args.push_back(Entry);
6992 
6993   Entry.Ty = SizeTy;
6994   Entry.Node = Size;
6995   Args.push_back(Entry);
6996 
6997   RTLIB::Libcall LibraryCall =
6998       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6999   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7000     report_fatal_error("Unsupported element size");
7001 
7002   TargetLowering::CallLoweringInfo CLI(*this);
7003   CLI.setDebugLoc(dl)
7004       .setChain(Chain)
7005       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7006                     Type::getVoidTy(*getContext()),
7007                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7008                                       TLI->getPointerTy(getDataLayout())),
7009                     std::move(Args))
7010       .setDiscardResult()
7011       .setTailCall(isTailCall);
7012 
7013   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7014   return CallResult.second;
7015 }
7016 
7017 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7018                                  SDValue Src, SDValue Size, Align Alignment,
7019                                  bool isVol, bool isTailCall,
7020                                  MachinePointerInfo DstPtrInfo,
7021                                  MachinePointerInfo SrcPtrInfo,
7022                                  const AAMDNodes &AAInfo) {
7023   // Check to see if we should lower the memmove to loads and stores first.
7024   // For cases within the target-specified limits, this is the best choice.
7025   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7026   if (ConstantSize) {
7027     // Memmove with size zero? Just return the original chain.
7028     if (ConstantSize->isZero())
7029       return Chain;
7030 
7031     SDValue Result = getMemmoveLoadsAndStores(
7032         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7033         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7034     if (Result.getNode())
7035       return Result;
7036   }
7037 
7038   // Then check to see if we should lower the memmove with target-specific
7039   // code. If the target chooses to do this, this is the next best.
7040   if (TSI) {
7041     SDValue Result =
7042         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7043                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7044     if (Result.getNode())
7045       return Result;
7046   }
7047 
7048   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7049   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7050 
7051   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7052   // not be safe.  See memcpy above for more details.
7053 
7054   // Emit a library call.
7055   TargetLowering::ArgListTy Args;
7056   TargetLowering::ArgListEntry Entry;
7057   Entry.Ty = Type::getInt8PtrTy(*getContext());
7058   Entry.Node = Dst; Args.push_back(Entry);
7059   Entry.Node = Src; Args.push_back(Entry);
7060 
7061   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7062   Entry.Node = Size; Args.push_back(Entry);
7063   // FIXME:  pass in SDLoc
7064   TargetLowering::CallLoweringInfo CLI(*this);
7065   CLI.setDebugLoc(dl)
7066       .setChain(Chain)
7067       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7068                     Dst.getValueType().getTypeForEVT(*getContext()),
7069                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7070                                       TLI->getPointerTy(getDataLayout())),
7071                     std::move(Args))
7072       .setDiscardResult()
7073       .setTailCall(isTailCall);
7074 
7075   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7076   return CallResult.second;
7077 }
7078 
7079 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7080                                        SDValue Dst, unsigned DstAlign,
7081                                        SDValue Src, unsigned SrcAlign,
7082                                        SDValue Size, Type *SizeTy,
7083                                        unsigned ElemSz, bool isTailCall,
7084                                        MachinePointerInfo DstPtrInfo,
7085                                        MachinePointerInfo SrcPtrInfo) {
7086   // Emit a library call.
7087   TargetLowering::ArgListTy Args;
7088   TargetLowering::ArgListEntry Entry;
7089   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7090   Entry.Node = Dst;
7091   Args.push_back(Entry);
7092 
7093   Entry.Node = Src;
7094   Args.push_back(Entry);
7095 
7096   Entry.Ty = SizeTy;
7097   Entry.Node = Size;
7098   Args.push_back(Entry);
7099 
7100   RTLIB::Libcall LibraryCall =
7101       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7102   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7103     report_fatal_error("Unsupported element size");
7104 
7105   TargetLowering::CallLoweringInfo CLI(*this);
7106   CLI.setDebugLoc(dl)
7107       .setChain(Chain)
7108       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7109                     Type::getVoidTy(*getContext()),
7110                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7111                                       TLI->getPointerTy(getDataLayout())),
7112                     std::move(Args))
7113       .setDiscardResult()
7114       .setTailCall(isTailCall);
7115 
7116   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7117   return CallResult.second;
7118 }
7119 
7120 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7121                                 SDValue Src, SDValue Size, Align Alignment,
7122                                 bool isVol, bool isTailCall,
7123                                 MachinePointerInfo DstPtrInfo,
7124                                 const AAMDNodes &AAInfo) {
7125   // Check to see if we should lower the memset to stores first.
7126   // For cases within the target-specified limits, this is the best choice.
7127   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7128   if (ConstantSize) {
7129     // Memset with size zero? Just return the original chain.
7130     if (ConstantSize->isZero())
7131       return Chain;
7132 
7133     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7134                                      ConstantSize->getZExtValue(), Alignment,
7135                                      isVol, DstPtrInfo, AAInfo);
7136 
7137     if (Result.getNode())
7138       return Result;
7139   }
7140 
7141   // Then check to see if we should lower the memset with target-specific
7142   // code. If the target chooses to do this, this is the next best.
7143   if (TSI) {
7144     SDValue Result = TSI->EmitTargetCodeForMemset(
7145         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7146     if (Result.getNode())
7147       return Result;
7148   }
7149 
7150   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7151 
7152   // Emit a library call.
7153   TargetLowering::ArgListTy Args;
7154   TargetLowering::ArgListEntry Entry;
7155   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7156   Args.push_back(Entry);
7157   Entry.Node = Src;
7158   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7159   Args.push_back(Entry);
7160   Entry.Node = Size;
7161   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7162   Args.push_back(Entry);
7163 
7164   // FIXME: pass in SDLoc
7165   TargetLowering::CallLoweringInfo CLI(*this);
7166   CLI.setDebugLoc(dl)
7167       .setChain(Chain)
7168       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7169                     Dst.getValueType().getTypeForEVT(*getContext()),
7170                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7171                                       TLI->getPointerTy(getDataLayout())),
7172                     std::move(Args))
7173       .setDiscardResult()
7174       .setTailCall(isTailCall);
7175 
7176   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7177   return CallResult.second;
7178 }
7179 
7180 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7181                                       SDValue Dst, unsigned DstAlign,
7182                                       SDValue Value, SDValue Size, Type *SizeTy,
7183                                       unsigned ElemSz, bool isTailCall,
7184                                       MachinePointerInfo DstPtrInfo) {
7185   // Emit a library call.
7186   TargetLowering::ArgListTy Args;
7187   TargetLowering::ArgListEntry Entry;
7188   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7189   Entry.Node = Dst;
7190   Args.push_back(Entry);
7191 
7192   Entry.Ty = Type::getInt8Ty(*getContext());
7193   Entry.Node = Value;
7194   Args.push_back(Entry);
7195 
7196   Entry.Ty = SizeTy;
7197   Entry.Node = Size;
7198   Args.push_back(Entry);
7199 
7200   RTLIB::Libcall LibraryCall =
7201       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7202   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7203     report_fatal_error("Unsupported element size");
7204 
7205   TargetLowering::CallLoweringInfo CLI(*this);
7206   CLI.setDebugLoc(dl)
7207       .setChain(Chain)
7208       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7209                     Type::getVoidTy(*getContext()),
7210                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7211                                       TLI->getPointerTy(getDataLayout())),
7212                     std::move(Args))
7213       .setDiscardResult()
7214       .setTailCall(isTailCall);
7215 
7216   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7217   return CallResult.second;
7218 }
7219 
7220 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7221                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7222                                 MachineMemOperand *MMO) {
7223   FoldingSetNodeID ID;
7224   ID.AddInteger(MemVT.getRawBits());
7225   AddNodeIDNode(ID, Opcode, VTList, Ops);
7226   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7227   void* IP = nullptr;
7228   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7229     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7230     return SDValue(E, 0);
7231   }
7232 
7233   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7234                                     VTList, MemVT, MMO);
7235   createOperands(N, Ops);
7236 
7237   CSEMap.InsertNode(N, IP);
7238   InsertNode(N);
7239   return SDValue(N, 0);
7240 }
7241 
7242 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7243                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7244                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7245                                        MachineMemOperand *MMO) {
7246   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7247          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7248   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7249 
7250   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7251   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7252 }
7253 
7254 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7255                                 SDValue Chain, SDValue Ptr, SDValue Val,
7256                                 MachineMemOperand *MMO) {
7257   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7258           Opcode == ISD::ATOMIC_LOAD_SUB ||
7259           Opcode == ISD::ATOMIC_LOAD_AND ||
7260           Opcode == ISD::ATOMIC_LOAD_CLR ||
7261           Opcode == ISD::ATOMIC_LOAD_OR ||
7262           Opcode == ISD::ATOMIC_LOAD_XOR ||
7263           Opcode == ISD::ATOMIC_LOAD_NAND ||
7264           Opcode == ISD::ATOMIC_LOAD_MIN ||
7265           Opcode == ISD::ATOMIC_LOAD_MAX ||
7266           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7267           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7268           Opcode == ISD::ATOMIC_LOAD_FADD ||
7269           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7270           Opcode == ISD::ATOMIC_SWAP ||
7271           Opcode == ISD::ATOMIC_STORE) &&
7272          "Invalid Atomic Op");
7273 
7274   EVT VT = Val.getValueType();
7275 
7276   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7277                                                getVTList(VT, MVT::Other);
7278   SDValue Ops[] = {Chain, Ptr, Val};
7279   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7280 }
7281 
7282 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7283                                 EVT VT, SDValue Chain, SDValue Ptr,
7284                                 MachineMemOperand *MMO) {
7285   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7286 
7287   SDVTList VTs = getVTList(VT, MVT::Other);
7288   SDValue Ops[] = {Chain, Ptr};
7289   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7290 }
7291 
7292 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7293 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7294   if (Ops.size() == 1)
7295     return Ops[0];
7296 
7297   SmallVector<EVT, 4> VTs;
7298   VTs.reserve(Ops.size());
7299   for (const SDValue &Op : Ops)
7300     VTs.push_back(Op.getValueType());
7301   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7302 }
7303 
7304 SDValue SelectionDAG::getMemIntrinsicNode(
7305     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7306     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7307     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7308   if (!Size && MemVT.isScalableVector())
7309     Size = MemoryLocation::UnknownSize;
7310   else if (!Size)
7311     Size = MemVT.getStoreSize();
7312 
7313   MachineFunction &MF = getMachineFunction();
7314   MachineMemOperand *MMO =
7315       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7316 
7317   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7318 }
7319 
7320 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7321                                           SDVTList VTList,
7322                                           ArrayRef<SDValue> Ops, EVT MemVT,
7323                                           MachineMemOperand *MMO) {
7324   assert((Opcode == ISD::INTRINSIC_VOID ||
7325           Opcode == ISD::INTRINSIC_W_CHAIN ||
7326           Opcode == ISD::PREFETCH ||
7327           ((int)Opcode <= std::numeric_limits<int>::max() &&
7328            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7329          "Opcode is not a memory-accessing opcode!");
7330 
7331   // Memoize the node unless it returns a flag.
7332   MemIntrinsicSDNode *N;
7333   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7334     FoldingSetNodeID ID;
7335     AddNodeIDNode(ID, Opcode, VTList, Ops);
7336     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7337         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7338     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7339     void *IP = nullptr;
7340     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7341       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7342       return SDValue(E, 0);
7343     }
7344 
7345     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7346                                       VTList, MemVT, MMO);
7347     createOperands(N, Ops);
7348 
7349   CSEMap.InsertNode(N, IP);
7350   } else {
7351     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7352                                       VTList, MemVT, MMO);
7353     createOperands(N, Ops);
7354   }
7355   InsertNode(N);
7356   SDValue V(N, 0);
7357   NewSDValueDbgMsg(V, "Creating new node: ", this);
7358   return V;
7359 }
7360 
7361 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7362                                       SDValue Chain, int FrameIndex,
7363                                       int64_t Size, int64_t Offset) {
7364   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7365   const auto VTs = getVTList(MVT::Other);
7366   SDValue Ops[2] = {
7367       Chain,
7368       getFrameIndex(FrameIndex,
7369                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7370                     true)};
7371 
7372   FoldingSetNodeID ID;
7373   AddNodeIDNode(ID, Opcode, VTs, Ops);
7374   ID.AddInteger(FrameIndex);
7375   ID.AddInteger(Size);
7376   ID.AddInteger(Offset);
7377   void *IP = nullptr;
7378   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7379     return SDValue(E, 0);
7380 
7381   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7382       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7383   createOperands(N, Ops);
7384   CSEMap.InsertNode(N, IP);
7385   InsertNode(N);
7386   SDValue V(N, 0);
7387   NewSDValueDbgMsg(V, "Creating new node: ", this);
7388   return V;
7389 }
7390 
7391 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7392                                          uint64_t Guid, uint64_t Index,
7393                                          uint32_t Attr) {
7394   const unsigned Opcode = ISD::PSEUDO_PROBE;
7395   const auto VTs = getVTList(MVT::Other);
7396   SDValue Ops[] = {Chain};
7397   FoldingSetNodeID ID;
7398   AddNodeIDNode(ID, Opcode, VTs, Ops);
7399   ID.AddInteger(Guid);
7400   ID.AddInteger(Index);
7401   void *IP = nullptr;
7402   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7403     return SDValue(E, 0);
7404 
7405   auto *N = newSDNode<PseudoProbeSDNode>(
7406       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7407   createOperands(N, Ops);
7408   CSEMap.InsertNode(N, IP);
7409   InsertNode(N);
7410   SDValue V(N, 0);
7411   NewSDValueDbgMsg(V, "Creating new node: ", this);
7412   return V;
7413 }
7414 
7415 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7416 /// MachinePointerInfo record from it.  This is particularly useful because the
7417 /// code generator has many cases where it doesn't bother passing in a
7418 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7419 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7420                                            SelectionDAG &DAG, SDValue Ptr,
7421                                            int64_t Offset = 0) {
7422   // If this is FI+Offset, we can model it.
7423   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7424     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7425                                              FI->getIndex(), Offset);
7426 
7427   // If this is (FI+Offset1)+Offset2, we can model it.
7428   if (Ptr.getOpcode() != ISD::ADD ||
7429       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7430       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7431     return Info;
7432 
7433   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7434   return MachinePointerInfo::getFixedStack(
7435       DAG.getMachineFunction(), FI,
7436       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7437 }
7438 
7439 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7440 /// MachinePointerInfo record from it.  This is particularly useful because the
7441 /// code generator has many cases where it doesn't bother passing in a
7442 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7443 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7444                                            SelectionDAG &DAG, SDValue Ptr,
7445                                            SDValue OffsetOp) {
7446   // If the 'Offset' value isn't a constant, we can't handle this.
7447   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7448     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7449   if (OffsetOp.isUndef())
7450     return InferPointerInfo(Info, DAG, Ptr);
7451   return Info;
7452 }
7453 
7454 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7455                               EVT VT, const SDLoc &dl, SDValue Chain,
7456                               SDValue Ptr, SDValue Offset,
7457                               MachinePointerInfo PtrInfo, EVT MemVT,
7458                               Align Alignment,
7459                               MachineMemOperand::Flags MMOFlags,
7460                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7461   assert(Chain.getValueType() == MVT::Other &&
7462         "Invalid chain type");
7463 
7464   MMOFlags |= MachineMemOperand::MOLoad;
7465   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7466   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7467   // clients.
7468   if (PtrInfo.V.isNull())
7469     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7470 
7471   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7472   MachineFunction &MF = getMachineFunction();
7473   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7474                                                    Alignment, AAInfo, Ranges);
7475   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7476 }
7477 
7478 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7479                               EVT VT, const SDLoc &dl, SDValue Chain,
7480                               SDValue Ptr, SDValue Offset, EVT MemVT,
7481                               MachineMemOperand *MMO) {
7482   if (VT == MemVT) {
7483     ExtType = ISD::NON_EXTLOAD;
7484   } else if (ExtType == ISD::NON_EXTLOAD) {
7485     assert(VT == MemVT && "Non-extending load from different memory type!");
7486   } else {
7487     // Extending load.
7488     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7489            "Should only be an extending load, not truncating!");
7490     assert(VT.isInteger() == MemVT.isInteger() &&
7491            "Cannot convert from FP to Int or Int -> FP!");
7492     assert(VT.isVector() == MemVT.isVector() &&
7493            "Cannot use an ext load to convert to or from a vector!");
7494     assert((!VT.isVector() ||
7495             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7496            "Cannot use an ext load to change the number of vector elements!");
7497   }
7498 
7499   bool Indexed = AM != ISD::UNINDEXED;
7500   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7501 
7502   SDVTList VTs = Indexed ?
7503     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7504   SDValue Ops[] = { Chain, Ptr, Offset };
7505   FoldingSetNodeID ID;
7506   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7507   ID.AddInteger(MemVT.getRawBits());
7508   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7509       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7510   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7511   void *IP = nullptr;
7512   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7513     cast<LoadSDNode>(E)->refineAlignment(MMO);
7514     return SDValue(E, 0);
7515   }
7516   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7517                                   ExtType, MemVT, MMO);
7518   createOperands(N, Ops);
7519 
7520   CSEMap.InsertNode(N, IP);
7521   InsertNode(N);
7522   SDValue V(N, 0);
7523   NewSDValueDbgMsg(V, "Creating new node: ", this);
7524   return V;
7525 }
7526 
7527 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7528                               SDValue Ptr, MachinePointerInfo PtrInfo,
7529                               MaybeAlign Alignment,
7530                               MachineMemOperand::Flags MMOFlags,
7531                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7532   SDValue Undef = getUNDEF(Ptr.getValueType());
7533   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7534                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7535 }
7536 
7537 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7538                               SDValue Ptr, MachineMemOperand *MMO) {
7539   SDValue Undef = getUNDEF(Ptr.getValueType());
7540   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7541                  VT, MMO);
7542 }
7543 
7544 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7545                                  EVT VT, SDValue Chain, SDValue Ptr,
7546                                  MachinePointerInfo PtrInfo, EVT MemVT,
7547                                  MaybeAlign Alignment,
7548                                  MachineMemOperand::Flags MMOFlags,
7549                                  const AAMDNodes &AAInfo) {
7550   SDValue Undef = getUNDEF(Ptr.getValueType());
7551   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7552                  MemVT, Alignment, MMOFlags, AAInfo);
7553 }
7554 
7555 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7556                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7557                                  MachineMemOperand *MMO) {
7558   SDValue Undef = getUNDEF(Ptr.getValueType());
7559   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7560                  MemVT, MMO);
7561 }
7562 
7563 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7564                                      SDValue Base, SDValue Offset,
7565                                      ISD::MemIndexedMode AM) {
7566   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7567   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7568   // Don't propagate the invariant or dereferenceable flags.
7569   auto MMOFlags =
7570       LD->getMemOperand()->getFlags() &
7571       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7572   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7573                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7574                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7575 }
7576 
7577 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7578                                SDValue Ptr, MachinePointerInfo PtrInfo,
7579                                Align Alignment,
7580                                MachineMemOperand::Flags MMOFlags,
7581                                const AAMDNodes &AAInfo) {
7582   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7583 
7584   MMOFlags |= MachineMemOperand::MOStore;
7585   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7586 
7587   if (PtrInfo.V.isNull())
7588     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7589 
7590   MachineFunction &MF = getMachineFunction();
7591   uint64_t Size =
7592       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7593   MachineMemOperand *MMO =
7594       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7595   return getStore(Chain, dl, Val, Ptr, MMO);
7596 }
7597 
7598 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7599                                SDValue Ptr, MachineMemOperand *MMO) {
7600   assert(Chain.getValueType() == MVT::Other &&
7601         "Invalid chain type");
7602   EVT VT = Val.getValueType();
7603   SDVTList VTs = getVTList(MVT::Other);
7604   SDValue Undef = getUNDEF(Ptr.getValueType());
7605   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7606   FoldingSetNodeID ID;
7607   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7608   ID.AddInteger(VT.getRawBits());
7609   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7610       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7611   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7612   void *IP = nullptr;
7613   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7614     cast<StoreSDNode>(E)->refineAlignment(MMO);
7615     return SDValue(E, 0);
7616   }
7617   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7618                                    ISD::UNINDEXED, false, VT, MMO);
7619   createOperands(N, Ops);
7620 
7621   CSEMap.InsertNode(N, IP);
7622   InsertNode(N);
7623   SDValue V(N, 0);
7624   NewSDValueDbgMsg(V, "Creating new node: ", this);
7625   return V;
7626 }
7627 
7628 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7629                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7630                                     EVT SVT, Align Alignment,
7631                                     MachineMemOperand::Flags MMOFlags,
7632                                     const AAMDNodes &AAInfo) {
7633   assert(Chain.getValueType() == MVT::Other &&
7634         "Invalid chain type");
7635 
7636   MMOFlags |= MachineMemOperand::MOStore;
7637   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7638 
7639   if (PtrInfo.V.isNull())
7640     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7641 
7642   MachineFunction &MF = getMachineFunction();
7643   MachineMemOperand *MMO = MF.getMachineMemOperand(
7644       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7645       Alignment, AAInfo);
7646   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7647 }
7648 
7649 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7650                                     SDValue Ptr, EVT SVT,
7651                                     MachineMemOperand *MMO) {
7652   EVT VT = Val.getValueType();
7653 
7654   assert(Chain.getValueType() == MVT::Other &&
7655         "Invalid chain type");
7656   if (VT == SVT)
7657     return getStore(Chain, dl, Val, Ptr, MMO);
7658 
7659   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7660          "Should only be a truncating store, not extending!");
7661   assert(VT.isInteger() == SVT.isInteger() &&
7662          "Can't do FP-INT conversion!");
7663   assert(VT.isVector() == SVT.isVector() &&
7664          "Cannot use trunc store to convert to or from a vector!");
7665   assert((!VT.isVector() ||
7666           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7667          "Cannot use trunc store to change the number of vector elements!");
7668 
7669   SDVTList VTs = getVTList(MVT::Other);
7670   SDValue Undef = getUNDEF(Ptr.getValueType());
7671   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7672   FoldingSetNodeID ID;
7673   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7674   ID.AddInteger(SVT.getRawBits());
7675   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7676       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7677   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7678   void *IP = nullptr;
7679   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7680     cast<StoreSDNode>(E)->refineAlignment(MMO);
7681     return SDValue(E, 0);
7682   }
7683   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7684                                    ISD::UNINDEXED, true, SVT, MMO);
7685   createOperands(N, Ops);
7686 
7687   CSEMap.InsertNode(N, IP);
7688   InsertNode(N);
7689   SDValue V(N, 0);
7690   NewSDValueDbgMsg(V, "Creating new node: ", this);
7691   return V;
7692 }
7693 
7694 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7695                                       SDValue Base, SDValue Offset,
7696                                       ISD::MemIndexedMode AM) {
7697   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7698   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7699   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7700   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7701   FoldingSetNodeID ID;
7702   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7703   ID.AddInteger(ST->getMemoryVT().getRawBits());
7704   ID.AddInteger(ST->getRawSubclassData());
7705   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7706   void *IP = nullptr;
7707   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7708     return SDValue(E, 0);
7709 
7710   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7711                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7712                                    ST->getMemOperand());
7713   createOperands(N, Ops);
7714 
7715   CSEMap.InsertNode(N, IP);
7716   InsertNode(N);
7717   SDValue V(N, 0);
7718   NewSDValueDbgMsg(V, "Creating new node: ", this);
7719   return V;
7720 }
7721 
7722 SDValue SelectionDAG::getLoadVP(
7723     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7724     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7725     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7726     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7727     const MDNode *Ranges, bool IsExpanding) {
7728   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7729 
7730   MMOFlags |= MachineMemOperand::MOLoad;
7731   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7732   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7733   // clients.
7734   if (PtrInfo.V.isNull())
7735     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7736 
7737   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7738   MachineFunction &MF = getMachineFunction();
7739   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7740                                                    Alignment, AAInfo, Ranges);
7741   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7742                    MMO, IsExpanding);
7743 }
7744 
7745 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7746                                 ISD::LoadExtType ExtType, EVT VT,
7747                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7748                                 SDValue Offset, SDValue Mask, SDValue EVL,
7749                                 EVT MemVT, MachineMemOperand *MMO,
7750                                 bool IsExpanding) {
7751   bool Indexed = AM != ISD::UNINDEXED;
7752   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7753 
7754   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7755                          : getVTList(VT, MVT::Other);
7756   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7757   FoldingSetNodeID ID;
7758   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7759   ID.AddInteger(VT.getRawBits());
7760   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7761       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7762   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7763   void *IP = nullptr;
7764   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7765     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7766     return SDValue(E, 0);
7767   }
7768   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7769                                     ExtType, IsExpanding, MemVT, MMO);
7770   createOperands(N, Ops);
7771 
7772   CSEMap.InsertNode(N, IP);
7773   InsertNode(N);
7774   SDValue V(N, 0);
7775   NewSDValueDbgMsg(V, "Creating new node: ", this);
7776   return V;
7777 }
7778 
7779 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7780                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7781                                 MachinePointerInfo PtrInfo,
7782                                 MaybeAlign Alignment,
7783                                 MachineMemOperand::Flags MMOFlags,
7784                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7785                                 bool IsExpanding) {
7786   SDValue Undef = getUNDEF(Ptr.getValueType());
7787   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7788                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7789                    IsExpanding);
7790 }
7791 
7792 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7793                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7794                                 MachineMemOperand *MMO, bool IsExpanding) {
7795   SDValue Undef = getUNDEF(Ptr.getValueType());
7796   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7797                    Mask, EVL, VT, MMO, IsExpanding);
7798 }
7799 
7800 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7801                                    EVT VT, SDValue Chain, SDValue Ptr,
7802                                    SDValue Mask, SDValue EVL,
7803                                    MachinePointerInfo PtrInfo, EVT MemVT,
7804                                    MaybeAlign Alignment,
7805                                    MachineMemOperand::Flags MMOFlags,
7806                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7807   SDValue Undef = getUNDEF(Ptr.getValueType());
7808   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7809                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7810                    IsExpanding);
7811 }
7812 
7813 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7814                                    EVT VT, SDValue Chain, SDValue Ptr,
7815                                    SDValue Mask, SDValue EVL, EVT MemVT,
7816                                    MachineMemOperand *MMO, bool IsExpanding) {
7817   SDValue Undef = getUNDEF(Ptr.getValueType());
7818   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7819                    EVL, MemVT, MMO, IsExpanding);
7820 }
7821 
7822 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7823                                        SDValue Base, SDValue Offset,
7824                                        ISD::MemIndexedMode AM) {
7825   auto *LD = cast<VPLoadSDNode>(OrigLoad);
7826   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7827   // Don't propagate the invariant or dereferenceable flags.
7828   auto MMOFlags =
7829       LD->getMemOperand()->getFlags() &
7830       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7831   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7832                    LD->getChain(), Base, Offset, LD->getMask(),
7833                    LD->getVectorLength(), LD->getPointerInfo(),
7834                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7835                    nullptr, LD->isExpandingLoad());
7836 }
7837 
7838 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7839                                  SDValue Ptr, SDValue Offset, SDValue Mask,
7840                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
7841                                  ISD::MemIndexedMode AM, bool IsTruncating,
7842                                  bool IsCompressing) {
7843   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7844   bool Indexed = AM != ISD::UNINDEXED;
7845   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
7846   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
7847                          : getVTList(MVT::Other);
7848   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
7849   FoldingSetNodeID ID;
7850   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7851   ID.AddInteger(MemVT.getRawBits());
7852   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7853       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7854   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7855   void *IP = nullptr;
7856   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7857     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7858     return SDValue(E, 0);
7859   }
7860   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7861                                      IsTruncating, IsCompressing, MemVT, MMO);
7862   createOperands(N, Ops);
7863 
7864   CSEMap.InsertNode(N, IP);
7865   InsertNode(N);
7866   SDValue V(N, 0);
7867   NewSDValueDbgMsg(V, "Creating new node: ", this);
7868   return V;
7869 }
7870 
7871 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7872                                       SDValue Val, SDValue Ptr, SDValue Mask,
7873                                       SDValue EVL, MachinePointerInfo PtrInfo,
7874                                       EVT SVT, Align Alignment,
7875                                       MachineMemOperand::Flags MMOFlags,
7876                                       const AAMDNodes &AAInfo,
7877                                       bool IsCompressing) {
7878   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7879 
7880   MMOFlags |= MachineMemOperand::MOStore;
7881   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7882 
7883   if (PtrInfo.V.isNull())
7884     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7885 
7886   MachineFunction &MF = getMachineFunction();
7887   MachineMemOperand *MMO = MF.getMachineMemOperand(
7888       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7889       Alignment, AAInfo);
7890   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7891                          IsCompressing);
7892 }
7893 
7894 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7895                                       SDValue Val, SDValue Ptr, SDValue Mask,
7896                                       SDValue EVL, EVT SVT,
7897                                       MachineMemOperand *MMO,
7898                                       bool IsCompressing) {
7899   EVT VT = Val.getValueType();
7900 
7901   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7902   if (VT == SVT)
7903     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
7904                       EVL, VT, MMO, ISD::UNINDEXED,
7905                       /*IsTruncating*/ false, IsCompressing);
7906 
7907   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7908          "Should only be a truncating store, not extending!");
7909   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
7910   assert(VT.isVector() == SVT.isVector() &&
7911          "Cannot use trunc store to convert to or from a vector!");
7912   assert((!VT.isVector() ||
7913           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7914          "Cannot use trunc store to change the number of vector elements!");
7915 
7916   SDVTList VTs = getVTList(MVT::Other);
7917   SDValue Undef = getUNDEF(Ptr.getValueType());
7918   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7919   FoldingSetNodeID ID;
7920   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7921   ID.AddInteger(SVT.getRawBits());
7922   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7923       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
7924   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7925   void *IP = nullptr;
7926   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7927     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7928     return SDValue(E, 0);
7929   }
7930   auto *N =
7931       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7932                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
7933   createOperands(N, Ops);
7934 
7935   CSEMap.InsertNode(N, IP);
7936   InsertNode(N);
7937   SDValue V(N, 0);
7938   NewSDValueDbgMsg(V, "Creating new node: ", this);
7939   return V;
7940 }
7941 
7942 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
7943                                         SDValue Base, SDValue Offset,
7944                                         ISD::MemIndexedMode AM) {
7945   auto *ST = cast<VPStoreSDNode>(OrigStore);
7946   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
7947   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7948   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
7949                    Offset,         ST->getMask(),  ST->getVectorLength()};
7950   FoldingSetNodeID ID;
7951   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7952   ID.AddInteger(ST->getMemoryVT().getRawBits());
7953   ID.AddInteger(ST->getRawSubclassData());
7954   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7955   void *IP = nullptr;
7956   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7957     return SDValue(E, 0);
7958 
7959   auto *N = newSDNode<VPStoreSDNode>(
7960       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
7961       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
7962   createOperands(N, Ops);
7963 
7964   CSEMap.InsertNode(N, IP);
7965   InsertNode(N);
7966   SDValue V(N, 0);
7967   NewSDValueDbgMsg(V, "Creating new node: ", this);
7968   return V;
7969 }
7970 
7971 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7972                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
7973                                   ISD::MemIndexType IndexType) {
7974   assert(Ops.size() == 6 && "Incompatible number of operands");
7975 
7976   FoldingSetNodeID ID;
7977   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
7978   ID.AddInteger(VT.getRawBits());
7979   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
7980       dl.getIROrder(), VTs, VT, MMO, IndexType));
7981   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7982   void *IP = nullptr;
7983   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7984     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
7985     return SDValue(E, 0);
7986   }
7987 
7988   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7989                                       VT, MMO, IndexType);
7990   createOperands(N, Ops);
7991 
7992   assert(N->getMask().getValueType().getVectorElementCount() ==
7993              N->getValueType(0).getVectorElementCount() &&
7994          "Vector width mismatch between mask and data");
7995   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7996              N->getValueType(0).getVectorElementCount().isScalable() &&
7997          "Scalable flags of index and data do not match");
7998   assert(ElementCount::isKnownGE(
7999              N->getIndex().getValueType().getVectorElementCount(),
8000              N->getValueType(0).getVectorElementCount()) &&
8001          "Vector width mismatch between index and data");
8002   assert(isa<ConstantSDNode>(N->getScale()) &&
8003          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8004          "Scale should be a constant power of 2");
8005 
8006   CSEMap.InsertNode(N, IP);
8007   InsertNode(N);
8008   SDValue V(N, 0);
8009   NewSDValueDbgMsg(V, "Creating new node: ", this);
8010   return V;
8011 }
8012 
8013 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8014                                    ArrayRef<SDValue> Ops,
8015                                    MachineMemOperand *MMO,
8016                                    ISD::MemIndexType IndexType) {
8017   assert(Ops.size() == 7 && "Incompatible number of operands");
8018 
8019   FoldingSetNodeID ID;
8020   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8021   ID.AddInteger(VT.getRawBits());
8022   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8023       dl.getIROrder(), VTs, VT, MMO, IndexType));
8024   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8025   void *IP = nullptr;
8026   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8027     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8028     return SDValue(E, 0);
8029   }
8030   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8031                                        VT, MMO, IndexType);
8032   createOperands(N, Ops);
8033 
8034   assert(N->getMask().getValueType().getVectorElementCount() ==
8035              N->getValue().getValueType().getVectorElementCount() &&
8036          "Vector width mismatch between mask and data");
8037   assert(
8038       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8039           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8040       "Scalable flags of index and data do not match");
8041   assert(ElementCount::isKnownGE(
8042              N->getIndex().getValueType().getVectorElementCount(),
8043              N->getValue().getValueType().getVectorElementCount()) &&
8044          "Vector width mismatch between index and data");
8045   assert(isa<ConstantSDNode>(N->getScale()) &&
8046          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8047          "Scale should be a constant power of 2");
8048 
8049   CSEMap.InsertNode(N, IP);
8050   InsertNode(N);
8051   SDValue V(N, 0);
8052   NewSDValueDbgMsg(V, "Creating new node: ", this);
8053   return V;
8054 }
8055 
8056 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8057                                     SDValue Base, SDValue Offset, SDValue Mask,
8058                                     SDValue PassThru, EVT MemVT,
8059                                     MachineMemOperand *MMO,
8060                                     ISD::MemIndexedMode AM,
8061                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8062   bool Indexed = AM != ISD::UNINDEXED;
8063   assert((Indexed || Offset.isUndef()) &&
8064          "Unindexed masked load with an offset!");
8065   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8066                          : getVTList(VT, MVT::Other);
8067   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8068   FoldingSetNodeID ID;
8069   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8070   ID.AddInteger(MemVT.getRawBits());
8071   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8072       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8073   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8074   void *IP = nullptr;
8075   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8076     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8077     return SDValue(E, 0);
8078   }
8079   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8080                                         AM, ExtTy, isExpanding, MemVT, MMO);
8081   createOperands(N, Ops);
8082 
8083   CSEMap.InsertNode(N, IP);
8084   InsertNode(N);
8085   SDValue V(N, 0);
8086   NewSDValueDbgMsg(V, "Creating new node: ", this);
8087   return V;
8088 }
8089 
8090 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8091                                            SDValue Base, SDValue Offset,
8092                                            ISD::MemIndexedMode AM) {
8093   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8094   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8095   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8096                        Offset, LD->getMask(), LD->getPassThru(),
8097                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8098                        LD->getExtensionType(), LD->isExpandingLoad());
8099 }
8100 
8101 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8102                                      SDValue Val, SDValue Base, SDValue Offset,
8103                                      SDValue Mask, EVT MemVT,
8104                                      MachineMemOperand *MMO,
8105                                      ISD::MemIndexedMode AM, bool IsTruncating,
8106                                      bool IsCompressing) {
8107   assert(Chain.getValueType() == MVT::Other &&
8108         "Invalid chain type");
8109   bool Indexed = AM != ISD::UNINDEXED;
8110   assert((Indexed || Offset.isUndef()) &&
8111          "Unindexed masked store with an offset!");
8112   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8113                          : getVTList(MVT::Other);
8114   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8115   FoldingSetNodeID ID;
8116   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8117   ID.AddInteger(MemVT.getRawBits());
8118   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8119       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8120   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8121   void *IP = nullptr;
8122   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8123     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8124     return SDValue(E, 0);
8125   }
8126   auto *N =
8127       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8128                                    IsTruncating, IsCompressing, MemVT, MMO);
8129   createOperands(N, Ops);
8130 
8131   CSEMap.InsertNode(N, IP);
8132   InsertNode(N);
8133   SDValue V(N, 0);
8134   NewSDValueDbgMsg(V, "Creating new node: ", this);
8135   return V;
8136 }
8137 
8138 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8139                                             SDValue Base, SDValue Offset,
8140                                             ISD::MemIndexedMode AM) {
8141   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8142   assert(ST->getOffset().isUndef() &&
8143          "Masked store is already a indexed store!");
8144   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8145                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8146                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8147 }
8148 
8149 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8150                                       ArrayRef<SDValue> Ops,
8151                                       MachineMemOperand *MMO,
8152                                       ISD::MemIndexType IndexType,
8153                                       ISD::LoadExtType ExtTy) {
8154   assert(Ops.size() == 6 && "Incompatible number of operands");
8155 
8156   FoldingSetNodeID ID;
8157   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8158   ID.AddInteger(MemVT.getRawBits());
8159   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8160       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8161   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8162   void *IP = nullptr;
8163   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8164     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8165     return SDValue(E, 0);
8166   }
8167 
8168   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8169   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8170                                           VTs, MemVT, MMO, IndexType, ExtTy);
8171   createOperands(N, Ops);
8172 
8173   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8174          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8175   assert(N->getMask().getValueType().getVectorElementCount() ==
8176              N->getValueType(0).getVectorElementCount() &&
8177          "Vector width mismatch between mask and data");
8178   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8179              N->getValueType(0).getVectorElementCount().isScalable() &&
8180          "Scalable flags of index and data do not match");
8181   assert(ElementCount::isKnownGE(
8182              N->getIndex().getValueType().getVectorElementCount(),
8183              N->getValueType(0).getVectorElementCount()) &&
8184          "Vector width mismatch between index and data");
8185   assert(isa<ConstantSDNode>(N->getScale()) &&
8186          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8187          "Scale should be a constant power of 2");
8188 
8189   CSEMap.InsertNode(N, IP);
8190   InsertNode(N);
8191   SDValue V(N, 0);
8192   NewSDValueDbgMsg(V, "Creating new node: ", this);
8193   return V;
8194 }
8195 
8196 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8197                                        ArrayRef<SDValue> Ops,
8198                                        MachineMemOperand *MMO,
8199                                        ISD::MemIndexType IndexType,
8200                                        bool IsTrunc) {
8201   assert(Ops.size() == 6 && "Incompatible number of operands");
8202 
8203   FoldingSetNodeID ID;
8204   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8205   ID.AddInteger(MemVT.getRawBits());
8206   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8207       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8208   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8209   void *IP = nullptr;
8210   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8211     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8212     return SDValue(E, 0);
8213   }
8214 
8215   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8216   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8217                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8218   createOperands(N, Ops);
8219 
8220   assert(N->getMask().getValueType().getVectorElementCount() ==
8221              N->getValue().getValueType().getVectorElementCount() &&
8222          "Vector width mismatch between mask and data");
8223   assert(
8224       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8225           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8226       "Scalable flags of index and data do not match");
8227   assert(ElementCount::isKnownGE(
8228              N->getIndex().getValueType().getVectorElementCount(),
8229              N->getValue().getValueType().getVectorElementCount()) &&
8230          "Vector width mismatch between index and data");
8231   assert(isa<ConstantSDNode>(N->getScale()) &&
8232          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8233          "Scale should be a constant power of 2");
8234 
8235   CSEMap.InsertNode(N, IP);
8236   InsertNode(N);
8237   SDValue V(N, 0);
8238   NewSDValueDbgMsg(V, "Creating new node: ", this);
8239   return V;
8240 }
8241 
8242 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8243   // select undef, T, F --> T (if T is a constant), otherwise F
8244   // select, ?, undef, F --> F
8245   // select, ?, T, undef --> T
8246   if (Cond.isUndef())
8247     return isConstantValueOfAnyType(T) ? T : F;
8248   if (T.isUndef())
8249     return F;
8250   if (F.isUndef())
8251     return T;
8252 
8253   // select true, T, F --> T
8254   // select false, T, F --> F
8255   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8256     return CondC->isZero() ? F : T;
8257 
8258   // TODO: This should simplify VSELECT with constant condition using something
8259   // like this (but check boolean contents to be complete?):
8260   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8261   //    return T;
8262   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8263   //    return F;
8264 
8265   // select ?, T, T --> T
8266   if (T == F)
8267     return T;
8268 
8269   return SDValue();
8270 }
8271 
8272 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8273   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8274   if (X.isUndef())
8275     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8276   // shift X, undef --> undef (because it may shift by the bitwidth)
8277   if (Y.isUndef())
8278     return getUNDEF(X.getValueType());
8279 
8280   // shift 0, Y --> 0
8281   // shift X, 0 --> X
8282   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8283     return X;
8284 
8285   // shift X, C >= bitwidth(X) --> undef
8286   // All vector elements must be too big (or undef) to avoid partial undefs.
8287   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8288     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8289   };
8290   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8291     return getUNDEF(X.getValueType());
8292 
8293   return SDValue();
8294 }
8295 
8296 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8297                                       SDNodeFlags Flags) {
8298   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8299   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8300   // operation is poison. That result can be relaxed to undef.
8301   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8302   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8303   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8304                 (YC && YC->getValueAPF().isNaN());
8305   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8306                 (YC && YC->getValueAPF().isInfinity());
8307 
8308   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8309     return getUNDEF(X.getValueType());
8310 
8311   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8312     return getUNDEF(X.getValueType());
8313 
8314   if (!YC)
8315     return SDValue();
8316 
8317   // X + -0.0 --> X
8318   if (Opcode == ISD::FADD)
8319     if (YC->getValueAPF().isNegZero())
8320       return X;
8321 
8322   // X - +0.0 --> X
8323   if (Opcode == ISD::FSUB)
8324     if (YC->getValueAPF().isPosZero())
8325       return X;
8326 
8327   // X * 1.0 --> X
8328   // X / 1.0 --> X
8329   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8330     if (YC->getValueAPF().isExactlyValue(1.0))
8331       return X;
8332 
8333   // X * 0.0 --> 0.0
8334   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8335     if (YC->getValueAPF().isZero())
8336       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8337 
8338   return SDValue();
8339 }
8340 
8341 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8342                                SDValue Ptr, SDValue SV, unsigned Align) {
8343   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8344   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8345 }
8346 
8347 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8348                               ArrayRef<SDUse> Ops) {
8349   switch (Ops.size()) {
8350   case 0: return getNode(Opcode, DL, VT);
8351   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8352   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8353   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8354   default: break;
8355   }
8356 
8357   // Copy from an SDUse array into an SDValue array for use with
8358   // the regular getNode logic.
8359   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8360   return getNode(Opcode, DL, VT, NewOps);
8361 }
8362 
8363 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8364                               ArrayRef<SDValue> Ops) {
8365   SDNodeFlags Flags;
8366   if (Inserter)
8367     Flags = Inserter->getFlags();
8368   return getNode(Opcode, DL, VT, Ops, Flags);
8369 }
8370 
8371 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8372                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8373   unsigned NumOps = Ops.size();
8374   switch (NumOps) {
8375   case 0: return getNode(Opcode, DL, VT);
8376   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8377   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8378   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8379   default: break;
8380   }
8381 
8382 #ifndef NDEBUG
8383   for (auto &Op : Ops)
8384     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8385            "Operand is DELETED_NODE!");
8386 #endif
8387 
8388   switch (Opcode) {
8389   default: break;
8390   case ISD::BUILD_VECTOR:
8391     // Attempt to simplify BUILD_VECTOR.
8392     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8393       return V;
8394     break;
8395   case ISD::CONCAT_VECTORS:
8396     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8397       return V;
8398     break;
8399   case ISD::SELECT_CC:
8400     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8401     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8402            "LHS and RHS of condition must have same type!");
8403     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8404            "True and False arms of SelectCC must have same type!");
8405     assert(Ops[2].getValueType() == VT &&
8406            "select_cc node must be of same type as true and false value!");
8407     break;
8408   case ISD::BR_CC:
8409     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8410     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8411            "LHS/RHS of comparison should match types!");
8412     break;
8413   }
8414 
8415   // Memoize nodes.
8416   SDNode *N;
8417   SDVTList VTs = getVTList(VT);
8418 
8419   if (VT != MVT::Glue) {
8420     FoldingSetNodeID ID;
8421     AddNodeIDNode(ID, Opcode, VTs, Ops);
8422     void *IP = nullptr;
8423 
8424     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8425       return SDValue(E, 0);
8426 
8427     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8428     createOperands(N, Ops);
8429 
8430     CSEMap.InsertNode(N, IP);
8431   } else {
8432     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8433     createOperands(N, Ops);
8434   }
8435 
8436   N->setFlags(Flags);
8437   InsertNode(N);
8438   SDValue V(N, 0);
8439   NewSDValueDbgMsg(V, "Creating new node: ", this);
8440   return V;
8441 }
8442 
8443 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8444                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8445   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8446 }
8447 
8448 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8449                               ArrayRef<SDValue> Ops) {
8450   SDNodeFlags Flags;
8451   if (Inserter)
8452     Flags = Inserter->getFlags();
8453   return getNode(Opcode, DL, VTList, Ops, Flags);
8454 }
8455 
8456 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8457                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8458   if (VTList.NumVTs == 1)
8459     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8460 
8461 #ifndef NDEBUG
8462   for (auto &Op : Ops)
8463     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8464            "Operand is DELETED_NODE!");
8465 #endif
8466 
8467   switch (Opcode) {
8468   case ISD::STRICT_FP_EXTEND:
8469     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8470            "Invalid STRICT_FP_EXTEND!");
8471     assert(VTList.VTs[0].isFloatingPoint() &&
8472            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8473     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8474            "STRICT_FP_EXTEND result type should be vector iff the operand "
8475            "type is vector!");
8476     assert((!VTList.VTs[0].isVector() ||
8477             VTList.VTs[0].getVectorNumElements() ==
8478             Ops[1].getValueType().getVectorNumElements()) &&
8479            "Vector element count mismatch!");
8480     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8481            "Invalid fpext node, dst <= src!");
8482     break;
8483   case ISD::STRICT_FP_ROUND:
8484     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8485     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8486            "STRICT_FP_ROUND result type should be vector iff the operand "
8487            "type is vector!");
8488     assert((!VTList.VTs[0].isVector() ||
8489             VTList.VTs[0].getVectorNumElements() ==
8490             Ops[1].getValueType().getVectorNumElements()) &&
8491            "Vector element count mismatch!");
8492     assert(VTList.VTs[0].isFloatingPoint() &&
8493            Ops[1].getValueType().isFloatingPoint() &&
8494            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8495            isa<ConstantSDNode>(Ops[2]) &&
8496            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8497             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8498            "Invalid STRICT_FP_ROUND!");
8499     break;
8500 #if 0
8501   // FIXME: figure out how to safely handle things like
8502   // int foo(int x) { return 1 << (x & 255); }
8503   // int bar() { return foo(256); }
8504   case ISD::SRA_PARTS:
8505   case ISD::SRL_PARTS:
8506   case ISD::SHL_PARTS:
8507     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8508         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8509       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8510     else if (N3.getOpcode() == ISD::AND)
8511       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8512         // If the and is only masking out bits that cannot effect the shift,
8513         // eliminate the and.
8514         unsigned NumBits = VT.getScalarSizeInBits()*2;
8515         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8516           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8517       }
8518     break;
8519 #endif
8520   }
8521 
8522   // Memoize the node unless it returns a flag.
8523   SDNode *N;
8524   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8525     FoldingSetNodeID ID;
8526     AddNodeIDNode(ID, Opcode, VTList, Ops);
8527     void *IP = nullptr;
8528     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8529       return SDValue(E, 0);
8530 
8531     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8532     createOperands(N, Ops);
8533     CSEMap.InsertNode(N, IP);
8534   } else {
8535     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8536     createOperands(N, Ops);
8537   }
8538 
8539   N->setFlags(Flags);
8540   InsertNode(N);
8541   SDValue V(N, 0);
8542   NewSDValueDbgMsg(V, "Creating new node: ", this);
8543   return V;
8544 }
8545 
8546 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8547                               SDVTList VTList) {
8548   return getNode(Opcode, DL, VTList, None);
8549 }
8550 
8551 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8552                               SDValue N1) {
8553   SDValue Ops[] = { N1 };
8554   return getNode(Opcode, DL, VTList, Ops);
8555 }
8556 
8557 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8558                               SDValue N1, SDValue N2) {
8559   SDValue Ops[] = { N1, N2 };
8560   return getNode(Opcode, DL, VTList, Ops);
8561 }
8562 
8563 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8564                               SDValue N1, SDValue N2, SDValue N3) {
8565   SDValue Ops[] = { N1, N2, N3 };
8566   return getNode(Opcode, DL, VTList, Ops);
8567 }
8568 
8569 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8570                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8571   SDValue Ops[] = { N1, N2, N3, N4 };
8572   return getNode(Opcode, DL, VTList, Ops);
8573 }
8574 
8575 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8576                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8577                               SDValue N5) {
8578   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8579   return getNode(Opcode, DL, VTList, Ops);
8580 }
8581 
8582 SDVTList SelectionDAG::getVTList(EVT VT) {
8583   return makeVTList(SDNode::getValueTypeList(VT), 1);
8584 }
8585 
8586 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8587   FoldingSetNodeID ID;
8588   ID.AddInteger(2U);
8589   ID.AddInteger(VT1.getRawBits());
8590   ID.AddInteger(VT2.getRawBits());
8591 
8592   void *IP = nullptr;
8593   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8594   if (!Result) {
8595     EVT *Array = Allocator.Allocate<EVT>(2);
8596     Array[0] = VT1;
8597     Array[1] = VT2;
8598     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8599     VTListMap.InsertNode(Result, IP);
8600   }
8601   return Result->getSDVTList();
8602 }
8603 
8604 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8605   FoldingSetNodeID ID;
8606   ID.AddInteger(3U);
8607   ID.AddInteger(VT1.getRawBits());
8608   ID.AddInteger(VT2.getRawBits());
8609   ID.AddInteger(VT3.getRawBits());
8610 
8611   void *IP = nullptr;
8612   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8613   if (!Result) {
8614     EVT *Array = Allocator.Allocate<EVT>(3);
8615     Array[0] = VT1;
8616     Array[1] = VT2;
8617     Array[2] = VT3;
8618     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8619     VTListMap.InsertNode(Result, IP);
8620   }
8621   return Result->getSDVTList();
8622 }
8623 
8624 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8625   FoldingSetNodeID ID;
8626   ID.AddInteger(4U);
8627   ID.AddInteger(VT1.getRawBits());
8628   ID.AddInteger(VT2.getRawBits());
8629   ID.AddInteger(VT3.getRawBits());
8630   ID.AddInteger(VT4.getRawBits());
8631 
8632   void *IP = nullptr;
8633   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8634   if (!Result) {
8635     EVT *Array = Allocator.Allocate<EVT>(4);
8636     Array[0] = VT1;
8637     Array[1] = VT2;
8638     Array[2] = VT3;
8639     Array[3] = VT4;
8640     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8641     VTListMap.InsertNode(Result, IP);
8642   }
8643   return Result->getSDVTList();
8644 }
8645 
8646 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8647   unsigned NumVTs = VTs.size();
8648   FoldingSetNodeID ID;
8649   ID.AddInteger(NumVTs);
8650   for (unsigned index = 0; index < NumVTs; index++) {
8651     ID.AddInteger(VTs[index].getRawBits());
8652   }
8653 
8654   void *IP = nullptr;
8655   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8656   if (!Result) {
8657     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8658     llvm::copy(VTs, Array);
8659     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8660     VTListMap.InsertNode(Result, IP);
8661   }
8662   return Result->getSDVTList();
8663 }
8664 
8665 
8666 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8667 /// specified operands.  If the resultant node already exists in the DAG,
8668 /// this does not modify the specified node, instead it returns the node that
8669 /// already exists.  If the resultant node does not exist in the DAG, the
8670 /// input node is returned.  As a degenerate case, if you specify the same
8671 /// input operands as the node already has, the input node is returned.
8672 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8673   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8674 
8675   // Check to see if there is no change.
8676   if (Op == N->getOperand(0)) return N;
8677 
8678   // See if the modified node already exists.
8679   void *InsertPos = nullptr;
8680   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8681     return Existing;
8682 
8683   // Nope it doesn't.  Remove the node from its current place in the maps.
8684   if (InsertPos)
8685     if (!RemoveNodeFromCSEMaps(N))
8686       InsertPos = nullptr;
8687 
8688   // Now we update the operands.
8689   N->OperandList[0].set(Op);
8690 
8691   updateDivergence(N);
8692   // If this gets put into a CSE map, add it.
8693   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8694   return N;
8695 }
8696 
8697 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8698   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8699 
8700   // Check to see if there is no change.
8701   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8702     return N;   // No operands changed, just return the input node.
8703 
8704   // See if the modified node already exists.
8705   void *InsertPos = nullptr;
8706   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8707     return Existing;
8708 
8709   // Nope it doesn't.  Remove the node from its current place in the maps.
8710   if (InsertPos)
8711     if (!RemoveNodeFromCSEMaps(N))
8712       InsertPos = nullptr;
8713 
8714   // Now we update the operands.
8715   if (N->OperandList[0] != Op1)
8716     N->OperandList[0].set(Op1);
8717   if (N->OperandList[1] != Op2)
8718     N->OperandList[1].set(Op2);
8719 
8720   updateDivergence(N);
8721   // If this gets put into a CSE map, add it.
8722   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8723   return N;
8724 }
8725 
8726 SDNode *SelectionDAG::
8727 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8728   SDValue Ops[] = { Op1, Op2, Op3 };
8729   return UpdateNodeOperands(N, Ops);
8730 }
8731 
8732 SDNode *SelectionDAG::
8733 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8734                    SDValue Op3, SDValue Op4) {
8735   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8736   return UpdateNodeOperands(N, Ops);
8737 }
8738 
8739 SDNode *SelectionDAG::
8740 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8741                    SDValue Op3, SDValue Op4, SDValue Op5) {
8742   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8743   return UpdateNodeOperands(N, Ops);
8744 }
8745 
8746 SDNode *SelectionDAG::
8747 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8748   unsigned NumOps = Ops.size();
8749   assert(N->getNumOperands() == NumOps &&
8750          "Update with wrong number of operands");
8751 
8752   // If no operands changed just return the input node.
8753   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8754     return N;
8755 
8756   // See if the modified node already exists.
8757   void *InsertPos = nullptr;
8758   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8759     return Existing;
8760 
8761   // Nope it doesn't.  Remove the node from its current place in the maps.
8762   if (InsertPos)
8763     if (!RemoveNodeFromCSEMaps(N))
8764       InsertPos = nullptr;
8765 
8766   // Now we update the operands.
8767   for (unsigned i = 0; i != NumOps; ++i)
8768     if (N->OperandList[i] != Ops[i])
8769       N->OperandList[i].set(Ops[i]);
8770 
8771   updateDivergence(N);
8772   // If this gets put into a CSE map, add it.
8773   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8774   return N;
8775 }
8776 
8777 /// DropOperands - Release the operands and set this node to have
8778 /// zero operands.
8779 void SDNode::DropOperands() {
8780   // Unlike the code in MorphNodeTo that does this, we don't need to
8781   // watch for dead nodes here.
8782   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8783     SDUse &Use = *I++;
8784     Use.set(SDValue());
8785   }
8786 }
8787 
8788 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8789                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8790   if (NewMemRefs.empty()) {
8791     N->clearMemRefs();
8792     return;
8793   }
8794 
8795   // Check if we can avoid allocating by storing a single reference directly.
8796   if (NewMemRefs.size() == 1) {
8797     N->MemRefs = NewMemRefs[0];
8798     N->NumMemRefs = 1;
8799     return;
8800   }
8801 
8802   MachineMemOperand **MemRefsBuffer =
8803       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8804   llvm::copy(NewMemRefs, MemRefsBuffer);
8805   N->MemRefs = MemRefsBuffer;
8806   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8807 }
8808 
8809 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8810 /// machine opcode.
8811 ///
8812 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8813                                    EVT VT) {
8814   SDVTList VTs = getVTList(VT);
8815   return SelectNodeTo(N, MachineOpc, VTs, None);
8816 }
8817 
8818 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8819                                    EVT VT, SDValue Op1) {
8820   SDVTList VTs = getVTList(VT);
8821   SDValue Ops[] = { Op1 };
8822   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8823 }
8824 
8825 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8826                                    EVT VT, SDValue Op1,
8827                                    SDValue Op2) {
8828   SDVTList VTs = getVTList(VT);
8829   SDValue Ops[] = { Op1, Op2 };
8830   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8831 }
8832 
8833 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8834                                    EVT VT, SDValue Op1,
8835                                    SDValue Op2, SDValue Op3) {
8836   SDVTList VTs = getVTList(VT);
8837   SDValue Ops[] = { Op1, Op2, Op3 };
8838   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8839 }
8840 
8841 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8842                                    EVT VT, ArrayRef<SDValue> Ops) {
8843   SDVTList VTs = getVTList(VT);
8844   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8845 }
8846 
8847 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8848                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8849   SDVTList VTs = getVTList(VT1, VT2);
8850   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8851 }
8852 
8853 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8854                                    EVT VT1, EVT VT2) {
8855   SDVTList VTs = getVTList(VT1, VT2);
8856   return SelectNodeTo(N, MachineOpc, VTs, None);
8857 }
8858 
8859 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8860                                    EVT VT1, EVT VT2, EVT VT3,
8861                                    ArrayRef<SDValue> Ops) {
8862   SDVTList VTs = getVTList(VT1, VT2, VT3);
8863   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8864 }
8865 
8866 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8867                                    EVT VT1, EVT VT2,
8868                                    SDValue Op1, SDValue Op2) {
8869   SDVTList VTs = getVTList(VT1, VT2);
8870   SDValue Ops[] = { Op1, Op2 };
8871   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8872 }
8873 
8874 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8875                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8876   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8877   // Reset the NodeID to -1.
8878   New->setNodeId(-1);
8879   if (New != N) {
8880     ReplaceAllUsesWith(N, New);
8881     RemoveDeadNode(N);
8882   }
8883   return New;
8884 }
8885 
8886 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8887 /// the line number information on the merged node since it is not possible to
8888 /// preserve the information that operation is associated with multiple lines.
8889 /// This will make the debugger working better at -O0, were there is a higher
8890 /// probability having other instructions associated with that line.
8891 ///
8892 /// For IROrder, we keep the smaller of the two
8893 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8894   DebugLoc NLoc = N->getDebugLoc();
8895   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8896     N->setDebugLoc(DebugLoc());
8897   }
8898   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8899   N->setIROrder(Order);
8900   return N;
8901 }
8902 
8903 /// MorphNodeTo - This *mutates* the specified node to have the specified
8904 /// return type, opcode, and operands.
8905 ///
8906 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8907 /// node of the specified opcode and operands, it returns that node instead of
8908 /// the current one.  Note that the SDLoc need not be the same.
8909 ///
8910 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8911 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8912 /// node, and because it doesn't require CSE recalculation for any of
8913 /// the node's users.
8914 ///
8915 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8916 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8917 /// the legalizer which maintain worklists that would need to be updated when
8918 /// deleting things.
8919 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8920                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8921   // If an identical node already exists, use it.
8922   void *IP = nullptr;
8923   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8924     FoldingSetNodeID ID;
8925     AddNodeIDNode(ID, Opc, VTs, Ops);
8926     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8927       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8928   }
8929 
8930   if (!RemoveNodeFromCSEMaps(N))
8931     IP = nullptr;
8932 
8933   // Start the morphing.
8934   N->NodeType = Opc;
8935   N->ValueList = VTs.VTs;
8936   N->NumValues = VTs.NumVTs;
8937 
8938   // Clear the operands list, updating used nodes to remove this from their
8939   // use list.  Keep track of any operands that become dead as a result.
8940   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8941   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8942     SDUse &Use = *I++;
8943     SDNode *Used = Use.getNode();
8944     Use.set(SDValue());
8945     if (Used->use_empty())
8946       DeadNodeSet.insert(Used);
8947   }
8948 
8949   // For MachineNode, initialize the memory references information.
8950   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8951     MN->clearMemRefs();
8952 
8953   // Swap for an appropriately sized array from the recycler.
8954   removeOperands(N);
8955   createOperands(N, Ops);
8956 
8957   // Delete any nodes that are still dead after adding the uses for the
8958   // new operands.
8959   if (!DeadNodeSet.empty()) {
8960     SmallVector<SDNode *, 16> DeadNodes;
8961     for (SDNode *N : DeadNodeSet)
8962       if (N->use_empty())
8963         DeadNodes.push_back(N);
8964     RemoveDeadNodes(DeadNodes);
8965   }
8966 
8967   if (IP)
8968     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8969   return N;
8970 }
8971 
8972 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8973   unsigned OrigOpc = Node->getOpcode();
8974   unsigned NewOpc;
8975   switch (OrigOpc) {
8976   default:
8977     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8978 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8979   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8980 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8981   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8982 #include "llvm/IR/ConstrainedOps.def"
8983   }
8984 
8985   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8986 
8987   // We're taking this node out of the chain, so we need to re-link things.
8988   SDValue InputChain = Node->getOperand(0);
8989   SDValue OutputChain = SDValue(Node, 1);
8990   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8991 
8992   SmallVector<SDValue, 3> Ops;
8993   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8994     Ops.push_back(Node->getOperand(i));
8995 
8996   SDVTList VTs = getVTList(Node->getValueType(0));
8997   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8998 
8999   // MorphNodeTo can operate in two ways: if an existing node with the
9000   // specified operands exists, it can just return it.  Otherwise, it
9001   // updates the node in place to have the requested operands.
9002   if (Res == Node) {
9003     // If we updated the node in place, reset the node ID.  To the isel,
9004     // this should be just like a newly allocated machine node.
9005     Res->setNodeId(-1);
9006   } else {
9007     ReplaceAllUsesWith(Node, Res);
9008     RemoveDeadNode(Node);
9009   }
9010 
9011   return Res;
9012 }
9013 
9014 /// getMachineNode - These are used for target selectors to create a new node
9015 /// with specified return type(s), MachineInstr opcode, and operands.
9016 ///
9017 /// Note that getMachineNode returns the resultant node.  If there is already a
9018 /// node of the specified opcode and operands, it returns that node instead of
9019 /// the current one.
9020 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9021                                             EVT VT) {
9022   SDVTList VTs = getVTList(VT);
9023   return getMachineNode(Opcode, dl, VTs, None);
9024 }
9025 
9026 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9027                                             EVT VT, SDValue Op1) {
9028   SDVTList VTs = getVTList(VT);
9029   SDValue Ops[] = { Op1 };
9030   return getMachineNode(Opcode, dl, VTs, Ops);
9031 }
9032 
9033 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9034                                             EVT VT, SDValue Op1, SDValue Op2) {
9035   SDVTList VTs = getVTList(VT);
9036   SDValue Ops[] = { Op1, Op2 };
9037   return getMachineNode(Opcode, dl, VTs, Ops);
9038 }
9039 
9040 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9041                                             EVT VT, SDValue Op1, SDValue Op2,
9042                                             SDValue Op3) {
9043   SDVTList VTs = getVTList(VT);
9044   SDValue Ops[] = { Op1, Op2, Op3 };
9045   return getMachineNode(Opcode, dl, VTs, Ops);
9046 }
9047 
9048 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9049                                             EVT VT, ArrayRef<SDValue> Ops) {
9050   SDVTList VTs = getVTList(VT);
9051   return getMachineNode(Opcode, dl, VTs, Ops);
9052 }
9053 
9054 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9055                                             EVT VT1, EVT VT2, SDValue Op1,
9056                                             SDValue Op2) {
9057   SDVTList VTs = getVTList(VT1, VT2);
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, SDValue Op1,
9064                                             SDValue Op2, SDValue Op3) {
9065   SDVTList VTs = getVTList(VT1, VT2);
9066   SDValue Ops[] = { Op1, Op2, Op3 };
9067   return getMachineNode(Opcode, dl, VTs, Ops);
9068 }
9069 
9070 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9071                                             EVT VT1, EVT VT2,
9072                                             ArrayRef<SDValue> Ops) {
9073   SDVTList VTs = getVTList(VT1, VT2);
9074   return getMachineNode(Opcode, dl, VTs, Ops);
9075 }
9076 
9077 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9078                                             EVT VT1, EVT VT2, EVT VT3,
9079                                             SDValue Op1, SDValue Op2) {
9080   SDVTList VTs = getVTList(VT1, VT2, VT3);
9081   SDValue Ops[] = { Op1, Op2 };
9082   return getMachineNode(Opcode, dl, VTs, Ops);
9083 }
9084 
9085 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9086                                             EVT VT1, EVT VT2, EVT VT3,
9087                                             SDValue Op1, SDValue Op2,
9088                                             SDValue Op3) {
9089   SDVTList VTs = getVTList(VT1, VT2, VT3);
9090   SDValue Ops[] = { Op1, Op2, Op3 };
9091   return getMachineNode(Opcode, dl, VTs, Ops);
9092 }
9093 
9094 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9095                                             EVT VT1, EVT VT2, EVT VT3,
9096                                             ArrayRef<SDValue> Ops) {
9097   SDVTList VTs = getVTList(VT1, VT2, VT3);
9098   return getMachineNode(Opcode, dl, VTs, Ops);
9099 }
9100 
9101 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9102                                             ArrayRef<EVT> ResultTys,
9103                                             ArrayRef<SDValue> Ops) {
9104   SDVTList VTs = getVTList(ResultTys);
9105   return getMachineNode(Opcode, dl, VTs, Ops);
9106 }
9107 
9108 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9109                                             SDVTList VTs,
9110                                             ArrayRef<SDValue> Ops) {
9111   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9112   MachineSDNode *N;
9113   void *IP = nullptr;
9114 
9115   if (DoCSE) {
9116     FoldingSetNodeID ID;
9117     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9118     IP = nullptr;
9119     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9120       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9121     }
9122   }
9123 
9124   // Allocate a new MachineSDNode.
9125   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9126   createOperands(N, Ops);
9127 
9128   if (DoCSE)
9129     CSEMap.InsertNode(N, IP);
9130 
9131   InsertNode(N);
9132   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9133   return N;
9134 }
9135 
9136 /// getTargetExtractSubreg - A convenience function for creating
9137 /// TargetOpcode::EXTRACT_SUBREG nodes.
9138 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9139                                              SDValue Operand) {
9140   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9141   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9142                                   VT, Operand, SRIdxVal);
9143   return SDValue(Subreg, 0);
9144 }
9145 
9146 /// getTargetInsertSubreg - A convenience function for creating
9147 /// TargetOpcode::INSERT_SUBREG nodes.
9148 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9149                                             SDValue Operand, SDValue Subreg) {
9150   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9151   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9152                                   VT, Operand, Subreg, SRIdxVal);
9153   return SDValue(Result, 0);
9154 }
9155 
9156 /// getNodeIfExists - Get the specified node if it's already available, or
9157 /// else return NULL.
9158 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9159                                       ArrayRef<SDValue> Ops) {
9160   SDNodeFlags Flags;
9161   if (Inserter)
9162     Flags = Inserter->getFlags();
9163   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9164 }
9165 
9166 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9167                                       ArrayRef<SDValue> Ops,
9168                                       const SDNodeFlags Flags) {
9169   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9170     FoldingSetNodeID ID;
9171     AddNodeIDNode(ID, Opcode, VTList, Ops);
9172     void *IP = nullptr;
9173     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9174       E->intersectFlagsWith(Flags);
9175       return E;
9176     }
9177   }
9178   return nullptr;
9179 }
9180 
9181 /// doesNodeExist - Check if a node exists without modifying its flags.
9182 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9183                                  ArrayRef<SDValue> Ops) {
9184   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9185     FoldingSetNodeID ID;
9186     AddNodeIDNode(ID, Opcode, VTList, Ops);
9187     void *IP = nullptr;
9188     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9189       return true;
9190   }
9191   return false;
9192 }
9193 
9194 /// getDbgValue - Creates a SDDbgValue node.
9195 ///
9196 /// SDNode
9197 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9198                                       SDNode *N, unsigned R, bool IsIndirect,
9199                                       const DebugLoc &DL, unsigned O) {
9200   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9201          "Expected inlined-at fields to agree");
9202   return new (DbgInfo->getAlloc())
9203       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9204                  {}, IsIndirect, DL, O,
9205                  /*IsVariadic=*/false);
9206 }
9207 
9208 /// Constant
9209 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9210                                               DIExpression *Expr,
9211                                               const Value *C,
9212                                               const DebugLoc &DL, unsigned O) {
9213   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9214          "Expected inlined-at fields to agree");
9215   return new (DbgInfo->getAlloc())
9216       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9217                  /*IsIndirect=*/false, DL, O,
9218                  /*IsVariadic=*/false);
9219 }
9220 
9221 /// FrameIndex
9222 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9223                                                 DIExpression *Expr, unsigned FI,
9224                                                 bool IsIndirect,
9225                                                 const DebugLoc &DL,
9226                                                 unsigned O) {
9227   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9228          "Expected inlined-at fields to agree");
9229   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9230 }
9231 
9232 /// FrameIndex with dependencies
9233 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9234                                                 DIExpression *Expr, unsigned FI,
9235                                                 ArrayRef<SDNode *> Dependencies,
9236                                                 bool IsIndirect,
9237                                                 const DebugLoc &DL,
9238                                                 unsigned O) {
9239   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9240          "Expected inlined-at fields to agree");
9241   return new (DbgInfo->getAlloc())
9242       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9243                  Dependencies, IsIndirect, DL, O,
9244                  /*IsVariadic=*/false);
9245 }
9246 
9247 /// VReg
9248 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9249                                           unsigned VReg, bool IsIndirect,
9250                                           const DebugLoc &DL, unsigned O) {
9251   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9252          "Expected inlined-at fields to agree");
9253   return new (DbgInfo->getAlloc())
9254       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9255                  {}, IsIndirect, DL, O,
9256                  /*IsVariadic=*/false);
9257 }
9258 
9259 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9260                                           ArrayRef<SDDbgOperand> Locs,
9261                                           ArrayRef<SDNode *> Dependencies,
9262                                           bool IsIndirect, const DebugLoc &DL,
9263                                           unsigned O, bool IsVariadic) {
9264   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9265          "Expected inlined-at fields to agree");
9266   return new (DbgInfo->getAlloc())
9267       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9268                  DL, O, IsVariadic);
9269 }
9270 
9271 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9272                                      unsigned OffsetInBits, unsigned SizeInBits,
9273                                      bool InvalidateDbg) {
9274   SDNode *FromNode = From.getNode();
9275   SDNode *ToNode = To.getNode();
9276   assert(FromNode && ToNode && "Can't modify dbg values");
9277 
9278   // PR35338
9279   // TODO: assert(From != To && "Redundant dbg value transfer");
9280   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9281   if (From == To || FromNode == ToNode)
9282     return;
9283 
9284   if (!FromNode->getHasDebugValue())
9285     return;
9286 
9287   SDDbgOperand FromLocOp =
9288       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9289   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9290 
9291   SmallVector<SDDbgValue *, 2> ClonedDVs;
9292   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9293     if (Dbg->isInvalidated())
9294       continue;
9295 
9296     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9297 
9298     // Create a new location ops vector that is equal to the old vector, but
9299     // with each instance of FromLocOp replaced with ToLocOp.
9300     bool Changed = false;
9301     auto NewLocOps = Dbg->copyLocationOps();
9302     std::replace_if(
9303         NewLocOps.begin(), NewLocOps.end(),
9304         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9305           bool Match = Op == FromLocOp;
9306           Changed |= Match;
9307           return Match;
9308         },
9309         ToLocOp);
9310     // Ignore this SDDbgValue if we didn't find a matching location.
9311     if (!Changed)
9312       continue;
9313 
9314     DIVariable *Var = Dbg->getVariable();
9315     auto *Expr = Dbg->getExpression();
9316     // If a fragment is requested, update the expression.
9317     if (SizeInBits) {
9318       // When splitting a larger (e.g., sign-extended) value whose
9319       // lower bits are described with an SDDbgValue, do not attempt
9320       // to transfer the SDDbgValue to the upper bits.
9321       if (auto FI = Expr->getFragmentInfo())
9322         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9323           continue;
9324       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9325                                                              SizeInBits);
9326       if (!Fragment)
9327         continue;
9328       Expr = *Fragment;
9329     }
9330 
9331     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9332     // Clone the SDDbgValue and move it to To.
9333     SDDbgValue *Clone = getDbgValueList(
9334         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9335         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9336         Dbg->isVariadic());
9337     ClonedDVs.push_back(Clone);
9338 
9339     if (InvalidateDbg) {
9340       // Invalidate value and indicate the SDDbgValue should not be emitted.
9341       Dbg->setIsInvalidated();
9342       Dbg->setIsEmitted();
9343     }
9344   }
9345 
9346   for (SDDbgValue *Dbg : ClonedDVs) {
9347     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9348            "Transferred DbgValues should depend on the new SDNode");
9349     AddDbgValue(Dbg, false);
9350   }
9351 }
9352 
9353 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9354   if (!N.getHasDebugValue())
9355     return;
9356 
9357   SmallVector<SDDbgValue *, 2> ClonedDVs;
9358   for (auto DV : GetDbgValues(&N)) {
9359     if (DV->isInvalidated())
9360       continue;
9361     switch (N.getOpcode()) {
9362     default:
9363       break;
9364     case ISD::ADD:
9365       SDValue N0 = N.getOperand(0);
9366       SDValue N1 = N.getOperand(1);
9367       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9368           isConstantIntBuildVectorOrConstantInt(N1)) {
9369         uint64_t Offset = N.getConstantOperandVal(1);
9370 
9371         // Rewrite an ADD constant node into a DIExpression. Since we are
9372         // performing arithmetic to compute the variable's *value* in the
9373         // DIExpression, we need to mark the expression with a
9374         // DW_OP_stack_value.
9375         auto *DIExpr = DV->getExpression();
9376         auto NewLocOps = DV->copyLocationOps();
9377         bool Changed = false;
9378         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9379           // We're not given a ResNo to compare against because the whole
9380           // node is going away. We know that any ISD::ADD only has one
9381           // result, so we can assume any node match is using the result.
9382           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9383               NewLocOps[i].getSDNode() != &N)
9384             continue;
9385           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9386           SmallVector<uint64_t, 3> ExprOps;
9387           DIExpression::appendOffset(ExprOps, Offset);
9388           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9389           Changed = true;
9390         }
9391         (void)Changed;
9392         assert(Changed && "Salvage target doesn't use N");
9393 
9394         auto AdditionalDependencies = DV->getAdditionalDependencies();
9395         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9396                                             NewLocOps, AdditionalDependencies,
9397                                             DV->isIndirect(), DV->getDebugLoc(),
9398                                             DV->getOrder(), DV->isVariadic());
9399         ClonedDVs.push_back(Clone);
9400         DV->setIsInvalidated();
9401         DV->setIsEmitted();
9402         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9403                    N0.getNode()->dumprFull(this);
9404                    dbgs() << " into " << *DIExpr << '\n');
9405       }
9406     }
9407   }
9408 
9409   for (SDDbgValue *Dbg : ClonedDVs) {
9410     assert(!Dbg->getSDNodes().empty() &&
9411            "Salvaged DbgValue should depend on a new SDNode");
9412     AddDbgValue(Dbg, false);
9413   }
9414 }
9415 
9416 /// Creates a SDDbgLabel node.
9417 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9418                                       const DebugLoc &DL, unsigned O) {
9419   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9420          "Expected inlined-at fields to agree");
9421   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9422 }
9423 
9424 namespace {
9425 
9426 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9427 /// pointed to by a use iterator is deleted, increment the use iterator
9428 /// so that it doesn't dangle.
9429 ///
9430 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9431   SDNode::use_iterator &UI;
9432   SDNode::use_iterator &UE;
9433 
9434   void NodeDeleted(SDNode *N, SDNode *E) override {
9435     // Increment the iterator as needed.
9436     while (UI != UE && N == *UI)
9437       ++UI;
9438   }
9439 
9440 public:
9441   RAUWUpdateListener(SelectionDAG &d,
9442                      SDNode::use_iterator &ui,
9443                      SDNode::use_iterator &ue)
9444     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9445 };
9446 
9447 } // end anonymous namespace
9448 
9449 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9450 /// This can cause recursive merging of nodes in the DAG.
9451 ///
9452 /// This version assumes From has a single result value.
9453 ///
9454 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9455   SDNode *From = FromN.getNode();
9456   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9457          "Cannot replace with this method!");
9458   assert(From != To.getNode() && "Cannot replace uses of with self");
9459 
9460   // Preserve Debug Values
9461   transferDbgValues(FromN, To);
9462 
9463   // Iterate over all the existing uses of From. New uses will be added
9464   // to the beginning of the use list, which we avoid visiting.
9465   // This specifically avoids visiting uses of From that arise while the
9466   // replacement is happening, because any such uses would be the result
9467   // of CSE: If an existing node looks like From after one of its operands
9468   // is replaced by To, we don't want to replace of all its users with To
9469   // too. See PR3018 for more info.
9470   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9471   RAUWUpdateListener Listener(*this, UI, UE);
9472   while (UI != UE) {
9473     SDNode *User = *UI;
9474 
9475     // This node is about to morph, remove its old self from the CSE maps.
9476     RemoveNodeFromCSEMaps(User);
9477 
9478     // A user can appear in a use list multiple times, and when this
9479     // happens the uses are usually next to each other in the list.
9480     // To help reduce the number of CSE recomputations, process all
9481     // the uses of this user that we can find this way.
9482     do {
9483       SDUse &Use = UI.getUse();
9484       ++UI;
9485       Use.set(To);
9486       if (To->isDivergent() != From->isDivergent())
9487         updateDivergence(User);
9488     } while (UI != UE && *UI == User);
9489     // Now that we have modified User, add it back to the CSE maps.  If it
9490     // already exists there, recursively merge the results together.
9491     AddModifiedNodeToCSEMaps(User);
9492   }
9493 
9494   // If we just RAUW'd the root, take note.
9495   if (FromN == getRoot())
9496     setRoot(To);
9497 }
9498 
9499 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9500 /// This can cause recursive merging of nodes in the DAG.
9501 ///
9502 /// This version assumes that for each value of From, there is a
9503 /// corresponding value in To in the same position with the same type.
9504 ///
9505 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9506 #ifndef NDEBUG
9507   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9508     assert((!From->hasAnyUseOfValue(i) ||
9509             From->getValueType(i) == To->getValueType(i)) &&
9510            "Cannot use this version of ReplaceAllUsesWith!");
9511 #endif
9512 
9513   // Handle the trivial case.
9514   if (From == To)
9515     return;
9516 
9517   // Preserve Debug Info. Only do this if there's a use.
9518   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9519     if (From->hasAnyUseOfValue(i)) {
9520       assert((i < To->getNumValues()) && "Invalid To location");
9521       transferDbgValues(SDValue(From, i), SDValue(To, i));
9522     }
9523 
9524   // Iterate over just the existing users of From. See the comments in
9525   // the ReplaceAllUsesWith above.
9526   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9527   RAUWUpdateListener Listener(*this, UI, UE);
9528   while (UI != UE) {
9529     SDNode *User = *UI;
9530 
9531     // This node is about to morph, remove its old self from the CSE maps.
9532     RemoveNodeFromCSEMaps(User);
9533 
9534     // A user can appear in a use list multiple times, and when this
9535     // happens the uses are usually next to each other in the list.
9536     // To help reduce the number of CSE recomputations, process all
9537     // the uses of this user that we can find this way.
9538     do {
9539       SDUse &Use = UI.getUse();
9540       ++UI;
9541       Use.setNode(To);
9542       if (To->isDivergent() != From->isDivergent())
9543         updateDivergence(User);
9544     } while (UI != UE && *UI == User);
9545 
9546     // Now that we have modified User, add it back to the CSE maps.  If it
9547     // already exists there, recursively merge the results together.
9548     AddModifiedNodeToCSEMaps(User);
9549   }
9550 
9551   // If we just RAUW'd the root, take note.
9552   if (From == getRoot().getNode())
9553     setRoot(SDValue(To, getRoot().getResNo()));
9554 }
9555 
9556 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9557 /// This can cause recursive merging of nodes in the DAG.
9558 ///
9559 /// This version can replace From with any result values.  To must match the
9560 /// number and types of values returned by From.
9561 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9562   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9563     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9564 
9565   // Preserve Debug Info.
9566   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9567     transferDbgValues(SDValue(From, i), To[i]);
9568 
9569   // Iterate over just the existing users of From. See the comments in
9570   // the ReplaceAllUsesWith above.
9571   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9572   RAUWUpdateListener Listener(*this, UI, UE);
9573   while (UI != UE) {
9574     SDNode *User = *UI;
9575 
9576     // This node is about to morph, remove its old self from the CSE maps.
9577     RemoveNodeFromCSEMaps(User);
9578 
9579     // A user can appear in a use list multiple times, and when this happens the
9580     // uses are usually next to each other in the list.  To help reduce the
9581     // number of CSE and divergence recomputations, process all the uses of this
9582     // user that we can find this way.
9583     bool To_IsDivergent = false;
9584     do {
9585       SDUse &Use = UI.getUse();
9586       const SDValue &ToOp = To[Use.getResNo()];
9587       ++UI;
9588       Use.set(ToOp);
9589       To_IsDivergent |= ToOp->isDivergent();
9590     } while (UI != UE && *UI == User);
9591 
9592     if (To_IsDivergent != From->isDivergent())
9593       updateDivergence(User);
9594 
9595     // Now that we have modified User, add it back to the CSE maps.  If it
9596     // already exists there, recursively merge the results together.
9597     AddModifiedNodeToCSEMaps(User);
9598   }
9599 
9600   // If we just RAUW'd the root, take note.
9601   if (From == getRoot().getNode())
9602     setRoot(SDValue(To[getRoot().getResNo()]));
9603 }
9604 
9605 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9606 /// uses of other values produced by From.getNode() alone.  The Deleted
9607 /// vector is handled the same way as for ReplaceAllUsesWith.
9608 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9609   // Handle the really simple, really trivial case efficiently.
9610   if (From == To) return;
9611 
9612   // Handle the simple, trivial, case efficiently.
9613   if (From.getNode()->getNumValues() == 1) {
9614     ReplaceAllUsesWith(From, To);
9615     return;
9616   }
9617 
9618   // Preserve Debug Info.
9619   transferDbgValues(From, To);
9620 
9621   // Iterate over just the existing users of From. See the comments in
9622   // the ReplaceAllUsesWith above.
9623   SDNode::use_iterator UI = From.getNode()->use_begin(),
9624                        UE = From.getNode()->use_end();
9625   RAUWUpdateListener Listener(*this, UI, UE);
9626   while (UI != UE) {
9627     SDNode *User = *UI;
9628     bool UserRemovedFromCSEMaps = false;
9629 
9630     // A user can appear in a use list multiple times, and when this
9631     // happens the uses are usually next to each other in the list.
9632     // To help reduce the number of CSE recomputations, process all
9633     // the uses of this user that we can find this way.
9634     do {
9635       SDUse &Use = UI.getUse();
9636 
9637       // Skip uses of different values from the same node.
9638       if (Use.getResNo() != From.getResNo()) {
9639         ++UI;
9640         continue;
9641       }
9642 
9643       // If this node hasn't been modified yet, it's still in the CSE maps,
9644       // so remove its old self from the CSE maps.
9645       if (!UserRemovedFromCSEMaps) {
9646         RemoveNodeFromCSEMaps(User);
9647         UserRemovedFromCSEMaps = true;
9648       }
9649 
9650       ++UI;
9651       Use.set(To);
9652       if (To->isDivergent() != From->isDivergent())
9653         updateDivergence(User);
9654     } while (UI != UE && *UI == User);
9655     // We are iterating over all uses of the From node, so if a use
9656     // doesn't use the specific value, no changes are made.
9657     if (!UserRemovedFromCSEMaps)
9658       continue;
9659 
9660     // Now that we have modified User, add it back to the CSE maps.  If it
9661     // already exists there, recursively merge the results together.
9662     AddModifiedNodeToCSEMaps(User);
9663   }
9664 
9665   // If we just RAUW'd the root, take note.
9666   if (From == getRoot())
9667     setRoot(To);
9668 }
9669 
9670 namespace {
9671 
9672   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9673   /// to record information about a use.
9674   struct UseMemo {
9675     SDNode *User;
9676     unsigned Index;
9677     SDUse *Use;
9678   };
9679 
9680   /// operator< - Sort Memos by User.
9681   bool operator<(const UseMemo &L, const UseMemo &R) {
9682     return (intptr_t)L.User < (intptr_t)R.User;
9683   }
9684 
9685 } // end anonymous namespace
9686 
9687 bool SelectionDAG::calculateDivergence(SDNode *N) {
9688   if (TLI->isSDNodeAlwaysUniform(N)) {
9689     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9690            "Conflicting divergence information!");
9691     return false;
9692   }
9693   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9694     return true;
9695   for (auto &Op : N->ops()) {
9696     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9697       return true;
9698   }
9699   return false;
9700 }
9701 
9702 void SelectionDAG::updateDivergence(SDNode *N) {
9703   SmallVector<SDNode *, 16> Worklist(1, N);
9704   do {
9705     N = Worklist.pop_back_val();
9706     bool IsDivergent = calculateDivergence(N);
9707     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9708       N->SDNodeBits.IsDivergent = IsDivergent;
9709       llvm::append_range(Worklist, N->uses());
9710     }
9711   } while (!Worklist.empty());
9712 }
9713 
9714 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9715   DenseMap<SDNode *, unsigned> Degree;
9716   Order.reserve(AllNodes.size());
9717   for (auto &N : allnodes()) {
9718     unsigned NOps = N.getNumOperands();
9719     Degree[&N] = NOps;
9720     if (0 == NOps)
9721       Order.push_back(&N);
9722   }
9723   for (size_t I = 0; I != Order.size(); ++I) {
9724     SDNode *N = Order[I];
9725     for (auto U : N->uses()) {
9726       unsigned &UnsortedOps = Degree[U];
9727       if (0 == --UnsortedOps)
9728         Order.push_back(U);
9729     }
9730   }
9731 }
9732 
9733 #ifndef NDEBUG
9734 void SelectionDAG::VerifyDAGDivergence() {
9735   std::vector<SDNode *> TopoOrder;
9736   CreateTopologicalOrder(TopoOrder);
9737   for (auto *N : TopoOrder) {
9738     assert(calculateDivergence(N) == N->isDivergent() &&
9739            "Divergence bit inconsistency detected");
9740   }
9741 }
9742 #endif
9743 
9744 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9745 /// uses of other values produced by From.getNode() alone.  The same value
9746 /// may appear in both the From and To list.  The Deleted vector is
9747 /// handled the same way as for ReplaceAllUsesWith.
9748 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9749                                               const SDValue *To,
9750                                               unsigned Num){
9751   // Handle the simple, trivial case efficiently.
9752   if (Num == 1)
9753     return ReplaceAllUsesOfValueWith(*From, *To);
9754 
9755   transferDbgValues(*From, *To);
9756 
9757   // Read up all the uses and make records of them. This helps
9758   // processing new uses that are introduced during the
9759   // replacement process.
9760   SmallVector<UseMemo, 4> Uses;
9761   for (unsigned i = 0; i != Num; ++i) {
9762     unsigned FromResNo = From[i].getResNo();
9763     SDNode *FromNode = From[i].getNode();
9764     for (SDNode::use_iterator UI = FromNode->use_begin(),
9765          E = FromNode->use_end(); UI != E; ++UI) {
9766       SDUse &Use = UI.getUse();
9767       if (Use.getResNo() == FromResNo) {
9768         UseMemo Memo = { *UI, i, &Use };
9769         Uses.push_back(Memo);
9770       }
9771     }
9772   }
9773 
9774   // Sort the uses, so that all the uses from a given User are together.
9775   llvm::sort(Uses);
9776 
9777   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9778        UseIndex != UseIndexEnd; ) {
9779     // We know that this user uses some value of From.  If it is the right
9780     // value, update it.
9781     SDNode *User = Uses[UseIndex].User;
9782 
9783     // This node is about to morph, remove its old self from the CSE maps.
9784     RemoveNodeFromCSEMaps(User);
9785 
9786     // The Uses array is sorted, so all the uses for a given User
9787     // are next to each other in the list.
9788     // To help reduce the number of CSE recomputations, process all
9789     // the uses of this user that we can find this way.
9790     do {
9791       unsigned i = Uses[UseIndex].Index;
9792       SDUse &Use = *Uses[UseIndex].Use;
9793       ++UseIndex;
9794 
9795       Use.set(To[i]);
9796     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9797 
9798     // Now that we have modified User, add it back to the CSE maps.  If it
9799     // already exists there, recursively merge the results together.
9800     AddModifiedNodeToCSEMaps(User);
9801   }
9802 }
9803 
9804 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9805 /// based on their topological order. It returns the maximum id and a vector
9806 /// of the SDNodes* in assigned order by reference.
9807 unsigned SelectionDAG::AssignTopologicalOrder() {
9808   unsigned DAGSize = 0;
9809 
9810   // SortedPos tracks the progress of the algorithm. Nodes before it are
9811   // sorted, nodes after it are unsorted. When the algorithm completes
9812   // it is at the end of the list.
9813   allnodes_iterator SortedPos = allnodes_begin();
9814 
9815   // Visit all the nodes. Move nodes with no operands to the front of
9816   // the list immediately. Annotate nodes that do have operands with their
9817   // operand count. Before we do this, the Node Id fields of the nodes
9818   // may contain arbitrary values. After, the Node Id fields for nodes
9819   // before SortedPos will contain the topological sort index, and the
9820   // Node Id fields for nodes At SortedPos and after will contain the
9821   // count of outstanding operands.
9822   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
9823     checkForCycles(&N, this);
9824     unsigned Degree = N.getNumOperands();
9825     if (Degree == 0) {
9826       // A node with no uses, add it to the result array immediately.
9827       N.setNodeId(DAGSize++);
9828       allnodes_iterator Q(&N);
9829       if (Q != SortedPos)
9830         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9831       assert(SortedPos != AllNodes.end() && "Overran node list");
9832       ++SortedPos;
9833     } else {
9834       // Temporarily use the Node Id as scratch space for the degree count.
9835       N.setNodeId(Degree);
9836     }
9837   }
9838 
9839   // Visit all the nodes. As we iterate, move nodes into sorted order,
9840   // such that by the time the end is reached all nodes will be sorted.
9841   for (SDNode &Node : allnodes()) {
9842     SDNode *N = &Node;
9843     checkForCycles(N, this);
9844     // N is in sorted position, so all its uses have one less operand
9845     // that needs to be sorted.
9846     for (SDNode *P : N->uses()) {
9847       unsigned Degree = P->getNodeId();
9848       assert(Degree != 0 && "Invalid node degree");
9849       --Degree;
9850       if (Degree == 0) {
9851         // All of P's operands are sorted, so P may sorted now.
9852         P->setNodeId(DAGSize++);
9853         if (P->getIterator() != SortedPos)
9854           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9855         assert(SortedPos != AllNodes.end() && "Overran node list");
9856         ++SortedPos;
9857       } else {
9858         // Update P's outstanding operand count.
9859         P->setNodeId(Degree);
9860       }
9861     }
9862     if (Node.getIterator() == SortedPos) {
9863 #ifndef NDEBUG
9864       allnodes_iterator I(N);
9865       SDNode *S = &*++I;
9866       dbgs() << "Overran sorted position:\n";
9867       S->dumprFull(this); dbgs() << "\n";
9868       dbgs() << "Checking if this is due to cycles\n";
9869       checkForCycles(this, true);
9870 #endif
9871       llvm_unreachable(nullptr);
9872     }
9873   }
9874 
9875   assert(SortedPos == AllNodes.end() &&
9876          "Topological sort incomplete!");
9877   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9878          "First node in topological sort is not the entry token!");
9879   assert(AllNodes.front().getNodeId() == 0 &&
9880          "First node in topological sort has non-zero id!");
9881   assert(AllNodes.front().getNumOperands() == 0 &&
9882          "First node in topological sort has operands!");
9883   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9884          "Last node in topologic sort has unexpected id!");
9885   assert(AllNodes.back().use_empty() &&
9886          "Last node in topologic sort has users!");
9887   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9888   return DAGSize;
9889 }
9890 
9891 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9892 /// value is produced by SD.
9893 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9894   for (SDNode *SD : DB->getSDNodes()) {
9895     if (!SD)
9896       continue;
9897     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9898     SD->setHasDebugValue(true);
9899   }
9900   DbgInfo->add(DB, isParameter);
9901 }
9902 
9903 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9904 
9905 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9906                                                    SDValue NewMemOpChain) {
9907   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9908   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9909   // The new memory operation must have the same position as the old load in
9910   // terms of memory dependency. Create a TokenFactor for the old load and new
9911   // memory operation and update uses of the old load's output chain to use that
9912   // TokenFactor.
9913   if (OldChain == NewMemOpChain || OldChain.use_empty())
9914     return NewMemOpChain;
9915 
9916   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9917                                 OldChain, NewMemOpChain);
9918   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9919   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9920   return TokenFactor;
9921 }
9922 
9923 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9924                                                    SDValue NewMemOp) {
9925   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9926   SDValue OldChain = SDValue(OldLoad, 1);
9927   SDValue NewMemOpChain = NewMemOp.getValue(1);
9928   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9929 }
9930 
9931 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9932                                                      Function **OutFunction) {
9933   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9934 
9935   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9936   auto *Module = MF->getFunction().getParent();
9937   auto *Function = Module->getFunction(Symbol);
9938 
9939   if (OutFunction != nullptr)
9940       *OutFunction = Function;
9941 
9942   if (Function != nullptr) {
9943     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9944     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9945   }
9946 
9947   std::string ErrorStr;
9948   raw_string_ostream ErrorFormatter(ErrorStr);
9949   ErrorFormatter << "Undefined external symbol ";
9950   ErrorFormatter << '"' << Symbol << '"';
9951   report_fatal_error(Twine(ErrorFormatter.str()));
9952 }
9953 
9954 //===----------------------------------------------------------------------===//
9955 //                              SDNode Class
9956 //===----------------------------------------------------------------------===//
9957 
9958 bool llvm::isNullConstant(SDValue V) {
9959   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9960   return Const != nullptr && Const->isZero();
9961 }
9962 
9963 bool llvm::isNullFPConstant(SDValue V) {
9964   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9965   return Const != nullptr && Const->isZero() && !Const->isNegative();
9966 }
9967 
9968 bool llvm::isAllOnesConstant(SDValue V) {
9969   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9970   return Const != nullptr && Const->isAllOnes();
9971 }
9972 
9973 bool llvm::isOneConstant(SDValue V) {
9974   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9975   return Const != nullptr && Const->isOne();
9976 }
9977 
9978 SDValue llvm::peekThroughBitcasts(SDValue V) {
9979   while (V.getOpcode() == ISD::BITCAST)
9980     V = V.getOperand(0);
9981   return V;
9982 }
9983 
9984 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9985   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9986     V = V.getOperand(0);
9987   return V;
9988 }
9989 
9990 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9991   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9992     V = V.getOperand(0);
9993   return V;
9994 }
9995 
9996 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9997   if (V.getOpcode() != ISD::XOR)
9998     return false;
9999   V = peekThroughBitcasts(V.getOperand(1));
10000   unsigned NumBits = V.getScalarValueSizeInBits();
10001   ConstantSDNode *C =
10002       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10003   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10004 }
10005 
10006 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10007                                           bool AllowTruncation) {
10008   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10009     return CN;
10010 
10011   // SplatVectors can truncate their operands. Ignore that case here unless
10012   // AllowTruncation is set.
10013   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10014     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10015     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10016       EVT CVT = CN->getValueType(0);
10017       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10018       if (AllowTruncation || CVT == VecEltVT)
10019         return CN;
10020     }
10021   }
10022 
10023   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10024     BitVector UndefElements;
10025     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10026 
10027     // BuildVectors can truncate their operands. Ignore that case here unless
10028     // AllowTruncation is set.
10029     if (CN && (UndefElements.none() || AllowUndefs)) {
10030       EVT CVT = CN->getValueType(0);
10031       EVT NSVT = N.getValueType().getScalarType();
10032       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10033       if (AllowTruncation || (CVT == NSVT))
10034         return CN;
10035     }
10036   }
10037 
10038   return nullptr;
10039 }
10040 
10041 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10042                                           bool AllowUndefs,
10043                                           bool AllowTruncation) {
10044   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10045     return CN;
10046 
10047   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10048     BitVector UndefElements;
10049     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10050 
10051     // BuildVectors can truncate their operands. Ignore that case here unless
10052     // AllowTruncation is set.
10053     if (CN && (UndefElements.none() || AllowUndefs)) {
10054       EVT CVT = CN->getValueType(0);
10055       EVT NSVT = N.getValueType().getScalarType();
10056       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10057       if (AllowTruncation || (CVT == NSVT))
10058         return CN;
10059     }
10060   }
10061 
10062   return nullptr;
10063 }
10064 
10065 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10066   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10067     return CN;
10068 
10069   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10070     BitVector UndefElements;
10071     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10072     if (CN && (UndefElements.none() || AllowUndefs))
10073       return CN;
10074   }
10075 
10076   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10077     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10078       return CN;
10079 
10080   return nullptr;
10081 }
10082 
10083 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10084                                               const APInt &DemandedElts,
10085                                               bool AllowUndefs) {
10086   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10087     return CN;
10088 
10089   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10090     BitVector UndefElements;
10091     ConstantFPSDNode *CN =
10092         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10093     if (CN && (UndefElements.none() || AllowUndefs))
10094       return CN;
10095   }
10096 
10097   return nullptr;
10098 }
10099 
10100 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10101   // TODO: may want to use peekThroughBitcast() here.
10102   ConstantSDNode *C =
10103       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10104   return C && C->isZero();
10105 }
10106 
10107 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10108   // TODO: may want to use peekThroughBitcast() here.
10109   unsigned BitWidth = N.getScalarValueSizeInBits();
10110   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10111   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10112 }
10113 
10114 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10115   N = peekThroughBitcasts(N);
10116   unsigned BitWidth = N.getScalarValueSizeInBits();
10117   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10118   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10119 }
10120 
10121 HandleSDNode::~HandleSDNode() {
10122   DropOperands();
10123 }
10124 
10125 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10126                                          const DebugLoc &DL,
10127                                          const GlobalValue *GA, EVT VT,
10128                                          int64_t o, unsigned TF)
10129     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10130   TheGlobal = GA;
10131 }
10132 
10133 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10134                                          EVT VT, unsigned SrcAS,
10135                                          unsigned DestAS)
10136     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10137       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10138 
10139 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10140                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10141     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10142   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10143   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10144   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10145   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10146 
10147   // We check here that the size of the memory operand fits within the size of
10148   // the MMO. This is because the MMO might indicate only a possible address
10149   // range instead of specifying the affected memory addresses precisely.
10150   // TODO: Make MachineMemOperands aware of scalable vectors.
10151   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10152          "Size mismatch!");
10153 }
10154 
10155 /// Profile - Gather unique data for the node.
10156 ///
10157 void SDNode::Profile(FoldingSetNodeID &ID) const {
10158   AddNodeIDNode(ID, this);
10159 }
10160 
10161 namespace {
10162 
10163   struct EVTArray {
10164     std::vector<EVT> VTs;
10165 
10166     EVTArray() {
10167       VTs.reserve(MVT::VALUETYPE_SIZE);
10168       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10169         VTs.push_back(MVT((MVT::SimpleValueType)i));
10170     }
10171   };
10172 
10173 } // end anonymous namespace
10174 
10175 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10176 static ManagedStatic<EVTArray> SimpleVTArray;
10177 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10178 
10179 /// getValueTypeList - Return a pointer to the specified value type.
10180 ///
10181 const EVT *SDNode::getValueTypeList(EVT VT) {
10182   if (VT.isExtended()) {
10183     sys::SmartScopedLock<true> Lock(*VTMutex);
10184     return &(*EVTs->insert(VT).first);
10185   }
10186   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10187   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10188 }
10189 
10190 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10191 /// indicated value.  This method ignores uses of other values defined by this
10192 /// operation.
10193 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10194   assert(Value < getNumValues() && "Bad value!");
10195 
10196   // TODO: Only iterate over uses of a given value of the node
10197   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10198     if (UI.getUse().getResNo() == Value) {
10199       if (NUses == 0)
10200         return false;
10201       --NUses;
10202     }
10203   }
10204 
10205   // Found exactly the right number of uses?
10206   return NUses == 0;
10207 }
10208 
10209 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10210 /// value. This method ignores uses of other values defined by this operation.
10211 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10212   assert(Value < getNumValues() && "Bad value!");
10213 
10214   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10215     if (UI.getUse().getResNo() == Value)
10216       return true;
10217 
10218   return false;
10219 }
10220 
10221 /// isOnlyUserOf - Return true if this node is the only use of N.
10222 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10223   bool Seen = false;
10224   for (const SDNode *User : N->uses()) {
10225     if (User == this)
10226       Seen = true;
10227     else
10228       return false;
10229   }
10230 
10231   return Seen;
10232 }
10233 
10234 /// Return true if the only users of N are contained in Nodes.
10235 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10236   bool Seen = false;
10237   for (const SDNode *User : N->uses()) {
10238     if (llvm::is_contained(Nodes, User))
10239       Seen = true;
10240     else
10241       return false;
10242   }
10243 
10244   return Seen;
10245 }
10246 
10247 /// isOperand - Return true if this node is an operand of N.
10248 bool SDValue::isOperandOf(const SDNode *N) const {
10249   return is_contained(N->op_values(), *this);
10250 }
10251 
10252 bool SDNode::isOperandOf(const SDNode *N) const {
10253   return any_of(N->op_values(),
10254                 [this](SDValue Op) { return this == Op.getNode(); });
10255 }
10256 
10257 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10258 /// be a chain) reaches the specified operand without crossing any
10259 /// side-effecting instructions on any chain path.  In practice, this looks
10260 /// through token factors and non-volatile loads.  In order to remain efficient,
10261 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10262 ///
10263 /// Note that we only need to examine chains when we're searching for
10264 /// side-effects; SelectionDAG requires that all side-effects are represented
10265 /// by chains, even if another operand would force a specific ordering. This
10266 /// constraint is necessary to allow transformations like splitting loads.
10267 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10268                                              unsigned Depth) const {
10269   if (*this == Dest) return true;
10270 
10271   // Don't search too deeply, we just want to be able to see through
10272   // TokenFactor's etc.
10273   if (Depth == 0) return false;
10274 
10275   // If this is a token factor, all inputs to the TF happen in parallel.
10276   if (getOpcode() == ISD::TokenFactor) {
10277     // First, try a shallow search.
10278     if (is_contained((*this)->ops(), Dest)) {
10279       // We found the chain we want as an operand of this TokenFactor.
10280       // Essentially, we reach the chain without side-effects if we could
10281       // serialize the TokenFactor into a simple chain of operations with
10282       // Dest as the last operation. This is automatically true if the
10283       // chain has one use: there are no other ordering constraints.
10284       // If the chain has more than one use, we give up: some other
10285       // use of Dest might force a side-effect between Dest and the current
10286       // node.
10287       if (Dest.hasOneUse())
10288         return true;
10289     }
10290     // Next, try a deep search: check whether every operand of the TokenFactor
10291     // reaches Dest.
10292     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10293       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10294     });
10295   }
10296 
10297   // Loads don't have side effects, look through them.
10298   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10299     if (Ld->isUnordered())
10300       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10301   }
10302   return false;
10303 }
10304 
10305 bool SDNode::hasPredecessor(const SDNode *N) const {
10306   SmallPtrSet<const SDNode *, 32> Visited;
10307   SmallVector<const SDNode *, 16> Worklist;
10308   Worklist.push_back(this);
10309   return hasPredecessorHelper(N, Visited, Worklist);
10310 }
10311 
10312 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10313   this->Flags.intersectWith(Flags);
10314 }
10315 
10316 SDValue
10317 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10318                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10319                                   bool AllowPartials) {
10320   // The pattern must end in an extract from index 0.
10321   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10322       !isNullConstant(Extract->getOperand(1)))
10323     return SDValue();
10324 
10325   // Match against one of the candidate binary ops.
10326   SDValue Op = Extract->getOperand(0);
10327   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10328         return Op.getOpcode() == unsigned(BinOp);
10329       }))
10330     return SDValue();
10331 
10332   // Floating-point reductions may require relaxed constraints on the final step
10333   // of the reduction because they may reorder intermediate operations.
10334   unsigned CandidateBinOp = Op.getOpcode();
10335   if (Op.getValueType().isFloatingPoint()) {
10336     SDNodeFlags Flags = Op->getFlags();
10337     switch (CandidateBinOp) {
10338     case ISD::FADD:
10339       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10340         return SDValue();
10341       break;
10342     default:
10343       llvm_unreachable("Unhandled FP opcode for binop reduction");
10344     }
10345   }
10346 
10347   // Matching failed - attempt to see if we did enough stages that a partial
10348   // reduction from a subvector is possible.
10349   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10350     if (!AllowPartials || !Op)
10351       return SDValue();
10352     EVT OpVT = Op.getValueType();
10353     EVT OpSVT = OpVT.getScalarType();
10354     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10355     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10356       return SDValue();
10357     BinOp = (ISD::NodeType)CandidateBinOp;
10358     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10359                    getVectorIdxConstant(0, SDLoc(Op)));
10360   };
10361 
10362   // At each stage, we're looking for something that looks like:
10363   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10364   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10365   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10366   // %a = binop <8 x i32> %op, %s
10367   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10368   // we expect something like:
10369   // <4,5,6,7,u,u,u,u>
10370   // <2,3,u,u,u,u,u,u>
10371   // <1,u,u,u,u,u,u,u>
10372   // While a partial reduction match would be:
10373   // <2,3,u,u,u,u,u,u>
10374   // <1,u,u,u,u,u,u,u>
10375   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10376   SDValue PrevOp;
10377   for (unsigned i = 0; i < Stages; ++i) {
10378     unsigned MaskEnd = (1 << i);
10379 
10380     if (Op.getOpcode() != CandidateBinOp)
10381       return PartialReduction(PrevOp, MaskEnd);
10382 
10383     SDValue Op0 = Op.getOperand(0);
10384     SDValue Op1 = Op.getOperand(1);
10385 
10386     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10387     if (Shuffle) {
10388       Op = Op1;
10389     } else {
10390       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10391       Op = Op0;
10392     }
10393 
10394     // The first operand of the shuffle should be the same as the other operand
10395     // of the binop.
10396     if (!Shuffle || Shuffle->getOperand(0) != Op)
10397       return PartialReduction(PrevOp, MaskEnd);
10398 
10399     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10400     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10401       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10402         return PartialReduction(PrevOp, MaskEnd);
10403 
10404     PrevOp = Op;
10405   }
10406 
10407   // Handle subvector reductions, which tend to appear after the shuffle
10408   // reduction stages.
10409   while (Op.getOpcode() == CandidateBinOp) {
10410     unsigned NumElts = Op.getValueType().getVectorNumElements();
10411     SDValue Op0 = Op.getOperand(0);
10412     SDValue Op1 = Op.getOperand(1);
10413     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10414         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10415         Op0.getOperand(0) != Op1.getOperand(0))
10416       break;
10417     SDValue Src = Op0.getOperand(0);
10418     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10419     if (NumSrcElts != (2 * NumElts))
10420       break;
10421     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10422           Op1.getConstantOperandAPInt(1) == NumElts) &&
10423         !(Op1.getConstantOperandAPInt(1) == 0 &&
10424           Op0.getConstantOperandAPInt(1) == NumElts))
10425       break;
10426     Op = Src;
10427   }
10428 
10429   BinOp = (ISD::NodeType)CandidateBinOp;
10430   return Op;
10431 }
10432 
10433 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10434   assert(N->getNumValues() == 1 &&
10435          "Can't unroll a vector with multiple results!");
10436 
10437   EVT VT = N->getValueType(0);
10438   unsigned NE = VT.getVectorNumElements();
10439   EVT EltVT = VT.getVectorElementType();
10440   SDLoc dl(N);
10441 
10442   SmallVector<SDValue, 8> Scalars;
10443   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10444 
10445   // If ResNE is 0, fully unroll the vector op.
10446   if (ResNE == 0)
10447     ResNE = NE;
10448   else if (NE > ResNE)
10449     NE = ResNE;
10450 
10451   unsigned i;
10452   for (i= 0; i != NE; ++i) {
10453     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10454       SDValue Operand = N->getOperand(j);
10455       EVT OperandVT = Operand.getValueType();
10456       if (OperandVT.isVector()) {
10457         // A vector operand; extract a single element.
10458         EVT OperandEltVT = OperandVT.getVectorElementType();
10459         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10460                               Operand, getVectorIdxConstant(i, dl));
10461       } else {
10462         // A scalar operand; just use it as is.
10463         Operands[j] = Operand;
10464       }
10465     }
10466 
10467     switch (N->getOpcode()) {
10468     default: {
10469       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10470                                 N->getFlags()));
10471       break;
10472     }
10473     case ISD::VSELECT:
10474       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10475       break;
10476     case ISD::SHL:
10477     case ISD::SRA:
10478     case ISD::SRL:
10479     case ISD::ROTL:
10480     case ISD::ROTR:
10481       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10482                                getShiftAmountOperand(Operands[0].getValueType(),
10483                                                      Operands[1])));
10484       break;
10485     case ISD::SIGN_EXTEND_INREG: {
10486       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10487       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10488                                 Operands[0],
10489                                 getValueType(ExtVT)));
10490     }
10491     }
10492   }
10493 
10494   for (; i < ResNE; ++i)
10495     Scalars.push_back(getUNDEF(EltVT));
10496 
10497   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10498   return getBuildVector(VecVT, dl, Scalars);
10499 }
10500 
10501 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10502     SDNode *N, unsigned ResNE) {
10503   unsigned Opcode = N->getOpcode();
10504   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10505           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10506           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10507          "Expected an overflow opcode");
10508 
10509   EVT ResVT = N->getValueType(0);
10510   EVT OvVT = N->getValueType(1);
10511   EVT ResEltVT = ResVT.getVectorElementType();
10512   EVT OvEltVT = OvVT.getVectorElementType();
10513   SDLoc dl(N);
10514 
10515   // If ResNE is 0, fully unroll the vector op.
10516   unsigned NE = ResVT.getVectorNumElements();
10517   if (ResNE == 0)
10518     ResNE = NE;
10519   else if (NE > ResNE)
10520     NE = ResNE;
10521 
10522   SmallVector<SDValue, 8> LHSScalars;
10523   SmallVector<SDValue, 8> RHSScalars;
10524   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10525   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10526 
10527   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10528   SDVTList VTs = getVTList(ResEltVT, SVT);
10529   SmallVector<SDValue, 8> ResScalars;
10530   SmallVector<SDValue, 8> OvScalars;
10531   for (unsigned i = 0; i < NE; ++i) {
10532     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10533     SDValue Ov =
10534         getSelect(dl, OvEltVT, Res.getValue(1),
10535                   getBoolConstant(true, dl, OvEltVT, ResVT),
10536                   getConstant(0, dl, OvEltVT));
10537 
10538     ResScalars.push_back(Res);
10539     OvScalars.push_back(Ov);
10540   }
10541 
10542   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10543   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10544 
10545   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10546   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10547   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10548                         getBuildVector(NewOvVT, dl, OvScalars));
10549 }
10550 
10551 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10552                                                   LoadSDNode *Base,
10553                                                   unsigned Bytes,
10554                                                   int Dist) const {
10555   if (LD->isVolatile() || Base->isVolatile())
10556     return false;
10557   // TODO: probably too restrictive for atomics, revisit
10558   if (!LD->isSimple())
10559     return false;
10560   if (LD->isIndexed() || Base->isIndexed())
10561     return false;
10562   if (LD->getChain() != Base->getChain())
10563     return false;
10564   EVT VT = LD->getValueType(0);
10565   if (VT.getSizeInBits() / 8 != Bytes)
10566     return false;
10567 
10568   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10569   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10570 
10571   int64_t Offset = 0;
10572   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10573     return (Dist * Bytes == Offset);
10574   return false;
10575 }
10576 
10577 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10578 /// if it cannot be inferred.
10579 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10580   // If this is a GlobalAddress + cst, return the alignment.
10581   const GlobalValue *GV = nullptr;
10582   int64_t GVOffset = 0;
10583   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10584     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10585     KnownBits Known(PtrWidth);
10586     llvm::computeKnownBits(GV, Known, getDataLayout());
10587     unsigned AlignBits = Known.countMinTrailingZeros();
10588     if (AlignBits)
10589       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10590   }
10591 
10592   // If this is a direct reference to a stack slot, use information about the
10593   // stack slot's alignment.
10594   int FrameIdx = INT_MIN;
10595   int64_t FrameOffset = 0;
10596   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10597     FrameIdx = FI->getIndex();
10598   } else if (isBaseWithConstantOffset(Ptr) &&
10599              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10600     // Handle FI+Cst
10601     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10602     FrameOffset = Ptr.getConstantOperandVal(1);
10603   }
10604 
10605   if (FrameIdx != INT_MIN) {
10606     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10607     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10608   }
10609 
10610   return None;
10611 }
10612 
10613 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10614 /// which is split (or expanded) into two not necessarily identical pieces.
10615 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10616   // Currently all types are split in half.
10617   EVT LoVT, HiVT;
10618   if (!VT.isVector())
10619     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10620   else
10621     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10622 
10623   return std::make_pair(LoVT, HiVT);
10624 }
10625 
10626 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10627 /// type, dependent on an enveloping VT that has been split into two identical
10628 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10629 std::pair<EVT, EVT>
10630 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10631                                        bool *HiIsEmpty) const {
10632   EVT EltTp = VT.getVectorElementType();
10633   // Examples:
10634   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10635   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10636   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10637   //   etc.
10638   ElementCount VTNumElts = VT.getVectorElementCount();
10639   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10640   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10641          "Mixing fixed width and scalable vectors when enveloping a type");
10642   EVT LoVT, HiVT;
10643   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10644     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10645     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10646     *HiIsEmpty = false;
10647   } else {
10648     // Flag that hi type has zero storage size, but return split envelop type
10649     // (this would be easier if vector types with zero elements were allowed).
10650     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10651     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10652     *HiIsEmpty = true;
10653   }
10654   return std::make_pair(LoVT, HiVT);
10655 }
10656 
10657 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10658 /// low/high part.
10659 std::pair<SDValue, SDValue>
10660 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10661                           const EVT &HiVT) {
10662   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10663          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10664          "Splitting vector with an invalid mixture of fixed and scalable "
10665          "vector types");
10666   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10667              N.getValueType().getVectorMinNumElements() &&
10668          "More vector elements requested than available!");
10669   SDValue Lo, Hi;
10670   Lo =
10671       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10672   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10673   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10674   // IDX with the runtime scaling factor of the result vector type. For
10675   // fixed-width result vectors, that runtime scaling factor is 1.
10676   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10677                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10678   return std::make_pair(Lo, Hi);
10679 }
10680 
10681 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
10682                                                    const SDLoc &DL) {
10683   // Split the vector length parameter.
10684   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
10685   EVT VT = N.getValueType();
10686   assert(VecVT.getVectorElementCount().isKnownEven() &&
10687          "Expecting the mask to be an evenly-sized vector");
10688   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
10689   SDValue HalfNumElts =
10690       VecVT.isFixedLengthVector()
10691           ? getConstant(HalfMinNumElts, DL, VT)
10692           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
10693   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
10694   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
10695   return std::make_pair(Lo, Hi);
10696 }
10697 
10698 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10699 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10700   EVT VT = N.getValueType();
10701   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10702                                 NextPowerOf2(VT.getVectorNumElements()));
10703   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10704                  getVectorIdxConstant(0, DL));
10705 }
10706 
10707 void SelectionDAG::ExtractVectorElements(SDValue Op,
10708                                          SmallVectorImpl<SDValue> &Args,
10709                                          unsigned Start, unsigned Count,
10710                                          EVT EltVT) {
10711   EVT VT = Op.getValueType();
10712   if (Count == 0)
10713     Count = VT.getVectorNumElements();
10714   if (EltVT == EVT())
10715     EltVT = VT.getVectorElementType();
10716   SDLoc SL(Op);
10717   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10718     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10719                            getVectorIdxConstant(i, SL)));
10720   }
10721 }
10722 
10723 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10724 unsigned GlobalAddressSDNode::getAddressSpace() const {
10725   return getGlobal()->getType()->getAddressSpace();
10726 }
10727 
10728 Type *ConstantPoolSDNode::getType() const {
10729   if (isMachineConstantPoolEntry())
10730     return Val.MachineCPVal->getType();
10731   return Val.ConstVal->getType();
10732 }
10733 
10734 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10735                                         unsigned &SplatBitSize,
10736                                         bool &HasAnyUndefs,
10737                                         unsigned MinSplatBits,
10738                                         bool IsBigEndian) const {
10739   EVT VT = getValueType(0);
10740   assert(VT.isVector() && "Expected a vector type");
10741   unsigned VecWidth = VT.getSizeInBits();
10742   if (MinSplatBits > VecWidth)
10743     return false;
10744 
10745   // FIXME: The widths are based on this node's type, but build vectors can
10746   // truncate their operands.
10747   SplatValue = APInt(VecWidth, 0);
10748   SplatUndef = APInt(VecWidth, 0);
10749 
10750   // Get the bits. Bits with undefined values (when the corresponding element
10751   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10752   // in SplatValue. If any of the values are not constant, give up and return
10753   // false.
10754   unsigned int NumOps = getNumOperands();
10755   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10756   unsigned EltWidth = VT.getScalarSizeInBits();
10757 
10758   for (unsigned j = 0; j < NumOps; ++j) {
10759     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10760     SDValue OpVal = getOperand(i);
10761     unsigned BitPos = j * EltWidth;
10762 
10763     if (OpVal.isUndef())
10764       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10765     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10766       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10767     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10768       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10769     else
10770       return false;
10771   }
10772 
10773   // The build_vector is all constants or undefs. Find the smallest element
10774   // size that splats the vector.
10775   HasAnyUndefs = (SplatUndef != 0);
10776 
10777   // FIXME: This does not work for vectors with elements less than 8 bits.
10778   while (VecWidth > 8) {
10779     unsigned HalfSize = VecWidth / 2;
10780     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10781     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10782     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10783     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10784 
10785     // If the two halves do not match (ignoring undef bits), stop here.
10786     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10787         MinSplatBits > HalfSize)
10788       break;
10789 
10790     SplatValue = HighValue | LowValue;
10791     SplatUndef = HighUndef & LowUndef;
10792 
10793     VecWidth = HalfSize;
10794   }
10795 
10796   SplatBitSize = VecWidth;
10797   return true;
10798 }
10799 
10800 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10801                                          BitVector *UndefElements) const {
10802   unsigned NumOps = getNumOperands();
10803   if (UndefElements) {
10804     UndefElements->clear();
10805     UndefElements->resize(NumOps);
10806   }
10807   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10808   if (!DemandedElts)
10809     return SDValue();
10810   SDValue Splatted;
10811   for (unsigned i = 0; i != NumOps; ++i) {
10812     if (!DemandedElts[i])
10813       continue;
10814     SDValue Op = getOperand(i);
10815     if (Op.isUndef()) {
10816       if (UndefElements)
10817         (*UndefElements)[i] = true;
10818     } else if (!Splatted) {
10819       Splatted = Op;
10820     } else if (Splatted != Op) {
10821       return SDValue();
10822     }
10823   }
10824 
10825   if (!Splatted) {
10826     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10827     assert(getOperand(FirstDemandedIdx).isUndef() &&
10828            "Can only have a splat without a constant for all undefs.");
10829     return getOperand(FirstDemandedIdx);
10830   }
10831 
10832   return Splatted;
10833 }
10834 
10835 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10836   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10837   return getSplatValue(DemandedElts, UndefElements);
10838 }
10839 
10840 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10841                                             SmallVectorImpl<SDValue> &Sequence,
10842                                             BitVector *UndefElements) const {
10843   unsigned NumOps = getNumOperands();
10844   Sequence.clear();
10845   if (UndefElements) {
10846     UndefElements->clear();
10847     UndefElements->resize(NumOps);
10848   }
10849   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10850   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10851     return false;
10852 
10853   // Set the undefs even if we don't find a sequence (like getSplatValue).
10854   if (UndefElements)
10855     for (unsigned I = 0; I != NumOps; ++I)
10856       if (DemandedElts[I] && getOperand(I).isUndef())
10857         (*UndefElements)[I] = true;
10858 
10859   // Iteratively widen the sequence length looking for repetitions.
10860   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10861     Sequence.append(SeqLen, SDValue());
10862     for (unsigned I = 0; I != NumOps; ++I) {
10863       if (!DemandedElts[I])
10864         continue;
10865       SDValue &SeqOp = Sequence[I % SeqLen];
10866       SDValue Op = getOperand(I);
10867       if (Op.isUndef()) {
10868         if (!SeqOp)
10869           SeqOp = Op;
10870         continue;
10871       }
10872       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10873         Sequence.clear();
10874         break;
10875       }
10876       SeqOp = Op;
10877     }
10878     if (!Sequence.empty())
10879       return true;
10880   }
10881 
10882   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10883   return false;
10884 }
10885 
10886 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10887                                             BitVector *UndefElements) const {
10888   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10889   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10890 }
10891 
10892 ConstantSDNode *
10893 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10894                                         BitVector *UndefElements) const {
10895   return dyn_cast_or_null<ConstantSDNode>(
10896       getSplatValue(DemandedElts, UndefElements));
10897 }
10898 
10899 ConstantSDNode *
10900 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10901   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10902 }
10903 
10904 ConstantFPSDNode *
10905 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10906                                           BitVector *UndefElements) const {
10907   return dyn_cast_or_null<ConstantFPSDNode>(
10908       getSplatValue(DemandedElts, UndefElements));
10909 }
10910 
10911 ConstantFPSDNode *
10912 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10913   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10914 }
10915 
10916 int32_t
10917 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10918                                                    uint32_t BitWidth) const {
10919   if (ConstantFPSDNode *CN =
10920           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10921     bool IsExact;
10922     APSInt IntVal(BitWidth);
10923     const APFloat &APF = CN->getValueAPF();
10924     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10925             APFloat::opOK ||
10926         !IsExact)
10927       return -1;
10928 
10929     return IntVal.exactLogBase2();
10930   }
10931   return -1;
10932 }
10933 
10934 bool BuildVectorSDNode::getConstantRawBits(
10935     bool IsLittleEndian, unsigned DstEltSizeInBits,
10936     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
10937   // Early-out if this contains anything but Undef/Constant/ConstantFP.
10938   if (!isConstant())
10939     return false;
10940 
10941   unsigned NumSrcOps = getNumOperands();
10942   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
10943   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10944          "Invalid bitcast scale");
10945 
10946   // Extract raw src bits.
10947   SmallVector<APInt> SrcBitElements(NumSrcOps,
10948                                     APInt::getNullValue(SrcEltSizeInBits));
10949   BitVector SrcUndeElements(NumSrcOps, false);
10950 
10951   for (unsigned I = 0; I != NumSrcOps; ++I) {
10952     SDValue Op = getOperand(I);
10953     if (Op.isUndef()) {
10954       SrcUndeElements.set(I);
10955       continue;
10956     }
10957     auto *CInt = dyn_cast<ConstantSDNode>(Op);
10958     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
10959     assert((CInt || CFP) && "Unknown constant");
10960     SrcBitElements[I] =
10961         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
10962              : CFP->getValueAPF().bitcastToAPInt();
10963   }
10964 
10965   // Recast to dst width.
10966   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
10967                 SrcBitElements, UndefElements, SrcUndeElements);
10968   return true;
10969 }
10970 
10971 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
10972                                       unsigned DstEltSizeInBits,
10973                                       SmallVectorImpl<APInt> &DstBitElements,
10974                                       ArrayRef<APInt> SrcBitElements,
10975                                       BitVector &DstUndefElements,
10976                                       const BitVector &SrcUndefElements) {
10977   unsigned NumSrcOps = SrcBitElements.size();
10978   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
10979   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10980          "Invalid bitcast scale");
10981   assert(NumSrcOps == SrcUndefElements.size() &&
10982          "Vector size mismatch");
10983 
10984   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
10985   DstUndefElements.clear();
10986   DstUndefElements.resize(NumDstOps, false);
10987   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
10988 
10989   // Concatenate src elements constant bits together into dst element.
10990   if (SrcEltSizeInBits <= DstEltSizeInBits) {
10991     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
10992     for (unsigned I = 0; I != NumDstOps; ++I) {
10993       DstUndefElements.set(I);
10994       APInt &DstBits = DstBitElements[I];
10995       for (unsigned J = 0; J != Scale; ++J) {
10996         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10997         if (SrcUndefElements[Idx])
10998           continue;
10999         DstUndefElements.reset(I);
11000         const APInt &SrcBits = SrcBitElements[Idx];
11001         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11002                "Illegal constant bitwidths");
11003         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11004       }
11005     }
11006     return;
11007   }
11008 
11009   // Split src element constant bits into dst elements.
11010   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11011   for (unsigned I = 0; I != NumSrcOps; ++I) {
11012     if (SrcUndefElements[I]) {
11013       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11014       continue;
11015     }
11016     const APInt &SrcBits = SrcBitElements[I];
11017     for (unsigned J = 0; J != Scale; ++J) {
11018       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11019       APInt &DstBits = DstBitElements[Idx];
11020       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11021     }
11022   }
11023 }
11024 
11025 bool BuildVectorSDNode::isConstant() const {
11026   for (const SDValue &Op : op_values()) {
11027     unsigned Opc = Op.getOpcode();
11028     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11029       return false;
11030   }
11031   return true;
11032 }
11033 
11034 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11035   // Find the first non-undef value in the shuffle mask.
11036   unsigned i, e;
11037   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11038     /* search */;
11039 
11040   // If all elements are undefined, this shuffle can be considered a splat
11041   // (although it should eventually get simplified away completely).
11042   if (i == e)
11043     return true;
11044 
11045   // Make sure all remaining elements are either undef or the same as the first
11046   // non-undef value.
11047   for (int Idx = Mask[i]; i != e; ++i)
11048     if (Mask[i] >= 0 && Mask[i] != Idx)
11049       return false;
11050   return true;
11051 }
11052 
11053 // Returns the SDNode if it is a constant integer BuildVector
11054 // or constant integer.
11055 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11056   if (isa<ConstantSDNode>(N))
11057     return N.getNode();
11058   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11059     return N.getNode();
11060   // Treat a GlobalAddress supporting constant offset folding as a
11061   // constant integer.
11062   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11063     if (GA->getOpcode() == ISD::GlobalAddress &&
11064         TLI->isOffsetFoldingLegal(GA))
11065       return GA;
11066   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11067       isa<ConstantSDNode>(N.getOperand(0)))
11068     return N.getNode();
11069   return nullptr;
11070 }
11071 
11072 // Returns the SDNode if it is a constant float BuildVector
11073 // or constant float.
11074 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11075   if (isa<ConstantFPSDNode>(N))
11076     return N.getNode();
11077 
11078   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11079     return N.getNode();
11080 
11081   return nullptr;
11082 }
11083 
11084 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11085   assert(!Node->OperandList && "Node already has operands");
11086   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11087          "too many operands to fit into SDNode");
11088   SDUse *Ops = OperandRecycler.allocate(
11089       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11090 
11091   bool IsDivergent = false;
11092   for (unsigned I = 0; I != Vals.size(); ++I) {
11093     Ops[I].setUser(Node);
11094     Ops[I].setInitial(Vals[I]);
11095     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11096       IsDivergent |= Ops[I].getNode()->isDivergent();
11097   }
11098   Node->NumOperands = Vals.size();
11099   Node->OperandList = Ops;
11100   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11101     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11102     Node->SDNodeBits.IsDivergent = IsDivergent;
11103   }
11104   checkForCycles(Node);
11105 }
11106 
11107 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11108                                      SmallVectorImpl<SDValue> &Vals) {
11109   size_t Limit = SDNode::getMaxNumOperands();
11110   while (Vals.size() > Limit) {
11111     unsigned SliceIdx = Vals.size() - Limit;
11112     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11113     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11114     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11115     Vals.emplace_back(NewTF);
11116   }
11117   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11118 }
11119 
11120 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11121                                         EVT VT, SDNodeFlags Flags) {
11122   switch (Opcode) {
11123   default:
11124     return SDValue();
11125   case ISD::ADD:
11126   case ISD::OR:
11127   case ISD::XOR:
11128   case ISD::UMAX:
11129     return getConstant(0, DL, VT);
11130   case ISD::MUL:
11131     return getConstant(1, DL, VT);
11132   case ISD::AND:
11133   case ISD::UMIN:
11134     return getAllOnesConstant(DL, VT);
11135   case ISD::SMAX:
11136     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11137   case ISD::SMIN:
11138     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11139   case ISD::FADD:
11140     return getConstantFP(-0.0, DL, VT);
11141   case ISD::FMUL:
11142     return getConstantFP(1.0, DL, VT);
11143   case ISD::FMINNUM:
11144   case ISD::FMAXNUM: {
11145     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11146     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11147     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11148                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11149                         APFloat::getLargest(Semantics);
11150     if (Opcode == ISD::FMAXNUM)
11151       NeutralAF.changeSign();
11152 
11153     return getConstantFP(NeutralAF, DL, VT);
11154   }
11155   }
11156 }
11157 
11158 #ifndef NDEBUG
11159 static void checkForCyclesHelper(const SDNode *N,
11160                                  SmallPtrSetImpl<const SDNode*> &Visited,
11161                                  SmallPtrSetImpl<const SDNode*> &Checked,
11162                                  const llvm::SelectionDAG *DAG) {
11163   // If this node has already been checked, don't check it again.
11164   if (Checked.count(N))
11165     return;
11166 
11167   // If a node has already been visited on this depth-first walk, reject it as
11168   // a cycle.
11169   if (!Visited.insert(N).second) {
11170     errs() << "Detected cycle in SelectionDAG\n";
11171     dbgs() << "Offending node:\n";
11172     N->dumprFull(DAG); dbgs() << "\n";
11173     abort();
11174   }
11175 
11176   for (const SDValue &Op : N->op_values())
11177     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11178 
11179   Checked.insert(N);
11180   Visited.erase(N);
11181 }
11182 #endif
11183 
11184 void llvm::checkForCycles(const llvm::SDNode *N,
11185                           const llvm::SelectionDAG *DAG,
11186                           bool force) {
11187 #ifndef NDEBUG
11188   bool check = force;
11189 #ifdef EXPENSIVE_CHECKS
11190   check = true;
11191 #endif  // EXPENSIVE_CHECKS
11192   if (check) {
11193     assert(N && "Checking nonexistent SDNode");
11194     SmallPtrSet<const SDNode*, 32> visited;
11195     SmallPtrSet<const SDNode*, 32> checked;
11196     checkForCyclesHelper(N, visited, checked, DAG);
11197   }
11198 #endif  // !NDEBUG
11199 }
11200 
11201 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11202   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11203 }
11204