1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/CodeGen/FunctionLoweringInfo.h"
33 #include "llvm/CodeGen/ISDOpcodes.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineConstantPool.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/RuntimeLibcalls.h"
40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
41 #include "llvm/CodeGen/SelectionDAGNodes.h"
42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
43 #include "llvm/CodeGen/TargetFrameLowering.h"
44 #include "llvm/CodeGen/TargetLowering.h"
45 #include "llvm/CodeGen/TargetRegisterInfo.h"
46 #include "llvm/CodeGen/TargetSubtargetInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugInfoMetadata.h"
52 #include "llvm/IR/DebugLoc.h"
53 #include "llvm/IR/DerivedTypes.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CodeGen.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/KnownBits.h"
65 #include "llvm/Support/MachineValueType.h"
66 #include "llvm/Support/ManagedStatic.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Support/Mutex.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Target/TargetMachine.h"
71 #include "llvm/Target/TargetOptions.h"
72 #include "llvm/Transforms/Utils/SizeOpts.h"
73 #include <algorithm>
74 #include <cassert>
75 #include <cstdint>
76 #include <cstdlib>
77 #include <limits>
78 #include <set>
79 #include <string>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 /// makeVTList - Return an instance of the SDVTList struct initialized with the
86 /// specified members.
87 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
88   SDVTList Res = {VTs, NumVTs};
89   return Res;
90 }
91 
92 // Default null implementations of the callbacks.
93 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
94 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
95 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
96 
97 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
98 
99 #define DEBUG_TYPE "selectiondag"
100 
101 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
102        cl::Hidden, cl::init(true),
103        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
104 
105 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
106        cl::desc("Number limit for gluing ld/st of memcpy."),
107        cl::Hidden, cl::init(0));
108 
109 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
110   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
111 }
112 
113 //===----------------------------------------------------------------------===//
114 //                              ConstantFPSDNode Class
115 //===----------------------------------------------------------------------===//
116 
117 /// isExactlyValue - We don't rely on operator== working on double values, as
118 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
119 /// As such, this method can be used to do an exact bit-for-bit comparison of
120 /// two floating point values.
121 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
122   return getValueAPF().bitwiseIsEqual(V);
123 }
124 
125 bool ConstantFPSDNode::isValueValidForType(EVT VT,
126                                            const APFloat& Val) {
127   assert(VT.isFloatingPoint() && "Can only convert between FP types");
128 
129   // convert modifies in place, so make a copy.
130   APFloat Val2 = APFloat(Val);
131   bool losesInfo;
132   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
133                       APFloat::rmNearestTiesToEven,
134                       &losesInfo);
135   return !losesInfo;
136 }
137 
138 //===----------------------------------------------------------------------===//
139 //                              ISD Namespace
140 //===----------------------------------------------------------------------===//
141 
142 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
143   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
144     unsigned EltSize =
145         N->getValueType(0).getVectorElementType().getSizeInBits();
146     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
147       SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
148       return true;
149     }
150     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
151       SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
152       return true;
153     }
154   }
155 
156   auto *BV = dyn_cast<BuildVectorSDNode>(N);
157   if (!BV)
158     return false;
159 
160   APInt SplatUndef;
161   unsigned SplatBitSize;
162   bool HasUndefs;
163   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
164   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
165                              EltSize) &&
166          EltSize == SplatBitSize;
167 }
168 
169 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
170 // specializations of the more general isConstantSplatVector()?
171 
172 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
173   // Look through a bit convert.
174   while (N->getOpcode() == ISD::BITCAST)
175     N = N->getOperand(0).getNode();
176 
177   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
178     APInt SplatVal;
179     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
180   }
181 
182   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
183 
184   unsigned i = 0, e = N->getNumOperands();
185 
186   // Skip over all of the undef values.
187   while (i != e && N->getOperand(i).isUndef())
188     ++i;
189 
190   // Do not accept an all-undef vector.
191   if (i == e) return false;
192 
193   // Do not accept build_vectors that aren't all constants or which have non-~0
194   // elements. We have to be a bit careful here, as the type of the constant
195   // may not be the same as the type of the vector elements due to type
196   // legalization (the elements are promoted to a legal type for the target and
197   // a vector of a type may be legal when the base element type is not).
198   // We only want to check enough bits to cover the vector elements, because
199   // we care if the resultant vector is all ones, not whether the individual
200   // constants are.
201   SDValue NotZero = N->getOperand(i);
202   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
203   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
204     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
205       return false;
206   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
207     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
208       return false;
209   } else
210     return false;
211 
212   // Okay, we have at least one ~0 value, check to see if the rest match or are
213   // undefs. Even with the above element type twiddling, this should be OK, as
214   // the same type legalization should have applied to all the elements.
215   for (++i; i != e; ++i)
216     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
217       return false;
218   return true;
219 }
220 
221 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
222   // Look through a bit convert.
223   while (N->getOpcode() == ISD::BITCAST)
224     N = N->getOperand(0).getNode();
225 
226   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
227     APInt SplatVal;
228     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
229   }
230 
231   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
232 
233   bool IsAllUndef = true;
234   for (const SDValue &Op : N->op_values()) {
235     if (Op.isUndef())
236       continue;
237     IsAllUndef = false;
238     // Do not accept build_vectors that aren't all constants or which have non-0
239     // elements. We have to be a bit careful here, as the type of the constant
240     // may not be the same as the type of the vector elements due to type
241     // legalization (the elements are promoted to a legal type for the target
242     // and a vector of a type may be legal when the base element type is not).
243     // We only want to check enough bits to cover the vector elements, because
244     // we care if the resultant vector is all zeros, not whether the individual
245     // constants are.
246     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
247     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
248       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
249         return false;
250     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
251       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
252         return false;
253     } else
254       return false;
255   }
256 
257   // Do not accept an all-undef vector.
258   if (IsAllUndef)
259     return false;
260   return true;
261 }
262 
263 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
264   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
265 }
266 
267 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
268   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
269 }
270 
271 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
272   if (N->getOpcode() != ISD::BUILD_VECTOR)
273     return false;
274 
275   for (const SDValue &Op : N->op_values()) {
276     if (Op.isUndef())
277       continue;
278     if (!isa<ConstantSDNode>(Op))
279       return false;
280   }
281   return true;
282 }
283 
284 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
285   if (N->getOpcode() != ISD::BUILD_VECTOR)
286     return false;
287 
288   for (const SDValue &Op : N->op_values()) {
289     if (Op.isUndef())
290       continue;
291     if (!isa<ConstantFPSDNode>(Op))
292       return false;
293   }
294   return true;
295 }
296 
297 bool ISD::allOperandsUndef(const SDNode *N) {
298   // Return false if the node has no operands.
299   // This is "logically inconsistent" with the definition of "all" but
300   // is probably the desired behavior.
301   if (N->getNumOperands() == 0)
302     return false;
303   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
304 }
305 
306 bool ISD::matchUnaryPredicate(SDValue Op,
307                               std::function<bool(ConstantSDNode *)> Match,
308                               bool AllowUndefs) {
309   // FIXME: Add support for scalar UNDEF cases?
310   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
311     return Match(Cst);
312 
313   // FIXME: Add support for vector UNDEF cases?
314   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
315       ISD::SPLAT_VECTOR != Op.getOpcode())
316     return false;
317 
318   EVT SVT = Op.getValueType().getScalarType();
319   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
320     if (AllowUndefs && Op.getOperand(i).isUndef()) {
321       if (!Match(nullptr))
322         return false;
323       continue;
324     }
325 
326     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
327     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
328       return false;
329   }
330   return true;
331 }
332 
333 bool ISD::matchBinaryPredicate(
334     SDValue LHS, SDValue RHS,
335     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
336     bool AllowUndefs, bool AllowTypeMismatch) {
337   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
338     return false;
339 
340   // TODO: Add support for scalar UNDEF cases?
341   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
342     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
343       return Match(LHSCst, RHSCst);
344 
345   // TODO: Add support for vector UNDEF cases?
346   if (LHS.getOpcode() != RHS.getOpcode() ||
347       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
348        LHS.getOpcode() != ISD::SPLAT_VECTOR))
349     return false;
350 
351   EVT SVT = LHS.getValueType().getScalarType();
352   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
353     SDValue LHSOp = LHS.getOperand(i);
354     SDValue RHSOp = RHS.getOperand(i);
355     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
356     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
357     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
358     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
359     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
360       return false;
361     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
362                                LHSOp.getValueType() != RHSOp.getValueType()))
363       return false;
364     if (!Match(LHSCst, RHSCst))
365       return false;
366   }
367   return true;
368 }
369 
370 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
371   switch (VecReduceOpcode) {
372   default:
373     llvm_unreachable("Expected VECREDUCE opcode");
374   case ISD::VECREDUCE_FADD:
375   case ISD::VECREDUCE_SEQ_FADD:
376     return ISD::FADD;
377   case ISD::VECREDUCE_FMUL:
378   case ISD::VECREDUCE_SEQ_FMUL:
379     return ISD::FMUL;
380   case ISD::VECREDUCE_ADD:
381     return ISD::ADD;
382   case ISD::VECREDUCE_MUL:
383     return ISD::MUL;
384   case ISD::VECREDUCE_AND:
385     return ISD::AND;
386   case ISD::VECREDUCE_OR:
387     return ISD::OR;
388   case ISD::VECREDUCE_XOR:
389     return ISD::XOR;
390   case ISD::VECREDUCE_SMAX:
391     return ISD::SMAX;
392   case ISD::VECREDUCE_SMIN:
393     return ISD::SMIN;
394   case ISD::VECREDUCE_UMAX:
395     return ISD::UMAX;
396   case ISD::VECREDUCE_UMIN:
397     return ISD::UMIN;
398   case ISD::VECREDUCE_FMAX:
399     return ISD::FMAXNUM;
400   case ISD::VECREDUCE_FMIN:
401     return ISD::FMINNUM;
402   }
403 }
404 
405 bool ISD::isVPOpcode(unsigned Opcode) {
406   switch (Opcode) {
407   default:
408     return false;
409 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
410   case ISD::VPSD:                                                              \
411     return true;
412 #include "llvm/IR/VPIntrinsics.def"
413   }
414 }
415 
416 bool ISD::isVPBinaryOp(unsigned Opcode) {
417   switch (Opcode) {
418   default:
419     break;
420 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
421 #define VP_PROPERTY_BINARYOP return true;
422 #define END_REGISTER_VP_SDNODE(VPSD) break;
423 #include "llvm/IR/VPIntrinsics.def"
424   }
425   return false;
426 }
427 
428 bool ISD::isVPReduction(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     break;
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437   return false;
438 }
439 
440 /// The operand position of the vector mask.
441 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
442   switch (Opcode) {
443   default:
444     return None;
445 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
446   case ISD::VPSD:                                                              \
447     return MASKPOS;
448 #include "llvm/IR/VPIntrinsics.def"
449   }
450 }
451 
452 /// The operand position of the explicit vector length parameter.
453 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
454   switch (Opcode) {
455   default:
456     return None;
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
458   case ISD::VPSD:                                                              \
459     return EVLPOS;
460 #include "llvm/IR/VPIntrinsics.def"
461   }
462 }
463 
464 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
465   switch (ExtType) {
466   case ISD::EXTLOAD:
467     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
468   case ISD::SEXTLOAD:
469     return ISD::SIGN_EXTEND;
470   case ISD::ZEXTLOAD:
471     return ISD::ZERO_EXTEND;
472   default:
473     break;
474   }
475 
476   llvm_unreachable("Invalid LoadExtType");
477 }
478 
479 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
480   // To perform this operation, we just need to swap the L and G bits of the
481   // operation.
482   unsigned OldL = (Operation >> 2) & 1;
483   unsigned OldG = (Operation >> 1) & 1;
484   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
485                        (OldL << 1) |       // New G bit
486                        (OldG << 2));       // New L bit.
487 }
488 
489 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
490   unsigned Operation = Op;
491   if (isIntegerLike)
492     Operation ^= 7;   // Flip L, G, E bits, but not U.
493   else
494     Operation ^= 15;  // Flip all of the condition bits.
495 
496   if (Operation > ISD::SETTRUE2)
497     Operation &= ~8;  // Don't let N and U bits get set.
498 
499   return ISD::CondCode(Operation);
500 }
501 
502 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
503   return getSetCCInverseImpl(Op, Type.isInteger());
504 }
505 
506 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
507                                                bool isIntegerLike) {
508   return getSetCCInverseImpl(Op, isIntegerLike);
509 }
510 
511 /// For an integer comparison, return 1 if the comparison is a signed operation
512 /// and 2 if the result is an unsigned comparison. Return zero if the operation
513 /// does not depend on the sign of the input (setne and seteq).
514 static int isSignedOp(ISD::CondCode Opcode) {
515   switch (Opcode) {
516   default: llvm_unreachable("Illegal integer setcc operation!");
517   case ISD::SETEQ:
518   case ISD::SETNE: return 0;
519   case ISD::SETLT:
520   case ISD::SETLE:
521   case ISD::SETGT:
522   case ISD::SETGE: return 1;
523   case ISD::SETULT:
524   case ISD::SETULE:
525   case ISD::SETUGT:
526   case ISD::SETUGE: return 2;
527   }
528 }
529 
530 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
531                                        EVT Type) {
532   bool IsInteger = Type.isInteger();
533   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
534     // Cannot fold a signed integer setcc with an unsigned integer setcc.
535     return ISD::SETCC_INVALID;
536 
537   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
538 
539   // If the N and U bits get set, then the resultant comparison DOES suddenly
540   // care about orderedness, and it is true when ordered.
541   if (Op > ISD::SETTRUE2)
542     Op &= ~16;     // Clear the U bit if the N bit is set.
543 
544   // Canonicalize illegal integer setcc's.
545   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
546     Op = ISD::SETNE;
547 
548   return ISD::CondCode(Op);
549 }
550 
551 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
552                                         EVT Type) {
553   bool IsInteger = Type.isInteger();
554   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
555     // Cannot fold a signed setcc with an unsigned setcc.
556     return ISD::SETCC_INVALID;
557 
558   // Combine all of the condition bits.
559   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
560 
561   // Canonicalize illegal integer setcc's.
562   if (IsInteger) {
563     switch (Result) {
564     default: break;
565     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
566     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
567     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
568     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
569     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
570     }
571   }
572 
573   return Result;
574 }
575 
576 //===----------------------------------------------------------------------===//
577 //                           SDNode Profile Support
578 //===----------------------------------------------------------------------===//
579 
580 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
581 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
582   ID.AddInteger(OpC);
583 }
584 
585 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
586 /// solely with their pointer.
587 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
588   ID.AddPointer(VTList.VTs);
589 }
590 
591 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
592 static void AddNodeIDOperands(FoldingSetNodeID &ID,
593                               ArrayRef<SDValue> Ops) {
594   for (auto& Op : Ops) {
595     ID.AddPointer(Op.getNode());
596     ID.AddInteger(Op.getResNo());
597   }
598 }
599 
600 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
601 static void AddNodeIDOperands(FoldingSetNodeID &ID,
602                               ArrayRef<SDUse> Ops) {
603   for (auto& Op : Ops) {
604     ID.AddPointer(Op.getNode());
605     ID.AddInteger(Op.getResNo());
606   }
607 }
608 
609 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
610                           SDVTList VTList, ArrayRef<SDValue> OpList) {
611   AddNodeIDOpcode(ID, OpC);
612   AddNodeIDValueTypes(ID, VTList);
613   AddNodeIDOperands(ID, OpList);
614 }
615 
616 /// If this is an SDNode with special info, add this info to the NodeID data.
617 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
618   switch (N->getOpcode()) {
619   case ISD::TargetExternalSymbol:
620   case ISD::ExternalSymbol:
621   case ISD::MCSymbol:
622     llvm_unreachable("Should only be used on nodes with operands");
623   default: break;  // Normal nodes don't need extra info.
624   case ISD::TargetConstant:
625   case ISD::Constant: {
626     const ConstantSDNode *C = cast<ConstantSDNode>(N);
627     ID.AddPointer(C->getConstantIntValue());
628     ID.AddBoolean(C->isOpaque());
629     break;
630   }
631   case ISD::TargetConstantFP:
632   case ISD::ConstantFP:
633     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
634     break;
635   case ISD::TargetGlobalAddress:
636   case ISD::GlobalAddress:
637   case ISD::TargetGlobalTLSAddress:
638   case ISD::GlobalTLSAddress: {
639     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
640     ID.AddPointer(GA->getGlobal());
641     ID.AddInteger(GA->getOffset());
642     ID.AddInteger(GA->getTargetFlags());
643     break;
644   }
645   case ISD::BasicBlock:
646     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
647     break;
648   case ISD::Register:
649     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
650     break;
651   case ISD::RegisterMask:
652     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
653     break;
654   case ISD::SRCVALUE:
655     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
656     break;
657   case ISD::FrameIndex:
658   case ISD::TargetFrameIndex:
659     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
660     break;
661   case ISD::LIFETIME_START:
662   case ISD::LIFETIME_END:
663     if (cast<LifetimeSDNode>(N)->hasOffset()) {
664       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
665       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
666     }
667     break;
668   case ISD::PSEUDO_PROBE:
669     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
670     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
671     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
672     break;
673   case ISD::JumpTable:
674   case ISD::TargetJumpTable:
675     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
676     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
677     break;
678   case ISD::ConstantPool:
679   case ISD::TargetConstantPool: {
680     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
681     ID.AddInteger(CP->getAlign().value());
682     ID.AddInteger(CP->getOffset());
683     if (CP->isMachineConstantPoolEntry())
684       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
685     else
686       ID.AddPointer(CP->getConstVal());
687     ID.AddInteger(CP->getTargetFlags());
688     break;
689   }
690   case ISD::TargetIndex: {
691     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
692     ID.AddInteger(TI->getIndex());
693     ID.AddInteger(TI->getOffset());
694     ID.AddInteger(TI->getTargetFlags());
695     break;
696   }
697   case ISD::LOAD: {
698     const LoadSDNode *LD = cast<LoadSDNode>(N);
699     ID.AddInteger(LD->getMemoryVT().getRawBits());
700     ID.AddInteger(LD->getRawSubclassData());
701     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
702     break;
703   }
704   case ISD::STORE: {
705     const StoreSDNode *ST = cast<StoreSDNode>(N);
706     ID.AddInteger(ST->getMemoryVT().getRawBits());
707     ID.AddInteger(ST->getRawSubclassData());
708     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
709     break;
710   }
711   case ISD::VP_LOAD: {
712     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
713     ID.AddInteger(ELD->getMemoryVT().getRawBits());
714     ID.AddInteger(ELD->getRawSubclassData());
715     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
716     break;
717   }
718   case ISD::VP_STORE: {
719     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
720     ID.AddInteger(EST->getMemoryVT().getRawBits());
721     ID.AddInteger(EST->getRawSubclassData());
722     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
723     break;
724   }
725   case ISD::VP_GATHER: {
726     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
727     ID.AddInteger(EG->getMemoryVT().getRawBits());
728     ID.AddInteger(EG->getRawSubclassData());
729     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
730     break;
731   }
732   case ISD::VP_SCATTER: {
733     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
734     ID.AddInteger(ES->getMemoryVT().getRawBits());
735     ID.AddInteger(ES->getRawSubclassData());
736     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
737     break;
738   }
739   case ISD::MLOAD: {
740     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
741     ID.AddInteger(MLD->getMemoryVT().getRawBits());
742     ID.AddInteger(MLD->getRawSubclassData());
743     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
744     break;
745   }
746   case ISD::MSTORE: {
747     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
748     ID.AddInteger(MST->getMemoryVT().getRawBits());
749     ID.AddInteger(MST->getRawSubclassData());
750     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
751     break;
752   }
753   case ISD::MGATHER: {
754     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
755     ID.AddInteger(MG->getMemoryVT().getRawBits());
756     ID.AddInteger(MG->getRawSubclassData());
757     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
758     break;
759   }
760   case ISD::MSCATTER: {
761     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
762     ID.AddInteger(MS->getMemoryVT().getRawBits());
763     ID.AddInteger(MS->getRawSubclassData());
764     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
765     break;
766   }
767   case ISD::ATOMIC_CMP_SWAP:
768   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
769   case ISD::ATOMIC_SWAP:
770   case ISD::ATOMIC_LOAD_ADD:
771   case ISD::ATOMIC_LOAD_SUB:
772   case ISD::ATOMIC_LOAD_AND:
773   case ISD::ATOMIC_LOAD_CLR:
774   case ISD::ATOMIC_LOAD_OR:
775   case ISD::ATOMIC_LOAD_XOR:
776   case ISD::ATOMIC_LOAD_NAND:
777   case ISD::ATOMIC_LOAD_MIN:
778   case ISD::ATOMIC_LOAD_MAX:
779   case ISD::ATOMIC_LOAD_UMIN:
780   case ISD::ATOMIC_LOAD_UMAX:
781   case ISD::ATOMIC_LOAD:
782   case ISD::ATOMIC_STORE: {
783     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
784     ID.AddInteger(AT->getMemoryVT().getRawBits());
785     ID.AddInteger(AT->getRawSubclassData());
786     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
787     break;
788   }
789   case ISD::PREFETCH: {
790     const MemSDNode *PF = cast<MemSDNode>(N);
791     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
792     break;
793   }
794   case ISD::VECTOR_SHUFFLE: {
795     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
796     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
797          i != e; ++i)
798       ID.AddInteger(SVN->getMaskElt(i));
799     break;
800   }
801   case ISD::TargetBlockAddress:
802   case ISD::BlockAddress: {
803     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
804     ID.AddPointer(BA->getBlockAddress());
805     ID.AddInteger(BA->getOffset());
806     ID.AddInteger(BA->getTargetFlags());
807     break;
808   }
809   } // end switch (N->getOpcode())
810 
811   // Target specific memory nodes could also have address spaces to check.
812   if (N->isTargetMemoryOpcode())
813     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
814 }
815 
816 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
817 /// data.
818 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
819   AddNodeIDOpcode(ID, N->getOpcode());
820   // Add the return value info.
821   AddNodeIDValueTypes(ID, N->getVTList());
822   // Add the operand info.
823   AddNodeIDOperands(ID, N->ops());
824 
825   // Handle SDNode leafs with special info.
826   AddNodeIDCustom(ID, N);
827 }
828 
829 //===----------------------------------------------------------------------===//
830 //                              SelectionDAG Class
831 //===----------------------------------------------------------------------===//
832 
833 /// doNotCSE - Return true if CSE should not be performed for this node.
834 static bool doNotCSE(SDNode *N) {
835   if (N->getValueType(0) == MVT::Glue)
836     return true; // Never CSE anything that produces a flag.
837 
838   switch (N->getOpcode()) {
839   default: break;
840   case ISD::HANDLENODE:
841   case ISD::EH_LABEL:
842     return true;   // Never CSE these nodes.
843   }
844 
845   // Check that remaining values produced are not flags.
846   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
847     if (N->getValueType(i) == MVT::Glue)
848       return true; // Never CSE anything that produces a flag.
849 
850   return false;
851 }
852 
853 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
854 /// SelectionDAG.
855 void SelectionDAG::RemoveDeadNodes() {
856   // Create a dummy node (which is not added to allnodes), that adds a reference
857   // to the root node, preventing it from being deleted.
858   HandleSDNode Dummy(getRoot());
859 
860   SmallVector<SDNode*, 128> DeadNodes;
861 
862   // Add all obviously-dead nodes to the DeadNodes worklist.
863   for (SDNode &Node : allnodes())
864     if (Node.use_empty())
865       DeadNodes.push_back(&Node);
866 
867   RemoveDeadNodes(DeadNodes);
868 
869   // If the root changed (e.g. it was a dead load, update the root).
870   setRoot(Dummy.getValue());
871 }
872 
873 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
874 /// given list, and any nodes that become unreachable as a result.
875 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
876 
877   // Process the worklist, deleting the nodes and adding their uses to the
878   // worklist.
879   while (!DeadNodes.empty()) {
880     SDNode *N = DeadNodes.pop_back_val();
881     // Skip to next node if we've already managed to delete the node. This could
882     // happen if replacing a node causes a node previously added to the node to
883     // be deleted.
884     if (N->getOpcode() == ISD::DELETED_NODE)
885       continue;
886 
887     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
888       DUL->NodeDeleted(N, nullptr);
889 
890     // Take the node out of the appropriate CSE map.
891     RemoveNodeFromCSEMaps(N);
892 
893     // Next, brutally remove the operand list.  This is safe to do, as there are
894     // no cycles in the graph.
895     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
896       SDUse &Use = *I++;
897       SDNode *Operand = Use.getNode();
898       Use.set(SDValue());
899 
900       // Now that we removed this operand, see if there are no uses of it left.
901       if (Operand->use_empty())
902         DeadNodes.push_back(Operand);
903     }
904 
905     DeallocateNode(N);
906   }
907 }
908 
909 void SelectionDAG::RemoveDeadNode(SDNode *N){
910   SmallVector<SDNode*, 16> DeadNodes(1, N);
911 
912   // Create a dummy node that adds a reference to the root node, preventing
913   // it from being deleted.  (This matters if the root is an operand of the
914   // dead node.)
915   HandleSDNode Dummy(getRoot());
916 
917   RemoveDeadNodes(DeadNodes);
918 }
919 
920 void SelectionDAG::DeleteNode(SDNode *N) {
921   // First take this out of the appropriate CSE map.
922   RemoveNodeFromCSEMaps(N);
923 
924   // Finally, remove uses due to operands of this node, remove from the
925   // AllNodes list, and delete the node.
926   DeleteNodeNotInCSEMaps(N);
927 }
928 
929 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
930   assert(N->getIterator() != AllNodes.begin() &&
931          "Cannot delete the entry node!");
932   assert(N->use_empty() && "Cannot delete a node that is not dead!");
933 
934   // Drop all of the operands and decrement used node's use counts.
935   N->DropOperands();
936 
937   DeallocateNode(N);
938 }
939 
940 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
941   assert(!(V->isVariadic() && isParameter));
942   if (isParameter)
943     ByvalParmDbgValues.push_back(V);
944   else
945     DbgValues.push_back(V);
946   for (const SDNode *Node : V->getSDNodes())
947     if (Node)
948       DbgValMap[Node].push_back(V);
949 }
950 
951 void SDDbgInfo::erase(const SDNode *Node) {
952   DbgValMapType::iterator I = DbgValMap.find(Node);
953   if (I == DbgValMap.end())
954     return;
955   for (auto &Val: I->second)
956     Val->setIsInvalidated();
957   DbgValMap.erase(I);
958 }
959 
960 void SelectionDAG::DeallocateNode(SDNode *N) {
961   // If we have operands, deallocate them.
962   removeOperands(N);
963 
964   NodeAllocator.Deallocate(AllNodes.remove(N));
965 
966   // Set the opcode to DELETED_NODE to help catch bugs when node
967   // memory is reallocated.
968   // FIXME: There are places in SDag that have grown a dependency on the opcode
969   // value in the released node.
970   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
971   N->NodeType = ISD::DELETED_NODE;
972 
973   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
974   // them and forget about that node.
975   DbgInfo->erase(N);
976 }
977 
978 #ifndef NDEBUG
979 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
980 static void VerifySDNode(SDNode *N) {
981   switch (N->getOpcode()) {
982   default:
983     break;
984   case ISD::BUILD_PAIR: {
985     EVT VT = N->getValueType(0);
986     assert(N->getNumValues() == 1 && "Too many results!");
987     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
988            "Wrong return type!");
989     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
990     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
991            "Mismatched operand types!");
992     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
993            "Wrong operand type!");
994     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
995            "Wrong return type size");
996     break;
997   }
998   case ISD::BUILD_VECTOR: {
999     assert(N->getNumValues() == 1 && "Too many results!");
1000     assert(N->getValueType(0).isVector() && "Wrong return type!");
1001     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1002            "Wrong number of operands!");
1003     EVT EltVT = N->getValueType(0).getVectorElementType();
1004     for (const SDUse &Op : N->ops()) {
1005       assert((Op.getValueType() == EltVT ||
1006               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1007                EltVT.bitsLE(Op.getValueType()))) &&
1008              "Wrong operand type!");
1009       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1010              "Operands must all have the same type");
1011     }
1012     break;
1013   }
1014   }
1015 }
1016 #endif // NDEBUG
1017 
1018 /// Insert a newly allocated node into the DAG.
1019 ///
1020 /// Handles insertion into the all nodes list and CSE map, as well as
1021 /// verification and other common operations when a new node is allocated.
1022 void SelectionDAG::InsertNode(SDNode *N) {
1023   AllNodes.push_back(N);
1024 #ifndef NDEBUG
1025   N->PersistentId = NextPersistentId++;
1026   VerifySDNode(N);
1027 #endif
1028   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1029     DUL->NodeInserted(N);
1030 }
1031 
1032 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1033 /// correspond to it.  This is useful when we're about to delete or repurpose
1034 /// the node.  We don't want future request for structurally identical nodes
1035 /// to return N anymore.
1036 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1037   bool Erased = false;
1038   switch (N->getOpcode()) {
1039   case ISD::HANDLENODE: return false;  // noop.
1040   case ISD::CONDCODE:
1041     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1042            "Cond code doesn't exist!");
1043     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1044     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1045     break;
1046   case ISD::ExternalSymbol:
1047     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1048     break;
1049   case ISD::TargetExternalSymbol: {
1050     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1051     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1052         ESN->getSymbol(), ESN->getTargetFlags()));
1053     break;
1054   }
1055   case ISD::MCSymbol: {
1056     auto *MCSN = cast<MCSymbolSDNode>(N);
1057     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1058     break;
1059   }
1060   case ISD::VALUETYPE: {
1061     EVT VT = cast<VTSDNode>(N)->getVT();
1062     if (VT.isExtended()) {
1063       Erased = ExtendedValueTypeNodes.erase(VT);
1064     } else {
1065       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1066       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1067     }
1068     break;
1069   }
1070   default:
1071     // Remove it from the CSE Map.
1072     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1073     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1074     Erased = CSEMap.RemoveNode(N);
1075     break;
1076   }
1077 #ifndef NDEBUG
1078   // Verify that the node was actually in one of the CSE maps, unless it has a
1079   // flag result (which cannot be CSE'd) or is one of the special cases that are
1080   // not subject to CSE.
1081   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1082       !N->isMachineOpcode() && !doNotCSE(N)) {
1083     N->dump(this);
1084     dbgs() << "\n";
1085     llvm_unreachable("Node is not in map!");
1086   }
1087 #endif
1088   return Erased;
1089 }
1090 
1091 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1092 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1093 /// node already exists, in which case transfer all its users to the existing
1094 /// node. This transfer can potentially trigger recursive merging.
1095 void
1096 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1097   // For node types that aren't CSE'd, just act as if no identical node
1098   // already exists.
1099   if (!doNotCSE(N)) {
1100     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1101     if (Existing != N) {
1102       // If there was already an existing matching node, use ReplaceAllUsesWith
1103       // to replace the dead one with the existing one.  This can cause
1104       // recursive merging of other unrelated nodes down the line.
1105       ReplaceAllUsesWith(N, Existing);
1106 
1107       // N is now dead. Inform the listeners and delete it.
1108       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1109         DUL->NodeDeleted(N, Existing);
1110       DeleteNodeNotInCSEMaps(N);
1111       return;
1112     }
1113   }
1114 
1115   // If the node doesn't already exist, we updated it.  Inform listeners.
1116   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1117     DUL->NodeUpdated(N);
1118 }
1119 
1120 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1121 /// were replaced with those specified.  If this node is never memoized,
1122 /// return null, otherwise return a pointer to the slot it would take.  If a
1123 /// node already exists with these operands, the slot will be non-null.
1124 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1125                                            void *&InsertPos) {
1126   if (doNotCSE(N))
1127     return nullptr;
1128 
1129   SDValue Ops[] = { Op };
1130   FoldingSetNodeID ID;
1131   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1132   AddNodeIDCustom(ID, N);
1133   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1134   if (Node)
1135     Node->intersectFlagsWith(N->getFlags());
1136   return Node;
1137 }
1138 
1139 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1140 /// were replaced with those specified.  If this node is never memoized,
1141 /// return null, otherwise return a pointer to the slot it would take.  If a
1142 /// node already exists with these operands, the slot will be non-null.
1143 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1144                                            SDValue Op1, SDValue Op2,
1145                                            void *&InsertPos) {
1146   if (doNotCSE(N))
1147     return nullptr;
1148 
1149   SDValue Ops[] = { Op1, Op2 };
1150   FoldingSetNodeID ID;
1151   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1152   AddNodeIDCustom(ID, N);
1153   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1154   if (Node)
1155     Node->intersectFlagsWith(N->getFlags());
1156   return Node;
1157 }
1158 
1159 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1160 /// were replaced with those specified.  If this node is never memoized,
1161 /// return null, otherwise return a pointer to the slot it would take.  If a
1162 /// node already exists with these operands, the slot will be non-null.
1163 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1164                                            void *&InsertPos) {
1165   if (doNotCSE(N))
1166     return nullptr;
1167 
1168   FoldingSetNodeID ID;
1169   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1170   AddNodeIDCustom(ID, N);
1171   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1172   if (Node)
1173     Node->intersectFlagsWith(N->getFlags());
1174   return Node;
1175 }
1176 
1177 Align SelectionDAG::getEVTAlign(EVT VT) const {
1178   Type *Ty = VT == MVT::iPTR ?
1179                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1180                    VT.getTypeForEVT(*getContext());
1181 
1182   return getDataLayout().getABITypeAlign(Ty);
1183 }
1184 
1185 // EntryNode could meaningfully have debug info if we can find it...
1186 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1187     : TM(tm), OptLevel(OL),
1188       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1189       Root(getEntryNode()) {
1190   InsertNode(&EntryNode);
1191   DbgInfo = new SDDbgInfo();
1192 }
1193 
1194 void SelectionDAG::init(MachineFunction &NewMF,
1195                         OptimizationRemarkEmitter &NewORE,
1196                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1197                         LegacyDivergenceAnalysis * Divergence,
1198                         ProfileSummaryInfo *PSIin,
1199                         BlockFrequencyInfo *BFIin) {
1200   MF = &NewMF;
1201   SDAGISelPass = PassPtr;
1202   ORE = &NewORE;
1203   TLI = getSubtarget().getTargetLowering();
1204   TSI = getSubtarget().getSelectionDAGInfo();
1205   LibInfo = LibraryInfo;
1206   Context = &MF->getFunction().getContext();
1207   DA = Divergence;
1208   PSI = PSIin;
1209   BFI = BFIin;
1210 }
1211 
1212 SelectionDAG::~SelectionDAG() {
1213   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1214   allnodes_clear();
1215   OperandRecycler.clear(OperandAllocator);
1216   delete DbgInfo;
1217 }
1218 
1219 bool SelectionDAG::shouldOptForSize() const {
1220   return MF->getFunction().hasOptSize() ||
1221       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1222 }
1223 
1224 void SelectionDAG::allnodes_clear() {
1225   assert(&*AllNodes.begin() == &EntryNode);
1226   AllNodes.remove(AllNodes.begin());
1227   while (!AllNodes.empty())
1228     DeallocateNode(&AllNodes.front());
1229 #ifndef NDEBUG
1230   NextPersistentId = 0;
1231 #endif
1232 }
1233 
1234 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1235                                           void *&InsertPos) {
1236   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1237   if (N) {
1238     switch (N->getOpcode()) {
1239     default: break;
1240     case ISD::Constant:
1241     case ISD::ConstantFP:
1242       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1243                        "debug location.  Use another overload.");
1244     }
1245   }
1246   return N;
1247 }
1248 
1249 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1250                                           const SDLoc &DL, void *&InsertPos) {
1251   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1252   if (N) {
1253     switch (N->getOpcode()) {
1254     case ISD::Constant:
1255     case ISD::ConstantFP:
1256       // Erase debug location from the node if the node is used at several
1257       // different places. Do not propagate one location to all uses as it
1258       // will cause a worse single stepping debugging experience.
1259       if (N->getDebugLoc() != DL.getDebugLoc())
1260         N->setDebugLoc(DebugLoc());
1261       break;
1262     default:
1263       // When the node's point of use is located earlier in the instruction
1264       // sequence than its prior point of use, update its debug info to the
1265       // earlier location.
1266       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1267         N->setDebugLoc(DL.getDebugLoc());
1268       break;
1269     }
1270   }
1271   return N;
1272 }
1273 
1274 void SelectionDAG::clear() {
1275   allnodes_clear();
1276   OperandRecycler.clear(OperandAllocator);
1277   OperandAllocator.Reset();
1278   CSEMap.clear();
1279 
1280   ExtendedValueTypeNodes.clear();
1281   ExternalSymbols.clear();
1282   TargetExternalSymbols.clear();
1283   MCSymbols.clear();
1284   SDCallSiteDbgInfo.clear();
1285   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1286             static_cast<CondCodeSDNode*>(nullptr));
1287   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1288             static_cast<SDNode*>(nullptr));
1289 
1290   EntryNode.UseList = nullptr;
1291   InsertNode(&EntryNode);
1292   Root = getEntryNode();
1293   DbgInfo->clear();
1294 }
1295 
1296 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1297   return VT.bitsGT(Op.getValueType())
1298              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1299              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1300 }
1301 
1302 std::pair<SDValue, SDValue>
1303 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1304                                        const SDLoc &DL, EVT VT) {
1305   assert(!VT.bitsEq(Op.getValueType()) &&
1306          "Strict no-op FP extend/round not allowed.");
1307   SDValue Res =
1308       VT.bitsGT(Op.getValueType())
1309           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1310           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1311                     {Chain, Op, getIntPtrConstant(0, DL)});
1312 
1313   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1314 }
1315 
1316 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1317   return VT.bitsGT(Op.getValueType()) ?
1318     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1319     getNode(ISD::TRUNCATE, DL, VT, Op);
1320 }
1321 
1322 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1323   return VT.bitsGT(Op.getValueType()) ?
1324     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1325     getNode(ISD::TRUNCATE, DL, VT, Op);
1326 }
1327 
1328 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1329   return VT.bitsGT(Op.getValueType()) ?
1330     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1331     getNode(ISD::TRUNCATE, DL, VT, Op);
1332 }
1333 
1334 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1335                                         EVT OpVT) {
1336   if (VT.bitsLE(Op.getValueType()))
1337     return getNode(ISD::TRUNCATE, SL, VT, Op);
1338 
1339   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1340   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1341 }
1342 
1343 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1344   EVT OpVT = Op.getValueType();
1345   assert(VT.isInteger() && OpVT.isInteger() &&
1346          "Cannot getZeroExtendInReg FP types");
1347   assert(VT.isVector() == OpVT.isVector() &&
1348          "getZeroExtendInReg type should be vector iff the operand "
1349          "type is vector!");
1350   assert((!VT.isVector() ||
1351           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1352          "Vector element counts must match in getZeroExtendInReg");
1353   assert(VT.bitsLE(OpVT) && "Not extending!");
1354   if (OpVT == VT)
1355     return Op;
1356   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1357                                    VT.getScalarSizeInBits());
1358   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1359 }
1360 
1361 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362   // Only unsigned pointer semantics are supported right now. In the future this
1363   // might delegate to TLI to check pointer signedness.
1364   return getZExtOrTrunc(Op, DL, VT);
1365 }
1366 
1367 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1368   // Only unsigned pointer semantics are supported right now. In the future this
1369   // might delegate to TLI to check pointer signedness.
1370   return getZeroExtendInReg(Op, DL, VT);
1371 }
1372 
1373 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1374 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1375   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1376 }
1377 
1378 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1379   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1380   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1381 }
1382 
1383 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1384                                       EVT OpVT) {
1385   if (!V)
1386     return getConstant(0, DL, VT);
1387 
1388   switch (TLI->getBooleanContents(OpVT)) {
1389   case TargetLowering::ZeroOrOneBooleanContent:
1390   case TargetLowering::UndefinedBooleanContent:
1391     return getConstant(1, DL, VT);
1392   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1393     return getAllOnesConstant(DL, VT);
1394   }
1395   llvm_unreachable("Unexpected boolean content enum!");
1396 }
1397 
1398 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1399                                   bool isT, bool isO) {
1400   EVT EltVT = VT.getScalarType();
1401   assert((EltVT.getSizeInBits() >= 64 ||
1402           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1403          "getConstant with a uint64_t value that doesn't fit in the type!");
1404   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1405 }
1406 
1407 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1408                                   bool isT, bool isO) {
1409   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1410 }
1411 
1412 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1413                                   EVT VT, bool isT, bool isO) {
1414   assert(VT.isInteger() && "Cannot create FP integer constant!");
1415 
1416   EVT EltVT = VT.getScalarType();
1417   const ConstantInt *Elt = &Val;
1418 
1419   // In some cases the vector type is legal but the element type is illegal and
1420   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1421   // inserted value (the type does not need to match the vector element type).
1422   // Any extra bits introduced will be truncated away.
1423   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1424                            TargetLowering::TypePromoteInteger) {
1425     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1426     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1427     Elt = ConstantInt::get(*getContext(), NewVal);
1428   }
1429   // In other cases the element type is illegal and needs to be expanded, for
1430   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1431   // the value into n parts and use a vector type with n-times the elements.
1432   // Then bitcast to the type requested.
1433   // Legalizing constants too early makes the DAGCombiner's job harder so we
1434   // only legalize if the DAG tells us we must produce legal types.
1435   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1436            TLI->getTypeAction(*getContext(), EltVT) ==
1437                TargetLowering::TypeExpandInteger) {
1438     const APInt &NewVal = Elt->getValue();
1439     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1440     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1441 
1442     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1443     if (VT.isScalableVector()) {
1444       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1445              "Can only handle an even split!");
1446       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1447 
1448       SmallVector<SDValue, 2> ScalarParts;
1449       for (unsigned i = 0; i != Parts; ++i)
1450         ScalarParts.push_back(getConstant(
1451             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1452             ViaEltVT, isT, isO));
1453 
1454       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1455     }
1456 
1457     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1458     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1459 
1460     // Check the temporary vector is the correct size. If this fails then
1461     // getTypeToTransformTo() probably returned a type whose size (in bits)
1462     // isn't a power-of-2 factor of the requested type size.
1463     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1464 
1465     SmallVector<SDValue, 2> EltParts;
1466     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1467       EltParts.push_back(getConstant(
1468           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1469           ViaEltVT, isT, isO));
1470 
1471     // EltParts is currently in little endian order. If we actually want
1472     // big-endian order then reverse it now.
1473     if (getDataLayout().isBigEndian())
1474       std::reverse(EltParts.begin(), EltParts.end());
1475 
1476     // The elements must be reversed when the element order is different
1477     // to the endianness of the elements (because the BITCAST is itself a
1478     // vector shuffle in this situation). However, we do not need any code to
1479     // perform this reversal because getConstant() is producing a vector
1480     // splat.
1481     // This situation occurs in MIPS MSA.
1482 
1483     SmallVector<SDValue, 8> Ops;
1484     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1485       llvm::append_range(Ops, EltParts);
1486 
1487     SDValue V =
1488         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1489     return V;
1490   }
1491 
1492   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1493          "APInt size does not match type size!");
1494   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1495   FoldingSetNodeID ID;
1496   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1497   ID.AddPointer(Elt);
1498   ID.AddBoolean(isO);
1499   void *IP = nullptr;
1500   SDNode *N = nullptr;
1501   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1502     if (!VT.isVector())
1503       return SDValue(N, 0);
1504 
1505   if (!N) {
1506     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1507     CSEMap.InsertNode(N, IP);
1508     InsertNode(N);
1509     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1510   }
1511 
1512   SDValue Result(N, 0);
1513   if (VT.isScalableVector())
1514     Result = getSplatVector(VT, DL, Result);
1515   else if (VT.isVector())
1516     Result = getSplatBuildVector(VT, DL, Result);
1517 
1518   return Result;
1519 }
1520 
1521 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1522                                         bool isTarget) {
1523   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1524 }
1525 
1526 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1527                                              const SDLoc &DL, bool LegalTypes) {
1528   assert(VT.isInteger() && "Shift amount is not an integer type!");
1529   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1530   return getConstant(Val, DL, ShiftVT);
1531 }
1532 
1533 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1534                                            bool isTarget) {
1535   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1536 }
1537 
1538 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1539                                     bool isTarget) {
1540   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1541 }
1542 
1543 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1544                                     EVT VT, bool isTarget) {
1545   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1546 
1547   EVT EltVT = VT.getScalarType();
1548 
1549   // Do the map lookup using the actual bit pattern for the floating point
1550   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1551   // we don't have issues with SNANs.
1552   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1553   FoldingSetNodeID ID;
1554   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1555   ID.AddPointer(&V);
1556   void *IP = nullptr;
1557   SDNode *N = nullptr;
1558   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1559     if (!VT.isVector())
1560       return SDValue(N, 0);
1561 
1562   if (!N) {
1563     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1564     CSEMap.InsertNode(N, IP);
1565     InsertNode(N);
1566   }
1567 
1568   SDValue Result(N, 0);
1569   if (VT.isScalableVector())
1570     Result = getSplatVector(VT, DL, Result);
1571   else if (VT.isVector())
1572     Result = getSplatBuildVector(VT, DL, Result);
1573   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1574   return Result;
1575 }
1576 
1577 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1578                                     bool isTarget) {
1579   EVT EltVT = VT.getScalarType();
1580   if (EltVT == MVT::f32)
1581     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1582   if (EltVT == MVT::f64)
1583     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1584   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1585       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1586     bool Ignored;
1587     APFloat APF = APFloat(Val);
1588     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1589                 &Ignored);
1590     return getConstantFP(APF, DL, VT, isTarget);
1591   }
1592   llvm_unreachable("Unsupported type in getConstantFP");
1593 }
1594 
1595 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1596                                        EVT VT, int64_t Offset, bool isTargetGA,
1597                                        unsigned TargetFlags) {
1598   assert((TargetFlags == 0 || isTargetGA) &&
1599          "Cannot set target flags on target-independent globals");
1600 
1601   // Truncate (with sign-extension) the offset value to the pointer size.
1602   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1603   if (BitWidth < 64)
1604     Offset = SignExtend64(Offset, BitWidth);
1605 
1606   unsigned Opc;
1607   if (GV->isThreadLocal())
1608     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1609   else
1610     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1611 
1612   FoldingSetNodeID ID;
1613   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1614   ID.AddPointer(GV);
1615   ID.AddInteger(Offset);
1616   ID.AddInteger(TargetFlags);
1617   void *IP = nullptr;
1618   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1619     return SDValue(E, 0);
1620 
1621   auto *N = newSDNode<GlobalAddressSDNode>(
1622       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1623   CSEMap.InsertNode(N, IP);
1624     InsertNode(N);
1625   return SDValue(N, 0);
1626 }
1627 
1628 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1629   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1630   FoldingSetNodeID ID;
1631   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1632   ID.AddInteger(FI);
1633   void *IP = nullptr;
1634   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1635     return SDValue(E, 0);
1636 
1637   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1638   CSEMap.InsertNode(N, IP);
1639   InsertNode(N);
1640   return SDValue(N, 0);
1641 }
1642 
1643 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1644                                    unsigned TargetFlags) {
1645   assert((TargetFlags == 0 || isTarget) &&
1646          "Cannot set target flags on target-independent jump tables");
1647   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1648   FoldingSetNodeID ID;
1649   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1650   ID.AddInteger(JTI);
1651   ID.AddInteger(TargetFlags);
1652   void *IP = nullptr;
1653   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1654     return SDValue(E, 0);
1655 
1656   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1657   CSEMap.InsertNode(N, IP);
1658   InsertNode(N);
1659   return SDValue(N, 0);
1660 }
1661 
1662 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1663                                       MaybeAlign Alignment, int Offset,
1664                                       bool isTarget, unsigned TargetFlags) {
1665   assert((TargetFlags == 0 || isTarget) &&
1666          "Cannot set target flags on target-independent globals");
1667   if (!Alignment)
1668     Alignment = shouldOptForSize()
1669                     ? getDataLayout().getABITypeAlign(C->getType())
1670                     : getDataLayout().getPrefTypeAlign(C->getType());
1671   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1672   FoldingSetNodeID ID;
1673   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1674   ID.AddInteger(Alignment->value());
1675   ID.AddInteger(Offset);
1676   ID.AddPointer(C);
1677   ID.AddInteger(TargetFlags);
1678   void *IP = nullptr;
1679   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1680     return SDValue(E, 0);
1681 
1682   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1683                                           TargetFlags);
1684   CSEMap.InsertNode(N, IP);
1685   InsertNode(N);
1686   SDValue V = SDValue(N, 0);
1687   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1688   return V;
1689 }
1690 
1691 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1692                                       MaybeAlign Alignment, int Offset,
1693                                       bool isTarget, unsigned TargetFlags) {
1694   assert((TargetFlags == 0 || isTarget) &&
1695          "Cannot set target flags on target-independent globals");
1696   if (!Alignment)
1697     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1698   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1699   FoldingSetNodeID ID;
1700   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1701   ID.AddInteger(Alignment->value());
1702   ID.AddInteger(Offset);
1703   C->addSelectionDAGCSEId(ID);
1704   ID.AddInteger(TargetFlags);
1705   void *IP = nullptr;
1706   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1707     return SDValue(E, 0);
1708 
1709   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1710                                           TargetFlags);
1711   CSEMap.InsertNode(N, IP);
1712   InsertNode(N);
1713   return SDValue(N, 0);
1714 }
1715 
1716 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1717                                      unsigned TargetFlags) {
1718   FoldingSetNodeID ID;
1719   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1720   ID.AddInteger(Index);
1721   ID.AddInteger(Offset);
1722   ID.AddInteger(TargetFlags);
1723   void *IP = nullptr;
1724   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1725     return SDValue(E, 0);
1726 
1727   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1728   CSEMap.InsertNode(N, IP);
1729   InsertNode(N);
1730   return SDValue(N, 0);
1731 }
1732 
1733 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1734   FoldingSetNodeID ID;
1735   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1736   ID.AddPointer(MBB);
1737   void *IP = nullptr;
1738   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1739     return SDValue(E, 0);
1740 
1741   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1742   CSEMap.InsertNode(N, IP);
1743   InsertNode(N);
1744   return SDValue(N, 0);
1745 }
1746 
1747 SDValue SelectionDAG::getValueType(EVT VT) {
1748   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1749       ValueTypeNodes.size())
1750     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1751 
1752   SDNode *&N = VT.isExtended() ?
1753     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1754 
1755   if (N) return SDValue(N, 0);
1756   N = newSDNode<VTSDNode>(VT);
1757   InsertNode(N);
1758   return SDValue(N, 0);
1759 }
1760 
1761 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1762   SDNode *&N = ExternalSymbols[Sym];
1763   if (N) return SDValue(N, 0);
1764   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1765   InsertNode(N);
1766   return SDValue(N, 0);
1767 }
1768 
1769 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1770   SDNode *&N = MCSymbols[Sym];
1771   if (N)
1772     return SDValue(N, 0);
1773   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1774   InsertNode(N);
1775   return SDValue(N, 0);
1776 }
1777 
1778 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1779                                               unsigned TargetFlags) {
1780   SDNode *&N =
1781       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1782   if (N) return SDValue(N, 0);
1783   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1784   InsertNode(N);
1785   return SDValue(N, 0);
1786 }
1787 
1788 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1789   if ((unsigned)Cond >= CondCodeNodes.size())
1790     CondCodeNodes.resize(Cond+1);
1791 
1792   if (!CondCodeNodes[Cond]) {
1793     auto *N = newSDNode<CondCodeSDNode>(Cond);
1794     CondCodeNodes[Cond] = N;
1795     InsertNode(N);
1796   }
1797 
1798   return SDValue(CondCodeNodes[Cond], 0);
1799 }
1800 
1801 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1802   APInt One(ResVT.getScalarSizeInBits(), 1);
1803   return getStepVector(DL, ResVT, One);
1804 }
1805 
1806 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1807   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1808   if (ResVT.isScalableVector())
1809     return getNode(
1810         ISD::STEP_VECTOR, DL, ResVT,
1811         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1812 
1813   SmallVector<SDValue, 16> OpsStepConstants;
1814   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1815     OpsStepConstants.push_back(
1816         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1817   return getBuildVector(ResVT, DL, OpsStepConstants);
1818 }
1819 
1820 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1821 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1822 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1823   std::swap(N1, N2);
1824   ShuffleVectorSDNode::commuteMask(M);
1825 }
1826 
1827 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1828                                        SDValue N2, ArrayRef<int> Mask) {
1829   assert(VT.getVectorNumElements() == Mask.size() &&
1830          "Must have the same number of vector elements as mask elements!");
1831   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1832          "Invalid VECTOR_SHUFFLE");
1833 
1834   // Canonicalize shuffle undef, undef -> undef
1835   if (N1.isUndef() && N2.isUndef())
1836     return getUNDEF(VT);
1837 
1838   // Validate that all indices in Mask are within the range of the elements
1839   // input to the shuffle.
1840   int NElts = Mask.size();
1841   assert(llvm::all_of(Mask,
1842                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1843          "Index out of range");
1844 
1845   // Copy the mask so we can do any needed cleanup.
1846   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1847 
1848   // Canonicalize shuffle v, v -> v, undef
1849   if (N1 == N2) {
1850     N2 = getUNDEF(VT);
1851     for (int i = 0; i != NElts; ++i)
1852       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1853   }
1854 
1855   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1856   if (N1.isUndef())
1857     commuteShuffle(N1, N2, MaskVec);
1858 
1859   if (TLI->hasVectorBlend()) {
1860     // If shuffling a splat, try to blend the splat instead. We do this here so
1861     // that even when this arises during lowering we don't have to re-handle it.
1862     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1863       BitVector UndefElements;
1864       SDValue Splat = BV->getSplatValue(&UndefElements);
1865       if (!Splat)
1866         return;
1867 
1868       for (int i = 0; i < NElts; ++i) {
1869         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1870           continue;
1871 
1872         // If this input comes from undef, mark it as such.
1873         if (UndefElements[MaskVec[i] - Offset]) {
1874           MaskVec[i] = -1;
1875           continue;
1876         }
1877 
1878         // If we can blend a non-undef lane, use that instead.
1879         if (!UndefElements[i])
1880           MaskVec[i] = i + Offset;
1881       }
1882     };
1883     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1884       BlendSplat(N1BV, 0);
1885     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1886       BlendSplat(N2BV, NElts);
1887   }
1888 
1889   // Canonicalize all index into lhs, -> shuffle lhs, undef
1890   // Canonicalize all index into rhs, -> shuffle rhs, undef
1891   bool AllLHS = true, AllRHS = true;
1892   bool N2Undef = N2.isUndef();
1893   for (int i = 0; i != NElts; ++i) {
1894     if (MaskVec[i] >= NElts) {
1895       if (N2Undef)
1896         MaskVec[i] = -1;
1897       else
1898         AllLHS = false;
1899     } else if (MaskVec[i] >= 0) {
1900       AllRHS = false;
1901     }
1902   }
1903   if (AllLHS && AllRHS)
1904     return getUNDEF(VT);
1905   if (AllLHS && !N2Undef)
1906     N2 = getUNDEF(VT);
1907   if (AllRHS) {
1908     N1 = getUNDEF(VT);
1909     commuteShuffle(N1, N2, MaskVec);
1910   }
1911   // Reset our undef status after accounting for the mask.
1912   N2Undef = N2.isUndef();
1913   // Re-check whether both sides ended up undef.
1914   if (N1.isUndef() && N2Undef)
1915     return getUNDEF(VT);
1916 
1917   // If Identity shuffle return that node.
1918   bool Identity = true, AllSame = true;
1919   for (int i = 0; i != NElts; ++i) {
1920     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1921     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1922   }
1923   if (Identity && NElts)
1924     return N1;
1925 
1926   // Shuffling a constant splat doesn't change the result.
1927   if (N2Undef) {
1928     SDValue V = N1;
1929 
1930     // Look through any bitcasts. We check that these don't change the number
1931     // (and size) of elements and just changes their types.
1932     while (V.getOpcode() == ISD::BITCAST)
1933       V = V->getOperand(0);
1934 
1935     // A splat should always show up as a build vector node.
1936     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1937       BitVector UndefElements;
1938       SDValue Splat = BV->getSplatValue(&UndefElements);
1939       // If this is a splat of an undef, shuffling it is also undef.
1940       if (Splat && Splat.isUndef())
1941         return getUNDEF(VT);
1942 
1943       bool SameNumElts =
1944           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1945 
1946       // We only have a splat which can skip shuffles if there is a splatted
1947       // value and no undef lanes rearranged by the shuffle.
1948       if (Splat && UndefElements.none()) {
1949         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1950         // number of elements match or the value splatted is a zero constant.
1951         if (SameNumElts)
1952           return N1;
1953         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1954           if (C->isZero())
1955             return N1;
1956       }
1957 
1958       // If the shuffle itself creates a splat, build the vector directly.
1959       if (AllSame && SameNumElts) {
1960         EVT BuildVT = BV->getValueType(0);
1961         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1962         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1963 
1964         // We may have jumped through bitcasts, so the type of the
1965         // BUILD_VECTOR may not match the type of the shuffle.
1966         if (BuildVT != VT)
1967           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1968         return NewBV;
1969       }
1970     }
1971   }
1972 
1973   FoldingSetNodeID ID;
1974   SDValue Ops[2] = { N1, N2 };
1975   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1976   for (int i = 0; i != NElts; ++i)
1977     ID.AddInteger(MaskVec[i]);
1978 
1979   void* IP = nullptr;
1980   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1981     return SDValue(E, 0);
1982 
1983   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1984   // SDNode doesn't have access to it.  This memory will be "leaked" when
1985   // the node is deallocated, but recovered when the NodeAllocator is released.
1986   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1987   llvm::copy(MaskVec, MaskAlloc);
1988 
1989   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1990                                            dl.getDebugLoc(), MaskAlloc);
1991   createOperands(N, Ops);
1992 
1993   CSEMap.InsertNode(N, IP);
1994   InsertNode(N);
1995   SDValue V = SDValue(N, 0);
1996   NewSDValueDbgMsg(V, "Creating new node: ", this);
1997   return V;
1998 }
1999 
2000 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2001   EVT VT = SV.getValueType(0);
2002   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2003   ShuffleVectorSDNode::commuteMask(MaskVec);
2004 
2005   SDValue Op0 = SV.getOperand(0);
2006   SDValue Op1 = SV.getOperand(1);
2007   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2008 }
2009 
2010 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2011   FoldingSetNodeID ID;
2012   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2013   ID.AddInteger(RegNo);
2014   void *IP = nullptr;
2015   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2016     return SDValue(E, 0);
2017 
2018   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2019   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2020   CSEMap.InsertNode(N, IP);
2021   InsertNode(N);
2022   return SDValue(N, 0);
2023 }
2024 
2025 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2026   FoldingSetNodeID ID;
2027   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2028   ID.AddPointer(RegMask);
2029   void *IP = nullptr;
2030   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2031     return SDValue(E, 0);
2032 
2033   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2034   CSEMap.InsertNode(N, IP);
2035   InsertNode(N);
2036   return SDValue(N, 0);
2037 }
2038 
2039 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2040                                  MCSymbol *Label) {
2041   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2042 }
2043 
2044 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2045                                    SDValue Root, MCSymbol *Label) {
2046   FoldingSetNodeID ID;
2047   SDValue Ops[] = { Root };
2048   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2049   ID.AddPointer(Label);
2050   void *IP = nullptr;
2051   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2052     return SDValue(E, 0);
2053 
2054   auto *N =
2055       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2056   createOperands(N, Ops);
2057 
2058   CSEMap.InsertNode(N, IP);
2059   InsertNode(N);
2060   return SDValue(N, 0);
2061 }
2062 
2063 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2064                                       int64_t Offset, bool isTarget,
2065                                       unsigned TargetFlags) {
2066   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2067 
2068   FoldingSetNodeID ID;
2069   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2070   ID.AddPointer(BA);
2071   ID.AddInteger(Offset);
2072   ID.AddInteger(TargetFlags);
2073   void *IP = nullptr;
2074   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2075     return SDValue(E, 0);
2076 
2077   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2078   CSEMap.InsertNode(N, IP);
2079   InsertNode(N);
2080   return SDValue(N, 0);
2081 }
2082 
2083 SDValue SelectionDAG::getSrcValue(const Value *V) {
2084   FoldingSetNodeID ID;
2085   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2086   ID.AddPointer(V);
2087 
2088   void *IP = nullptr;
2089   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2090     return SDValue(E, 0);
2091 
2092   auto *N = newSDNode<SrcValueSDNode>(V);
2093   CSEMap.InsertNode(N, IP);
2094   InsertNode(N);
2095   return SDValue(N, 0);
2096 }
2097 
2098 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2099   FoldingSetNodeID ID;
2100   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2101   ID.AddPointer(MD);
2102 
2103   void *IP = nullptr;
2104   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2105     return SDValue(E, 0);
2106 
2107   auto *N = newSDNode<MDNodeSDNode>(MD);
2108   CSEMap.InsertNode(N, IP);
2109   InsertNode(N);
2110   return SDValue(N, 0);
2111 }
2112 
2113 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2114   if (VT == V.getValueType())
2115     return V;
2116 
2117   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2118 }
2119 
2120 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2121                                        unsigned SrcAS, unsigned DestAS) {
2122   SDValue Ops[] = {Ptr};
2123   FoldingSetNodeID ID;
2124   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2125   ID.AddInteger(SrcAS);
2126   ID.AddInteger(DestAS);
2127 
2128   void *IP = nullptr;
2129   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2130     return SDValue(E, 0);
2131 
2132   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2133                                            VT, SrcAS, DestAS);
2134   createOperands(N, Ops);
2135 
2136   CSEMap.InsertNode(N, IP);
2137   InsertNode(N);
2138   return SDValue(N, 0);
2139 }
2140 
2141 SDValue SelectionDAG::getFreeze(SDValue V) {
2142   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2143 }
2144 
2145 /// getShiftAmountOperand - Return the specified value casted to
2146 /// the target's desired shift amount type.
2147 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2148   EVT OpTy = Op.getValueType();
2149   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2150   if (OpTy == ShTy || OpTy.isVector()) return Op;
2151 
2152   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2153 }
2154 
2155 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2156   SDLoc dl(Node);
2157   const TargetLowering &TLI = getTargetLoweringInfo();
2158   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2159   EVT VT = Node->getValueType(0);
2160   SDValue Tmp1 = Node->getOperand(0);
2161   SDValue Tmp2 = Node->getOperand(1);
2162   const MaybeAlign MA(Node->getConstantOperandVal(3));
2163 
2164   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2165                                Tmp2, MachinePointerInfo(V));
2166   SDValue VAList = VAListLoad;
2167 
2168   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2169     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2170                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2171 
2172     VAList =
2173         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2174                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2175   }
2176 
2177   // Increment the pointer, VAList, to the next vaarg
2178   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2179                  getConstant(getDataLayout().getTypeAllocSize(
2180                                                VT.getTypeForEVT(*getContext())),
2181                              dl, VAList.getValueType()));
2182   // Store the incremented VAList to the legalized pointer
2183   Tmp1 =
2184       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2185   // Load the actual argument out of the pointer VAList
2186   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2187 }
2188 
2189 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2190   SDLoc dl(Node);
2191   const TargetLowering &TLI = getTargetLoweringInfo();
2192   // This defaults to loading a pointer from the input and storing it to the
2193   // output, returning the chain.
2194   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2195   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2196   SDValue Tmp1 =
2197       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2198               Node->getOperand(2), MachinePointerInfo(VS));
2199   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2200                   MachinePointerInfo(VD));
2201 }
2202 
2203 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2204   const DataLayout &DL = getDataLayout();
2205   Type *Ty = VT.getTypeForEVT(*getContext());
2206   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2207 
2208   if (TLI->isTypeLegal(VT) || !VT.isVector())
2209     return RedAlign;
2210 
2211   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2212   const Align StackAlign = TFI->getStackAlign();
2213 
2214   // See if we can choose a smaller ABI alignment in cases where it's an
2215   // illegal vector type that will get broken down.
2216   if (RedAlign > StackAlign) {
2217     EVT IntermediateVT;
2218     MVT RegisterVT;
2219     unsigned NumIntermediates;
2220     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2221                                 NumIntermediates, RegisterVT);
2222     Ty = IntermediateVT.getTypeForEVT(*getContext());
2223     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2224     if (RedAlign2 < RedAlign)
2225       RedAlign = RedAlign2;
2226   }
2227 
2228   return RedAlign;
2229 }
2230 
2231 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2232   MachineFrameInfo &MFI = MF->getFrameInfo();
2233   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2234   int StackID = 0;
2235   if (Bytes.isScalable())
2236     StackID = TFI->getStackIDForScalableVectors();
2237   // The stack id gives an indication of whether the object is scalable or
2238   // not, so it's safe to pass in the minimum size here.
2239   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2240                                        false, nullptr, StackID);
2241   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2242 }
2243 
2244 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2245   Type *Ty = VT.getTypeForEVT(*getContext());
2246   Align StackAlign =
2247       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2248   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2249 }
2250 
2251 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2252   TypeSize VT1Size = VT1.getStoreSize();
2253   TypeSize VT2Size = VT2.getStoreSize();
2254   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2255          "Don't know how to choose the maximum size when creating a stack "
2256          "temporary");
2257   TypeSize Bytes =
2258       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2259 
2260   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2261   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2262   const DataLayout &DL = getDataLayout();
2263   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2264   return CreateStackTemporary(Bytes, Align);
2265 }
2266 
2267 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2268                                 ISD::CondCode Cond, const SDLoc &dl) {
2269   EVT OpVT = N1.getValueType();
2270 
2271   // These setcc operations always fold.
2272   switch (Cond) {
2273   default: break;
2274   case ISD::SETFALSE:
2275   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2276   case ISD::SETTRUE:
2277   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2278 
2279   case ISD::SETOEQ:
2280   case ISD::SETOGT:
2281   case ISD::SETOGE:
2282   case ISD::SETOLT:
2283   case ISD::SETOLE:
2284   case ISD::SETONE:
2285   case ISD::SETO:
2286   case ISD::SETUO:
2287   case ISD::SETUEQ:
2288   case ISD::SETUNE:
2289     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2290     break;
2291   }
2292 
2293   if (OpVT.isInteger()) {
2294     // For EQ and NE, we can always pick a value for the undef to make the
2295     // predicate pass or fail, so we can return undef.
2296     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2297     // icmp eq/ne X, undef -> undef.
2298     if ((N1.isUndef() || N2.isUndef()) &&
2299         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2300       return getUNDEF(VT);
2301 
2302     // If both operands are undef, we can return undef for int comparison.
2303     // icmp undef, undef -> undef.
2304     if (N1.isUndef() && N2.isUndef())
2305       return getUNDEF(VT);
2306 
2307     // icmp X, X -> true/false
2308     // icmp X, undef -> true/false because undef could be X.
2309     if (N1 == N2)
2310       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2311   }
2312 
2313   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2314     const APInt &C2 = N2C->getAPIntValue();
2315     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2316       const APInt &C1 = N1C->getAPIntValue();
2317 
2318       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2319                              dl, VT, OpVT);
2320     }
2321   }
2322 
2323   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2324   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2325 
2326   if (N1CFP && N2CFP) {
2327     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2328     switch (Cond) {
2329     default: break;
2330     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2331                         return getUNDEF(VT);
2332                       LLVM_FALLTHROUGH;
2333     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2334                                              OpVT);
2335     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2336                         return getUNDEF(VT);
2337                       LLVM_FALLTHROUGH;
2338     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2339                                              R==APFloat::cmpLessThan, dl, VT,
2340                                              OpVT);
2341     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2342                         return getUNDEF(VT);
2343                       LLVM_FALLTHROUGH;
2344     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2345                                              OpVT);
2346     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2347                         return getUNDEF(VT);
2348                       LLVM_FALLTHROUGH;
2349     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2350                                              VT, OpVT);
2351     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2352                         return getUNDEF(VT);
2353                       LLVM_FALLTHROUGH;
2354     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2355                                              R==APFloat::cmpEqual, dl, VT,
2356                                              OpVT);
2357     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2358                         return getUNDEF(VT);
2359                       LLVM_FALLTHROUGH;
2360     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2361                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2362     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2363                                              OpVT);
2364     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2365                                              OpVT);
2366     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2367                                              R==APFloat::cmpEqual, dl, VT,
2368                                              OpVT);
2369     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2370                                              OpVT);
2371     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2372                                              R==APFloat::cmpLessThan, dl, VT,
2373                                              OpVT);
2374     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2375                                              R==APFloat::cmpUnordered, dl, VT,
2376                                              OpVT);
2377     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2378                                              VT, OpVT);
2379     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2380                                              OpVT);
2381     }
2382   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2383     // Ensure that the constant occurs on the RHS.
2384     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2385     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2386       return SDValue();
2387     return getSetCC(dl, VT, N2, N1, SwappedCond);
2388   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2389              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2390     // If an operand is known to be a nan (or undef that could be a nan), we can
2391     // fold it.
2392     // Choosing NaN for the undef will always make unordered comparison succeed
2393     // and ordered comparison fails.
2394     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2395     switch (ISD::getUnorderedFlavor(Cond)) {
2396     default:
2397       llvm_unreachable("Unknown flavor!");
2398     case 0: // Known false.
2399       return getBoolConstant(false, dl, VT, OpVT);
2400     case 1: // Known true.
2401       return getBoolConstant(true, dl, VT, OpVT);
2402     case 2: // Undefined.
2403       return getUNDEF(VT);
2404     }
2405   }
2406 
2407   // Could not fold it.
2408   return SDValue();
2409 }
2410 
2411 /// See if the specified operand can be simplified with the knowledge that only
2412 /// the bits specified by DemandedBits are used.
2413 /// TODO: really we should be making this into the DAG equivalent of
2414 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2415 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2416   EVT VT = V.getValueType();
2417 
2418   if (VT.isScalableVector())
2419     return SDValue();
2420 
2421   APInt DemandedElts = VT.isVector()
2422                            ? APInt::getAllOnes(VT.getVectorNumElements())
2423                            : APInt(1, 1);
2424   return GetDemandedBits(V, DemandedBits, DemandedElts);
2425 }
2426 
2427 /// See if the specified operand can be simplified with the knowledge that only
2428 /// the bits specified by DemandedBits are used in the elements specified by
2429 /// DemandedElts.
2430 /// TODO: really we should be making this into the DAG equivalent of
2431 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2432 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2433                                       const APInt &DemandedElts) {
2434   switch (V.getOpcode()) {
2435   default:
2436     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2437                                                 *this, 0);
2438   case ISD::Constant: {
2439     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2440     APInt NewVal = CVal & DemandedBits;
2441     if (NewVal != CVal)
2442       return getConstant(NewVal, SDLoc(V), V.getValueType());
2443     break;
2444   }
2445   case ISD::SRL:
2446     // Only look at single-use SRLs.
2447     if (!V.getNode()->hasOneUse())
2448       break;
2449     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2450       // See if we can recursively simplify the LHS.
2451       unsigned Amt = RHSC->getZExtValue();
2452 
2453       // Watch out for shift count overflow though.
2454       if (Amt >= DemandedBits.getBitWidth())
2455         break;
2456       APInt SrcDemandedBits = DemandedBits << Amt;
2457       if (SDValue SimplifyLHS =
2458               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2459         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2460                        V.getOperand(1));
2461     }
2462     break;
2463   }
2464   return SDValue();
2465 }
2466 
2467 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2468 /// use this predicate to simplify operations downstream.
2469 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2470   unsigned BitWidth = Op.getScalarValueSizeInBits();
2471   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2472 }
2473 
2474 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2475 /// this predicate to simplify operations downstream.  Mask is known to be zero
2476 /// for bits that V cannot have.
2477 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2478                                      unsigned Depth) const {
2479   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2480 }
2481 
2482 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2483 /// DemandedElts.  We use this predicate to simplify operations downstream.
2484 /// Mask is known to be zero for bits that V cannot have.
2485 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2486                                      const APInt &DemandedElts,
2487                                      unsigned Depth) const {
2488   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2489 }
2490 
2491 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2492 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2493                                         unsigned Depth) const {
2494   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2495 }
2496 
2497 /// isSplatValue - Return true if the vector V has the same value
2498 /// across all DemandedElts. For scalable vectors it does not make
2499 /// sense to specify which elements are demanded or undefined, therefore
2500 /// they are simply ignored.
2501 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2502                                 APInt &UndefElts, unsigned Depth) const {
2503   unsigned Opcode = V.getOpcode();
2504   EVT VT = V.getValueType();
2505   assert(VT.isVector() && "Vector type expected");
2506 
2507   if (!VT.isScalableVector() && !DemandedElts)
2508     return false; // No demanded elts, better to assume we don't know anything.
2509 
2510   if (Depth >= MaxRecursionDepth)
2511     return false; // Limit search depth.
2512 
2513   // Deal with some common cases here that work for both fixed and scalable
2514   // vector types.
2515   switch (Opcode) {
2516   case ISD::SPLAT_VECTOR:
2517     UndefElts = V.getOperand(0).isUndef()
2518                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2519                     : APInt(DemandedElts.getBitWidth(), 0);
2520     return true;
2521   case ISD::ADD:
2522   case ISD::SUB:
2523   case ISD::AND:
2524   case ISD::XOR:
2525   case ISD::OR: {
2526     APInt UndefLHS, UndefRHS;
2527     SDValue LHS = V.getOperand(0);
2528     SDValue RHS = V.getOperand(1);
2529     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2530         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2531       UndefElts = UndefLHS | UndefRHS;
2532       return true;
2533     }
2534     return false;
2535   }
2536   case ISD::ABS:
2537   case ISD::TRUNCATE:
2538   case ISD::SIGN_EXTEND:
2539   case ISD::ZERO_EXTEND:
2540     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2541   default:
2542     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2543         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2544       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2545     break;
2546 }
2547 
2548   // We don't support other cases than those above for scalable vectors at
2549   // the moment.
2550   if (VT.isScalableVector())
2551     return false;
2552 
2553   unsigned NumElts = VT.getVectorNumElements();
2554   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2555   UndefElts = APInt::getZero(NumElts);
2556 
2557   switch (Opcode) {
2558   case ISD::BUILD_VECTOR: {
2559     SDValue Scl;
2560     for (unsigned i = 0; i != NumElts; ++i) {
2561       SDValue Op = V.getOperand(i);
2562       if (Op.isUndef()) {
2563         UndefElts.setBit(i);
2564         continue;
2565       }
2566       if (!DemandedElts[i])
2567         continue;
2568       if (Scl && Scl != Op)
2569         return false;
2570       Scl = Op;
2571     }
2572     return true;
2573   }
2574   case ISD::VECTOR_SHUFFLE: {
2575     // Check if this is a shuffle node doing a splat.
2576     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2577     int SplatIndex = -1;
2578     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2579     for (int i = 0; i != (int)NumElts; ++i) {
2580       int M = Mask[i];
2581       if (M < 0) {
2582         UndefElts.setBit(i);
2583         continue;
2584       }
2585       if (!DemandedElts[i])
2586         continue;
2587       if (0 <= SplatIndex && SplatIndex != M)
2588         return false;
2589       SplatIndex = M;
2590     }
2591     return true;
2592   }
2593   case ISD::EXTRACT_SUBVECTOR: {
2594     // Offset the demanded elts by the subvector index.
2595     SDValue Src = V.getOperand(0);
2596     // We don't support scalable vectors at the moment.
2597     if (Src.getValueType().isScalableVector())
2598       return false;
2599     uint64_t Idx = V.getConstantOperandVal(1);
2600     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2601     APInt UndefSrcElts;
2602     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2603     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2604       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2605       return true;
2606     }
2607     break;
2608   }
2609   case ISD::ANY_EXTEND_VECTOR_INREG:
2610   case ISD::SIGN_EXTEND_VECTOR_INREG:
2611   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2612     // Widen the demanded elts by the src element count.
2613     SDValue Src = V.getOperand(0);
2614     // We don't support scalable vectors at the moment.
2615     if (Src.getValueType().isScalableVector())
2616       return false;
2617     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2618     APInt UndefSrcElts;
2619     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2620     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2621       UndefElts = UndefSrcElts.truncOrSelf(NumElts);
2622       return true;
2623     }
2624     break;
2625   }
2626   }
2627 
2628   return false;
2629 }
2630 
2631 /// Helper wrapper to main isSplatValue function.
2632 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2633   EVT VT = V.getValueType();
2634   assert(VT.isVector() && "Vector type expected");
2635 
2636   APInt UndefElts;
2637   APInt DemandedElts;
2638 
2639   // For now we don't support this with scalable vectors.
2640   if (!VT.isScalableVector())
2641     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2642   return isSplatValue(V, DemandedElts, UndefElts) &&
2643          (AllowUndefs || !UndefElts);
2644 }
2645 
2646 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2647   V = peekThroughExtractSubvectors(V);
2648 
2649   EVT VT = V.getValueType();
2650   unsigned Opcode = V.getOpcode();
2651   switch (Opcode) {
2652   default: {
2653     APInt UndefElts;
2654     APInt DemandedElts;
2655 
2656     if (!VT.isScalableVector())
2657       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2658 
2659     if (isSplatValue(V, DemandedElts, UndefElts)) {
2660       if (VT.isScalableVector()) {
2661         // DemandedElts and UndefElts are ignored for scalable vectors, since
2662         // the only supported cases are SPLAT_VECTOR nodes.
2663         SplatIdx = 0;
2664       } else {
2665         // Handle case where all demanded elements are UNDEF.
2666         if (DemandedElts.isSubsetOf(UndefElts)) {
2667           SplatIdx = 0;
2668           return getUNDEF(VT);
2669         }
2670         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2671       }
2672       return V;
2673     }
2674     break;
2675   }
2676   case ISD::SPLAT_VECTOR:
2677     SplatIdx = 0;
2678     return V;
2679   case ISD::VECTOR_SHUFFLE: {
2680     if (VT.isScalableVector())
2681       return SDValue();
2682 
2683     // Check if this is a shuffle node doing a splat.
2684     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2685     // getTargetVShiftNode currently struggles without the splat source.
2686     auto *SVN = cast<ShuffleVectorSDNode>(V);
2687     if (!SVN->isSplat())
2688       break;
2689     int Idx = SVN->getSplatIndex();
2690     int NumElts = V.getValueType().getVectorNumElements();
2691     SplatIdx = Idx % NumElts;
2692     return V.getOperand(Idx / NumElts);
2693   }
2694   }
2695 
2696   return SDValue();
2697 }
2698 
2699 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2700   int SplatIdx;
2701   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2702     EVT SVT = SrcVector.getValueType().getScalarType();
2703     EVT LegalSVT = SVT;
2704     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2705       if (!SVT.isInteger())
2706         return SDValue();
2707       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2708       if (LegalSVT.bitsLT(SVT))
2709         return SDValue();
2710     }
2711     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2712                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2713   }
2714   return SDValue();
2715 }
2716 
2717 const APInt *
2718 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2719                                           const APInt &DemandedElts) const {
2720   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2721           V.getOpcode() == ISD::SRA) &&
2722          "Unknown shift node");
2723   unsigned BitWidth = V.getScalarValueSizeInBits();
2724   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2725     // Shifting more than the bitwidth is not valid.
2726     const APInt &ShAmt = SA->getAPIntValue();
2727     if (ShAmt.ult(BitWidth))
2728       return &ShAmt;
2729   }
2730   return nullptr;
2731 }
2732 
2733 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2734     SDValue V, const APInt &DemandedElts) const {
2735   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2736           V.getOpcode() == ISD::SRA) &&
2737          "Unknown shift node");
2738   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2739     return ValidAmt;
2740   unsigned BitWidth = V.getScalarValueSizeInBits();
2741   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2742   if (!BV)
2743     return nullptr;
2744   const APInt *MinShAmt = nullptr;
2745   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2746     if (!DemandedElts[i])
2747       continue;
2748     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2749     if (!SA)
2750       return nullptr;
2751     // Shifting more than the bitwidth is not valid.
2752     const APInt &ShAmt = SA->getAPIntValue();
2753     if (ShAmt.uge(BitWidth))
2754       return nullptr;
2755     if (MinShAmt && MinShAmt->ule(ShAmt))
2756       continue;
2757     MinShAmt = &ShAmt;
2758   }
2759   return MinShAmt;
2760 }
2761 
2762 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2763     SDValue V, const APInt &DemandedElts) const {
2764   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2765           V.getOpcode() == ISD::SRA) &&
2766          "Unknown shift node");
2767   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2768     return ValidAmt;
2769   unsigned BitWidth = V.getScalarValueSizeInBits();
2770   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2771   if (!BV)
2772     return nullptr;
2773   const APInt *MaxShAmt = nullptr;
2774   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2775     if (!DemandedElts[i])
2776       continue;
2777     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2778     if (!SA)
2779       return nullptr;
2780     // Shifting more than the bitwidth is not valid.
2781     const APInt &ShAmt = SA->getAPIntValue();
2782     if (ShAmt.uge(BitWidth))
2783       return nullptr;
2784     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2785       continue;
2786     MaxShAmt = &ShAmt;
2787   }
2788   return MaxShAmt;
2789 }
2790 
2791 /// Determine which bits of Op are known to be either zero or one and return
2792 /// them in Known. For vectors, the known bits are those that are shared by
2793 /// every vector element.
2794 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2795   EVT VT = Op.getValueType();
2796 
2797   // TOOD: Until we have a plan for how to represent demanded elements for
2798   // scalable vectors, we can just bail out for now.
2799   if (Op.getValueType().isScalableVector()) {
2800     unsigned BitWidth = Op.getScalarValueSizeInBits();
2801     return KnownBits(BitWidth);
2802   }
2803 
2804   APInt DemandedElts = VT.isVector()
2805                            ? APInt::getAllOnes(VT.getVectorNumElements())
2806                            : APInt(1, 1);
2807   return computeKnownBits(Op, DemandedElts, Depth);
2808 }
2809 
2810 /// Determine which bits of Op are known to be either zero or one and return
2811 /// them in Known. The DemandedElts argument allows us to only collect the known
2812 /// bits that are shared by the requested vector elements.
2813 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2814                                          unsigned Depth) const {
2815   unsigned BitWidth = Op.getScalarValueSizeInBits();
2816 
2817   KnownBits Known(BitWidth);   // Don't know anything.
2818 
2819   // TOOD: Until we have a plan for how to represent demanded elements for
2820   // scalable vectors, we can just bail out for now.
2821   if (Op.getValueType().isScalableVector())
2822     return Known;
2823 
2824   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2825     // We know all of the bits for a constant!
2826     return KnownBits::makeConstant(C->getAPIntValue());
2827   }
2828   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2829     // We know all of the bits for a constant fp!
2830     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2831   }
2832 
2833   if (Depth >= MaxRecursionDepth)
2834     return Known;  // Limit search depth.
2835 
2836   KnownBits Known2;
2837   unsigned NumElts = DemandedElts.getBitWidth();
2838   assert((!Op.getValueType().isVector() ||
2839           NumElts == Op.getValueType().getVectorNumElements()) &&
2840          "Unexpected vector size");
2841 
2842   if (!DemandedElts)
2843     return Known;  // No demanded elts, better to assume we don't know anything.
2844 
2845   unsigned Opcode = Op.getOpcode();
2846   switch (Opcode) {
2847   case ISD::BUILD_VECTOR:
2848     // Collect the known bits that are shared by every demanded vector element.
2849     Known.Zero.setAllBits(); Known.One.setAllBits();
2850     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2851       if (!DemandedElts[i])
2852         continue;
2853 
2854       SDValue SrcOp = Op.getOperand(i);
2855       Known2 = computeKnownBits(SrcOp, Depth + 1);
2856 
2857       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2858       if (SrcOp.getValueSizeInBits() != BitWidth) {
2859         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2860                "Expected BUILD_VECTOR implicit truncation");
2861         Known2 = Known2.trunc(BitWidth);
2862       }
2863 
2864       // Known bits are the values that are shared by every demanded element.
2865       Known = KnownBits::commonBits(Known, Known2);
2866 
2867       // If we don't know any bits, early out.
2868       if (Known.isUnknown())
2869         break;
2870     }
2871     break;
2872   case ISD::VECTOR_SHUFFLE: {
2873     // Collect the known bits that are shared by every vector element referenced
2874     // by the shuffle.
2875     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2876     Known.Zero.setAllBits(); Known.One.setAllBits();
2877     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2878     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2879     for (unsigned i = 0; i != NumElts; ++i) {
2880       if (!DemandedElts[i])
2881         continue;
2882 
2883       int M = SVN->getMaskElt(i);
2884       if (M < 0) {
2885         // For UNDEF elements, we don't know anything about the common state of
2886         // the shuffle result.
2887         Known.resetAll();
2888         DemandedLHS.clearAllBits();
2889         DemandedRHS.clearAllBits();
2890         break;
2891       }
2892 
2893       if ((unsigned)M < NumElts)
2894         DemandedLHS.setBit((unsigned)M % NumElts);
2895       else
2896         DemandedRHS.setBit((unsigned)M % NumElts);
2897     }
2898     // Known bits are the values that are shared by every demanded element.
2899     if (!!DemandedLHS) {
2900       SDValue LHS = Op.getOperand(0);
2901       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2902       Known = KnownBits::commonBits(Known, Known2);
2903     }
2904     // If we don't know any bits, early out.
2905     if (Known.isUnknown())
2906       break;
2907     if (!!DemandedRHS) {
2908       SDValue RHS = Op.getOperand(1);
2909       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2910       Known = KnownBits::commonBits(Known, Known2);
2911     }
2912     break;
2913   }
2914   case ISD::CONCAT_VECTORS: {
2915     // Split DemandedElts and test each of the demanded subvectors.
2916     Known.Zero.setAllBits(); Known.One.setAllBits();
2917     EVT SubVectorVT = Op.getOperand(0).getValueType();
2918     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2919     unsigned NumSubVectors = Op.getNumOperands();
2920     for (unsigned i = 0; i != NumSubVectors; ++i) {
2921       APInt DemandedSub =
2922           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2923       if (!!DemandedSub) {
2924         SDValue Sub = Op.getOperand(i);
2925         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2926         Known = KnownBits::commonBits(Known, Known2);
2927       }
2928       // If we don't know any bits, early out.
2929       if (Known.isUnknown())
2930         break;
2931     }
2932     break;
2933   }
2934   case ISD::INSERT_SUBVECTOR: {
2935     // Demand any elements from the subvector and the remainder from the src its
2936     // inserted into.
2937     SDValue Src = Op.getOperand(0);
2938     SDValue Sub = Op.getOperand(1);
2939     uint64_t Idx = Op.getConstantOperandVal(2);
2940     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2941     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2942     APInt DemandedSrcElts = DemandedElts;
2943     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2944 
2945     Known.One.setAllBits();
2946     Known.Zero.setAllBits();
2947     if (!!DemandedSubElts) {
2948       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2949       if (Known.isUnknown())
2950         break; // early-out.
2951     }
2952     if (!!DemandedSrcElts) {
2953       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2954       Known = KnownBits::commonBits(Known, Known2);
2955     }
2956     break;
2957   }
2958   case ISD::EXTRACT_SUBVECTOR: {
2959     // Offset the demanded elts by the subvector index.
2960     SDValue Src = Op.getOperand(0);
2961     // Bail until we can represent demanded elements for scalable vectors.
2962     if (Src.getValueType().isScalableVector())
2963       break;
2964     uint64_t Idx = Op.getConstantOperandVal(1);
2965     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2966     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2967     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2968     break;
2969   }
2970   case ISD::SCALAR_TO_VECTOR: {
2971     // We know about scalar_to_vector as much as we know about it source,
2972     // which becomes the first element of otherwise unknown vector.
2973     if (DemandedElts != 1)
2974       break;
2975 
2976     SDValue N0 = Op.getOperand(0);
2977     Known = computeKnownBits(N0, Depth + 1);
2978     if (N0.getValueSizeInBits() != BitWidth)
2979       Known = Known.trunc(BitWidth);
2980 
2981     break;
2982   }
2983   case ISD::BITCAST: {
2984     SDValue N0 = Op.getOperand(0);
2985     EVT SubVT = N0.getValueType();
2986     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2987 
2988     // Ignore bitcasts from unsupported types.
2989     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2990       break;
2991 
2992     // Fast handling of 'identity' bitcasts.
2993     if (BitWidth == SubBitWidth) {
2994       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2995       break;
2996     }
2997 
2998     bool IsLE = getDataLayout().isLittleEndian();
2999 
3000     // Bitcast 'small element' vector to 'large element' scalar/vector.
3001     if ((BitWidth % SubBitWidth) == 0) {
3002       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3003 
3004       // Collect known bits for the (larger) output by collecting the known
3005       // bits from each set of sub elements and shift these into place.
3006       // We need to separately call computeKnownBits for each set of
3007       // sub elements as the knownbits for each is likely to be different.
3008       unsigned SubScale = BitWidth / SubBitWidth;
3009       APInt SubDemandedElts(NumElts * SubScale, 0);
3010       for (unsigned i = 0; i != NumElts; ++i)
3011         if (DemandedElts[i])
3012           SubDemandedElts.setBit(i * SubScale);
3013 
3014       for (unsigned i = 0; i != SubScale; ++i) {
3015         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3016                          Depth + 1);
3017         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3018         Known.insertBits(Known2, SubBitWidth * Shifts);
3019       }
3020     }
3021 
3022     // Bitcast 'large element' scalar/vector to 'small element' vector.
3023     if ((SubBitWidth % BitWidth) == 0) {
3024       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3025 
3026       // Collect known bits for the (smaller) output by collecting the known
3027       // bits from the overlapping larger input elements and extracting the
3028       // sub sections we actually care about.
3029       unsigned SubScale = SubBitWidth / BitWidth;
3030       APInt SubDemandedElts =
3031           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3032       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3033 
3034       Known.Zero.setAllBits(); Known.One.setAllBits();
3035       for (unsigned i = 0; i != NumElts; ++i)
3036         if (DemandedElts[i]) {
3037           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3038           unsigned Offset = (Shifts % SubScale) * BitWidth;
3039           Known = KnownBits::commonBits(Known,
3040                                         Known2.extractBits(BitWidth, Offset));
3041           // If we don't know any bits, early out.
3042           if (Known.isUnknown())
3043             break;
3044         }
3045     }
3046     break;
3047   }
3048   case ISD::AND:
3049     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3050     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3051 
3052     Known &= Known2;
3053     break;
3054   case ISD::OR:
3055     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3056     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3057 
3058     Known |= Known2;
3059     break;
3060   case ISD::XOR:
3061     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3062     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3063 
3064     Known ^= Known2;
3065     break;
3066   case ISD::MUL: {
3067     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3068     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3069     Known = KnownBits::mul(Known, Known2);
3070     break;
3071   }
3072   case ISD::MULHU: {
3073     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3074     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3075     Known = KnownBits::mulhu(Known, Known2);
3076     break;
3077   }
3078   case ISD::MULHS: {
3079     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3080     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3081     Known = KnownBits::mulhs(Known, Known2);
3082     break;
3083   }
3084   case ISD::UMUL_LOHI: {
3085     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3086     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3087     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3088     if (Op.getResNo() == 0)
3089       Known = KnownBits::mul(Known, Known2);
3090     else
3091       Known = KnownBits::mulhu(Known, Known2);
3092     break;
3093   }
3094   case ISD::SMUL_LOHI: {
3095     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3096     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3097     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3098     if (Op.getResNo() == 0)
3099       Known = KnownBits::mul(Known, Known2);
3100     else
3101       Known = KnownBits::mulhs(Known, Known2);
3102     break;
3103   }
3104   case ISD::UDIV: {
3105     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3106     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3107     Known = KnownBits::udiv(Known, Known2);
3108     break;
3109   }
3110   case ISD::SELECT:
3111   case ISD::VSELECT:
3112     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3113     // If we don't know any bits, early out.
3114     if (Known.isUnknown())
3115       break;
3116     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3117 
3118     // Only known if known in both the LHS and RHS.
3119     Known = KnownBits::commonBits(Known, Known2);
3120     break;
3121   case ISD::SELECT_CC:
3122     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3123     // If we don't know any bits, early out.
3124     if (Known.isUnknown())
3125       break;
3126     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3127 
3128     // Only known if known in both the LHS and RHS.
3129     Known = KnownBits::commonBits(Known, Known2);
3130     break;
3131   case ISD::SMULO:
3132   case ISD::UMULO:
3133     if (Op.getResNo() != 1)
3134       break;
3135     // The boolean result conforms to getBooleanContents.
3136     // If we know the result of a setcc has the top bits zero, use this info.
3137     // We know that we have an integer-based boolean since these operations
3138     // are only available for integer.
3139     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3140             TargetLowering::ZeroOrOneBooleanContent &&
3141         BitWidth > 1)
3142       Known.Zero.setBitsFrom(1);
3143     break;
3144   case ISD::SETCC:
3145   case ISD::STRICT_FSETCC:
3146   case ISD::STRICT_FSETCCS: {
3147     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3148     // If we know the result of a setcc has the top bits zero, use this info.
3149     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3150             TargetLowering::ZeroOrOneBooleanContent &&
3151         BitWidth > 1)
3152       Known.Zero.setBitsFrom(1);
3153     break;
3154   }
3155   case ISD::SHL:
3156     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3157     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3158     Known = KnownBits::shl(Known, Known2);
3159 
3160     // Minimum shift low bits are known zero.
3161     if (const APInt *ShMinAmt =
3162             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3163       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3164     break;
3165   case ISD::SRL:
3166     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3167     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3168     Known = KnownBits::lshr(Known, Known2);
3169 
3170     // Minimum shift high bits are known zero.
3171     if (const APInt *ShMinAmt =
3172             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3173       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3174     break;
3175   case ISD::SRA:
3176     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3177     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3178     Known = KnownBits::ashr(Known, Known2);
3179     // TODO: Add minimum shift high known sign bits.
3180     break;
3181   case ISD::FSHL:
3182   case ISD::FSHR:
3183     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3184       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3185 
3186       // For fshl, 0-shift returns the 1st arg.
3187       // For fshr, 0-shift returns the 2nd arg.
3188       if (Amt == 0) {
3189         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3190                                  DemandedElts, Depth + 1);
3191         break;
3192       }
3193 
3194       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3195       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3196       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3197       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3198       if (Opcode == ISD::FSHL) {
3199         Known.One <<= Amt;
3200         Known.Zero <<= Amt;
3201         Known2.One.lshrInPlace(BitWidth - Amt);
3202         Known2.Zero.lshrInPlace(BitWidth - Amt);
3203       } else {
3204         Known.One <<= BitWidth - Amt;
3205         Known.Zero <<= BitWidth - Amt;
3206         Known2.One.lshrInPlace(Amt);
3207         Known2.Zero.lshrInPlace(Amt);
3208       }
3209       Known.One |= Known2.One;
3210       Known.Zero |= Known2.Zero;
3211     }
3212     break;
3213   case ISD::SIGN_EXTEND_INREG: {
3214     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3215     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3216     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3217     break;
3218   }
3219   case ISD::CTTZ:
3220   case ISD::CTTZ_ZERO_UNDEF: {
3221     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3222     // If we have a known 1, its position is our upper bound.
3223     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3224     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3225     Known.Zero.setBitsFrom(LowBits);
3226     break;
3227   }
3228   case ISD::CTLZ:
3229   case ISD::CTLZ_ZERO_UNDEF: {
3230     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3231     // If we have a known 1, its position is our upper bound.
3232     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3233     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3234     Known.Zero.setBitsFrom(LowBits);
3235     break;
3236   }
3237   case ISD::CTPOP: {
3238     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3239     // If we know some of the bits are zero, they can't be one.
3240     unsigned PossibleOnes = Known2.countMaxPopulation();
3241     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3242     break;
3243   }
3244   case ISD::PARITY: {
3245     // Parity returns 0 everywhere but the LSB.
3246     Known.Zero.setBitsFrom(1);
3247     break;
3248   }
3249   case ISD::LOAD: {
3250     LoadSDNode *LD = cast<LoadSDNode>(Op);
3251     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3252     if (ISD::isNON_EXTLoad(LD) && Cst) {
3253       // Determine any common known bits from the loaded constant pool value.
3254       Type *CstTy = Cst->getType();
3255       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3256         // If its a vector splat, then we can (quickly) reuse the scalar path.
3257         // NOTE: We assume all elements match and none are UNDEF.
3258         if (CstTy->isVectorTy()) {
3259           if (const Constant *Splat = Cst->getSplatValue()) {
3260             Cst = Splat;
3261             CstTy = Cst->getType();
3262           }
3263         }
3264         // TODO - do we need to handle different bitwidths?
3265         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3266           // Iterate across all vector elements finding common known bits.
3267           Known.One.setAllBits();
3268           Known.Zero.setAllBits();
3269           for (unsigned i = 0; i != NumElts; ++i) {
3270             if (!DemandedElts[i])
3271               continue;
3272             if (Constant *Elt = Cst->getAggregateElement(i)) {
3273               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3274                 const APInt &Value = CInt->getValue();
3275                 Known.One &= Value;
3276                 Known.Zero &= ~Value;
3277                 continue;
3278               }
3279               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3280                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3281                 Known.One &= Value;
3282                 Known.Zero &= ~Value;
3283                 continue;
3284               }
3285             }
3286             Known.One.clearAllBits();
3287             Known.Zero.clearAllBits();
3288             break;
3289           }
3290         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3291           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3292             Known = KnownBits::makeConstant(CInt->getValue());
3293           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3294             Known =
3295                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3296           }
3297         }
3298       }
3299     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3300       // If this is a ZEXTLoad and we are looking at the loaded value.
3301       EVT VT = LD->getMemoryVT();
3302       unsigned MemBits = VT.getScalarSizeInBits();
3303       Known.Zero.setBitsFrom(MemBits);
3304     } else if (const MDNode *Ranges = LD->getRanges()) {
3305       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3306         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3307     }
3308     break;
3309   }
3310   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3311     EVT InVT = Op.getOperand(0).getValueType();
3312     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3313     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3314     Known = Known.zext(BitWidth);
3315     break;
3316   }
3317   case ISD::ZERO_EXTEND: {
3318     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3319     Known = Known.zext(BitWidth);
3320     break;
3321   }
3322   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3323     EVT InVT = Op.getOperand(0).getValueType();
3324     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3325     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3326     // If the sign bit is known to be zero or one, then sext will extend
3327     // it to the top bits, else it will just zext.
3328     Known = Known.sext(BitWidth);
3329     break;
3330   }
3331   case ISD::SIGN_EXTEND: {
3332     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3333     // If the sign bit is known to be zero or one, then sext will extend
3334     // it to the top bits, else it will just zext.
3335     Known = Known.sext(BitWidth);
3336     break;
3337   }
3338   case ISD::ANY_EXTEND_VECTOR_INREG: {
3339     EVT InVT = Op.getOperand(0).getValueType();
3340     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3341     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3342     Known = Known.anyext(BitWidth);
3343     break;
3344   }
3345   case ISD::ANY_EXTEND: {
3346     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3347     Known = Known.anyext(BitWidth);
3348     break;
3349   }
3350   case ISD::TRUNCATE: {
3351     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3352     Known = Known.trunc(BitWidth);
3353     break;
3354   }
3355   case ISD::AssertZext: {
3356     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3357     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3358     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3359     Known.Zero |= (~InMask);
3360     Known.One  &= (~Known.Zero);
3361     break;
3362   }
3363   case ISD::AssertAlign: {
3364     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3365     assert(LogOfAlign != 0);
3366 
3367     // TODO: Should use maximum with source
3368     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3369     // well as clearing one bits.
3370     Known.Zero.setLowBits(LogOfAlign);
3371     Known.One.clearLowBits(LogOfAlign);
3372     break;
3373   }
3374   case ISD::FGETSIGN:
3375     // All bits are zero except the low bit.
3376     Known.Zero.setBitsFrom(1);
3377     break;
3378   case ISD::USUBO:
3379   case ISD::SSUBO:
3380     if (Op.getResNo() == 1) {
3381       // If we know the result of a setcc has the top bits zero, use this info.
3382       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3383               TargetLowering::ZeroOrOneBooleanContent &&
3384           BitWidth > 1)
3385         Known.Zero.setBitsFrom(1);
3386       break;
3387     }
3388     LLVM_FALLTHROUGH;
3389   case ISD::SUB:
3390   case ISD::SUBC: {
3391     assert(Op.getResNo() == 0 &&
3392            "We only compute knownbits for the difference here.");
3393 
3394     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3395     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3396     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3397                                         Known, Known2);
3398     break;
3399   }
3400   case ISD::UADDO:
3401   case ISD::SADDO:
3402   case ISD::ADDCARRY:
3403     if (Op.getResNo() == 1) {
3404       // If we know the result of a setcc has the top bits zero, use this info.
3405       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3406               TargetLowering::ZeroOrOneBooleanContent &&
3407           BitWidth > 1)
3408         Known.Zero.setBitsFrom(1);
3409       break;
3410     }
3411     LLVM_FALLTHROUGH;
3412   case ISD::ADD:
3413   case ISD::ADDC:
3414   case ISD::ADDE: {
3415     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3416 
3417     // With ADDE and ADDCARRY, a carry bit may be added in.
3418     KnownBits Carry(1);
3419     if (Opcode == ISD::ADDE)
3420       // Can't track carry from glue, set carry to unknown.
3421       Carry.resetAll();
3422     else if (Opcode == ISD::ADDCARRY)
3423       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3424       // the trouble (how often will we find a known carry bit). And I haven't
3425       // tested this very much yet, but something like this might work:
3426       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3427       //   Carry = Carry.zextOrTrunc(1, false);
3428       Carry.resetAll();
3429     else
3430       Carry.setAllZero();
3431 
3432     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3433     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3434     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3435     break;
3436   }
3437   case ISD::SREM: {
3438     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3439     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3440     Known = KnownBits::srem(Known, Known2);
3441     break;
3442   }
3443   case ISD::UREM: {
3444     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3445     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3446     Known = KnownBits::urem(Known, Known2);
3447     break;
3448   }
3449   case ISD::EXTRACT_ELEMENT: {
3450     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3451     const unsigned Index = Op.getConstantOperandVal(1);
3452     const unsigned EltBitWidth = Op.getValueSizeInBits();
3453 
3454     // Remove low part of known bits mask
3455     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3456     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3457 
3458     // Remove high part of known bit mask
3459     Known = Known.trunc(EltBitWidth);
3460     break;
3461   }
3462   case ISD::EXTRACT_VECTOR_ELT: {
3463     SDValue InVec = Op.getOperand(0);
3464     SDValue EltNo = Op.getOperand(1);
3465     EVT VecVT = InVec.getValueType();
3466     // computeKnownBits not yet implemented for scalable vectors.
3467     if (VecVT.isScalableVector())
3468       break;
3469     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3470     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3471 
3472     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3473     // anything about the extended bits.
3474     if (BitWidth > EltBitWidth)
3475       Known = Known.trunc(EltBitWidth);
3476 
3477     // If we know the element index, just demand that vector element, else for
3478     // an unknown element index, ignore DemandedElts and demand them all.
3479     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3480     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3481     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3482       DemandedSrcElts =
3483           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3484 
3485     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3486     if (BitWidth > EltBitWidth)
3487       Known = Known.anyext(BitWidth);
3488     break;
3489   }
3490   case ISD::INSERT_VECTOR_ELT: {
3491     // If we know the element index, split the demand between the
3492     // source vector and the inserted element, otherwise assume we need
3493     // the original demanded vector elements and the value.
3494     SDValue InVec = Op.getOperand(0);
3495     SDValue InVal = Op.getOperand(1);
3496     SDValue EltNo = Op.getOperand(2);
3497     bool DemandedVal = true;
3498     APInt DemandedVecElts = DemandedElts;
3499     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3500     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3501       unsigned EltIdx = CEltNo->getZExtValue();
3502       DemandedVal = !!DemandedElts[EltIdx];
3503       DemandedVecElts.clearBit(EltIdx);
3504     }
3505     Known.One.setAllBits();
3506     Known.Zero.setAllBits();
3507     if (DemandedVal) {
3508       Known2 = computeKnownBits(InVal, Depth + 1);
3509       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3510     }
3511     if (!!DemandedVecElts) {
3512       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3513       Known = KnownBits::commonBits(Known, Known2);
3514     }
3515     break;
3516   }
3517   case ISD::BITREVERSE: {
3518     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3519     Known = Known2.reverseBits();
3520     break;
3521   }
3522   case ISD::BSWAP: {
3523     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3524     Known = Known2.byteSwap();
3525     break;
3526   }
3527   case ISD::ABS: {
3528     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3529     Known = Known2.abs();
3530     break;
3531   }
3532   case ISD::USUBSAT: {
3533     // The result of usubsat will never be larger than the LHS.
3534     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3535     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3536     break;
3537   }
3538   case ISD::UMIN: {
3539     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3540     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3541     Known = KnownBits::umin(Known, Known2);
3542     break;
3543   }
3544   case ISD::UMAX: {
3545     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3546     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3547     Known = KnownBits::umax(Known, Known2);
3548     break;
3549   }
3550   case ISD::SMIN:
3551   case ISD::SMAX: {
3552     // If we have a clamp pattern, we know that the number of sign bits will be
3553     // the minimum of the clamp min/max range.
3554     bool IsMax = (Opcode == ISD::SMAX);
3555     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3556     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3557       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3558         CstHigh =
3559             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3560     if (CstLow && CstHigh) {
3561       if (!IsMax)
3562         std::swap(CstLow, CstHigh);
3563 
3564       const APInt &ValueLow = CstLow->getAPIntValue();
3565       const APInt &ValueHigh = CstHigh->getAPIntValue();
3566       if (ValueLow.sle(ValueHigh)) {
3567         unsigned LowSignBits = ValueLow.getNumSignBits();
3568         unsigned HighSignBits = ValueHigh.getNumSignBits();
3569         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3570         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3571           Known.One.setHighBits(MinSignBits);
3572           break;
3573         }
3574         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3575           Known.Zero.setHighBits(MinSignBits);
3576           break;
3577         }
3578       }
3579     }
3580 
3581     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3582     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3583     if (IsMax)
3584       Known = KnownBits::smax(Known, Known2);
3585     else
3586       Known = KnownBits::smin(Known, Known2);
3587     break;
3588   }
3589   case ISD::FP_TO_UINT_SAT: {
3590     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3591     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3592     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3593     break;
3594   }
3595   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3596     if (Op.getResNo() == 1) {
3597       // The boolean result conforms to getBooleanContents.
3598       // If we know the result of a setcc has the top bits zero, use this info.
3599       // We know that we have an integer-based boolean since these operations
3600       // are only available for integer.
3601       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3602               TargetLowering::ZeroOrOneBooleanContent &&
3603           BitWidth > 1)
3604         Known.Zero.setBitsFrom(1);
3605       break;
3606     }
3607     LLVM_FALLTHROUGH;
3608   case ISD::ATOMIC_CMP_SWAP:
3609   case ISD::ATOMIC_SWAP:
3610   case ISD::ATOMIC_LOAD_ADD:
3611   case ISD::ATOMIC_LOAD_SUB:
3612   case ISD::ATOMIC_LOAD_AND:
3613   case ISD::ATOMIC_LOAD_CLR:
3614   case ISD::ATOMIC_LOAD_OR:
3615   case ISD::ATOMIC_LOAD_XOR:
3616   case ISD::ATOMIC_LOAD_NAND:
3617   case ISD::ATOMIC_LOAD_MIN:
3618   case ISD::ATOMIC_LOAD_MAX:
3619   case ISD::ATOMIC_LOAD_UMIN:
3620   case ISD::ATOMIC_LOAD_UMAX:
3621   case ISD::ATOMIC_LOAD: {
3622     unsigned MemBits =
3623         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3624     // If we are looking at the loaded value.
3625     if (Op.getResNo() == 0) {
3626       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3627         Known.Zero.setBitsFrom(MemBits);
3628     }
3629     break;
3630   }
3631   case ISD::FrameIndex:
3632   case ISD::TargetFrameIndex:
3633     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3634                                        Known, getMachineFunction());
3635     break;
3636 
3637   default:
3638     if (Opcode < ISD::BUILTIN_OP_END)
3639       break;
3640     LLVM_FALLTHROUGH;
3641   case ISD::INTRINSIC_WO_CHAIN:
3642   case ISD::INTRINSIC_W_CHAIN:
3643   case ISD::INTRINSIC_VOID:
3644     // Allow the target to implement this method for its nodes.
3645     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3646     break;
3647   }
3648 
3649   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3650   return Known;
3651 }
3652 
3653 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3654                                                              SDValue N1) const {
3655   // X + 0 never overflow
3656   if (isNullConstant(N1))
3657     return OFK_Never;
3658 
3659   KnownBits N1Known = computeKnownBits(N1);
3660   if (N1Known.Zero.getBoolValue()) {
3661     KnownBits N0Known = computeKnownBits(N0);
3662 
3663     bool overflow;
3664     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3665     if (!overflow)
3666       return OFK_Never;
3667   }
3668 
3669   // mulhi + 1 never overflow
3670   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3671       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3672     return OFK_Never;
3673 
3674   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3675     KnownBits N0Known = computeKnownBits(N0);
3676 
3677     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3678       return OFK_Never;
3679   }
3680 
3681   return OFK_Sometime;
3682 }
3683 
3684 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3685   EVT OpVT = Val.getValueType();
3686   unsigned BitWidth = OpVT.getScalarSizeInBits();
3687 
3688   // Is the constant a known power of 2?
3689   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3690     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3691 
3692   // A left-shift of a constant one will have exactly one bit set because
3693   // shifting the bit off the end is undefined.
3694   if (Val.getOpcode() == ISD::SHL) {
3695     auto *C = isConstOrConstSplat(Val.getOperand(0));
3696     if (C && C->getAPIntValue() == 1)
3697       return true;
3698   }
3699 
3700   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3701   // one bit set.
3702   if (Val.getOpcode() == ISD::SRL) {
3703     auto *C = isConstOrConstSplat(Val.getOperand(0));
3704     if (C && C->getAPIntValue().isSignMask())
3705       return true;
3706   }
3707 
3708   // Are all operands of a build vector constant powers of two?
3709   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3710     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3711           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3712             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3713           return false;
3714         }))
3715       return true;
3716 
3717   // Is the operand of a splat vector a constant power of two?
3718   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3719     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3720       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3721         return true;
3722 
3723   // More could be done here, though the above checks are enough
3724   // to handle some common cases.
3725 
3726   // Fall back to computeKnownBits to catch other known cases.
3727   KnownBits Known = computeKnownBits(Val);
3728   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3729 }
3730 
3731 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3732   EVT VT = Op.getValueType();
3733 
3734   // TODO: Assume we don't know anything for now.
3735   if (VT.isScalableVector())
3736     return 1;
3737 
3738   APInt DemandedElts = VT.isVector()
3739                            ? APInt::getAllOnes(VT.getVectorNumElements())
3740                            : APInt(1, 1);
3741   return ComputeNumSignBits(Op, DemandedElts, Depth);
3742 }
3743 
3744 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3745                                           unsigned Depth) const {
3746   EVT VT = Op.getValueType();
3747   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3748   unsigned VTBits = VT.getScalarSizeInBits();
3749   unsigned NumElts = DemandedElts.getBitWidth();
3750   unsigned Tmp, Tmp2;
3751   unsigned FirstAnswer = 1;
3752 
3753   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3754     const APInt &Val = C->getAPIntValue();
3755     return Val.getNumSignBits();
3756   }
3757 
3758   if (Depth >= MaxRecursionDepth)
3759     return 1;  // Limit search depth.
3760 
3761   if (!DemandedElts || VT.isScalableVector())
3762     return 1;  // No demanded elts, better to assume we don't know anything.
3763 
3764   unsigned Opcode = Op.getOpcode();
3765   switch (Opcode) {
3766   default: break;
3767   case ISD::AssertSext:
3768     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3769     return VTBits-Tmp+1;
3770   case ISD::AssertZext:
3771     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3772     return VTBits-Tmp;
3773 
3774   case ISD::BUILD_VECTOR:
3775     Tmp = VTBits;
3776     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3777       if (!DemandedElts[i])
3778         continue;
3779 
3780       SDValue SrcOp = Op.getOperand(i);
3781       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3782 
3783       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3784       if (SrcOp.getValueSizeInBits() != VTBits) {
3785         assert(SrcOp.getValueSizeInBits() > VTBits &&
3786                "Expected BUILD_VECTOR implicit truncation");
3787         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3788         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3789       }
3790       Tmp = std::min(Tmp, Tmp2);
3791     }
3792     return Tmp;
3793 
3794   case ISD::VECTOR_SHUFFLE: {
3795     // Collect the minimum number of sign bits that are shared by every vector
3796     // element referenced by the shuffle.
3797     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3798     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3799     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3800     for (unsigned i = 0; i != NumElts; ++i) {
3801       int M = SVN->getMaskElt(i);
3802       if (!DemandedElts[i])
3803         continue;
3804       // For UNDEF elements, we don't know anything about the common state of
3805       // the shuffle result.
3806       if (M < 0)
3807         return 1;
3808       if ((unsigned)M < NumElts)
3809         DemandedLHS.setBit((unsigned)M % NumElts);
3810       else
3811         DemandedRHS.setBit((unsigned)M % NumElts);
3812     }
3813     Tmp = std::numeric_limits<unsigned>::max();
3814     if (!!DemandedLHS)
3815       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3816     if (!!DemandedRHS) {
3817       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3818       Tmp = std::min(Tmp, Tmp2);
3819     }
3820     // If we don't know anything, early out and try computeKnownBits fall-back.
3821     if (Tmp == 1)
3822       break;
3823     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3824     return Tmp;
3825   }
3826 
3827   case ISD::BITCAST: {
3828     SDValue N0 = Op.getOperand(0);
3829     EVT SrcVT = N0.getValueType();
3830     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3831 
3832     // Ignore bitcasts from unsupported types..
3833     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3834       break;
3835 
3836     // Fast handling of 'identity' bitcasts.
3837     if (VTBits == SrcBits)
3838       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3839 
3840     bool IsLE = getDataLayout().isLittleEndian();
3841 
3842     // Bitcast 'large element' scalar/vector to 'small element' vector.
3843     if ((SrcBits % VTBits) == 0) {
3844       assert(VT.isVector() && "Expected bitcast to vector");
3845 
3846       unsigned Scale = SrcBits / VTBits;
3847       APInt SrcDemandedElts =
3848           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3849 
3850       // Fast case - sign splat can be simply split across the small elements.
3851       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3852       if (Tmp == SrcBits)
3853         return VTBits;
3854 
3855       // Slow case - determine how far the sign extends into each sub-element.
3856       Tmp2 = VTBits;
3857       for (unsigned i = 0; i != NumElts; ++i)
3858         if (DemandedElts[i]) {
3859           unsigned SubOffset = i % Scale;
3860           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3861           SubOffset = SubOffset * VTBits;
3862           if (Tmp <= SubOffset)
3863             return 1;
3864           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3865         }
3866       return Tmp2;
3867     }
3868     break;
3869   }
3870 
3871   case ISD::FP_TO_SINT_SAT:
3872     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
3873     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3874     return VTBits - Tmp + 1;
3875   case ISD::SIGN_EXTEND:
3876     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3877     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3878   case ISD::SIGN_EXTEND_INREG:
3879     // Max of the input and what this extends.
3880     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3881     Tmp = VTBits-Tmp+1;
3882     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3883     return std::max(Tmp, Tmp2);
3884   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3885     SDValue Src = Op.getOperand(0);
3886     EVT SrcVT = Src.getValueType();
3887     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3888     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3889     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3890   }
3891   case ISD::SRA:
3892     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3893     // SRA X, C -> adds C sign bits.
3894     if (const APInt *ShAmt =
3895             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3896       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3897     return Tmp;
3898   case ISD::SHL:
3899     if (const APInt *ShAmt =
3900             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3901       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3902       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3903       if (ShAmt->ult(Tmp))
3904         return Tmp - ShAmt->getZExtValue();
3905     }
3906     break;
3907   case ISD::AND:
3908   case ISD::OR:
3909   case ISD::XOR:    // NOT is handled here.
3910     // Logical binary ops preserve the number of sign bits at the worst.
3911     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3912     if (Tmp != 1) {
3913       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3914       FirstAnswer = std::min(Tmp, Tmp2);
3915       // We computed what we know about the sign bits as our first
3916       // answer. Now proceed to the generic code that uses
3917       // computeKnownBits, and pick whichever answer is better.
3918     }
3919     break;
3920 
3921   case ISD::SELECT:
3922   case ISD::VSELECT:
3923     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3924     if (Tmp == 1) return 1;  // Early out.
3925     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3926     return std::min(Tmp, Tmp2);
3927   case ISD::SELECT_CC:
3928     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3929     if (Tmp == 1) return 1;  // Early out.
3930     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3931     return std::min(Tmp, Tmp2);
3932 
3933   case ISD::SMIN:
3934   case ISD::SMAX: {
3935     // If we have a clamp pattern, we know that the number of sign bits will be
3936     // the minimum of the clamp min/max range.
3937     bool IsMax = (Opcode == ISD::SMAX);
3938     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3939     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3940       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3941         CstHigh =
3942             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3943     if (CstLow && CstHigh) {
3944       if (!IsMax)
3945         std::swap(CstLow, CstHigh);
3946       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3947         Tmp = CstLow->getAPIntValue().getNumSignBits();
3948         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3949         return std::min(Tmp, Tmp2);
3950       }
3951     }
3952 
3953     // Fallback - just get the minimum number of sign bits of the operands.
3954     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3955     if (Tmp == 1)
3956       return 1;  // Early out.
3957     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3958     return std::min(Tmp, Tmp2);
3959   }
3960   case ISD::UMIN:
3961   case ISD::UMAX:
3962     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3963     if (Tmp == 1)
3964       return 1;  // Early out.
3965     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3966     return std::min(Tmp, Tmp2);
3967   case ISD::SADDO:
3968   case ISD::UADDO:
3969   case ISD::SSUBO:
3970   case ISD::USUBO:
3971   case ISD::SMULO:
3972   case ISD::UMULO:
3973     if (Op.getResNo() != 1)
3974       break;
3975     // The boolean result conforms to getBooleanContents.  Fall through.
3976     // If setcc returns 0/-1, all bits are sign bits.
3977     // We know that we have an integer-based boolean since these operations
3978     // are only available for integer.
3979     if (TLI->getBooleanContents(VT.isVector(), false) ==
3980         TargetLowering::ZeroOrNegativeOneBooleanContent)
3981       return VTBits;
3982     break;
3983   case ISD::SETCC:
3984   case ISD::STRICT_FSETCC:
3985   case ISD::STRICT_FSETCCS: {
3986     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3987     // If setcc returns 0/-1, all bits are sign bits.
3988     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3989         TargetLowering::ZeroOrNegativeOneBooleanContent)
3990       return VTBits;
3991     break;
3992   }
3993   case ISD::ROTL:
3994   case ISD::ROTR:
3995     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3996 
3997     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3998     if (Tmp == VTBits)
3999       return VTBits;
4000 
4001     if (ConstantSDNode *C =
4002             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4003       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4004 
4005       // Handle rotate right by N like a rotate left by 32-N.
4006       if (Opcode == ISD::ROTR)
4007         RotAmt = (VTBits - RotAmt) % VTBits;
4008 
4009       // If we aren't rotating out all of the known-in sign bits, return the
4010       // number that are left.  This handles rotl(sext(x), 1) for example.
4011       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4012     }
4013     break;
4014   case ISD::ADD:
4015   case ISD::ADDC:
4016     // Add can have at most one carry bit.  Thus we know that the output
4017     // is, at worst, one more bit than the inputs.
4018     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4019     if (Tmp == 1) return 1; // Early out.
4020 
4021     // Special case decrementing a value (ADD X, -1):
4022     if (ConstantSDNode *CRHS =
4023             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4024       if (CRHS->isAllOnes()) {
4025         KnownBits Known =
4026             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4027 
4028         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4029         // sign bits set.
4030         if ((Known.Zero | 1).isAllOnes())
4031           return VTBits;
4032 
4033         // If we are subtracting one from a positive number, there is no carry
4034         // out of the result.
4035         if (Known.isNonNegative())
4036           return Tmp;
4037       }
4038 
4039     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4040     if (Tmp2 == 1) return 1; // Early out.
4041     return std::min(Tmp, Tmp2) - 1;
4042   case ISD::SUB:
4043     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4044     if (Tmp2 == 1) return 1; // Early out.
4045 
4046     // Handle NEG.
4047     if (ConstantSDNode *CLHS =
4048             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4049       if (CLHS->isZero()) {
4050         KnownBits Known =
4051             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4052         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4053         // sign bits set.
4054         if ((Known.Zero | 1).isAllOnes())
4055           return VTBits;
4056 
4057         // If the input is known to be positive (the sign bit is known clear),
4058         // the output of the NEG has the same number of sign bits as the input.
4059         if (Known.isNonNegative())
4060           return Tmp2;
4061 
4062         // Otherwise, we treat this like a SUB.
4063       }
4064 
4065     // Sub can have at most one carry bit.  Thus we know that the output
4066     // is, at worst, one more bit than the inputs.
4067     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4068     if (Tmp == 1) return 1; // Early out.
4069     return std::min(Tmp, Tmp2) - 1;
4070   case ISD::MUL: {
4071     // The output of the Mul can be at most twice the valid bits in the inputs.
4072     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4073     if (SignBitsOp0 == 1)
4074       break;
4075     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4076     if (SignBitsOp1 == 1)
4077       break;
4078     unsigned OutValidBits =
4079         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4080     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4081   }
4082   case ISD::SREM:
4083     // The sign bit is the LHS's sign bit, except when the result of the
4084     // remainder is zero. The magnitude of the result should be less than or
4085     // equal to the magnitude of the LHS. Therefore, the result should have
4086     // at least as many sign bits as the left hand side.
4087     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4088   case ISD::TRUNCATE: {
4089     // Check if the sign bits of source go down as far as the truncated value.
4090     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4091     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4092     if (NumSrcSignBits > (NumSrcBits - VTBits))
4093       return NumSrcSignBits - (NumSrcBits - VTBits);
4094     break;
4095   }
4096   case ISD::EXTRACT_ELEMENT: {
4097     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4098     const int BitWidth = Op.getValueSizeInBits();
4099     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4100 
4101     // Get reverse index (starting from 1), Op1 value indexes elements from
4102     // little end. Sign starts at big end.
4103     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4104 
4105     // If the sign portion ends in our element the subtraction gives correct
4106     // result. Otherwise it gives either negative or > bitwidth result
4107     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4108   }
4109   case ISD::INSERT_VECTOR_ELT: {
4110     // If we know the element index, split the demand between the
4111     // source vector and the inserted element, otherwise assume we need
4112     // the original demanded vector elements and the value.
4113     SDValue InVec = Op.getOperand(0);
4114     SDValue InVal = Op.getOperand(1);
4115     SDValue EltNo = Op.getOperand(2);
4116     bool DemandedVal = true;
4117     APInt DemandedVecElts = DemandedElts;
4118     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4119     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4120       unsigned EltIdx = CEltNo->getZExtValue();
4121       DemandedVal = !!DemandedElts[EltIdx];
4122       DemandedVecElts.clearBit(EltIdx);
4123     }
4124     Tmp = std::numeric_limits<unsigned>::max();
4125     if (DemandedVal) {
4126       // TODO - handle implicit truncation of inserted elements.
4127       if (InVal.getScalarValueSizeInBits() != VTBits)
4128         break;
4129       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4130       Tmp = std::min(Tmp, Tmp2);
4131     }
4132     if (!!DemandedVecElts) {
4133       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4134       Tmp = std::min(Tmp, Tmp2);
4135     }
4136     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4137     return Tmp;
4138   }
4139   case ISD::EXTRACT_VECTOR_ELT: {
4140     SDValue InVec = Op.getOperand(0);
4141     SDValue EltNo = Op.getOperand(1);
4142     EVT VecVT = InVec.getValueType();
4143     // ComputeNumSignBits not yet implemented for scalable vectors.
4144     if (VecVT.isScalableVector())
4145       break;
4146     const unsigned BitWidth = Op.getValueSizeInBits();
4147     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4148     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4149 
4150     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4151     // anything about sign bits. But if the sizes match we can derive knowledge
4152     // about sign bits from the vector operand.
4153     if (BitWidth != EltBitWidth)
4154       break;
4155 
4156     // If we know the element index, just demand that vector element, else for
4157     // an unknown element index, ignore DemandedElts and demand them all.
4158     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4159     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4160     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4161       DemandedSrcElts =
4162           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4163 
4164     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4165   }
4166   case ISD::EXTRACT_SUBVECTOR: {
4167     // Offset the demanded elts by the subvector index.
4168     SDValue Src = Op.getOperand(0);
4169     // Bail until we can represent demanded elements for scalable vectors.
4170     if (Src.getValueType().isScalableVector())
4171       break;
4172     uint64_t Idx = Op.getConstantOperandVal(1);
4173     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4174     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4175     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4176   }
4177   case ISD::CONCAT_VECTORS: {
4178     // Determine the minimum number of sign bits across all demanded
4179     // elts of the input vectors. Early out if the result is already 1.
4180     Tmp = std::numeric_limits<unsigned>::max();
4181     EVT SubVectorVT = Op.getOperand(0).getValueType();
4182     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4183     unsigned NumSubVectors = Op.getNumOperands();
4184     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4185       APInt DemandedSub =
4186           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4187       if (!DemandedSub)
4188         continue;
4189       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4190       Tmp = std::min(Tmp, Tmp2);
4191     }
4192     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4193     return Tmp;
4194   }
4195   case ISD::INSERT_SUBVECTOR: {
4196     // Demand any elements from the subvector and the remainder from the src its
4197     // inserted into.
4198     SDValue Src = Op.getOperand(0);
4199     SDValue Sub = Op.getOperand(1);
4200     uint64_t Idx = Op.getConstantOperandVal(2);
4201     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4202     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4203     APInt DemandedSrcElts = DemandedElts;
4204     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4205 
4206     Tmp = std::numeric_limits<unsigned>::max();
4207     if (!!DemandedSubElts) {
4208       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4209       if (Tmp == 1)
4210         return 1; // early-out
4211     }
4212     if (!!DemandedSrcElts) {
4213       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4214       Tmp = std::min(Tmp, Tmp2);
4215     }
4216     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4217     return Tmp;
4218   }
4219   case ISD::ATOMIC_CMP_SWAP:
4220   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4221   case ISD::ATOMIC_SWAP:
4222   case ISD::ATOMIC_LOAD_ADD:
4223   case ISD::ATOMIC_LOAD_SUB:
4224   case ISD::ATOMIC_LOAD_AND:
4225   case ISD::ATOMIC_LOAD_CLR:
4226   case ISD::ATOMIC_LOAD_OR:
4227   case ISD::ATOMIC_LOAD_XOR:
4228   case ISD::ATOMIC_LOAD_NAND:
4229   case ISD::ATOMIC_LOAD_MIN:
4230   case ISD::ATOMIC_LOAD_MAX:
4231   case ISD::ATOMIC_LOAD_UMIN:
4232   case ISD::ATOMIC_LOAD_UMAX:
4233   case ISD::ATOMIC_LOAD: {
4234     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4235     // If we are looking at the loaded value.
4236     if (Op.getResNo() == 0) {
4237       if (Tmp == VTBits)
4238         return 1; // early-out
4239       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4240         return VTBits - Tmp + 1;
4241       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4242         return VTBits - Tmp;
4243     }
4244     break;
4245   }
4246   }
4247 
4248   // If we are looking at the loaded value of the SDNode.
4249   if (Op.getResNo() == 0) {
4250     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4251     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4252       unsigned ExtType = LD->getExtensionType();
4253       switch (ExtType) {
4254       default: break;
4255       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4256         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4257         return VTBits - Tmp + 1;
4258       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4259         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4260         return VTBits - Tmp;
4261       case ISD::NON_EXTLOAD:
4262         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4263           // We only need to handle vectors - computeKnownBits should handle
4264           // scalar cases.
4265           Type *CstTy = Cst->getType();
4266           if (CstTy->isVectorTy() &&
4267               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4268             Tmp = VTBits;
4269             for (unsigned i = 0; i != NumElts; ++i) {
4270               if (!DemandedElts[i])
4271                 continue;
4272               if (Constant *Elt = Cst->getAggregateElement(i)) {
4273                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4274                   const APInt &Value = CInt->getValue();
4275                   Tmp = std::min(Tmp, Value.getNumSignBits());
4276                   continue;
4277                 }
4278                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4279                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4280                   Tmp = std::min(Tmp, Value.getNumSignBits());
4281                   continue;
4282                 }
4283               }
4284               // Unknown type. Conservatively assume no bits match sign bit.
4285               return 1;
4286             }
4287             return Tmp;
4288           }
4289         }
4290         break;
4291       }
4292     }
4293   }
4294 
4295   // Allow the target to implement this method for its nodes.
4296   if (Opcode >= ISD::BUILTIN_OP_END ||
4297       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4298       Opcode == ISD::INTRINSIC_W_CHAIN ||
4299       Opcode == ISD::INTRINSIC_VOID) {
4300     unsigned NumBits =
4301         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4302     if (NumBits > 1)
4303       FirstAnswer = std::max(FirstAnswer, NumBits);
4304   }
4305 
4306   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4307   // use this information.
4308   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4309   return std::max(FirstAnswer, Known.countMinSignBits());
4310 }
4311 
4312 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4313                                                  unsigned Depth) const {
4314   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4315   return Op.getScalarValueSizeInBits() - SignBits + 1;
4316 }
4317 
4318 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4319                                                  const APInt &DemandedElts,
4320                                                  unsigned Depth) const {
4321   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4322   return Op.getScalarValueSizeInBits() - SignBits + 1;
4323 }
4324 
4325 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4326                                                     unsigned Depth) const {
4327   // Early out for FREEZE.
4328   if (Op.getOpcode() == ISD::FREEZE)
4329     return true;
4330 
4331   // TODO: Assume we don't know anything for now.
4332   EVT VT = Op.getValueType();
4333   if (VT.isScalableVector())
4334     return false;
4335 
4336   APInt DemandedElts = VT.isVector()
4337                            ? APInt::getAllOnes(VT.getVectorNumElements())
4338                            : APInt(1, 1);
4339   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4340 }
4341 
4342 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4343                                                     const APInt &DemandedElts,
4344                                                     bool PoisonOnly,
4345                                                     unsigned Depth) const {
4346   unsigned Opcode = Op.getOpcode();
4347 
4348   // Early out for FREEZE.
4349   if (Opcode == ISD::FREEZE)
4350     return true;
4351 
4352   if (Depth >= MaxRecursionDepth)
4353     return false; // Limit search depth.
4354 
4355   if (isIntOrFPConstant(Op))
4356     return true;
4357 
4358   switch (Opcode) {
4359   case ISD::UNDEF:
4360     return PoisonOnly;
4361 
4362   case ISD::BUILD_VECTOR:
4363     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4364     // this shouldn't affect the result.
4365     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4366       if (!DemandedElts[i])
4367         continue;
4368       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4369                                             Depth + 1))
4370         return false;
4371     }
4372     return true;
4373 
4374   // TODO: Search for noundef attributes from library functions.
4375 
4376   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4377 
4378   default:
4379     // Allow the target to implement this method for its nodes.
4380     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4381         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4382       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4383           Op, DemandedElts, *this, PoisonOnly, Depth);
4384     break;
4385   }
4386 
4387   return false;
4388 }
4389 
4390 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4391   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4392       !isa<ConstantSDNode>(Op.getOperand(1)))
4393     return false;
4394 
4395   if (Op.getOpcode() == ISD::OR &&
4396       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4397     return false;
4398 
4399   return true;
4400 }
4401 
4402 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4403   // If we're told that NaNs won't happen, assume they won't.
4404   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4405     return true;
4406 
4407   if (Depth >= MaxRecursionDepth)
4408     return false; // Limit search depth.
4409 
4410   // TODO: Handle vectors.
4411   // If the value is a constant, we can obviously see if it is a NaN or not.
4412   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4413     return !C->getValueAPF().isNaN() ||
4414            (SNaN && !C->getValueAPF().isSignaling());
4415   }
4416 
4417   unsigned Opcode = Op.getOpcode();
4418   switch (Opcode) {
4419   case ISD::FADD:
4420   case ISD::FSUB:
4421   case ISD::FMUL:
4422   case ISD::FDIV:
4423   case ISD::FREM:
4424   case ISD::FSIN:
4425   case ISD::FCOS: {
4426     if (SNaN)
4427       return true;
4428     // TODO: Need isKnownNeverInfinity
4429     return false;
4430   }
4431   case ISD::FCANONICALIZE:
4432   case ISD::FEXP:
4433   case ISD::FEXP2:
4434   case ISD::FTRUNC:
4435   case ISD::FFLOOR:
4436   case ISD::FCEIL:
4437   case ISD::FROUND:
4438   case ISD::FROUNDEVEN:
4439   case ISD::FRINT:
4440   case ISD::FNEARBYINT: {
4441     if (SNaN)
4442       return true;
4443     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4444   }
4445   case ISD::FABS:
4446   case ISD::FNEG:
4447   case ISD::FCOPYSIGN: {
4448     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4449   }
4450   case ISD::SELECT:
4451     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4452            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4453   case ISD::FP_EXTEND:
4454   case ISD::FP_ROUND: {
4455     if (SNaN)
4456       return true;
4457     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4458   }
4459   case ISD::SINT_TO_FP:
4460   case ISD::UINT_TO_FP:
4461     return true;
4462   case ISD::FMA:
4463   case ISD::FMAD: {
4464     if (SNaN)
4465       return true;
4466     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4467            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4468            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4469   }
4470   case ISD::FSQRT: // Need is known positive
4471   case ISD::FLOG:
4472   case ISD::FLOG2:
4473   case ISD::FLOG10:
4474   case ISD::FPOWI:
4475   case ISD::FPOW: {
4476     if (SNaN)
4477       return true;
4478     // TODO: Refine on operand
4479     return false;
4480   }
4481   case ISD::FMINNUM:
4482   case ISD::FMAXNUM: {
4483     // Only one needs to be known not-nan, since it will be returned if the
4484     // other ends up being one.
4485     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4486            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4487   }
4488   case ISD::FMINNUM_IEEE:
4489   case ISD::FMAXNUM_IEEE: {
4490     if (SNaN)
4491       return true;
4492     // This can return a NaN if either operand is an sNaN, or if both operands
4493     // are NaN.
4494     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4495             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4496            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4497             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4498   }
4499   case ISD::FMINIMUM:
4500   case ISD::FMAXIMUM: {
4501     // TODO: Does this quiet or return the origina NaN as-is?
4502     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4503            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4504   }
4505   case ISD::EXTRACT_VECTOR_ELT: {
4506     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4507   }
4508   default:
4509     if (Opcode >= ISD::BUILTIN_OP_END ||
4510         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4511         Opcode == ISD::INTRINSIC_W_CHAIN ||
4512         Opcode == ISD::INTRINSIC_VOID) {
4513       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4514     }
4515 
4516     return false;
4517   }
4518 }
4519 
4520 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4521   assert(Op.getValueType().isFloatingPoint() &&
4522          "Floating point type expected");
4523 
4524   // If the value is a constant, we can obviously see if it is a zero or not.
4525   // TODO: Add BuildVector support.
4526   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4527     return !C->isZero();
4528   return false;
4529 }
4530 
4531 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4532   assert(!Op.getValueType().isFloatingPoint() &&
4533          "Floating point types unsupported - use isKnownNeverZeroFloat");
4534 
4535   // If the value is a constant, we can obviously see if it is a zero or not.
4536   if (ISD::matchUnaryPredicate(Op,
4537                                [](ConstantSDNode *C) { return !C->isZero(); }))
4538     return true;
4539 
4540   // TODO: Recognize more cases here.
4541   switch (Op.getOpcode()) {
4542   default: break;
4543   case ISD::OR:
4544     if (isKnownNeverZero(Op.getOperand(1)) ||
4545         isKnownNeverZero(Op.getOperand(0)))
4546       return true;
4547     break;
4548   }
4549 
4550   return false;
4551 }
4552 
4553 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4554   // Check the obvious case.
4555   if (A == B) return true;
4556 
4557   // For for negative and positive zero.
4558   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4559     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4560       if (CA->isZero() && CB->isZero()) return true;
4561 
4562   // Otherwise they may not be equal.
4563   return false;
4564 }
4565 
4566 // FIXME: unify with llvm::haveNoCommonBitsSet.
4567 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4568   assert(A.getValueType() == B.getValueType() &&
4569          "Values must have the same type");
4570   // Match masked merge pattern (X & ~M) op (Y & M)
4571   if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) {
4572     auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) {
4573       if (isBitwiseNot(NotM, true)) {
4574         SDValue NotOperand = NotM->getOperand(0);
4575         return NotOperand == And->getOperand(0) ||
4576                NotOperand == And->getOperand(1);
4577       }
4578       return false;
4579     };
4580     if (MatchNoCommonBitsPattern(A->getOperand(0), B) ||
4581         MatchNoCommonBitsPattern(A->getOperand(1), B) ||
4582         MatchNoCommonBitsPattern(B->getOperand(0), A) ||
4583         MatchNoCommonBitsPattern(B->getOperand(1), A))
4584       return true;
4585   }
4586   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4587                                         computeKnownBits(B));
4588 }
4589 
4590 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4591                                SelectionDAG &DAG) {
4592   if (cast<ConstantSDNode>(Step)->isZero())
4593     return DAG.getConstant(0, DL, VT);
4594 
4595   return SDValue();
4596 }
4597 
4598 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4599                                 ArrayRef<SDValue> Ops,
4600                                 SelectionDAG &DAG) {
4601   int NumOps = Ops.size();
4602   assert(NumOps != 0 && "Can't build an empty vector!");
4603   assert(!VT.isScalableVector() &&
4604          "BUILD_VECTOR cannot be used with scalable types");
4605   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4606          "Incorrect element count in BUILD_VECTOR!");
4607 
4608   // BUILD_VECTOR of UNDEFs is UNDEF.
4609   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4610     return DAG.getUNDEF(VT);
4611 
4612   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4613   SDValue IdentitySrc;
4614   bool IsIdentity = true;
4615   for (int i = 0; i != NumOps; ++i) {
4616     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4617         Ops[i].getOperand(0).getValueType() != VT ||
4618         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4619         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4620         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4621       IsIdentity = false;
4622       break;
4623     }
4624     IdentitySrc = Ops[i].getOperand(0);
4625   }
4626   if (IsIdentity)
4627     return IdentitySrc;
4628 
4629   return SDValue();
4630 }
4631 
4632 /// Try to simplify vector concatenation to an input value, undef, or build
4633 /// vector.
4634 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4635                                   ArrayRef<SDValue> Ops,
4636                                   SelectionDAG &DAG) {
4637   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4638   assert(llvm::all_of(Ops,
4639                       [Ops](SDValue Op) {
4640                         return Ops[0].getValueType() == Op.getValueType();
4641                       }) &&
4642          "Concatenation of vectors with inconsistent value types!");
4643   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4644              VT.getVectorElementCount() &&
4645          "Incorrect element count in vector concatenation!");
4646 
4647   if (Ops.size() == 1)
4648     return Ops[0];
4649 
4650   // Concat of UNDEFs is UNDEF.
4651   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4652     return DAG.getUNDEF(VT);
4653 
4654   // Scan the operands and look for extract operations from a single source
4655   // that correspond to insertion at the same location via this concatenation:
4656   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4657   SDValue IdentitySrc;
4658   bool IsIdentity = true;
4659   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4660     SDValue Op = Ops[i];
4661     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4662     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4663         Op.getOperand(0).getValueType() != VT ||
4664         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4665         Op.getConstantOperandVal(1) != IdentityIndex) {
4666       IsIdentity = false;
4667       break;
4668     }
4669     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4670            "Unexpected identity source vector for concat of extracts");
4671     IdentitySrc = Op.getOperand(0);
4672   }
4673   if (IsIdentity) {
4674     assert(IdentitySrc && "Failed to set source vector of extracts");
4675     return IdentitySrc;
4676   }
4677 
4678   // The code below this point is only designed to work for fixed width
4679   // vectors, so we bail out for now.
4680   if (VT.isScalableVector())
4681     return SDValue();
4682 
4683   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4684   // simplified to one big BUILD_VECTOR.
4685   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4686   EVT SVT = VT.getScalarType();
4687   SmallVector<SDValue, 16> Elts;
4688   for (SDValue Op : Ops) {
4689     EVT OpVT = Op.getValueType();
4690     if (Op.isUndef())
4691       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4692     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4693       Elts.append(Op->op_begin(), Op->op_end());
4694     else
4695       return SDValue();
4696   }
4697 
4698   // BUILD_VECTOR requires all inputs to be of the same type, find the
4699   // maximum type and extend them all.
4700   for (SDValue Op : Elts)
4701     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4702 
4703   if (SVT.bitsGT(VT.getScalarType())) {
4704     for (SDValue &Op : Elts) {
4705       if (Op.isUndef())
4706         Op = DAG.getUNDEF(SVT);
4707       else
4708         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4709                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4710                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4711     }
4712   }
4713 
4714   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4715   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4716   return V;
4717 }
4718 
4719 /// Gets or creates the specified node.
4720 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4721   FoldingSetNodeID ID;
4722   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4723   void *IP = nullptr;
4724   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4725     return SDValue(E, 0);
4726 
4727   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4728                               getVTList(VT));
4729   CSEMap.InsertNode(N, IP);
4730 
4731   InsertNode(N);
4732   SDValue V = SDValue(N, 0);
4733   NewSDValueDbgMsg(V, "Creating new node: ", this);
4734   return V;
4735 }
4736 
4737 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4738                               SDValue Operand) {
4739   SDNodeFlags Flags;
4740   if (Inserter)
4741     Flags = Inserter->getFlags();
4742   return getNode(Opcode, DL, VT, Operand, Flags);
4743 }
4744 
4745 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4746                               SDValue Operand, const SDNodeFlags Flags) {
4747   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4748          "Operand is DELETED_NODE!");
4749   // Constant fold unary operations with an integer constant operand. Even
4750   // opaque constant will be folded, because the folding of unary operations
4751   // doesn't create new constants with different values. Nevertheless, the
4752   // opaque flag is preserved during folding to prevent future folding with
4753   // other constants.
4754   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4755     const APInt &Val = C->getAPIntValue();
4756     switch (Opcode) {
4757     default: break;
4758     case ISD::SIGN_EXTEND:
4759       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4760                          C->isTargetOpcode(), C->isOpaque());
4761     case ISD::TRUNCATE:
4762       if (C->isOpaque())
4763         break;
4764       LLVM_FALLTHROUGH;
4765     case ISD::ZERO_EXTEND:
4766       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4767                          C->isTargetOpcode(), C->isOpaque());
4768     case ISD::ANY_EXTEND:
4769       // Some targets like RISCV prefer to sign extend some types.
4770       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4771         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4772                            C->isTargetOpcode(), C->isOpaque());
4773       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4774                          C->isTargetOpcode(), C->isOpaque());
4775     case ISD::UINT_TO_FP:
4776     case ISD::SINT_TO_FP: {
4777       APFloat apf(EVTToAPFloatSemantics(VT),
4778                   APInt::getZero(VT.getSizeInBits()));
4779       (void)apf.convertFromAPInt(Val,
4780                                  Opcode==ISD::SINT_TO_FP,
4781                                  APFloat::rmNearestTiesToEven);
4782       return getConstantFP(apf, DL, VT);
4783     }
4784     case ISD::BITCAST:
4785       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4786         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4787       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4788         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4789       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4790         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4791       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4792         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4793       break;
4794     case ISD::ABS:
4795       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4796                          C->isOpaque());
4797     case ISD::BITREVERSE:
4798       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4799                          C->isOpaque());
4800     case ISD::BSWAP:
4801       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4802                          C->isOpaque());
4803     case ISD::CTPOP:
4804       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4805                          C->isOpaque());
4806     case ISD::CTLZ:
4807     case ISD::CTLZ_ZERO_UNDEF:
4808       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4809                          C->isOpaque());
4810     case ISD::CTTZ:
4811     case ISD::CTTZ_ZERO_UNDEF:
4812       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4813                          C->isOpaque());
4814     case ISD::FP16_TO_FP: {
4815       bool Ignored;
4816       APFloat FPV(APFloat::IEEEhalf(),
4817                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4818 
4819       // This can return overflow, underflow, or inexact; we don't care.
4820       // FIXME need to be more flexible about rounding mode.
4821       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4822                         APFloat::rmNearestTiesToEven, &Ignored);
4823       return getConstantFP(FPV, DL, VT);
4824     }
4825     case ISD::STEP_VECTOR: {
4826       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4827         return V;
4828       break;
4829     }
4830     }
4831   }
4832 
4833   // Constant fold unary operations with a floating point constant operand.
4834   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4835     APFloat V = C->getValueAPF();    // make copy
4836     switch (Opcode) {
4837     case ISD::FNEG:
4838       V.changeSign();
4839       return getConstantFP(V, DL, VT);
4840     case ISD::FABS:
4841       V.clearSign();
4842       return getConstantFP(V, DL, VT);
4843     case ISD::FCEIL: {
4844       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4845       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4846         return getConstantFP(V, DL, VT);
4847       break;
4848     }
4849     case ISD::FTRUNC: {
4850       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4851       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4852         return getConstantFP(V, DL, VT);
4853       break;
4854     }
4855     case ISD::FFLOOR: {
4856       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4857       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4858         return getConstantFP(V, DL, VT);
4859       break;
4860     }
4861     case ISD::FP_EXTEND: {
4862       bool ignored;
4863       // This can return overflow, underflow, or inexact; we don't care.
4864       // FIXME need to be more flexible about rounding mode.
4865       (void)V.convert(EVTToAPFloatSemantics(VT),
4866                       APFloat::rmNearestTiesToEven, &ignored);
4867       return getConstantFP(V, DL, VT);
4868     }
4869     case ISD::FP_TO_SINT:
4870     case ISD::FP_TO_UINT: {
4871       bool ignored;
4872       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4873       // FIXME need to be more flexible about rounding mode.
4874       APFloat::opStatus s =
4875           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4876       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4877         break;
4878       return getConstant(IntVal, DL, VT);
4879     }
4880     case ISD::BITCAST:
4881       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4882         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4883       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4884         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4885       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4886         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4887       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4888         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4889       break;
4890     case ISD::FP_TO_FP16: {
4891       bool Ignored;
4892       // This can return overflow, underflow, or inexact; we don't care.
4893       // FIXME need to be more flexible about rounding mode.
4894       (void)V.convert(APFloat::IEEEhalf(),
4895                       APFloat::rmNearestTiesToEven, &Ignored);
4896       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4897     }
4898     }
4899   }
4900 
4901   // Constant fold unary operations with a vector integer or float operand.
4902   switch (Opcode) {
4903   default:
4904     // FIXME: Entirely reasonable to perform folding of other unary
4905     // operations here as the need arises.
4906     break;
4907   case ISD::FNEG:
4908   case ISD::FABS:
4909   case ISD::FCEIL:
4910   case ISD::FTRUNC:
4911   case ISD::FFLOOR:
4912   case ISD::FP_EXTEND:
4913   case ISD::FP_TO_SINT:
4914   case ISD::FP_TO_UINT:
4915   case ISD::TRUNCATE:
4916   case ISD::ANY_EXTEND:
4917   case ISD::ZERO_EXTEND:
4918   case ISD::SIGN_EXTEND:
4919   case ISD::UINT_TO_FP:
4920   case ISD::SINT_TO_FP:
4921   case ISD::ABS:
4922   case ISD::BITREVERSE:
4923   case ISD::BSWAP:
4924   case ISD::CTLZ:
4925   case ISD::CTLZ_ZERO_UNDEF:
4926   case ISD::CTTZ:
4927   case ISD::CTTZ_ZERO_UNDEF:
4928   case ISD::CTPOP: {
4929     SDValue Ops = {Operand};
4930     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
4931       return Fold;
4932   }
4933   }
4934 
4935   unsigned OpOpcode = Operand.getNode()->getOpcode();
4936   switch (Opcode) {
4937   case ISD::STEP_VECTOR:
4938     assert(VT.isScalableVector() &&
4939            "STEP_VECTOR can only be used with scalable types");
4940     assert(OpOpcode == ISD::TargetConstant &&
4941            VT.getVectorElementType() == Operand.getValueType() &&
4942            "Unexpected step operand");
4943     break;
4944   case ISD::FREEZE:
4945     assert(VT == Operand.getValueType() && "Unexpected VT!");
4946     break;
4947   case ISD::TokenFactor:
4948   case ISD::MERGE_VALUES:
4949   case ISD::CONCAT_VECTORS:
4950     return Operand;         // Factor, merge or concat of one node?  No need.
4951   case ISD::BUILD_VECTOR: {
4952     // Attempt to simplify BUILD_VECTOR.
4953     SDValue Ops[] = {Operand};
4954     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4955       return V;
4956     break;
4957   }
4958   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4959   case ISD::FP_EXTEND:
4960     assert(VT.isFloatingPoint() &&
4961            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4962     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4963     assert((!VT.isVector() ||
4964             VT.getVectorElementCount() ==
4965             Operand.getValueType().getVectorElementCount()) &&
4966            "Vector element count mismatch!");
4967     assert(Operand.getValueType().bitsLT(VT) &&
4968            "Invalid fpext node, dst < src!");
4969     if (Operand.isUndef())
4970       return getUNDEF(VT);
4971     break;
4972   case ISD::FP_TO_SINT:
4973   case ISD::FP_TO_UINT:
4974     if (Operand.isUndef())
4975       return getUNDEF(VT);
4976     break;
4977   case ISD::SINT_TO_FP:
4978   case ISD::UINT_TO_FP:
4979     // [us]itofp(undef) = 0, because the result value is bounded.
4980     if (Operand.isUndef())
4981       return getConstantFP(0.0, DL, VT);
4982     break;
4983   case ISD::SIGN_EXTEND:
4984     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4985            "Invalid SIGN_EXTEND!");
4986     assert(VT.isVector() == Operand.getValueType().isVector() &&
4987            "SIGN_EXTEND result type type should be vector iff the operand "
4988            "type is vector!");
4989     if (Operand.getValueType() == VT) return Operand;   // noop extension
4990     assert((!VT.isVector() ||
4991             VT.getVectorElementCount() ==
4992                 Operand.getValueType().getVectorElementCount()) &&
4993            "Vector element count mismatch!");
4994     assert(Operand.getValueType().bitsLT(VT) &&
4995            "Invalid sext node, dst < src!");
4996     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4997       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4998     if (OpOpcode == ISD::UNDEF)
4999       // sext(undef) = 0, because the top bits will all be the same.
5000       return getConstant(0, DL, VT);
5001     break;
5002   case ISD::ZERO_EXTEND:
5003     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5004            "Invalid ZERO_EXTEND!");
5005     assert(VT.isVector() == Operand.getValueType().isVector() &&
5006            "ZERO_EXTEND result type type should be vector iff the operand "
5007            "type is vector!");
5008     if (Operand.getValueType() == VT) return Operand;   // noop extension
5009     assert((!VT.isVector() ||
5010             VT.getVectorElementCount() ==
5011                 Operand.getValueType().getVectorElementCount()) &&
5012            "Vector element count mismatch!");
5013     assert(Operand.getValueType().bitsLT(VT) &&
5014            "Invalid zext node, dst < src!");
5015     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5016       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5017     if (OpOpcode == ISD::UNDEF)
5018       // zext(undef) = 0, because the top bits will be zero.
5019       return getConstant(0, DL, VT);
5020     break;
5021   case ISD::ANY_EXTEND:
5022     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5023            "Invalid ANY_EXTEND!");
5024     assert(VT.isVector() == Operand.getValueType().isVector() &&
5025            "ANY_EXTEND result type type should be vector iff the operand "
5026            "type is vector!");
5027     if (Operand.getValueType() == VT) return Operand;   // noop extension
5028     assert((!VT.isVector() ||
5029             VT.getVectorElementCount() ==
5030                 Operand.getValueType().getVectorElementCount()) &&
5031            "Vector element count mismatch!");
5032     assert(Operand.getValueType().bitsLT(VT) &&
5033            "Invalid anyext node, dst < src!");
5034 
5035     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5036         OpOpcode == ISD::ANY_EXTEND)
5037       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5038       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5039     if (OpOpcode == ISD::UNDEF)
5040       return getUNDEF(VT);
5041 
5042     // (ext (trunc x)) -> x
5043     if (OpOpcode == ISD::TRUNCATE) {
5044       SDValue OpOp = Operand.getOperand(0);
5045       if (OpOp.getValueType() == VT) {
5046         transferDbgValues(Operand, OpOp);
5047         return OpOp;
5048       }
5049     }
5050     break;
5051   case ISD::TRUNCATE:
5052     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5053            "Invalid TRUNCATE!");
5054     assert(VT.isVector() == Operand.getValueType().isVector() &&
5055            "TRUNCATE result type type should be vector iff the operand "
5056            "type is vector!");
5057     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5058     assert((!VT.isVector() ||
5059             VT.getVectorElementCount() ==
5060                 Operand.getValueType().getVectorElementCount()) &&
5061            "Vector element count mismatch!");
5062     assert(Operand.getValueType().bitsGT(VT) &&
5063            "Invalid truncate node, src < dst!");
5064     if (OpOpcode == ISD::TRUNCATE)
5065       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5066     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5067         OpOpcode == ISD::ANY_EXTEND) {
5068       // If the source is smaller than the dest, we still need an extend.
5069       if (Operand.getOperand(0).getValueType().getScalarType()
5070             .bitsLT(VT.getScalarType()))
5071         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5072       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5073         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5074       return Operand.getOperand(0);
5075     }
5076     if (OpOpcode == ISD::UNDEF)
5077       return getUNDEF(VT);
5078     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5079       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5080     break;
5081   case ISD::ANY_EXTEND_VECTOR_INREG:
5082   case ISD::ZERO_EXTEND_VECTOR_INREG:
5083   case ISD::SIGN_EXTEND_VECTOR_INREG:
5084     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5085     assert(Operand.getValueType().bitsLE(VT) &&
5086            "The input must be the same size or smaller than the result.");
5087     assert(VT.getVectorMinNumElements() <
5088                Operand.getValueType().getVectorMinNumElements() &&
5089            "The destination vector type must have fewer lanes than the input.");
5090     break;
5091   case ISD::ABS:
5092     assert(VT.isInteger() && VT == Operand.getValueType() &&
5093            "Invalid ABS!");
5094     if (OpOpcode == ISD::UNDEF)
5095       return getUNDEF(VT);
5096     break;
5097   case ISD::BSWAP:
5098     assert(VT.isInteger() && VT == Operand.getValueType() &&
5099            "Invalid BSWAP!");
5100     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5101            "BSWAP types must be a multiple of 16 bits!");
5102     if (OpOpcode == ISD::UNDEF)
5103       return getUNDEF(VT);
5104     break;
5105   case ISD::BITREVERSE:
5106     assert(VT.isInteger() && VT == Operand.getValueType() &&
5107            "Invalid BITREVERSE!");
5108     if (OpOpcode == ISD::UNDEF)
5109       return getUNDEF(VT);
5110     break;
5111   case ISD::BITCAST:
5112     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5113            "Cannot BITCAST between types of different sizes!");
5114     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5115     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5116       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5117     if (OpOpcode == ISD::UNDEF)
5118       return getUNDEF(VT);
5119     break;
5120   case ISD::SCALAR_TO_VECTOR:
5121     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5122            (VT.getVectorElementType() == Operand.getValueType() ||
5123             (VT.getVectorElementType().isInteger() &&
5124              Operand.getValueType().isInteger() &&
5125              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5126            "Illegal SCALAR_TO_VECTOR node!");
5127     if (OpOpcode == ISD::UNDEF)
5128       return getUNDEF(VT);
5129     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5130     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5131         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5132         Operand.getConstantOperandVal(1) == 0 &&
5133         Operand.getOperand(0).getValueType() == VT)
5134       return Operand.getOperand(0);
5135     break;
5136   case ISD::FNEG:
5137     // Negation of an unknown bag of bits is still completely undefined.
5138     if (OpOpcode == ISD::UNDEF)
5139       return getUNDEF(VT);
5140 
5141     if (OpOpcode == ISD::FNEG)  // --X -> X
5142       return Operand.getOperand(0);
5143     break;
5144   case ISD::FABS:
5145     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5146       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5147     break;
5148   case ISD::VSCALE:
5149     assert(VT == Operand.getValueType() && "Unexpected VT!");
5150     break;
5151   case ISD::CTPOP:
5152     if (Operand.getValueType().getScalarType() == MVT::i1)
5153       return Operand;
5154     break;
5155   case ISD::CTLZ:
5156   case ISD::CTTZ:
5157     if (Operand.getValueType().getScalarType() == MVT::i1)
5158       return getNOT(DL, Operand, Operand.getValueType());
5159     break;
5160   case ISD::VECREDUCE_SMIN:
5161   case ISD::VECREDUCE_UMAX:
5162     if (Operand.getValueType().getScalarType() == MVT::i1)
5163       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5164     break;
5165   case ISD::VECREDUCE_SMAX:
5166   case ISD::VECREDUCE_UMIN:
5167     if (Operand.getValueType().getScalarType() == MVT::i1)
5168       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5169     break;
5170   }
5171 
5172   SDNode *N;
5173   SDVTList VTs = getVTList(VT);
5174   SDValue Ops[] = {Operand};
5175   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5176     FoldingSetNodeID ID;
5177     AddNodeIDNode(ID, Opcode, VTs, Ops);
5178     void *IP = nullptr;
5179     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5180       E->intersectFlagsWith(Flags);
5181       return SDValue(E, 0);
5182     }
5183 
5184     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5185     N->setFlags(Flags);
5186     createOperands(N, Ops);
5187     CSEMap.InsertNode(N, IP);
5188   } else {
5189     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5190     createOperands(N, Ops);
5191   }
5192 
5193   InsertNode(N);
5194   SDValue V = SDValue(N, 0);
5195   NewSDValueDbgMsg(V, "Creating new node: ", this);
5196   return V;
5197 }
5198 
5199 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5200                                        const APInt &C2) {
5201   switch (Opcode) {
5202   case ISD::ADD:  return C1 + C2;
5203   case ISD::SUB:  return C1 - C2;
5204   case ISD::MUL:  return C1 * C2;
5205   case ISD::AND:  return C1 & C2;
5206   case ISD::OR:   return C1 | C2;
5207   case ISD::XOR:  return C1 ^ C2;
5208   case ISD::SHL:  return C1 << C2;
5209   case ISD::SRL:  return C1.lshr(C2);
5210   case ISD::SRA:  return C1.ashr(C2);
5211   case ISD::ROTL: return C1.rotl(C2);
5212   case ISD::ROTR: return C1.rotr(C2);
5213   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5214   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5215   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5216   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5217   case ISD::SADDSAT: return C1.sadd_sat(C2);
5218   case ISD::UADDSAT: return C1.uadd_sat(C2);
5219   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5220   case ISD::USUBSAT: return C1.usub_sat(C2);
5221   case ISD::UDIV:
5222     if (!C2.getBoolValue())
5223       break;
5224     return C1.udiv(C2);
5225   case ISD::UREM:
5226     if (!C2.getBoolValue())
5227       break;
5228     return C1.urem(C2);
5229   case ISD::SDIV:
5230     if (!C2.getBoolValue())
5231       break;
5232     return C1.sdiv(C2);
5233   case ISD::SREM:
5234     if (!C2.getBoolValue())
5235       break;
5236     return C1.srem(C2);
5237   case ISD::MULHS: {
5238     unsigned FullWidth = C1.getBitWidth() * 2;
5239     APInt C1Ext = C1.sext(FullWidth);
5240     APInt C2Ext = C2.sext(FullWidth);
5241     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5242   }
5243   case ISD::MULHU: {
5244     unsigned FullWidth = C1.getBitWidth() * 2;
5245     APInt C1Ext = C1.zext(FullWidth);
5246     APInt C2Ext = C2.zext(FullWidth);
5247     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5248   }
5249   }
5250   return llvm::None;
5251 }
5252 
5253 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5254                                        const GlobalAddressSDNode *GA,
5255                                        const SDNode *N2) {
5256   if (GA->getOpcode() != ISD::GlobalAddress)
5257     return SDValue();
5258   if (!TLI->isOffsetFoldingLegal(GA))
5259     return SDValue();
5260   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5261   if (!C2)
5262     return SDValue();
5263   int64_t Offset = C2->getSExtValue();
5264   switch (Opcode) {
5265   case ISD::ADD: break;
5266   case ISD::SUB: Offset = -uint64_t(Offset); break;
5267   default: return SDValue();
5268   }
5269   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5270                           GA->getOffset() + uint64_t(Offset));
5271 }
5272 
5273 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5274   switch (Opcode) {
5275   case ISD::SDIV:
5276   case ISD::UDIV:
5277   case ISD::SREM:
5278   case ISD::UREM: {
5279     // If a divisor is zero/undef or any element of a divisor vector is
5280     // zero/undef, the whole op is undef.
5281     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5282     SDValue Divisor = Ops[1];
5283     if (Divisor.isUndef() || isNullConstant(Divisor))
5284       return true;
5285 
5286     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5287            llvm::any_of(Divisor->op_values(),
5288                         [](SDValue V) { return V.isUndef() ||
5289                                         isNullConstant(V); });
5290     // TODO: Handle signed overflow.
5291   }
5292   // TODO: Handle oversized shifts.
5293   default:
5294     return false;
5295   }
5296 }
5297 
5298 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5299                                              EVT VT, ArrayRef<SDValue> Ops) {
5300   // If the opcode is a target-specific ISD node, there's nothing we can
5301   // do here and the operand rules may not line up with the below, so
5302   // bail early.
5303   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5304   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5305   // foldCONCAT_VECTORS in getNode before this is called.
5306   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5307     return SDValue();
5308 
5309   unsigned NumOps = Ops.size();
5310   if (NumOps == 0)
5311     return SDValue();
5312 
5313   if (isUndef(Opcode, Ops))
5314     return getUNDEF(VT);
5315 
5316   // Handle binops special cases.
5317   if (NumOps == 2) {
5318     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5319       return CFP;
5320 
5321     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5322       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5323         if (C1->isOpaque() || C2->isOpaque())
5324           return SDValue();
5325 
5326         Optional<APInt> FoldAttempt =
5327             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5328         if (!FoldAttempt)
5329           return SDValue();
5330 
5331         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5332         assert((!Folded || !VT.isVector()) &&
5333                "Can't fold vectors ops with scalar operands");
5334         return Folded;
5335       }
5336     }
5337 
5338     // fold (add Sym, c) -> Sym+c
5339     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5340       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5341     if (TLI->isCommutativeBinOp(Opcode))
5342       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5343         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5344   }
5345 
5346   // This is for vector folding only from here on.
5347   if (!VT.isVector())
5348     return SDValue();
5349 
5350   ElementCount NumElts = VT.getVectorElementCount();
5351 
5352   // See if we can fold through bitcasted integer ops.
5353   // TODO: Can we handle undef elements?
5354   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5355       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5356       Ops[0].getOpcode() == ISD::BITCAST &&
5357       Ops[1].getOpcode() == ISD::BITCAST) {
5358     SDValue N1 = peekThroughBitcasts(Ops[0]);
5359     SDValue N2 = peekThroughBitcasts(Ops[1]);
5360     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5361     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5362     EVT BVVT = N1.getValueType();
5363     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5364       bool IsLE = getDataLayout().isLittleEndian();
5365       unsigned EltBits = VT.getScalarSizeInBits();
5366       SmallVector<APInt> RawBits1, RawBits2;
5367       BitVector UndefElts1, UndefElts2;
5368       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5369           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5370           UndefElts1.none() && UndefElts2.none()) {
5371         SmallVector<APInt> RawBits;
5372         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5373           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5374           if (!Fold)
5375             break;
5376           RawBits.push_back(Fold.getValue());
5377         }
5378         if (RawBits.size() == NumElts.getFixedValue()) {
5379           // We have constant folded, but we need to cast this again back to
5380           // the original (possibly legalized) type.
5381           SmallVector<APInt> DstBits;
5382           BitVector DstUndefs;
5383           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5384                                            DstBits, RawBits, DstUndefs,
5385                                            BitVector(RawBits.size(), false));
5386           EVT BVEltVT = BV1->getOperand(0).getValueType();
5387           unsigned BVEltBits = BVEltVT.getSizeInBits();
5388           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5389           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5390             if (DstUndefs[I])
5391               continue;
5392             Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5393           }
5394           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5395         }
5396       }
5397     }
5398   }
5399 
5400   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5401     return !Op.getValueType().isVector() ||
5402            Op.getValueType().getVectorElementCount() == NumElts;
5403   };
5404 
5405   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5406     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5407            Op.getOpcode() == ISD::BUILD_VECTOR ||
5408            Op.getOpcode() == ISD::SPLAT_VECTOR;
5409   };
5410 
5411   // All operands must be vector types with the same number of elements as
5412   // the result type and must be either UNDEF or a build/splat vector
5413   // or UNDEF scalars.
5414   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5415       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5416     return SDValue();
5417 
5418   // If we are comparing vectors, then the result needs to be a i1 boolean
5419   // that is then sign-extended back to the legal result type.
5420   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5421 
5422   // Find legal integer scalar type for constant promotion and
5423   // ensure that its scalar size is at least as large as source.
5424   EVT LegalSVT = VT.getScalarType();
5425   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5426     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5427     if (LegalSVT.bitsLT(VT.getScalarType()))
5428       return SDValue();
5429   }
5430 
5431   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5432   // only have one operand to check. For fixed-length vector types we may have
5433   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5434   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5435 
5436   // Constant fold each scalar lane separately.
5437   SmallVector<SDValue, 4> ScalarResults;
5438   for (unsigned I = 0; I != NumVectorElts; I++) {
5439     SmallVector<SDValue, 4> ScalarOps;
5440     for (SDValue Op : Ops) {
5441       EVT InSVT = Op.getValueType().getScalarType();
5442       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5443           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5444         if (Op.isUndef())
5445           ScalarOps.push_back(getUNDEF(InSVT));
5446         else
5447           ScalarOps.push_back(Op);
5448         continue;
5449       }
5450 
5451       SDValue ScalarOp =
5452           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5453       EVT ScalarVT = ScalarOp.getValueType();
5454 
5455       // Build vector (integer) scalar operands may need implicit
5456       // truncation - do this before constant folding.
5457       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5458         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5459 
5460       ScalarOps.push_back(ScalarOp);
5461     }
5462 
5463     // Constant fold the scalar operands.
5464     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5465 
5466     // Legalize the (integer) scalar constant if necessary.
5467     if (LegalSVT != SVT)
5468       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5469 
5470     // Scalar folding only succeeded if the result is a constant or UNDEF.
5471     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5472         ScalarResult.getOpcode() != ISD::ConstantFP)
5473       return SDValue();
5474     ScalarResults.push_back(ScalarResult);
5475   }
5476 
5477   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5478                                    : getBuildVector(VT, DL, ScalarResults);
5479   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5480   return V;
5481 }
5482 
5483 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5484                                          EVT VT, SDValue N1, SDValue N2) {
5485   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5486   //       should. That will require dealing with a potentially non-default
5487   //       rounding mode, checking the "opStatus" return value from the APFloat
5488   //       math calculations, and possibly other variations.
5489   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5490   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5491   if (N1CFP && N2CFP) {
5492     APFloat C1 = N1CFP->getValueAPF(); // make copy
5493     const APFloat &C2 = N2CFP->getValueAPF();
5494     switch (Opcode) {
5495     case ISD::FADD:
5496       C1.add(C2, APFloat::rmNearestTiesToEven);
5497       return getConstantFP(C1, DL, VT);
5498     case ISD::FSUB:
5499       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5500       return getConstantFP(C1, DL, VT);
5501     case ISD::FMUL:
5502       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5503       return getConstantFP(C1, DL, VT);
5504     case ISD::FDIV:
5505       C1.divide(C2, APFloat::rmNearestTiesToEven);
5506       return getConstantFP(C1, DL, VT);
5507     case ISD::FREM:
5508       C1.mod(C2);
5509       return getConstantFP(C1, DL, VT);
5510     case ISD::FCOPYSIGN:
5511       C1.copySign(C2);
5512       return getConstantFP(C1, DL, VT);
5513     case ISD::FMINNUM:
5514       return getConstantFP(minnum(C1, C2), DL, VT);
5515     case ISD::FMAXNUM:
5516       return getConstantFP(maxnum(C1, C2), DL, VT);
5517     case ISD::FMINIMUM:
5518       return getConstantFP(minimum(C1, C2), DL, VT);
5519     case ISD::FMAXIMUM:
5520       return getConstantFP(maximum(C1, C2), DL, VT);
5521     default: break;
5522     }
5523   }
5524   if (N1CFP && Opcode == ISD::FP_ROUND) {
5525     APFloat C1 = N1CFP->getValueAPF();    // make copy
5526     bool Unused;
5527     // This can return overflow, underflow, or inexact; we don't care.
5528     // FIXME need to be more flexible about rounding mode.
5529     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5530                       &Unused);
5531     return getConstantFP(C1, DL, VT);
5532   }
5533 
5534   switch (Opcode) {
5535   case ISD::FSUB:
5536     // -0.0 - undef --> undef (consistent with "fneg undef")
5537     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5538       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5539         return getUNDEF(VT);
5540     LLVM_FALLTHROUGH;
5541 
5542   case ISD::FADD:
5543   case ISD::FMUL:
5544   case ISD::FDIV:
5545   case ISD::FREM:
5546     // If both operands are undef, the result is undef. If 1 operand is undef,
5547     // the result is NaN. This should match the behavior of the IR optimizer.
5548     if (N1.isUndef() && N2.isUndef())
5549       return getUNDEF(VT);
5550     if (N1.isUndef() || N2.isUndef())
5551       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5552   }
5553   return SDValue();
5554 }
5555 
5556 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5557   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5558 
5559   // There's no need to assert on a byte-aligned pointer. All pointers are at
5560   // least byte aligned.
5561   if (A == Align(1))
5562     return Val;
5563 
5564   FoldingSetNodeID ID;
5565   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5566   ID.AddInteger(A.value());
5567 
5568   void *IP = nullptr;
5569   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5570     return SDValue(E, 0);
5571 
5572   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5573                                          Val.getValueType(), A);
5574   createOperands(N, {Val});
5575 
5576   CSEMap.InsertNode(N, IP);
5577   InsertNode(N);
5578 
5579   SDValue V(N, 0);
5580   NewSDValueDbgMsg(V, "Creating new node: ", this);
5581   return V;
5582 }
5583 
5584 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5585                               SDValue N1, SDValue N2) {
5586   SDNodeFlags Flags;
5587   if (Inserter)
5588     Flags = Inserter->getFlags();
5589   return getNode(Opcode, DL, VT, N1, N2, Flags);
5590 }
5591 
5592 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5593                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5594   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5595          N2.getOpcode() != ISD::DELETED_NODE &&
5596          "Operand is DELETED_NODE!");
5597   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5598   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5599   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5600   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5601 
5602   // Canonicalize constant to RHS if commutative.
5603   if (TLI->isCommutativeBinOp(Opcode)) {
5604     if (N1C && !N2C) {
5605       std::swap(N1C, N2C);
5606       std::swap(N1, N2);
5607     } else if (N1CFP && !N2CFP) {
5608       std::swap(N1CFP, N2CFP);
5609       std::swap(N1, N2);
5610     }
5611   }
5612 
5613   switch (Opcode) {
5614   default: break;
5615   case ISD::TokenFactor:
5616     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5617            N2.getValueType() == MVT::Other && "Invalid token factor!");
5618     // Fold trivial token factors.
5619     if (N1.getOpcode() == ISD::EntryToken) return N2;
5620     if (N2.getOpcode() == ISD::EntryToken) return N1;
5621     if (N1 == N2) return N1;
5622     break;
5623   case ISD::BUILD_VECTOR: {
5624     // Attempt to simplify BUILD_VECTOR.
5625     SDValue Ops[] = {N1, N2};
5626     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5627       return V;
5628     break;
5629   }
5630   case ISD::CONCAT_VECTORS: {
5631     SDValue Ops[] = {N1, N2};
5632     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5633       return V;
5634     break;
5635   }
5636   case ISD::AND:
5637     assert(VT.isInteger() && "This operator does not apply to FP types!");
5638     assert(N1.getValueType() == N2.getValueType() &&
5639            N1.getValueType() == VT && "Binary operator types must match!");
5640     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5641     // worth handling here.
5642     if (N2C && N2C->isZero())
5643       return N2;
5644     if (N2C && N2C->isAllOnes()) // X & -1 -> X
5645       return N1;
5646     break;
5647   case ISD::OR:
5648   case ISD::XOR:
5649   case ISD::ADD:
5650   case ISD::SUB:
5651     assert(VT.isInteger() && "This operator does not apply to FP types!");
5652     assert(N1.getValueType() == N2.getValueType() &&
5653            N1.getValueType() == VT && "Binary operator types must match!");
5654     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5655     // it's worth handling here.
5656     if (N2C && N2C->isZero())
5657       return N1;
5658     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5659         VT.getVectorElementType() == MVT::i1)
5660       return getNode(ISD::XOR, DL, VT, N1, N2);
5661     break;
5662   case ISD::MUL:
5663     assert(VT.isInteger() && "This operator does not apply to FP types!");
5664     assert(N1.getValueType() == N2.getValueType() &&
5665            N1.getValueType() == VT && "Binary operator types must match!");
5666     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5667       return getNode(ISD::AND, DL, VT, N1, N2);
5668     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5669       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5670       const APInt &N2CImm = N2C->getAPIntValue();
5671       return getVScale(DL, VT, MulImm * N2CImm);
5672     }
5673     break;
5674   case ISD::UDIV:
5675   case ISD::UREM:
5676   case ISD::MULHU:
5677   case ISD::MULHS:
5678   case ISD::SDIV:
5679   case ISD::SREM:
5680   case ISD::SADDSAT:
5681   case ISD::SSUBSAT:
5682   case ISD::UADDSAT:
5683   case ISD::USUBSAT:
5684     assert(VT.isInteger() && "This operator does not apply to FP types!");
5685     assert(N1.getValueType() == N2.getValueType() &&
5686            N1.getValueType() == VT && "Binary operator types must match!");
5687     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5688       // fold (add_sat x, y) -> (or x, y) for bool types.
5689       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5690         return getNode(ISD::OR, DL, VT, N1, N2);
5691       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5692       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5693         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5694     }
5695     break;
5696   case ISD::SMIN:
5697   case ISD::UMAX:
5698     assert(VT.isInteger() && "This operator does not apply to FP types!");
5699     assert(N1.getValueType() == N2.getValueType() &&
5700            N1.getValueType() == VT && "Binary operator types must match!");
5701     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5702       return getNode(ISD::OR, DL, VT, N1, N2);
5703     break;
5704   case ISD::SMAX:
5705   case ISD::UMIN:
5706     assert(VT.isInteger() && "This operator does not apply to FP types!");
5707     assert(N1.getValueType() == N2.getValueType() &&
5708            N1.getValueType() == VT && "Binary operator types must match!");
5709     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5710       return getNode(ISD::AND, DL, VT, N1, N2);
5711     break;
5712   case ISD::FADD:
5713   case ISD::FSUB:
5714   case ISD::FMUL:
5715   case ISD::FDIV:
5716   case ISD::FREM:
5717     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5718     assert(N1.getValueType() == N2.getValueType() &&
5719            N1.getValueType() == VT && "Binary operator types must match!");
5720     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5721       return V;
5722     break;
5723   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5724     assert(N1.getValueType() == VT &&
5725            N1.getValueType().isFloatingPoint() &&
5726            N2.getValueType().isFloatingPoint() &&
5727            "Invalid FCOPYSIGN!");
5728     break;
5729   case ISD::SHL:
5730     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5731       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5732       const APInt &ShiftImm = N2C->getAPIntValue();
5733       return getVScale(DL, VT, MulImm << ShiftImm);
5734     }
5735     LLVM_FALLTHROUGH;
5736   case ISD::SRA:
5737   case ISD::SRL:
5738     if (SDValue V = simplifyShift(N1, N2))
5739       return V;
5740     LLVM_FALLTHROUGH;
5741   case ISD::ROTL:
5742   case ISD::ROTR:
5743     assert(VT == N1.getValueType() &&
5744            "Shift operators return type must be the same as their first arg");
5745     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5746            "Shifts only work on integers");
5747     assert((!VT.isVector() || VT == N2.getValueType()) &&
5748            "Vector shift amounts must be in the same as their first arg");
5749     // Verify that the shift amount VT is big enough to hold valid shift
5750     // amounts.  This catches things like trying to shift an i1024 value by an
5751     // i8, which is easy to fall into in generic code that uses
5752     // TLI.getShiftAmount().
5753     assert(N2.getValueType().getScalarSizeInBits() >=
5754                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5755            "Invalid use of small shift amount with oversized value!");
5756 
5757     // Always fold shifts of i1 values so the code generator doesn't need to
5758     // handle them.  Since we know the size of the shift has to be less than the
5759     // size of the value, the shift/rotate count is guaranteed to be zero.
5760     if (VT == MVT::i1)
5761       return N1;
5762     if (N2C && N2C->isZero())
5763       return N1;
5764     break;
5765   case ISD::FP_ROUND:
5766     assert(VT.isFloatingPoint() &&
5767            N1.getValueType().isFloatingPoint() &&
5768            VT.bitsLE(N1.getValueType()) &&
5769            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5770            "Invalid FP_ROUND!");
5771     if (N1.getValueType() == VT) return N1;  // noop conversion.
5772     break;
5773   case ISD::AssertSext:
5774   case ISD::AssertZext: {
5775     EVT EVT = cast<VTSDNode>(N2)->getVT();
5776     assert(VT == N1.getValueType() && "Not an inreg extend!");
5777     assert(VT.isInteger() && EVT.isInteger() &&
5778            "Cannot *_EXTEND_INREG FP types");
5779     assert(!EVT.isVector() &&
5780            "AssertSExt/AssertZExt type should be the vector element type "
5781            "rather than the vector type!");
5782     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5783     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5784     break;
5785   }
5786   case ISD::SIGN_EXTEND_INREG: {
5787     EVT EVT = cast<VTSDNode>(N2)->getVT();
5788     assert(VT == N1.getValueType() && "Not an inreg extend!");
5789     assert(VT.isInteger() && EVT.isInteger() &&
5790            "Cannot *_EXTEND_INREG FP types");
5791     assert(EVT.isVector() == VT.isVector() &&
5792            "SIGN_EXTEND_INREG type should be vector iff the operand "
5793            "type is vector!");
5794     assert((!EVT.isVector() ||
5795             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5796            "Vector element counts must match in SIGN_EXTEND_INREG");
5797     assert(EVT.bitsLE(VT) && "Not extending!");
5798     if (EVT == VT) return N1;  // Not actually extending
5799 
5800     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5801       unsigned FromBits = EVT.getScalarSizeInBits();
5802       Val <<= Val.getBitWidth() - FromBits;
5803       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5804       return getConstant(Val, DL, ConstantVT);
5805     };
5806 
5807     if (N1C) {
5808       const APInt &Val = N1C->getAPIntValue();
5809       return SignExtendInReg(Val, VT);
5810     }
5811 
5812     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5813       SmallVector<SDValue, 8> Ops;
5814       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5815       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5816         SDValue Op = N1.getOperand(i);
5817         if (Op.isUndef()) {
5818           Ops.push_back(getUNDEF(OpVT));
5819           continue;
5820         }
5821         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5822         APInt Val = C->getAPIntValue();
5823         Ops.push_back(SignExtendInReg(Val, OpVT));
5824       }
5825       return getBuildVector(VT, DL, Ops);
5826     }
5827     break;
5828   }
5829   case ISD::FP_TO_SINT_SAT:
5830   case ISD::FP_TO_UINT_SAT: {
5831     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5832            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5833     assert(N1.getValueType().isVector() == VT.isVector() &&
5834            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5835            "vector!");
5836     assert((!VT.isVector() || VT.getVectorNumElements() ==
5837                                   N1.getValueType().getVectorNumElements()) &&
5838            "Vector element counts must match in FP_TO_*INT_SAT");
5839     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5840            "Type to saturate to must be a scalar.");
5841     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5842            "Not extending!");
5843     break;
5844   }
5845   case ISD::EXTRACT_VECTOR_ELT:
5846     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5847            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5848              element type of the vector.");
5849 
5850     // Extract from an undefined value or using an undefined index is undefined.
5851     if (N1.isUndef() || N2.isUndef())
5852       return getUNDEF(VT);
5853 
5854     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5855     // vectors. For scalable vectors we will provide appropriate support for
5856     // dealing with arbitrary indices.
5857     if (N2C && N1.getValueType().isFixedLengthVector() &&
5858         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5859       return getUNDEF(VT);
5860 
5861     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5862     // expanding copies of large vectors from registers. This only works for
5863     // fixed length vectors, since we need to know the exact number of
5864     // elements.
5865     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5866         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5867       unsigned Factor =
5868         N1.getOperand(0).getValueType().getVectorNumElements();
5869       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5870                      N1.getOperand(N2C->getZExtValue() / Factor),
5871                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5872     }
5873 
5874     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5875     // lowering is expanding large vector constants.
5876     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5877                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5878       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5879               N1.getValueType().isFixedLengthVector()) &&
5880              "BUILD_VECTOR used for scalable vectors");
5881       unsigned Index =
5882           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5883       SDValue Elt = N1.getOperand(Index);
5884 
5885       if (VT != Elt.getValueType())
5886         // If the vector element type is not legal, the BUILD_VECTOR operands
5887         // are promoted and implicitly truncated, and the result implicitly
5888         // extended. Make that explicit here.
5889         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5890 
5891       return Elt;
5892     }
5893 
5894     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5895     // operations are lowered to scalars.
5896     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5897       // If the indices are the same, return the inserted element else
5898       // if the indices are known different, extract the element from
5899       // the original vector.
5900       SDValue N1Op2 = N1.getOperand(2);
5901       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5902 
5903       if (N1Op2C && N2C) {
5904         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5905           if (VT == N1.getOperand(1).getValueType())
5906             return N1.getOperand(1);
5907           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5908         }
5909         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5910       }
5911     }
5912 
5913     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5914     // when vector types are scalarized and v1iX is legal.
5915     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5916     // Here we are completely ignoring the extract element index (N2),
5917     // which is fine for fixed width vectors, since any index other than 0
5918     // is undefined anyway. However, this cannot be ignored for scalable
5919     // vectors - in theory we could support this, but we don't want to do this
5920     // without a profitability check.
5921     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5922         N1.getValueType().isFixedLengthVector() &&
5923         N1.getValueType().getVectorNumElements() == 1) {
5924       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5925                      N1.getOperand(1));
5926     }
5927     break;
5928   case ISD::EXTRACT_ELEMENT:
5929     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5930     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5931            (N1.getValueType().isInteger() == VT.isInteger()) &&
5932            N1.getValueType() != VT &&
5933            "Wrong types for EXTRACT_ELEMENT!");
5934 
5935     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5936     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5937     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5938     if (N1.getOpcode() == ISD::BUILD_PAIR)
5939       return N1.getOperand(N2C->getZExtValue());
5940 
5941     // EXTRACT_ELEMENT of a constant int is also very common.
5942     if (N1C) {
5943       unsigned ElementSize = VT.getSizeInBits();
5944       unsigned Shift = ElementSize * N2C->getZExtValue();
5945       const APInt &Val = N1C->getAPIntValue();
5946       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5947     }
5948     break;
5949   case ISD::EXTRACT_SUBVECTOR: {
5950     EVT N1VT = N1.getValueType();
5951     assert(VT.isVector() && N1VT.isVector() &&
5952            "Extract subvector VTs must be vectors!");
5953     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5954            "Extract subvector VTs must have the same element type!");
5955     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5956            "Cannot extract a scalable vector from a fixed length vector!");
5957     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5958             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5959            "Extract subvector must be from larger vector to smaller vector!");
5960     assert(N2C && "Extract subvector index must be a constant");
5961     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5962             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5963                 N1VT.getVectorMinNumElements()) &&
5964            "Extract subvector overflow!");
5965     assert(N2C->getAPIntValue().getBitWidth() ==
5966                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5967            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5968 
5969     // Trivial extraction.
5970     if (VT == N1VT)
5971       return N1;
5972 
5973     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5974     if (N1.isUndef())
5975       return getUNDEF(VT);
5976 
5977     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5978     // the concat have the same type as the extract.
5979     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5980         VT == N1.getOperand(0).getValueType()) {
5981       unsigned Factor = VT.getVectorMinNumElements();
5982       return N1.getOperand(N2C->getZExtValue() / Factor);
5983     }
5984 
5985     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5986     // during shuffle legalization.
5987     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5988         VT == N1.getOperand(1).getValueType())
5989       return N1.getOperand(1);
5990     break;
5991   }
5992   }
5993 
5994   // Perform trivial constant folding.
5995   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5996     return SV;
5997 
5998   // Canonicalize an UNDEF to the RHS, even over a constant.
5999   if (N1.isUndef()) {
6000     if (TLI->isCommutativeBinOp(Opcode)) {
6001       std::swap(N1, N2);
6002     } else {
6003       switch (Opcode) {
6004       case ISD::SIGN_EXTEND_INREG:
6005       case ISD::SUB:
6006         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6007       case ISD::UDIV:
6008       case ISD::SDIV:
6009       case ISD::UREM:
6010       case ISD::SREM:
6011       case ISD::SSUBSAT:
6012       case ISD::USUBSAT:
6013         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6014       }
6015     }
6016   }
6017 
6018   // Fold a bunch of operators when the RHS is undef.
6019   if (N2.isUndef()) {
6020     switch (Opcode) {
6021     case ISD::XOR:
6022       if (N1.isUndef())
6023         // Handle undef ^ undef -> 0 special case. This is a common
6024         // idiom (misuse).
6025         return getConstant(0, DL, VT);
6026       LLVM_FALLTHROUGH;
6027     case ISD::ADD:
6028     case ISD::SUB:
6029     case ISD::UDIV:
6030     case ISD::SDIV:
6031     case ISD::UREM:
6032     case ISD::SREM:
6033       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6034     case ISD::MUL:
6035     case ISD::AND:
6036     case ISD::SSUBSAT:
6037     case ISD::USUBSAT:
6038       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6039     case ISD::OR:
6040     case ISD::SADDSAT:
6041     case ISD::UADDSAT:
6042       return getAllOnesConstant(DL, VT);
6043     }
6044   }
6045 
6046   // Memoize this node if possible.
6047   SDNode *N;
6048   SDVTList VTs = getVTList(VT);
6049   SDValue Ops[] = {N1, N2};
6050   if (VT != MVT::Glue) {
6051     FoldingSetNodeID ID;
6052     AddNodeIDNode(ID, Opcode, VTs, Ops);
6053     void *IP = nullptr;
6054     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6055       E->intersectFlagsWith(Flags);
6056       return SDValue(E, 0);
6057     }
6058 
6059     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6060     N->setFlags(Flags);
6061     createOperands(N, Ops);
6062     CSEMap.InsertNode(N, IP);
6063   } else {
6064     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6065     createOperands(N, Ops);
6066   }
6067 
6068   InsertNode(N);
6069   SDValue V = SDValue(N, 0);
6070   NewSDValueDbgMsg(V, "Creating new node: ", this);
6071   return V;
6072 }
6073 
6074 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6075                               SDValue N1, SDValue N2, SDValue N3) {
6076   SDNodeFlags Flags;
6077   if (Inserter)
6078     Flags = Inserter->getFlags();
6079   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6080 }
6081 
6082 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6083                               SDValue N1, SDValue N2, SDValue N3,
6084                               const SDNodeFlags Flags) {
6085   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6086          N2.getOpcode() != ISD::DELETED_NODE &&
6087          N3.getOpcode() != ISD::DELETED_NODE &&
6088          "Operand is DELETED_NODE!");
6089   // Perform various simplifications.
6090   switch (Opcode) {
6091   case ISD::FMA: {
6092     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6093     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6094            N3.getValueType() == VT && "FMA types must match!");
6095     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6096     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6097     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6098     if (N1CFP && N2CFP && N3CFP) {
6099       APFloat  V1 = N1CFP->getValueAPF();
6100       const APFloat &V2 = N2CFP->getValueAPF();
6101       const APFloat &V3 = N3CFP->getValueAPF();
6102       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6103       return getConstantFP(V1, DL, VT);
6104     }
6105     break;
6106   }
6107   case ISD::BUILD_VECTOR: {
6108     // Attempt to simplify BUILD_VECTOR.
6109     SDValue Ops[] = {N1, N2, N3};
6110     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6111       return V;
6112     break;
6113   }
6114   case ISD::CONCAT_VECTORS: {
6115     SDValue Ops[] = {N1, N2, N3};
6116     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6117       return V;
6118     break;
6119   }
6120   case ISD::SETCC: {
6121     assert(VT.isInteger() && "SETCC result type must be an integer!");
6122     assert(N1.getValueType() == N2.getValueType() &&
6123            "SETCC operands must have the same type!");
6124     assert(VT.isVector() == N1.getValueType().isVector() &&
6125            "SETCC type should be vector iff the operand type is vector!");
6126     assert((!VT.isVector() || VT.getVectorElementCount() ==
6127                                   N1.getValueType().getVectorElementCount()) &&
6128            "SETCC vector element counts must match!");
6129     // Use FoldSetCC to simplify SETCC's.
6130     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6131       return V;
6132     // Vector constant folding.
6133     SDValue Ops[] = {N1, N2, N3};
6134     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6135       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6136       return V;
6137     }
6138     break;
6139   }
6140   case ISD::SELECT:
6141   case ISD::VSELECT:
6142     if (SDValue V = simplifySelect(N1, N2, N3))
6143       return V;
6144     break;
6145   case ISD::VECTOR_SHUFFLE:
6146     llvm_unreachable("should use getVectorShuffle constructor!");
6147   case ISD::VECTOR_SPLICE: {
6148     if (cast<ConstantSDNode>(N3)->isNullValue())
6149       return N1;
6150     break;
6151   }
6152   case ISD::INSERT_VECTOR_ELT: {
6153     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6154     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6155     // for scalable vectors where we will generate appropriate code to
6156     // deal with out-of-bounds cases correctly.
6157     if (N3C && N1.getValueType().isFixedLengthVector() &&
6158         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6159       return getUNDEF(VT);
6160 
6161     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6162     if (N3.isUndef())
6163       return getUNDEF(VT);
6164 
6165     // If the inserted element is an UNDEF, just use the input vector.
6166     if (N2.isUndef())
6167       return N1;
6168 
6169     break;
6170   }
6171   case ISD::INSERT_SUBVECTOR: {
6172     // Inserting undef into undef is still undef.
6173     if (N1.isUndef() && N2.isUndef())
6174       return getUNDEF(VT);
6175 
6176     EVT N2VT = N2.getValueType();
6177     assert(VT == N1.getValueType() &&
6178            "Dest and insert subvector source types must match!");
6179     assert(VT.isVector() && N2VT.isVector() &&
6180            "Insert subvector VTs must be vectors!");
6181     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6182            "Cannot insert a scalable vector into a fixed length vector!");
6183     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6184             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6185            "Insert subvector must be from smaller vector to larger vector!");
6186     assert(isa<ConstantSDNode>(N3) &&
6187            "Insert subvector index must be constant");
6188     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6189             (N2VT.getVectorMinNumElements() +
6190              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6191                 VT.getVectorMinNumElements()) &&
6192            "Insert subvector overflow!");
6193     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6194                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6195            "Constant index for INSERT_SUBVECTOR has an invalid size");
6196 
6197     // Trivial insertion.
6198     if (VT == N2VT)
6199       return N2;
6200 
6201     // If this is an insert of an extracted vector into an undef vector, we
6202     // can just use the input to the extract.
6203     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6204         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6205       return N2.getOperand(0);
6206     break;
6207   }
6208   case ISD::BITCAST:
6209     // Fold bit_convert nodes from a type to themselves.
6210     if (N1.getValueType() == VT)
6211       return N1;
6212     break;
6213   }
6214 
6215   // Memoize node if it doesn't produce a flag.
6216   SDNode *N;
6217   SDVTList VTs = getVTList(VT);
6218   SDValue Ops[] = {N1, N2, N3};
6219   if (VT != MVT::Glue) {
6220     FoldingSetNodeID ID;
6221     AddNodeIDNode(ID, Opcode, VTs, Ops);
6222     void *IP = nullptr;
6223     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6224       E->intersectFlagsWith(Flags);
6225       return SDValue(E, 0);
6226     }
6227 
6228     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6229     N->setFlags(Flags);
6230     createOperands(N, Ops);
6231     CSEMap.InsertNode(N, IP);
6232   } else {
6233     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6234     createOperands(N, Ops);
6235   }
6236 
6237   InsertNode(N);
6238   SDValue V = SDValue(N, 0);
6239   NewSDValueDbgMsg(V, "Creating new node: ", this);
6240   return V;
6241 }
6242 
6243 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6244                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6245   SDValue Ops[] = { N1, N2, N3, N4 };
6246   return getNode(Opcode, DL, VT, Ops);
6247 }
6248 
6249 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6250                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6251                               SDValue N5) {
6252   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6253   return getNode(Opcode, DL, VT, Ops);
6254 }
6255 
6256 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6257 /// the incoming stack arguments to be loaded from the stack.
6258 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6259   SmallVector<SDValue, 8> ArgChains;
6260 
6261   // Include the original chain at the beginning of the list. When this is
6262   // used by target LowerCall hooks, this helps legalize find the
6263   // CALLSEQ_BEGIN node.
6264   ArgChains.push_back(Chain);
6265 
6266   // Add a chain value for each stack argument.
6267   for (SDNode *U : getEntryNode().getNode()->uses())
6268     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6269       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6270         if (FI->getIndex() < 0)
6271           ArgChains.push_back(SDValue(L, 1));
6272 
6273   // Build a tokenfactor for all the chains.
6274   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6275 }
6276 
6277 /// getMemsetValue - Vectorized representation of the memset value
6278 /// operand.
6279 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6280                               const SDLoc &dl) {
6281   assert(!Value.isUndef());
6282 
6283   unsigned NumBits = VT.getScalarSizeInBits();
6284   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6285     assert(C->getAPIntValue().getBitWidth() == 8);
6286     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6287     if (VT.isInteger()) {
6288       bool IsOpaque = VT.getSizeInBits() > 64 ||
6289           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6290       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6291     }
6292     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6293                              VT);
6294   }
6295 
6296   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6297   EVT IntVT = VT.getScalarType();
6298   if (!IntVT.isInteger())
6299     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6300 
6301   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6302   if (NumBits > 8) {
6303     // Use a multiplication with 0x010101... to extend the input to the
6304     // required length.
6305     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6306     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6307                         DAG.getConstant(Magic, dl, IntVT));
6308   }
6309 
6310   if (VT != Value.getValueType() && !VT.isInteger())
6311     Value = DAG.getBitcast(VT.getScalarType(), Value);
6312   if (VT != Value.getValueType())
6313     Value = DAG.getSplatBuildVector(VT, dl, Value);
6314 
6315   return Value;
6316 }
6317 
6318 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6319 /// used when a memcpy is turned into a memset when the source is a constant
6320 /// string ptr.
6321 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6322                                   const TargetLowering &TLI,
6323                                   const ConstantDataArraySlice &Slice) {
6324   // Handle vector with all elements zero.
6325   if (Slice.Array == nullptr) {
6326     if (VT.isInteger())
6327       return DAG.getConstant(0, dl, VT);
6328     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6329       return DAG.getConstantFP(0.0, dl, VT);
6330     if (VT.isVector()) {
6331       unsigned NumElts = VT.getVectorNumElements();
6332       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6333       return DAG.getNode(ISD::BITCAST, dl, VT,
6334                          DAG.getConstant(0, dl,
6335                                          EVT::getVectorVT(*DAG.getContext(),
6336                                                           EltVT, NumElts)));
6337     }
6338     llvm_unreachable("Expected type!");
6339   }
6340 
6341   assert(!VT.isVector() && "Can't handle vector type here!");
6342   unsigned NumVTBits = VT.getSizeInBits();
6343   unsigned NumVTBytes = NumVTBits / 8;
6344   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6345 
6346   APInt Val(NumVTBits, 0);
6347   if (DAG.getDataLayout().isLittleEndian()) {
6348     for (unsigned i = 0; i != NumBytes; ++i)
6349       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6350   } else {
6351     for (unsigned i = 0; i != NumBytes; ++i)
6352       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6353   }
6354 
6355   // If the "cost" of materializing the integer immediate is less than the cost
6356   // of a load, then it is cost effective to turn the load into the immediate.
6357   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6358   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6359     return DAG.getConstant(Val, dl, VT);
6360   return SDValue();
6361 }
6362 
6363 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6364                                            const SDLoc &DL,
6365                                            const SDNodeFlags Flags) {
6366   EVT VT = Base.getValueType();
6367   SDValue Index;
6368 
6369   if (Offset.isScalable())
6370     Index = getVScale(DL, Base.getValueType(),
6371                       APInt(Base.getValueSizeInBits().getFixedSize(),
6372                             Offset.getKnownMinSize()));
6373   else
6374     Index = getConstant(Offset.getFixedSize(), DL, VT);
6375 
6376   return getMemBasePlusOffset(Base, Index, DL, Flags);
6377 }
6378 
6379 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6380                                            const SDLoc &DL,
6381                                            const SDNodeFlags Flags) {
6382   assert(Offset.getValueType().isInteger());
6383   EVT BasePtrVT = Ptr.getValueType();
6384   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6385 }
6386 
6387 /// Returns true if memcpy source is constant data.
6388 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6389   uint64_t SrcDelta = 0;
6390   GlobalAddressSDNode *G = nullptr;
6391   if (Src.getOpcode() == ISD::GlobalAddress)
6392     G = cast<GlobalAddressSDNode>(Src);
6393   else if (Src.getOpcode() == ISD::ADD &&
6394            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6395            Src.getOperand(1).getOpcode() == ISD::Constant) {
6396     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6397     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6398   }
6399   if (!G)
6400     return false;
6401 
6402   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6403                                   SrcDelta + G->getOffset());
6404 }
6405 
6406 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6407                                       SelectionDAG &DAG) {
6408   // On Darwin, -Os means optimize for size without hurting performance, so
6409   // only really optimize for size when -Oz (MinSize) is used.
6410   if (MF.getTarget().getTargetTriple().isOSDarwin())
6411     return MF.getFunction().hasMinSize();
6412   return DAG.shouldOptForSize();
6413 }
6414 
6415 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6416                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6417                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6418                           SmallVector<SDValue, 16> &OutStoreChains) {
6419   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6420   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6421   SmallVector<SDValue, 16> GluedLoadChains;
6422   for (unsigned i = From; i < To; ++i) {
6423     OutChains.push_back(OutLoadChains[i]);
6424     GluedLoadChains.push_back(OutLoadChains[i]);
6425   }
6426 
6427   // Chain for all loads.
6428   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6429                                   GluedLoadChains);
6430 
6431   for (unsigned i = From; i < To; ++i) {
6432     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6433     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6434                                   ST->getBasePtr(), ST->getMemoryVT(),
6435                                   ST->getMemOperand());
6436     OutChains.push_back(NewStore);
6437   }
6438 }
6439 
6440 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6441                                        SDValue Chain, SDValue Dst, SDValue Src,
6442                                        uint64_t Size, Align Alignment,
6443                                        bool isVol, bool AlwaysInline,
6444                                        MachinePointerInfo DstPtrInfo,
6445                                        MachinePointerInfo SrcPtrInfo,
6446                                        const AAMDNodes &AAInfo) {
6447   // Turn a memcpy of undef to nop.
6448   // FIXME: We need to honor volatile even is Src is undef.
6449   if (Src.isUndef())
6450     return Chain;
6451 
6452   // Expand memcpy to a series of load and store ops if the size operand falls
6453   // below a certain threshold.
6454   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6455   // rather than maybe a humongous number of loads and stores.
6456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6457   const DataLayout &DL = DAG.getDataLayout();
6458   LLVMContext &C = *DAG.getContext();
6459   std::vector<EVT> MemOps;
6460   bool DstAlignCanChange = false;
6461   MachineFunction &MF = DAG.getMachineFunction();
6462   MachineFrameInfo &MFI = MF.getFrameInfo();
6463   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6464   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6465   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6466     DstAlignCanChange = true;
6467   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6468   if (!SrcAlign || Alignment > *SrcAlign)
6469     SrcAlign = Alignment;
6470   assert(SrcAlign && "SrcAlign must be set");
6471   ConstantDataArraySlice Slice;
6472   // If marked as volatile, perform a copy even when marked as constant.
6473   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6474   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6475   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6476   const MemOp Op = isZeroConstant
6477                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6478                                     /*IsZeroMemset*/ true, isVol)
6479                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6480                                      *SrcAlign, isVol, CopyFromConstant);
6481   if (!TLI.findOptimalMemOpLowering(
6482           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6483           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6484     return SDValue();
6485 
6486   if (DstAlignCanChange) {
6487     Type *Ty = MemOps[0].getTypeForEVT(C);
6488     Align NewAlign = DL.getABITypeAlign(Ty);
6489 
6490     // Don't promote to an alignment that would require dynamic stack
6491     // realignment.
6492     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6493     if (!TRI->hasStackRealignment(MF))
6494       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6495         NewAlign = NewAlign / 2;
6496 
6497     if (NewAlign > Alignment) {
6498       // Give the stack frame object a larger alignment if needed.
6499       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6500         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6501       Alignment = NewAlign;
6502     }
6503   }
6504 
6505   // Prepare AAInfo for loads/stores after lowering this memcpy.
6506   AAMDNodes NewAAInfo = AAInfo;
6507   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6508 
6509   MachineMemOperand::Flags MMOFlags =
6510       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6511   SmallVector<SDValue, 16> OutLoadChains;
6512   SmallVector<SDValue, 16> OutStoreChains;
6513   SmallVector<SDValue, 32> OutChains;
6514   unsigned NumMemOps = MemOps.size();
6515   uint64_t SrcOff = 0, DstOff = 0;
6516   for (unsigned i = 0; i != NumMemOps; ++i) {
6517     EVT VT = MemOps[i];
6518     unsigned VTSize = VT.getSizeInBits() / 8;
6519     SDValue Value, Store;
6520 
6521     if (VTSize > Size) {
6522       // Issuing an unaligned load / store pair  that overlaps with the previous
6523       // pair. Adjust the offset accordingly.
6524       assert(i == NumMemOps-1 && i != 0);
6525       SrcOff -= VTSize - Size;
6526       DstOff -= VTSize - Size;
6527     }
6528 
6529     if (CopyFromConstant &&
6530         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6531       // It's unlikely a store of a vector immediate can be done in a single
6532       // instruction. It would require a load from a constantpool first.
6533       // We only handle zero vectors here.
6534       // FIXME: Handle other cases where store of vector immediate is done in
6535       // a single instruction.
6536       ConstantDataArraySlice SubSlice;
6537       if (SrcOff < Slice.Length) {
6538         SubSlice = Slice;
6539         SubSlice.move(SrcOff);
6540       } else {
6541         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6542         SubSlice.Array = nullptr;
6543         SubSlice.Offset = 0;
6544         SubSlice.Length = VTSize;
6545       }
6546       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6547       if (Value.getNode()) {
6548         Store = DAG.getStore(
6549             Chain, dl, Value,
6550             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6551             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6552         OutChains.push_back(Store);
6553       }
6554     }
6555 
6556     if (!Store.getNode()) {
6557       // The type might not be legal for the target.  This should only happen
6558       // if the type is smaller than a legal type, as on PPC, so the right
6559       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6560       // to Load/Store if NVT==VT.
6561       // FIXME does the case above also need this?
6562       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6563       assert(NVT.bitsGE(VT));
6564 
6565       bool isDereferenceable =
6566         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6567       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6568       if (isDereferenceable)
6569         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6570 
6571       Value = DAG.getExtLoad(
6572           ISD::EXTLOAD, dl, NVT, Chain,
6573           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6574           SrcPtrInfo.getWithOffset(SrcOff), VT,
6575           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6576       OutLoadChains.push_back(Value.getValue(1));
6577 
6578       Store = DAG.getTruncStore(
6579           Chain, dl, Value,
6580           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6581           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6582       OutStoreChains.push_back(Store);
6583     }
6584     SrcOff += VTSize;
6585     DstOff += VTSize;
6586     Size -= VTSize;
6587   }
6588 
6589   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6590                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6591   unsigned NumLdStInMemcpy = OutStoreChains.size();
6592 
6593   if (NumLdStInMemcpy) {
6594     // It may be that memcpy might be converted to memset if it's memcpy
6595     // of constants. In such a case, we won't have loads and stores, but
6596     // just stores. In the absence of loads, there is nothing to gang up.
6597     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6598       // If target does not care, just leave as it.
6599       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6600         OutChains.push_back(OutLoadChains[i]);
6601         OutChains.push_back(OutStoreChains[i]);
6602       }
6603     } else {
6604       // Ld/St less than/equal limit set by target.
6605       if (NumLdStInMemcpy <= GluedLdStLimit) {
6606           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6607                                         NumLdStInMemcpy, OutLoadChains,
6608                                         OutStoreChains);
6609       } else {
6610         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6611         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6612         unsigned GlueIter = 0;
6613 
6614         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6615           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6616           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6617 
6618           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6619                                        OutLoadChains, OutStoreChains);
6620           GlueIter += GluedLdStLimit;
6621         }
6622 
6623         // Residual ld/st.
6624         if (RemainingLdStInMemcpy) {
6625           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6626                                         RemainingLdStInMemcpy, OutLoadChains,
6627                                         OutStoreChains);
6628         }
6629       }
6630     }
6631   }
6632   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6633 }
6634 
6635 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6636                                         SDValue Chain, SDValue Dst, SDValue Src,
6637                                         uint64_t Size, Align Alignment,
6638                                         bool isVol, bool AlwaysInline,
6639                                         MachinePointerInfo DstPtrInfo,
6640                                         MachinePointerInfo SrcPtrInfo,
6641                                         const AAMDNodes &AAInfo) {
6642   // Turn a memmove of undef to nop.
6643   // FIXME: We need to honor volatile even is Src is undef.
6644   if (Src.isUndef())
6645     return Chain;
6646 
6647   // Expand memmove to a series of load and store ops if the size operand falls
6648   // below a certain threshold.
6649   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6650   const DataLayout &DL = DAG.getDataLayout();
6651   LLVMContext &C = *DAG.getContext();
6652   std::vector<EVT> MemOps;
6653   bool DstAlignCanChange = false;
6654   MachineFunction &MF = DAG.getMachineFunction();
6655   MachineFrameInfo &MFI = MF.getFrameInfo();
6656   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6657   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6658   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6659     DstAlignCanChange = true;
6660   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6661   if (!SrcAlign || Alignment > *SrcAlign)
6662     SrcAlign = Alignment;
6663   assert(SrcAlign && "SrcAlign must be set");
6664   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6665   if (!TLI.findOptimalMemOpLowering(
6666           MemOps, Limit,
6667           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6668                       /*IsVolatile*/ true),
6669           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6670           MF.getFunction().getAttributes()))
6671     return SDValue();
6672 
6673   if (DstAlignCanChange) {
6674     Type *Ty = MemOps[0].getTypeForEVT(C);
6675     Align NewAlign = DL.getABITypeAlign(Ty);
6676     if (NewAlign > Alignment) {
6677       // Give the stack frame object a larger alignment if needed.
6678       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6679         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6680       Alignment = NewAlign;
6681     }
6682   }
6683 
6684   // Prepare AAInfo for loads/stores after lowering this memmove.
6685   AAMDNodes NewAAInfo = AAInfo;
6686   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6687 
6688   MachineMemOperand::Flags MMOFlags =
6689       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6690   uint64_t SrcOff = 0, DstOff = 0;
6691   SmallVector<SDValue, 8> LoadValues;
6692   SmallVector<SDValue, 8> LoadChains;
6693   SmallVector<SDValue, 8> OutChains;
6694   unsigned NumMemOps = MemOps.size();
6695   for (unsigned i = 0; i < NumMemOps; i++) {
6696     EVT VT = MemOps[i];
6697     unsigned VTSize = VT.getSizeInBits() / 8;
6698     SDValue Value;
6699 
6700     bool isDereferenceable =
6701       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6702     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6703     if (isDereferenceable)
6704       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6705 
6706     Value = DAG.getLoad(
6707         VT, dl, Chain,
6708         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6709         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6710     LoadValues.push_back(Value);
6711     LoadChains.push_back(Value.getValue(1));
6712     SrcOff += VTSize;
6713   }
6714   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6715   OutChains.clear();
6716   for (unsigned i = 0; i < NumMemOps; i++) {
6717     EVT VT = MemOps[i];
6718     unsigned VTSize = VT.getSizeInBits() / 8;
6719     SDValue Store;
6720 
6721     Store = DAG.getStore(
6722         Chain, dl, LoadValues[i],
6723         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6724         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6725     OutChains.push_back(Store);
6726     DstOff += VTSize;
6727   }
6728 
6729   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6730 }
6731 
6732 /// Lower the call to 'memset' intrinsic function into a series of store
6733 /// operations.
6734 ///
6735 /// \param DAG Selection DAG where lowered code is placed.
6736 /// \param dl Link to corresponding IR location.
6737 /// \param Chain Control flow dependency.
6738 /// \param Dst Pointer to destination memory location.
6739 /// \param Src Value of byte to write into the memory.
6740 /// \param Size Number of bytes to write.
6741 /// \param Alignment Alignment of the destination in bytes.
6742 /// \param isVol True if destination is volatile.
6743 /// \param DstPtrInfo IR information on the memory pointer.
6744 /// \returns New head in the control flow, if lowering was successful, empty
6745 /// SDValue otherwise.
6746 ///
6747 /// The function tries to replace 'llvm.memset' intrinsic with several store
6748 /// operations and value calculation code. This is usually profitable for small
6749 /// memory size.
6750 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6751                                SDValue Chain, SDValue Dst, SDValue Src,
6752                                uint64_t Size, Align Alignment, bool isVol,
6753                                MachinePointerInfo DstPtrInfo,
6754                                const AAMDNodes &AAInfo) {
6755   // Turn a memset of undef to nop.
6756   // FIXME: We need to honor volatile even is Src is undef.
6757   if (Src.isUndef())
6758     return Chain;
6759 
6760   // Expand memset to a series of load/store ops if the size operand
6761   // falls below a certain threshold.
6762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6763   std::vector<EVT> MemOps;
6764   bool DstAlignCanChange = false;
6765   MachineFunction &MF = DAG.getMachineFunction();
6766   MachineFrameInfo &MFI = MF.getFrameInfo();
6767   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6768   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6769   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6770     DstAlignCanChange = true;
6771   bool IsZeroVal =
6772       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6773   if (!TLI.findOptimalMemOpLowering(
6774           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6775           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6776           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6777     return SDValue();
6778 
6779   if (DstAlignCanChange) {
6780     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6781     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6782     if (NewAlign > Alignment) {
6783       // Give the stack frame object a larger alignment if needed.
6784       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6785         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6786       Alignment = NewAlign;
6787     }
6788   }
6789 
6790   SmallVector<SDValue, 8> OutChains;
6791   uint64_t DstOff = 0;
6792   unsigned NumMemOps = MemOps.size();
6793 
6794   // Find the largest store and generate the bit pattern for it.
6795   EVT LargestVT = MemOps[0];
6796   for (unsigned i = 1; i < NumMemOps; i++)
6797     if (MemOps[i].bitsGT(LargestVT))
6798       LargestVT = MemOps[i];
6799   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6800 
6801   // Prepare AAInfo for loads/stores after lowering this memset.
6802   AAMDNodes NewAAInfo = AAInfo;
6803   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6804 
6805   for (unsigned i = 0; i < NumMemOps; i++) {
6806     EVT VT = MemOps[i];
6807     unsigned VTSize = VT.getSizeInBits() / 8;
6808     if (VTSize > Size) {
6809       // Issuing an unaligned load / store pair  that overlaps with the previous
6810       // pair. Adjust the offset accordingly.
6811       assert(i == NumMemOps-1 && i != 0);
6812       DstOff -= VTSize - Size;
6813     }
6814 
6815     // If this store is smaller than the largest store see whether we can get
6816     // the smaller value for free with a truncate.
6817     SDValue Value = MemSetValue;
6818     if (VT.bitsLT(LargestVT)) {
6819       if (!LargestVT.isVector() && !VT.isVector() &&
6820           TLI.isTruncateFree(LargestVT, VT))
6821         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6822       else
6823         Value = getMemsetValue(Src, VT, DAG, dl);
6824     }
6825     assert(Value.getValueType() == VT && "Value with wrong type.");
6826     SDValue Store = DAG.getStore(
6827         Chain, dl, Value,
6828         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6829         DstPtrInfo.getWithOffset(DstOff), Alignment,
6830         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6831         NewAAInfo);
6832     OutChains.push_back(Store);
6833     DstOff += VT.getSizeInBits() / 8;
6834     Size -= VTSize;
6835   }
6836 
6837   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6838 }
6839 
6840 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6841                                             unsigned AS) {
6842   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6843   // pointer operands can be losslessly bitcasted to pointers of address space 0
6844   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6845     report_fatal_error("cannot lower memory intrinsic in address space " +
6846                        Twine(AS));
6847   }
6848 }
6849 
6850 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6851                                 SDValue Src, SDValue Size, Align Alignment,
6852                                 bool isVol, bool AlwaysInline, bool isTailCall,
6853                                 MachinePointerInfo DstPtrInfo,
6854                                 MachinePointerInfo SrcPtrInfo,
6855                                 const AAMDNodes &AAInfo) {
6856   // Check to see if we should lower the memcpy to loads and stores first.
6857   // For cases within the target-specified limits, this is the best choice.
6858   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6859   if (ConstantSize) {
6860     // Memcpy with size zero? Just return the original chain.
6861     if (ConstantSize->isZero())
6862       return Chain;
6863 
6864     SDValue Result = getMemcpyLoadsAndStores(
6865         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6866         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6867     if (Result.getNode())
6868       return Result;
6869   }
6870 
6871   // Then check to see if we should lower the memcpy with target-specific
6872   // code. If the target chooses to do this, this is the next best.
6873   if (TSI) {
6874     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6875         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6876         DstPtrInfo, SrcPtrInfo);
6877     if (Result.getNode())
6878       return Result;
6879   }
6880 
6881   // If we really need inline code and the target declined to provide it,
6882   // use a (potentially long) sequence of loads and stores.
6883   if (AlwaysInline) {
6884     assert(ConstantSize && "AlwaysInline requires a constant size!");
6885     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6886                                    ConstantSize->getZExtValue(), Alignment,
6887                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6888   }
6889 
6890   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6891   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6892 
6893   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6894   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6895   // respect volatile, so they may do things like read or write memory
6896   // beyond the given memory regions. But fixing this isn't easy, and most
6897   // people don't care.
6898 
6899   // Emit a library call.
6900   TargetLowering::ArgListTy Args;
6901   TargetLowering::ArgListEntry Entry;
6902   Entry.Ty = Type::getInt8PtrTy(*getContext());
6903   Entry.Node = Dst; Args.push_back(Entry);
6904   Entry.Node = Src; Args.push_back(Entry);
6905 
6906   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6907   Entry.Node = Size; Args.push_back(Entry);
6908   // FIXME: pass in SDLoc
6909   TargetLowering::CallLoweringInfo CLI(*this);
6910   CLI.setDebugLoc(dl)
6911       .setChain(Chain)
6912       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6913                     Dst.getValueType().getTypeForEVT(*getContext()),
6914                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6915                                       TLI->getPointerTy(getDataLayout())),
6916                     std::move(Args))
6917       .setDiscardResult()
6918       .setTailCall(isTailCall);
6919 
6920   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6921   return CallResult.second;
6922 }
6923 
6924 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6925                                       SDValue Dst, unsigned DstAlign,
6926                                       SDValue Src, unsigned SrcAlign,
6927                                       SDValue Size, Type *SizeTy,
6928                                       unsigned ElemSz, bool isTailCall,
6929                                       MachinePointerInfo DstPtrInfo,
6930                                       MachinePointerInfo SrcPtrInfo) {
6931   // Emit a library call.
6932   TargetLowering::ArgListTy Args;
6933   TargetLowering::ArgListEntry Entry;
6934   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6935   Entry.Node = Dst;
6936   Args.push_back(Entry);
6937 
6938   Entry.Node = Src;
6939   Args.push_back(Entry);
6940 
6941   Entry.Ty = SizeTy;
6942   Entry.Node = Size;
6943   Args.push_back(Entry);
6944 
6945   RTLIB::Libcall LibraryCall =
6946       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6947   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6948     report_fatal_error("Unsupported element size");
6949 
6950   TargetLowering::CallLoweringInfo CLI(*this);
6951   CLI.setDebugLoc(dl)
6952       .setChain(Chain)
6953       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6954                     Type::getVoidTy(*getContext()),
6955                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6956                                       TLI->getPointerTy(getDataLayout())),
6957                     std::move(Args))
6958       .setDiscardResult()
6959       .setTailCall(isTailCall);
6960 
6961   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6962   return CallResult.second;
6963 }
6964 
6965 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6966                                  SDValue Src, SDValue Size, Align Alignment,
6967                                  bool isVol, bool isTailCall,
6968                                  MachinePointerInfo DstPtrInfo,
6969                                  MachinePointerInfo SrcPtrInfo,
6970                                  const AAMDNodes &AAInfo) {
6971   // Check to see if we should lower the memmove to loads and stores first.
6972   // For cases within the target-specified limits, this is the best choice.
6973   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6974   if (ConstantSize) {
6975     // Memmove with size zero? Just return the original chain.
6976     if (ConstantSize->isZero())
6977       return Chain;
6978 
6979     SDValue Result = getMemmoveLoadsAndStores(
6980         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6981         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6982     if (Result.getNode())
6983       return Result;
6984   }
6985 
6986   // Then check to see if we should lower the memmove with target-specific
6987   // code. If the target chooses to do this, this is the next best.
6988   if (TSI) {
6989     SDValue Result =
6990         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6991                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6992     if (Result.getNode())
6993       return Result;
6994   }
6995 
6996   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6997   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6998 
6999   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7000   // not be safe.  See memcpy above for more details.
7001 
7002   // Emit a library call.
7003   TargetLowering::ArgListTy Args;
7004   TargetLowering::ArgListEntry Entry;
7005   Entry.Ty = Type::getInt8PtrTy(*getContext());
7006   Entry.Node = Dst; Args.push_back(Entry);
7007   Entry.Node = Src; Args.push_back(Entry);
7008 
7009   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7010   Entry.Node = Size; Args.push_back(Entry);
7011   // FIXME:  pass in SDLoc
7012   TargetLowering::CallLoweringInfo CLI(*this);
7013   CLI.setDebugLoc(dl)
7014       .setChain(Chain)
7015       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7016                     Dst.getValueType().getTypeForEVT(*getContext()),
7017                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7018                                       TLI->getPointerTy(getDataLayout())),
7019                     std::move(Args))
7020       .setDiscardResult()
7021       .setTailCall(isTailCall);
7022 
7023   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7024   return CallResult.second;
7025 }
7026 
7027 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7028                                        SDValue Dst, unsigned DstAlign,
7029                                        SDValue Src, unsigned SrcAlign,
7030                                        SDValue Size, Type *SizeTy,
7031                                        unsigned ElemSz, bool isTailCall,
7032                                        MachinePointerInfo DstPtrInfo,
7033                                        MachinePointerInfo SrcPtrInfo) {
7034   // Emit a library call.
7035   TargetLowering::ArgListTy Args;
7036   TargetLowering::ArgListEntry Entry;
7037   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7038   Entry.Node = Dst;
7039   Args.push_back(Entry);
7040 
7041   Entry.Node = Src;
7042   Args.push_back(Entry);
7043 
7044   Entry.Ty = SizeTy;
7045   Entry.Node = Size;
7046   Args.push_back(Entry);
7047 
7048   RTLIB::Libcall LibraryCall =
7049       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7050   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7051     report_fatal_error("Unsupported element size");
7052 
7053   TargetLowering::CallLoweringInfo CLI(*this);
7054   CLI.setDebugLoc(dl)
7055       .setChain(Chain)
7056       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7057                     Type::getVoidTy(*getContext()),
7058                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7059                                       TLI->getPointerTy(getDataLayout())),
7060                     std::move(Args))
7061       .setDiscardResult()
7062       .setTailCall(isTailCall);
7063 
7064   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7065   return CallResult.second;
7066 }
7067 
7068 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7069                                 SDValue Src, SDValue Size, Align Alignment,
7070                                 bool isVol, bool isTailCall,
7071                                 MachinePointerInfo DstPtrInfo,
7072                                 const AAMDNodes &AAInfo) {
7073   // Check to see if we should lower the memset to stores first.
7074   // For cases within the target-specified limits, this is the best choice.
7075   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7076   if (ConstantSize) {
7077     // Memset with size zero? Just return the original chain.
7078     if (ConstantSize->isZero())
7079       return Chain;
7080 
7081     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7082                                      ConstantSize->getZExtValue(), Alignment,
7083                                      isVol, DstPtrInfo, AAInfo);
7084 
7085     if (Result.getNode())
7086       return Result;
7087   }
7088 
7089   // Then check to see if we should lower the memset with target-specific
7090   // code. If the target chooses to do this, this is the next best.
7091   if (TSI) {
7092     SDValue Result = TSI->EmitTargetCodeForMemset(
7093         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7094     if (Result.getNode())
7095       return Result;
7096   }
7097 
7098   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7099 
7100   // Emit a library call.
7101   TargetLowering::ArgListTy Args;
7102   TargetLowering::ArgListEntry Entry;
7103   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7104   Args.push_back(Entry);
7105   Entry.Node = Src;
7106   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7107   Args.push_back(Entry);
7108   Entry.Node = Size;
7109   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7110   Args.push_back(Entry);
7111 
7112   // FIXME: pass in SDLoc
7113   TargetLowering::CallLoweringInfo CLI(*this);
7114   CLI.setDebugLoc(dl)
7115       .setChain(Chain)
7116       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7117                     Dst.getValueType().getTypeForEVT(*getContext()),
7118                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7119                                       TLI->getPointerTy(getDataLayout())),
7120                     std::move(Args))
7121       .setDiscardResult()
7122       .setTailCall(isTailCall);
7123 
7124   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7125   return CallResult.second;
7126 }
7127 
7128 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7129                                       SDValue Dst, unsigned DstAlign,
7130                                       SDValue Value, SDValue Size, Type *SizeTy,
7131                                       unsigned ElemSz, bool isTailCall,
7132                                       MachinePointerInfo DstPtrInfo) {
7133   // Emit a library call.
7134   TargetLowering::ArgListTy Args;
7135   TargetLowering::ArgListEntry Entry;
7136   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7137   Entry.Node = Dst;
7138   Args.push_back(Entry);
7139 
7140   Entry.Ty = Type::getInt8Ty(*getContext());
7141   Entry.Node = Value;
7142   Args.push_back(Entry);
7143 
7144   Entry.Ty = SizeTy;
7145   Entry.Node = Size;
7146   Args.push_back(Entry);
7147 
7148   RTLIB::Libcall LibraryCall =
7149       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7150   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7151     report_fatal_error("Unsupported element size");
7152 
7153   TargetLowering::CallLoweringInfo CLI(*this);
7154   CLI.setDebugLoc(dl)
7155       .setChain(Chain)
7156       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7157                     Type::getVoidTy(*getContext()),
7158                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7159                                       TLI->getPointerTy(getDataLayout())),
7160                     std::move(Args))
7161       .setDiscardResult()
7162       .setTailCall(isTailCall);
7163 
7164   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7165   return CallResult.second;
7166 }
7167 
7168 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7169                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7170                                 MachineMemOperand *MMO) {
7171   FoldingSetNodeID ID;
7172   ID.AddInteger(MemVT.getRawBits());
7173   AddNodeIDNode(ID, Opcode, VTList, Ops);
7174   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7175   void* IP = nullptr;
7176   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7177     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7178     return SDValue(E, 0);
7179   }
7180 
7181   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7182                                     VTList, MemVT, MMO);
7183   createOperands(N, Ops);
7184 
7185   CSEMap.InsertNode(N, IP);
7186   InsertNode(N);
7187   return SDValue(N, 0);
7188 }
7189 
7190 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7191                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7192                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7193                                        MachineMemOperand *MMO) {
7194   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7195          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7196   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7197 
7198   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7199   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7200 }
7201 
7202 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7203                                 SDValue Chain, SDValue Ptr, SDValue Val,
7204                                 MachineMemOperand *MMO) {
7205   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7206           Opcode == ISD::ATOMIC_LOAD_SUB ||
7207           Opcode == ISD::ATOMIC_LOAD_AND ||
7208           Opcode == ISD::ATOMIC_LOAD_CLR ||
7209           Opcode == ISD::ATOMIC_LOAD_OR ||
7210           Opcode == ISD::ATOMIC_LOAD_XOR ||
7211           Opcode == ISD::ATOMIC_LOAD_NAND ||
7212           Opcode == ISD::ATOMIC_LOAD_MIN ||
7213           Opcode == ISD::ATOMIC_LOAD_MAX ||
7214           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7215           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7216           Opcode == ISD::ATOMIC_LOAD_FADD ||
7217           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7218           Opcode == ISD::ATOMIC_SWAP ||
7219           Opcode == ISD::ATOMIC_STORE) &&
7220          "Invalid Atomic Op");
7221 
7222   EVT VT = Val.getValueType();
7223 
7224   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7225                                                getVTList(VT, MVT::Other);
7226   SDValue Ops[] = {Chain, Ptr, Val};
7227   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7228 }
7229 
7230 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7231                                 EVT VT, SDValue Chain, SDValue Ptr,
7232                                 MachineMemOperand *MMO) {
7233   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7234 
7235   SDVTList VTs = getVTList(VT, MVT::Other);
7236   SDValue Ops[] = {Chain, Ptr};
7237   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7238 }
7239 
7240 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7241 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7242   if (Ops.size() == 1)
7243     return Ops[0];
7244 
7245   SmallVector<EVT, 4> VTs;
7246   VTs.reserve(Ops.size());
7247   for (const SDValue &Op : Ops)
7248     VTs.push_back(Op.getValueType());
7249   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7250 }
7251 
7252 SDValue SelectionDAG::getMemIntrinsicNode(
7253     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7254     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7255     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7256   if (!Size && MemVT.isScalableVector())
7257     Size = MemoryLocation::UnknownSize;
7258   else if (!Size)
7259     Size = MemVT.getStoreSize();
7260 
7261   MachineFunction &MF = getMachineFunction();
7262   MachineMemOperand *MMO =
7263       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7264 
7265   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7266 }
7267 
7268 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7269                                           SDVTList VTList,
7270                                           ArrayRef<SDValue> Ops, EVT MemVT,
7271                                           MachineMemOperand *MMO) {
7272   assert((Opcode == ISD::INTRINSIC_VOID ||
7273           Opcode == ISD::INTRINSIC_W_CHAIN ||
7274           Opcode == ISD::PREFETCH ||
7275           ((int)Opcode <= std::numeric_limits<int>::max() &&
7276            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7277          "Opcode is not a memory-accessing opcode!");
7278 
7279   // Memoize the node unless it returns a flag.
7280   MemIntrinsicSDNode *N;
7281   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7282     FoldingSetNodeID ID;
7283     AddNodeIDNode(ID, Opcode, VTList, Ops);
7284     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7285         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7286     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7287     void *IP = nullptr;
7288     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7289       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7290       return SDValue(E, 0);
7291     }
7292 
7293     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7294                                       VTList, MemVT, MMO);
7295     createOperands(N, Ops);
7296 
7297   CSEMap.InsertNode(N, IP);
7298   } else {
7299     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7300                                       VTList, MemVT, MMO);
7301     createOperands(N, Ops);
7302   }
7303   InsertNode(N);
7304   SDValue V(N, 0);
7305   NewSDValueDbgMsg(V, "Creating new node: ", this);
7306   return V;
7307 }
7308 
7309 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7310                                       SDValue Chain, int FrameIndex,
7311                                       int64_t Size, int64_t Offset) {
7312   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7313   const auto VTs = getVTList(MVT::Other);
7314   SDValue Ops[2] = {
7315       Chain,
7316       getFrameIndex(FrameIndex,
7317                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7318                     true)};
7319 
7320   FoldingSetNodeID ID;
7321   AddNodeIDNode(ID, Opcode, VTs, Ops);
7322   ID.AddInteger(FrameIndex);
7323   ID.AddInteger(Size);
7324   ID.AddInteger(Offset);
7325   void *IP = nullptr;
7326   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7327     return SDValue(E, 0);
7328 
7329   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7330       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7331   createOperands(N, Ops);
7332   CSEMap.InsertNode(N, IP);
7333   InsertNode(N);
7334   SDValue V(N, 0);
7335   NewSDValueDbgMsg(V, "Creating new node: ", this);
7336   return V;
7337 }
7338 
7339 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7340                                          uint64_t Guid, uint64_t Index,
7341                                          uint32_t Attr) {
7342   const unsigned Opcode = ISD::PSEUDO_PROBE;
7343   const auto VTs = getVTList(MVT::Other);
7344   SDValue Ops[] = {Chain};
7345   FoldingSetNodeID ID;
7346   AddNodeIDNode(ID, Opcode, VTs, Ops);
7347   ID.AddInteger(Guid);
7348   ID.AddInteger(Index);
7349   void *IP = nullptr;
7350   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7351     return SDValue(E, 0);
7352 
7353   auto *N = newSDNode<PseudoProbeSDNode>(
7354       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7355   createOperands(N, Ops);
7356   CSEMap.InsertNode(N, IP);
7357   InsertNode(N);
7358   SDValue V(N, 0);
7359   NewSDValueDbgMsg(V, "Creating new node: ", this);
7360   return V;
7361 }
7362 
7363 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7364 /// MachinePointerInfo record from it.  This is particularly useful because the
7365 /// code generator has many cases where it doesn't bother passing in a
7366 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7367 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7368                                            SelectionDAG &DAG, SDValue Ptr,
7369                                            int64_t Offset = 0) {
7370   // If this is FI+Offset, we can model it.
7371   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7372     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7373                                              FI->getIndex(), Offset);
7374 
7375   // If this is (FI+Offset1)+Offset2, we can model it.
7376   if (Ptr.getOpcode() != ISD::ADD ||
7377       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7378       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7379     return Info;
7380 
7381   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7382   return MachinePointerInfo::getFixedStack(
7383       DAG.getMachineFunction(), FI,
7384       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7385 }
7386 
7387 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7388 /// MachinePointerInfo record from it.  This is particularly useful because the
7389 /// code generator has many cases where it doesn't bother passing in a
7390 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7391 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7392                                            SelectionDAG &DAG, SDValue Ptr,
7393                                            SDValue OffsetOp) {
7394   // If the 'Offset' value isn't a constant, we can't handle this.
7395   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7396     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7397   if (OffsetOp.isUndef())
7398     return InferPointerInfo(Info, DAG, Ptr);
7399   return Info;
7400 }
7401 
7402 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7403                               EVT VT, const SDLoc &dl, SDValue Chain,
7404                               SDValue Ptr, SDValue Offset,
7405                               MachinePointerInfo PtrInfo, EVT MemVT,
7406                               Align Alignment,
7407                               MachineMemOperand::Flags MMOFlags,
7408                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7409   assert(Chain.getValueType() == MVT::Other &&
7410         "Invalid chain type");
7411 
7412   MMOFlags |= MachineMemOperand::MOLoad;
7413   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7414   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7415   // clients.
7416   if (PtrInfo.V.isNull())
7417     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7418 
7419   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7420   MachineFunction &MF = getMachineFunction();
7421   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7422                                                    Alignment, AAInfo, Ranges);
7423   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7424 }
7425 
7426 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7427                               EVT VT, const SDLoc &dl, SDValue Chain,
7428                               SDValue Ptr, SDValue Offset, EVT MemVT,
7429                               MachineMemOperand *MMO) {
7430   if (VT == MemVT) {
7431     ExtType = ISD::NON_EXTLOAD;
7432   } else if (ExtType == ISD::NON_EXTLOAD) {
7433     assert(VT == MemVT && "Non-extending load from different memory type!");
7434   } else {
7435     // Extending load.
7436     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7437            "Should only be an extending load, not truncating!");
7438     assert(VT.isInteger() == MemVT.isInteger() &&
7439            "Cannot convert from FP to Int or Int -> FP!");
7440     assert(VT.isVector() == MemVT.isVector() &&
7441            "Cannot use an ext load to convert to or from a vector!");
7442     assert((!VT.isVector() ||
7443             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7444            "Cannot use an ext load to change the number of vector elements!");
7445   }
7446 
7447   bool Indexed = AM != ISD::UNINDEXED;
7448   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7449 
7450   SDVTList VTs = Indexed ?
7451     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7452   SDValue Ops[] = { Chain, Ptr, Offset };
7453   FoldingSetNodeID ID;
7454   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7455   ID.AddInteger(MemVT.getRawBits());
7456   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7457       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7458   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7459   void *IP = nullptr;
7460   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7461     cast<LoadSDNode>(E)->refineAlignment(MMO);
7462     return SDValue(E, 0);
7463   }
7464   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7465                                   ExtType, MemVT, MMO);
7466   createOperands(N, Ops);
7467 
7468   CSEMap.InsertNode(N, IP);
7469   InsertNode(N);
7470   SDValue V(N, 0);
7471   NewSDValueDbgMsg(V, "Creating new node: ", this);
7472   return V;
7473 }
7474 
7475 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7476                               SDValue Ptr, MachinePointerInfo PtrInfo,
7477                               MaybeAlign Alignment,
7478                               MachineMemOperand::Flags MMOFlags,
7479                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7480   SDValue Undef = getUNDEF(Ptr.getValueType());
7481   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7482                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7483 }
7484 
7485 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7486                               SDValue Ptr, MachineMemOperand *MMO) {
7487   SDValue Undef = getUNDEF(Ptr.getValueType());
7488   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7489                  VT, MMO);
7490 }
7491 
7492 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7493                                  EVT VT, SDValue Chain, SDValue Ptr,
7494                                  MachinePointerInfo PtrInfo, EVT MemVT,
7495                                  MaybeAlign Alignment,
7496                                  MachineMemOperand::Flags MMOFlags,
7497                                  const AAMDNodes &AAInfo) {
7498   SDValue Undef = getUNDEF(Ptr.getValueType());
7499   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7500                  MemVT, Alignment, MMOFlags, AAInfo);
7501 }
7502 
7503 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7504                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7505                                  MachineMemOperand *MMO) {
7506   SDValue Undef = getUNDEF(Ptr.getValueType());
7507   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7508                  MemVT, MMO);
7509 }
7510 
7511 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7512                                      SDValue Base, SDValue Offset,
7513                                      ISD::MemIndexedMode AM) {
7514   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7515   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7516   // Don't propagate the invariant or dereferenceable flags.
7517   auto MMOFlags =
7518       LD->getMemOperand()->getFlags() &
7519       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7520   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7521                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7522                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7523 }
7524 
7525 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7526                                SDValue Ptr, MachinePointerInfo PtrInfo,
7527                                Align Alignment,
7528                                MachineMemOperand::Flags MMOFlags,
7529                                const AAMDNodes &AAInfo) {
7530   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7531 
7532   MMOFlags |= MachineMemOperand::MOStore;
7533   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7534 
7535   if (PtrInfo.V.isNull())
7536     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7537 
7538   MachineFunction &MF = getMachineFunction();
7539   uint64_t Size =
7540       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7541   MachineMemOperand *MMO =
7542       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7543   return getStore(Chain, dl, Val, Ptr, MMO);
7544 }
7545 
7546 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7547                                SDValue Ptr, MachineMemOperand *MMO) {
7548   assert(Chain.getValueType() == MVT::Other &&
7549         "Invalid chain type");
7550   EVT VT = Val.getValueType();
7551   SDVTList VTs = getVTList(MVT::Other);
7552   SDValue Undef = getUNDEF(Ptr.getValueType());
7553   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7554   FoldingSetNodeID ID;
7555   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7556   ID.AddInteger(VT.getRawBits());
7557   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7558       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7559   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7560   void *IP = nullptr;
7561   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7562     cast<StoreSDNode>(E)->refineAlignment(MMO);
7563     return SDValue(E, 0);
7564   }
7565   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7566                                    ISD::UNINDEXED, false, VT, MMO);
7567   createOperands(N, Ops);
7568 
7569   CSEMap.InsertNode(N, IP);
7570   InsertNode(N);
7571   SDValue V(N, 0);
7572   NewSDValueDbgMsg(V, "Creating new node: ", this);
7573   return V;
7574 }
7575 
7576 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7577                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7578                                     EVT SVT, Align Alignment,
7579                                     MachineMemOperand::Flags MMOFlags,
7580                                     const AAMDNodes &AAInfo) {
7581   assert(Chain.getValueType() == MVT::Other &&
7582         "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   MachineMemOperand *MMO = MF.getMachineMemOperand(
7592       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7593       Alignment, AAInfo);
7594   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7595 }
7596 
7597 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7598                                     SDValue Ptr, EVT SVT,
7599                                     MachineMemOperand *MMO) {
7600   EVT VT = Val.getValueType();
7601 
7602   assert(Chain.getValueType() == MVT::Other &&
7603         "Invalid chain type");
7604   if (VT == SVT)
7605     return getStore(Chain, dl, Val, Ptr, MMO);
7606 
7607   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7608          "Should only be a truncating store, not extending!");
7609   assert(VT.isInteger() == SVT.isInteger() &&
7610          "Can't do FP-INT conversion!");
7611   assert(VT.isVector() == SVT.isVector() &&
7612          "Cannot use trunc store to convert to or from a vector!");
7613   assert((!VT.isVector() ||
7614           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7615          "Cannot use trunc store to change the number of vector elements!");
7616 
7617   SDVTList VTs = getVTList(MVT::Other);
7618   SDValue Undef = getUNDEF(Ptr.getValueType());
7619   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7620   FoldingSetNodeID ID;
7621   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7622   ID.AddInteger(SVT.getRawBits());
7623   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7624       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7625   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7626   void *IP = nullptr;
7627   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7628     cast<StoreSDNode>(E)->refineAlignment(MMO);
7629     return SDValue(E, 0);
7630   }
7631   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7632                                    ISD::UNINDEXED, true, SVT, MMO);
7633   createOperands(N, Ops);
7634 
7635   CSEMap.InsertNode(N, IP);
7636   InsertNode(N);
7637   SDValue V(N, 0);
7638   NewSDValueDbgMsg(V, "Creating new node: ", this);
7639   return V;
7640 }
7641 
7642 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7643                                       SDValue Base, SDValue Offset,
7644                                       ISD::MemIndexedMode AM) {
7645   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7646   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7647   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7648   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7649   FoldingSetNodeID ID;
7650   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7651   ID.AddInteger(ST->getMemoryVT().getRawBits());
7652   ID.AddInteger(ST->getRawSubclassData());
7653   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7654   void *IP = nullptr;
7655   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7656     return SDValue(E, 0);
7657 
7658   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7659                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7660                                    ST->getMemOperand());
7661   createOperands(N, Ops);
7662 
7663   CSEMap.InsertNode(N, IP);
7664   InsertNode(N);
7665   SDValue V(N, 0);
7666   NewSDValueDbgMsg(V, "Creating new node: ", this);
7667   return V;
7668 }
7669 
7670 SDValue SelectionDAG::getLoadVP(
7671     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7672     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7673     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7674     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7675     const MDNode *Ranges, bool IsExpanding) {
7676   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7677 
7678   MMOFlags |= MachineMemOperand::MOLoad;
7679   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7680   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7681   // clients.
7682   if (PtrInfo.V.isNull())
7683     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7684 
7685   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7686   MachineFunction &MF = getMachineFunction();
7687   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7688                                                    Alignment, AAInfo, Ranges);
7689   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7690                    MMO, IsExpanding);
7691 }
7692 
7693 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7694                                 ISD::LoadExtType ExtType, EVT VT,
7695                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7696                                 SDValue Offset, SDValue Mask, SDValue EVL,
7697                                 EVT MemVT, MachineMemOperand *MMO,
7698                                 bool IsExpanding) {
7699   if (VT == MemVT) {
7700     ExtType = ISD::NON_EXTLOAD;
7701   } else if (ExtType == ISD::NON_EXTLOAD) {
7702     assert(VT == MemVT && "Non-extending load from different memory type!");
7703   } else {
7704     // Extending load.
7705     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7706            "Should only be an extending load, not truncating!");
7707     assert(VT.isInteger() == MemVT.isInteger() &&
7708            "Cannot convert from FP to Int or Int -> FP!");
7709     assert(VT.isVector() == MemVT.isVector() &&
7710            "Cannot use an ext load to convert to or from a vector!");
7711     assert((!VT.isVector() ||
7712             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7713            "Cannot use an ext load to change the number of vector elements!");
7714   }
7715 
7716   bool Indexed = AM != ISD::UNINDEXED;
7717   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7718 
7719   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7720                          : getVTList(VT, MVT::Other);
7721   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7722   FoldingSetNodeID ID;
7723   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7724   ID.AddInteger(VT.getRawBits());
7725   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7726       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7727   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7728   void *IP = nullptr;
7729   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7730     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7731     return SDValue(E, 0);
7732   }
7733   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7734                                     ExtType, IsExpanding, MemVT, MMO);
7735   createOperands(N, Ops);
7736 
7737   CSEMap.InsertNode(N, IP);
7738   InsertNode(N);
7739   SDValue V(N, 0);
7740   NewSDValueDbgMsg(V, "Creating new node: ", this);
7741   return V;
7742 }
7743 
7744 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7745                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7746                                 MachinePointerInfo PtrInfo,
7747                                 MaybeAlign Alignment,
7748                                 MachineMemOperand::Flags MMOFlags,
7749                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7750                                 bool IsExpanding) {
7751   SDValue Undef = getUNDEF(Ptr.getValueType());
7752   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7753                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7754                    IsExpanding);
7755 }
7756 
7757 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7758                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7759                                 MachineMemOperand *MMO, bool IsExpanding) {
7760   SDValue Undef = getUNDEF(Ptr.getValueType());
7761   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7762                    Mask, EVL, VT, MMO, IsExpanding);
7763 }
7764 
7765 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7766                                    EVT VT, SDValue Chain, SDValue Ptr,
7767                                    SDValue Mask, SDValue EVL,
7768                                    MachinePointerInfo PtrInfo, EVT MemVT,
7769                                    MaybeAlign Alignment,
7770                                    MachineMemOperand::Flags MMOFlags,
7771                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7772   SDValue Undef = getUNDEF(Ptr.getValueType());
7773   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7774                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7775                    IsExpanding);
7776 }
7777 
7778 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7779                                    EVT VT, SDValue Chain, SDValue Ptr,
7780                                    SDValue Mask, SDValue EVL, EVT MemVT,
7781                                    MachineMemOperand *MMO, bool IsExpanding) {
7782   SDValue Undef = getUNDEF(Ptr.getValueType());
7783   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7784                    EVL, MemVT, MMO, IsExpanding);
7785 }
7786 
7787 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7788                                        SDValue Base, SDValue Offset,
7789                                        ISD::MemIndexedMode AM) {
7790   auto *LD = cast<VPLoadSDNode>(OrigLoad);
7791   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7792   // Don't propagate the invariant or dereferenceable flags.
7793   auto MMOFlags =
7794       LD->getMemOperand()->getFlags() &
7795       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7796   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7797                    LD->getChain(), Base, Offset, LD->getMask(),
7798                    LD->getVectorLength(), LD->getPointerInfo(),
7799                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7800                    nullptr, LD->isExpandingLoad());
7801 }
7802 
7803 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7804                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7805                                  MachinePointerInfo PtrInfo, Align Alignment,
7806                                  MachineMemOperand::Flags MMOFlags,
7807                                  const AAMDNodes &AAInfo, bool IsCompressing) {
7808   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7809 
7810   MMOFlags |= MachineMemOperand::MOStore;
7811   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7812 
7813   if (PtrInfo.V.isNull())
7814     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7815 
7816   MachineFunction &MF = getMachineFunction();
7817   uint64_t Size =
7818       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7819   MachineMemOperand *MMO =
7820       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7821   return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7822 }
7823 
7824 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7825                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7826                                  MachineMemOperand *MMO, bool IsCompressing) {
7827   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7828   EVT VT = Val.getValueType();
7829   SDVTList VTs = getVTList(MVT::Other);
7830   SDValue Undef = getUNDEF(Ptr.getValueType());
7831   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7832   FoldingSetNodeID ID;
7833   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7834   ID.AddInteger(VT.getRawBits());
7835   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7836       dl.getIROrder(), VTs, ISD::UNINDEXED, false, IsCompressing, VT, MMO));
7837   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7838   void *IP = nullptr;
7839   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7840     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7841     return SDValue(E, 0);
7842   }
7843   auto *N =
7844       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7845                                ISD::UNINDEXED, false, IsCompressing, VT, MMO);
7846   createOperands(N, Ops);
7847 
7848   CSEMap.InsertNode(N, IP);
7849   InsertNode(N);
7850   SDValue V(N, 0);
7851   NewSDValueDbgMsg(V, "Creating new node: ", this);
7852   return V;
7853 }
7854 
7855 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7856                                       SDValue Val, SDValue Ptr, SDValue Mask,
7857                                       SDValue EVL, MachinePointerInfo PtrInfo,
7858                                       EVT SVT, Align Alignment,
7859                                       MachineMemOperand::Flags MMOFlags,
7860                                       const AAMDNodes &AAInfo,
7861                                       bool IsCompressing) {
7862   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7863 
7864   MMOFlags |= MachineMemOperand::MOStore;
7865   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7866 
7867   if (PtrInfo.V.isNull())
7868     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7869 
7870   MachineFunction &MF = getMachineFunction();
7871   MachineMemOperand *MMO = MF.getMachineMemOperand(
7872       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7873       Alignment, AAInfo);
7874   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7875                          IsCompressing);
7876 }
7877 
7878 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7879                                       SDValue Val, SDValue Ptr, SDValue Mask,
7880                                       SDValue EVL, EVT SVT,
7881                                       MachineMemOperand *MMO,
7882                                       bool IsCompressing) {
7883   EVT VT = Val.getValueType();
7884 
7885   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7886   if (VT == SVT)
7887     return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7888 
7889   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7890          "Should only be a truncating store, not extending!");
7891   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
7892   assert(VT.isVector() == SVT.isVector() &&
7893          "Cannot use trunc store to convert to or from a vector!");
7894   assert((!VT.isVector() ||
7895           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7896          "Cannot use trunc store to change the number of vector elements!");
7897 
7898   SDVTList VTs = getVTList(MVT::Other);
7899   SDValue Undef = getUNDEF(Ptr.getValueType());
7900   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7901   FoldingSetNodeID ID;
7902   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7903   ID.AddInteger(SVT.getRawBits());
7904   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7905       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
7906   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7907   void *IP = nullptr;
7908   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7909     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7910     return SDValue(E, 0);
7911   }
7912   auto *N =
7913       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7914                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
7915   createOperands(N, Ops);
7916 
7917   CSEMap.InsertNode(N, IP);
7918   InsertNode(N);
7919   SDValue V(N, 0);
7920   NewSDValueDbgMsg(V, "Creating new node: ", this);
7921   return V;
7922 }
7923 
7924 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
7925                                         SDValue Base, SDValue Offset,
7926                                         ISD::MemIndexedMode AM) {
7927   auto *ST = cast<VPStoreSDNode>(OrigStore);
7928   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
7929   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7930   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
7931                    Offset,         ST->getMask(),  ST->getVectorLength()};
7932   FoldingSetNodeID ID;
7933   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7934   ID.AddInteger(ST->getMemoryVT().getRawBits());
7935   ID.AddInteger(ST->getRawSubclassData());
7936   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7937   void *IP = nullptr;
7938   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7939     return SDValue(E, 0);
7940 
7941   auto *N = newSDNode<VPStoreSDNode>(
7942       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
7943       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
7944   createOperands(N, Ops);
7945 
7946   CSEMap.InsertNode(N, IP);
7947   InsertNode(N);
7948   SDValue V(N, 0);
7949   NewSDValueDbgMsg(V, "Creating new node: ", this);
7950   return V;
7951 }
7952 
7953 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7954                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
7955                                   ISD::MemIndexType IndexType) {
7956   assert(Ops.size() == 6 && "Incompatible number of operands");
7957 
7958   FoldingSetNodeID ID;
7959   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
7960   ID.AddInteger(VT.getRawBits());
7961   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
7962       dl.getIROrder(), VTs, VT, MMO, IndexType));
7963   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7964   void *IP = nullptr;
7965   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7966     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
7967     return SDValue(E, 0);
7968   }
7969 
7970   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7971                                       VT, MMO, IndexType);
7972   createOperands(N, Ops);
7973 
7974   assert(N->getMask().getValueType().getVectorElementCount() ==
7975              N->getValueType(0).getVectorElementCount() &&
7976          "Vector width mismatch between mask and data");
7977   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7978              N->getValueType(0).getVectorElementCount().isScalable() &&
7979          "Scalable flags of index and data do not match");
7980   assert(ElementCount::isKnownGE(
7981              N->getIndex().getValueType().getVectorElementCount(),
7982              N->getValueType(0).getVectorElementCount()) &&
7983          "Vector width mismatch between index and data");
7984   assert(isa<ConstantSDNode>(N->getScale()) &&
7985          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7986          "Scale should be a constant power of 2");
7987 
7988   CSEMap.InsertNode(N, IP);
7989   InsertNode(N);
7990   SDValue V(N, 0);
7991   NewSDValueDbgMsg(V, "Creating new node: ", this);
7992   return V;
7993 }
7994 
7995 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7996                                    ArrayRef<SDValue> Ops,
7997                                    MachineMemOperand *MMO,
7998                                    ISD::MemIndexType IndexType) {
7999   assert(Ops.size() == 7 && "Incompatible number of operands");
8000 
8001   FoldingSetNodeID ID;
8002   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8003   ID.AddInteger(VT.getRawBits());
8004   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8005       dl.getIROrder(), VTs, VT, MMO, IndexType));
8006   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8007   void *IP = nullptr;
8008   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8009     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8010     return SDValue(E, 0);
8011   }
8012   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8013                                        VT, MMO, IndexType);
8014   createOperands(N, Ops);
8015 
8016   assert(N->getMask().getValueType().getVectorElementCount() ==
8017              N->getValue().getValueType().getVectorElementCount() &&
8018          "Vector width mismatch between mask and data");
8019   assert(
8020       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8021           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8022       "Scalable flags of index and data do not match");
8023   assert(ElementCount::isKnownGE(
8024              N->getIndex().getValueType().getVectorElementCount(),
8025              N->getValue().getValueType().getVectorElementCount()) &&
8026          "Vector width mismatch between index and data");
8027   assert(isa<ConstantSDNode>(N->getScale()) &&
8028          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8029          "Scale should be a constant power of 2");
8030 
8031   CSEMap.InsertNode(N, IP);
8032   InsertNode(N);
8033   SDValue V(N, 0);
8034   NewSDValueDbgMsg(V, "Creating new node: ", this);
8035   return V;
8036 }
8037 
8038 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8039                                     SDValue Base, SDValue Offset, SDValue Mask,
8040                                     SDValue PassThru, EVT MemVT,
8041                                     MachineMemOperand *MMO,
8042                                     ISD::MemIndexedMode AM,
8043                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8044   bool Indexed = AM != ISD::UNINDEXED;
8045   assert((Indexed || Offset.isUndef()) &&
8046          "Unindexed masked load with an offset!");
8047   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8048                          : getVTList(VT, MVT::Other);
8049   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8050   FoldingSetNodeID ID;
8051   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8052   ID.AddInteger(MemVT.getRawBits());
8053   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8054       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8055   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8056   void *IP = nullptr;
8057   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8058     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8059     return SDValue(E, 0);
8060   }
8061   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8062                                         AM, ExtTy, isExpanding, MemVT, MMO);
8063   createOperands(N, Ops);
8064 
8065   CSEMap.InsertNode(N, IP);
8066   InsertNode(N);
8067   SDValue V(N, 0);
8068   NewSDValueDbgMsg(V, "Creating new node: ", this);
8069   return V;
8070 }
8071 
8072 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8073                                            SDValue Base, SDValue Offset,
8074                                            ISD::MemIndexedMode AM) {
8075   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8076   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8077   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8078                        Offset, LD->getMask(), LD->getPassThru(),
8079                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8080                        LD->getExtensionType(), LD->isExpandingLoad());
8081 }
8082 
8083 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8084                                      SDValue Val, SDValue Base, SDValue Offset,
8085                                      SDValue Mask, EVT MemVT,
8086                                      MachineMemOperand *MMO,
8087                                      ISD::MemIndexedMode AM, bool IsTruncating,
8088                                      bool IsCompressing) {
8089   assert(Chain.getValueType() == MVT::Other &&
8090         "Invalid chain type");
8091   bool Indexed = AM != ISD::UNINDEXED;
8092   assert((Indexed || Offset.isUndef()) &&
8093          "Unindexed masked store with an offset!");
8094   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8095                          : getVTList(MVT::Other);
8096   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8097   FoldingSetNodeID ID;
8098   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8099   ID.AddInteger(MemVT.getRawBits());
8100   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8101       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8102   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8103   void *IP = nullptr;
8104   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8105     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8106     return SDValue(E, 0);
8107   }
8108   auto *N =
8109       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8110                                    IsTruncating, IsCompressing, MemVT, MMO);
8111   createOperands(N, Ops);
8112 
8113   CSEMap.InsertNode(N, IP);
8114   InsertNode(N);
8115   SDValue V(N, 0);
8116   NewSDValueDbgMsg(V, "Creating new node: ", this);
8117   return V;
8118 }
8119 
8120 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8121                                             SDValue Base, SDValue Offset,
8122                                             ISD::MemIndexedMode AM) {
8123   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8124   assert(ST->getOffset().isUndef() &&
8125          "Masked store is already a indexed store!");
8126   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8127                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8128                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8129 }
8130 
8131 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8132                                       ArrayRef<SDValue> Ops,
8133                                       MachineMemOperand *MMO,
8134                                       ISD::MemIndexType IndexType,
8135                                       ISD::LoadExtType ExtTy) {
8136   assert(Ops.size() == 6 && "Incompatible number of operands");
8137 
8138   FoldingSetNodeID ID;
8139   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8140   ID.AddInteger(MemVT.getRawBits());
8141   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8142       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8143   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8144   void *IP = nullptr;
8145   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8146     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8147     return SDValue(E, 0);
8148   }
8149 
8150   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8151   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8152                                           VTs, MemVT, MMO, IndexType, ExtTy);
8153   createOperands(N, Ops);
8154 
8155   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8156          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8157   assert(N->getMask().getValueType().getVectorElementCount() ==
8158              N->getValueType(0).getVectorElementCount() &&
8159          "Vector width mismatch between mask and data");
8160   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8161              N->getValueType(0).getVectorElementCount().isScalable() &&
8162          "Scalable flags of index and data do not match");
8163   assert(ElementCount::isKnownGE(
8164              N->getIndex().getValueType().getVectorElementCount(),
8165              N->getValueType(0).getVectorElementCount()) &&
8166          "Vector width mismatch between index and data");
8167   assert(isa<ConstantSDNode>(N->getScale()) &&
8168          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8169          "Scale should be a constant power of 2");
8170 
8171   CSEMap.InsertNode(N, IP);
8172   InsertNode(N);
8173   SDValue V(N, 0);
8174   NewSDValueDbgMsg(V, "Creating new node: ", this);
8175   return V;
8176 }
8177 
8178 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8179                                        ArrayRef<SDValue> Ops,
8180                                        MachineMemOperand *MMO,
8181                                        ISD::MemIndexType IndexType,
8182                                        bool IsTrunc) {
8183   assert(Ops.size() == 6 && "Incompatible number of operands");
8184 
8185   FoldingSetNodeID ID;
8186   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8187   ID.AddInteger(MemVT.getRawBits());
8188   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8189       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8190   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8191   void *IP = nullptr;
8192   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8193     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8194     return SDValue(E, 0);
8195   }
8196 
8197   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8198   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8199                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8200   createOperands(N, Ops);
8201 
8202   assert(N->getMask().getValueType().getVectorElementCount() ==
8203              N->getValue().getValueType().getVectorElementCount() &&
8204          "Vector width mismatch between mask and data");
8205   assert(
8206       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8207           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8208       "Scalable flags of index and data do not match");
8209   assert(ElementCount::isKnownGE(
8210              N->getIndex().getValueType().getVectorElementCount(),
8211              N->getValue().getValueType().getVectorElementCount()) &&
8212          "Vector width mismatch between index and data");
8213   assert(isa<ConstantSDNode>(N->getScale()) &&
8214          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8215          "Scale should be a constant power of 2");
8216 
8217   CSEMap.InsertNode(N, IP);
8218   InsertNode(N);
8219   SDValue V(N, 0);
8220   NewSDValueDbgMsg(V, "Creating new node: ", this);
8221   return V;
8222 }
8223 
8224 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8225   // select undef, T, F --> T (if T is a constant), otherwise F
8226   // select, ?, undef, F --> F
8227   // select, ?, T, undef --> T
8228   if (Cond.isUndef())
8229     return isConstantValueOfAnyType(T) ? T : F;
8230   if (T.isUndef())
8231     return F;
8232   if (F.isUndef())
8233     return T;
8234 
8235   // select true, T, F --> T
8236   // select false, T, F --> F
8237   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8238     return CondC->isZero() ? F : T;
8239 
8240   // TODO: This should simplify VSELECT with constant condition using something
8241   // like this (but check boolean contents to be complete?):
8242   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8243   //    return T;
8244   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8245   //    return F;
8246 
8247   // select ?, T, T --> T
8248   if (T == F)
8249     return T;
8250 
8251   return SDValue();
8252 }
8253 
8254 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8255   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8256   if (X.isUndef())
8257     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8258   // shift X, undef --> undef (because it may shift by the bitwidth)
8259   if (Y.isUndef())
8260     return getUNDEF(X.getValueType());
8261 
8262   // shift 0, Y --> 0
8263   // shift X, 0 --> X
8264   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8265     return X;
8266 
8267   // shift X, C >= bitwidth(X) --> undef
8268   // All vector elements must be too big (or undef) to avoid partial undefs.
8269   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8270     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8271   };
8272   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8273     return getUNDEF(X.getValueType());
8274 
8275   return SDValue();
8276 }
8277 
8278 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8279                                       SDNodeFlags Flags) {
8280   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8281   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8282   // operation is poison. That result can be relaxed to undef.
8283   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8284   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8285   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8286                 (YC && YC->getValueAPF().isNaN());
8287   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8288                 (YC && YC->getValueAPF().isInfinity());
8289 
8290   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8291     return getUNDEF(X.getValueType());
8292 
8293   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8294     return getUNDEF(X.getValueType());
8295 
8296   if (!YC)
8297     return SDValue();
8298 
8299   // X + -0.0 --> X
8300   if (Opcode == ISD::FADD)
8301     if (YC->getValueAPF().isNegZero())
8302       return X;
8303 
8304   // X - +0.0 --> X
8305   if (Opcode == ISD::FSUB)
8306     if (YC->getValueAPF().isPosZero())
8307       return X;
8308 
8309   // X * 1.0 --> X
8310   // X / 1.0 --> X
8311   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8312     if (YC->getValueAPF().isExactlyValue(1.0))
8313       return X;
8314 
8315   // X * 0.0 --> 0.0
8316   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8317     if (YC->getValueAPF().isZero())
8318       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8319 
8320   return SDValue();
8321 }
8322 
8323 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8324                                SDValue Ptr, SDValue SV, unsigned Align) {
8325   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8326   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8327 }
8328 
8329 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8330                               ArrayRef<SDUse> Ops) {
8331   switch (Ops.size()) {
8332   case 0: return getNode(Opcode, DL, VT);
8333   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8334   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8335   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8336   default: break;
8337   }
8338 
8339   // Copy from an SDUse array into an SDValue array for use with
8340   // the regular getNode logic.
8341   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8342   return getNode(Opcode, DL, VT, NewOps);
8343 }
8344 
8345 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8346                               ArrayRef<SDValue> Ops) {
8347   SDNodeFlags Flags;
8348   if (Inserter)
8349     Flags = Inserter->getFlags();
8350   return getNode(Opcode, DL, VT, Ops, Flags);
8351 }
8352 
8353 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8354                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8355   unsigned NumOps = Ops.size();
8356   switch (NumOps) {
8357   case 0: return getNode(Opcode, DL, VT);
8358   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8359   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8360   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8361   default: break;
8362   }
8363 
8364 #ifndef NDEBUG
8365   for (auto &Op : Ops)
8366     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8367            "Operand is DELETED_NODE!");
8368 #endif
8369 
8370   switch (Opcode) {
8371   default: break;
8372   case ISD::BUILD_VECTOR:
8373     // Attempt to simplify BUILD_VECTOR.
8374     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8375       return V;
8376     break;
8377   case ISD::CONCAT_VECTORS:
8378     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8379       return V;
8380     break;
8381   case ISD::SELECT_CC:
8382     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8383     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8384            "LHS and RHS of condition must have same type!");
8385     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8386            "True and False arms of SelectCC must have same type!");
8387     assert(Ops[2].getValueType() == VT &&
8388            "select_cc node must be of same type as true and false value!");
8389     break;
8390   case ISD::BR_CC:
8391     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8392     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8393            "LHS/RHS of comparison should match types!");
8394     break;
8395   }
8396 
8397   // Memoize nodes.
8398   SDNode *N;
8399   SDVTList VTs = getVTList(VT);
8400 
8401   if (VT != MVT::Glue) {
8402     FoldingSetNodeID ID;
8403     AddNodeIDNode(ID, Opcode, VTs, Ops);
8404     void *IP = nullptr;
8405 
8406     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8407       return SDValue(E, 0);
8408 
8409     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8410     createOperands(N, Ops);
8411 
8412     CSEMap.InsertNode(N, IP);
8413   } else {
8414     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8415     createOperands(N, Ops);
8416   }
8417 
8418   N->setFlags(Flags);
8419   InsertNode(N);
8420   SDValue V(N, 0);
8421   NewSDValueDbgMsg(V, "Creating new node: ", this);
8422   return V;
8423 }
8424 
8425 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8426                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8427   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8428 }
8429 
8430 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8431                               ArrayRef<SDValue> Ops) {
8432   SDNodeFlags Flags;
8433   if (Inserter)
8434     Flags = Inserter->getFlags();
8435   return getNode(Opcode, DL, VTList, Ops, Flags);
8436 }
8437 
8438 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8439                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8440   if (VTList.NumVTs == 1)
8441     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8442 
8443 #ifndef NDEBUG
8444   for (auto &Op : Ops)
8445     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8446            "Operand is DELETED_NODE!");
8447 #endif
8448 
8449   switch (Opcode) {
8450   case ISD::STRICT_FP_EXTEND:
8451     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8452            "Invalid STRICT_FP_EXTEND!");
8453     assert(VTList.VTs[0].isFloatingPoint() &&
8454            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8455     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8456            "STRICT_FP_EXTEND result type should be vector iff the operand "
8457            "type is vector!");
8458     assert((!VTList.VTs[0].isVector() ||
8459             VTList.VTs[0].getVectorNumElements() ==
8460             Ops[1].getValueType().getVectorNumElements()) &&
8461            "Vector element count mismatch!");
8462     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8463            "Invalid fpext node, dst <= src!");
8464     break;
8465   case ISD::STRICT_FP_ROUND:
8466     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8467     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8468            "STRICT_FP_ROUND result type should be vector iff the operand "
8469            "type is vector!");
8470     assert((!VTList.VTs[0].isVector() ||
8471             VTList.VTs[0].getVectorNumElements() ==
8472             Ops[1].getValueType().getVectorNumElements()) &&
8473            "Vector element count mismatch!");
8474     assert(VTList.VTs[0].isFloatingPoint() &&
8475            Ops[1].getValueType().isFloatingPoint() &&
8476            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8477            isa<ConstantSDNode>(Ops[2]) &&
8478            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8479             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8480            "Invalid STRICT_FP_ROUND!");
8481     break;
8482 #if 0
8483   // FIXME: figure out how to safely handle things like
8484   // int foo(int x) { return 1 << (x & 255); }
8485   // int bar() { return foo(256); }
8486   case ISD::SRA_PARTS:
8487   case ISD::SRL_PARTS:
8488   case ISD::SHL_PARTS:
8489     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8490         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8491       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8492     else if (N3.getOpcode() == ISD::AND)
8493       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8494         // If the and is only masking out bits that cannot effect the shift,
8495         // eliminate the and.
8496         unsigned NumBits = VT.getScalarSizeInBits()*2;
8497         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8498           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8499       }
8500     break;
8501 #endif
8502   }
8503 
8504   // Memoize the node unless it returns a flag.
8505   SDNode *N;
8506   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8507     FoldingSetNodeID ID;
8508     AddNodeIDNode(ID, Opcode, VTList, Ops);
8509     void *IP = nullptr;
8510     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8511       return SDValue(E, 0);
8512 
8513     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8514     createOperands(N, Ops);
8515     CSEMap.InsertNode(N, IP);
8516   } else {
8517     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8518     createOperands(N, Ops);
8519   }
8520 
8521   N->setFlags(Flags);
8522   InsertNode(N);
8523   SDValue V(N, 0);
8524   NewSDValueDbgMsg(V, "Creating new node: ", this);
8525   return V;
8526 }
8527 
8528 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8529                               SDVTList VTList) {
8530   return getNode(Opcode, DL, VTList, None);
8531 }
8532 
8533 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8534                               SDValue N1) {
8535   SDValue Ops[] = { N1 };
8536   return getNode(Opcode, DL, VTList, Ops);
8537 }
8538 
8539 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8540                               SDValue N1, SDValue N2) {
8541   SDValue Ops[] = { N1, N2 };
8542   return getNode(Opcode, DL, VTList, Ops);
8543 }
8544 
8545 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8546                               SDValue N1, SDValue N2, SDValue N3) {
8547   SDValue Ops[] = { N1, N2, N3 };
8548   return getNode(Opcode, DL, VTList, Ops);
8549 }
8550 
8551 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8552                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8553   SDValue Ops[] = { N1, N2, N3, N4 };
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, SDValue N3, SDValue N4,
8559                               SDValue N5) {
8560   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8561   return getNode(Opcode, DL, VTList, Ops);
8562 }
8563 
8564 SDVTList SelectionDAG::getVTList(EVT VT) {
8565   return makeVTList(SDNode::getValueTypeList(VT), 1);
8566 }
8567 
8568 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8569   FoldingSetNodeID ID;
8570   ID.AddInteger(2U);
8571   ID.AddInteger(VT1.getRawBits());
8572   ID.AddInteger(VT2.getRawBits());
8573 
8574   void *IP = nullptr;
8575   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8576   if (!Result) {
8577     EVT *Array = Allocator.Allocate<EVT>(2);
8578     Array[0] = VT1;
8579     Array[1] = VT2;
8580     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8581     VTListMap.InsertNode(Result, IP);
8582   }
8583   return Result->getSDVTList();
8584 }
8585 
8586 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8587   FoldingSetNodeID ID;
8588   ID.AddInteger(3U);
8589   ID.AddInteger(VT1.getRawBits());
8590   ID.AddInteger(VT2.getRawBits());
8591   ID.AddInteger(VT3.getRawBits());
8592 
8593   void *IP = nullptr;
8594   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8595   if (!Result) {
8596     EVT *Array = Allocator.Allocate<EVT>(3);
8597     Array[0] = VT1;
8598     Array[1] = VT2;
8599     Array[2] = VT3;
8600     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8601     VTListMap.InsertNode(Result, IP);
8602   }
8603   return Result->getSDVTList();
8604 }
8605 
8606 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8607   FoldingSetNodeID ID;
8608   ID.AddInteger(4U);
8609   ID.AddInteger(VT1.getRawBits());
8610   ID.AddInteger(VT2.getRawBits());
8611   ID.AddInteger(VT3.getRawBits());
8612   ID.AddInteger(VT4.getRawBits());
8613 
8614   void *IP = nullptr;
8615   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8616   if (!Result) {
8617     EVT *Array = Allocator.Allocate<EVT>(4);
8618     Array[0] = VT1;
8619     Array[1] = VT2;
8620     Array[2] = VT3;
8621     Array[3] = VT4;
8622     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8623     VTListMap.InsertNode(Result, IP);
8624   }
8625   return Result->getSDVTList();
8626 }
8627 
8628 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8629   unsigned NumVTs = VTs.size();
8630   FoldingSetNodeID ID;
8631   ID.AddInteger(NumVTs);
8632   for (unsigned index = 0; index < NumVTs; index++) {
8633     ID.AddInteger(VTs[index].getRawBits());
8634   }
8635 
8636   void *IP = nullptr;
8637   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8638   if (!Result) {
8639     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8640     llvm::copy(VTs, Array);
8641     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8642     VTListMap.InsertNode(Result, IP);
8643   }
8644   return Result->getSDVTList();
8645 }
8646 
8647 
8648 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8649 /// specified operands.  If the resultant node already exists in the DAG,
8650 /// this does not modify the specified node, instead it returns the node that
8651 /// already exists.  If the resultant node does not exist in the DAG, the
8652 /// input node is returned.  As a degenerate case, if you specify the same
8653 /// input operands as the node already has, the input node is returned.
8654 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8655   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8656 
8657   // Check to see if there is no change.
8658   if (Op == N->getOperand(0)) return N;
8659 
8660   // See if the modified node already exists.
8661   void *InsertPos = nullptr;
8662   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8663     return Existing;
8664 
8665   // Nope it doesn't.  Remove the node from its current place in the maps.
8666   if (InsertPos)
8667     if (!RemoveNodeFromCSEMaps(N))
8668       InsertPos = nullptr;
8669 
8670   // Now we update the operands.
8671   N->OperandList[0].set(Op);
8672 
8673   updateDivergence(N);
8674   // If this gets put into a CSE map, add it.
8675   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8676   return N;
8677 }
8678 
8679 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8680   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8681 
8682   // Check to see if there is no change.
8683   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8684     return N;   // No operands changed, just return the input node.
8685 
8686   // See if the modified node already exists.
8687   void *InsertPos = nullptr;
8688   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8689     return Existing;
8690 
8691   // Nope it doesn't.  Remove the node from its current place in the maps.
8692   if (InsertPos)
8693     if (!RemoveNodeFromCSEMaps(N))
8694       InsertPos = nullptr;
8695 
8696   // Now we update the operands.
8697   if (N->OperandList[0] != Op1)
8698     N->OperandList[0].set(Op1);
8699   if (N->OperandList[1] != Op2)
8700     N->OperandList[1].set(Op2);
8701 
8702   updateDivergence(N);
8703   // If this gets put into a CSE map, add it.
8704   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8705   return N;
8706 }
8707 
8708 SDNode *SelectionDAG::
8709 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8710   SDValue Ops[] = { Op1, Op2, Op3 };
8711   return UpdateNodeOperands(N, Ops);
8712 }
8713 
8714 SDNode *SelectionDAG::
8715 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8716                    SDValue Op3, SDValue Op4) {
8717   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8718   return UpdateNodeOperands(N, Ops);
8719 }
8720 
8721 SDNode *SelectionDAG::
8722 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8723                    SDValue Op3, SDValue Op4, SDValue Op5) {
8724   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8725   return UpdateNodeOperands(N, Ops);
8726 }
8727 
8728 SDNode *SelectionDAG::
8729 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8730   unsigned NumOps = Ops.size();
8731   assert(N->getNumOperands() == NumOps &&
8732          "Update with wrong number of operands");
8733 
8734   // If no operands changed just return the input node.
8735   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8736     return N;
8737 
8738   // See if the modified node already exists.
8739   void *InsertPos = nullptr;
8740   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8741     return Existing;
8742 
8743   // Nope it doesn't.  Remove the node from its current place in the maps.
8744   if (InsertPos)
8745     if (!RemoveNodeFromCSEMaps(N))
8746       InsertPos = nullptr;
8747 
8748   // Now we update the operands.
8749   for (unsigned i = 0; i != NumOps; ++i)
8750     if (N->OperandList[i] != Ops[i])
8751       N->OperandList[i].set(Ops[i]);
8752 
8753   updateDivergence(N);
8754   // If this gets put into a CSE map, add it.
8755   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8756   return N;
8757 }
8758 
8759 /// DropOperands - Release the operands and set this node to have
8760 /// zero operands.
8761 void SDNode::DropOperands() {
8762   // Unlike the code in MorphNodeTo that does this, we don't need to
8763   // watch for dead nodes here.
8764   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8765     SDUse &Use = *I++;
8766     Use.set(SDValue());
8767   }
8768 }
8769 
8770 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8771                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8772   if (NewMemRefs.empty()) {
8773     N->clearMemRefs();
8774     return;
8775   }
8776 
8777   // Check if we can avoid allocating by storing a single reference directly.
8778   if (NewMemRefs.size() == 1) {
8779     N->MemRefs = NewMemRefs[0];
8780     N->NumMemRefs = 1;
8781     return;
8782   }
8783 
8784   MachineMemOperand **MemRefsBuffer =
8785       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8786   llvm::copy(NewMemRefs, MemRefsBuffer);
8787   N->MemRefs = MemRefsBuffer;
8788   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8789 }
8790 
8791 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8792 /// machine opcode.
8793 ///
8794 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8795                                    EVT VT) {
8796   SDVTList VTs = getVTList(VT);
8797   return SelectNodeTo(N, MachineOpc, VTs, None);
8798 }
8799 
8800 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8801                                    EVT VT, SDValue Op1) {
8802   SDVTList VTs = getVTList(VT);
8803   SDValue Ops[] = { Op1 };
8804   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8805 }
8806 
8807 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8808                                    EVT VT, SDValue Op1,
8809                                    SDValue Op2) {
8810   SDVTList VTs = getVTList(VT);
8811   SDValue Ops[] = { Op1, Op2 };
8812   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8813 }
8814 
8815 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8816                                    EVT VT, SDValue Op1,
8817                                    SDValue Op2, SDValue Op3) {
8818   SDVTList VTs = getVTList(VT);
8819   SDValue Ops[] = { Op1, Op2, Op3 };
8820   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8821 }
8822 
8823 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8824                                    EVT VT, ArrayRef<SDValue> Ops) {
8825   SDVTList VTs = getVTList(VT);
8826   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8827 }
8828 
8829 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8830                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8831   SDVTList VTs = getVTList(VT1, VT2);
8832   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8833 }
8834 
8835 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8836                                    EVT VT1, EVT VT2) {
8837   SDVTList VTs = getVTList(VT1, VT2);
8838   return SelectNodeTo(N, MachineOpc, VTs, None);
8839 }
8840 
8841 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8842                                    EVT VT1, EVT VT2, EVT VT3,
8843                                    ArrayRef<SDValue> Ops) {
8844   SDVTList VTs = getVTList(VT1, VT2, VT3);
8845   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8846 }
8847 
8848 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8849                                    EVT VT1, EVT VT2,
8850                                    SDValue Op1, SDValue Op2) {
8851   SDVTList VTs = getVTList(VT1, VT2);
8852   SDValue Ops[] = { Op1, Op2 };
8853   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8854 }
8855 
8856 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8857                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8858   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8859   // Reset the NodeID to -1.
8860   New->setNodeId(-1);
8861   if (New != N) {
8862     ReplaceAllUsesWith(N, New);
8863     RemoveDeadNode(N);
8864   }
8865   return New;
8866 }
8867 
8868 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8869 /// the line number information on the merged node since it is not possible to
8870 /// preserve the information that operation is associated with multiple lines.
8871 /// This will make the debugger working better at -O0, were there is a higher
8872 /// probability having other instructions associated with that line.
8873 ///
8874 /// For IROrder, we keep the smaller of the two
8875 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8876   DebugLoc NLoc = N->getDebugLoc();
8877   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8878     N->setDebugLoc(DebugLoc());
8879   }
8880   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8881   N->setIROrder(Order);
8882   return N;
8883 }
8884 
8885 /// MorphNodeTo - This *mutates* the specified node to have the specified
8886 /// return type, opcode, and operands.
8887 ///
8888 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8889 /// node of the specified opcode and operands, it returns that node instead of
8890 /// the current one.  Note that the SDLoc need not be the same.
8891 ///
8892 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8893 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8894 /// node, and because it doesn't require CSE recalculation for any of
8895 /// the node's users.
8896 ///
8897 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8898 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8899 /// the legalizer which maintain worklists that would need to be updated when
8900 /// deleting things.
8901 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8902                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8903   // If an identical node already exists, use it.
8904   void *IP = nullptr;
8905   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8906     FoldingSetNodeID ID;
8907     AddNodeIDNode(ID, Opc, VTs, Ops);
8908     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8909       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8910   }
8911 
8912   if (!RemoveNodeFromCSEMaps(N))
8913     IP = nullptr;
8914 
8915   // Start the morphing.
8916   N->NodeType = Opc;
8917   N->ValueList = VTs.VTs;
8918   N->NumValues = VTs.NumVTs;
8919 
8920   // Clear the operands list, updating used nodes to remove this from their
8921   // use list.  Keep track of any operands that become dead as a result.
8922   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8923   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8924     SDUse &Use = *I++;
8925     SDNode *Used = Use.getNode();
8926     Use.set(SDValue());
8927     if (Used->use_empty())
8928       DeadNodeSet.insert(Used);
8929   }
8930 
8931   // For MachineNode, initialize the memory references information.
8932   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8933     MN->clearMemRefs();
8934 
8935   // Swap for an appropriately sized array from the recycler.
8936   removeOperands(N);
8937   createOperands(N, Ops);
8938 
8939   // Delete any nodes that are still dead after adding the uses for the
8940   // new operands.
8941   if (!DeadNodeSet.empty()) {
8942     SmallVector<SDNode *, 16> DeadNodes;
8943     for (SDNode *N : DeadNodeSet)
8944       if (N->use_empty())
8945         DeadNodes.push_back(N);
8946     RemoveDeadNodes(DeadNodes);
8947   }
8948 
8949   if (IP)
8950     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8951   return N;
8952 }
8953 
8954 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8955   unsigned OrigOpc = Node->getOpcode();
8956   unsigned NewOpc;
8957   switch (OrigOpc) {
8958   default:
8959     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8960 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8961   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8962 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8963   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8964 #include "llvm/IR/ConstrainedOps.def"
8965   }
8966 
8967   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8968 
8969   // We're taking this node out of the chain, so we need to re-link things.
8970   SDValue InputChain = Node->getOperand(0);
8971   SDValue OutputChain = SDValue(Node, 1);
8972   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8973 
8974   SmallVector<SDValue, 3> Ops;
8975   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8976     Ops.push_back(Node->getOperand(i));
8977 
8978   SDVTList VTs = getVTList(Node->getValueType(0));
8979   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8980 
8981   // MorphNodeTo can operate in two ways: if an existing node with the
8982   // specified operands exists, it can just return it.  Otherwise, it
8983   // updates the node in place to have the requested operands.
8984   if (Res == Node) {
8985     // If we updated the node in place, reset the node ID.  To the isel,
8986     // this should be just like a newly allocated machine node.
8987     Res->setNodeId(-1);
8988   } else {
8989     ReplaceAllUsesWith(Node, Res);
8990     RemoveDeadNode(Node);
8991   }
8992 
8993   return Res;
8994 }
8995 
8996 /// getMachineNode - These are used for target selectors to create a new node
8997 /// with specified return type(s), MachineInstr opcode, and operands.
8998 ///
8999 /// Note that getMachineNode returns the resultant node.  If there is already a
9000 /// node of the specified opcode and operands, it returns that node instead of
9001 /// the current one.
9002 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9003                                             EVT VT) {
9004   SDVTList VTs = getVTList(VT);
9005   return getMachineNode(Opcode, dl, VTs, None);
9006 }
9007 
9008 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9009                                             EVT VT, SDValue Op1) {
9010   SDVTList VTs = getVTList(VT);
9011   SDValue Ops[] = { Op1 };
9012   return getMachineNode(Opcode, dl, VTs, Ops);
9013 }
9014 
9015 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9016                                             EVT VT, SDValue Op1, SDValue Op2) {
9017   SDVTList VTs = getVTList(VT);
9018   SDValue Ops[] = { Op1, Op2 };
9019   return getMachineNode(Opcode, dl, VTs, Ops);
9020 }
9021 
9022 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9023                                             EVT VT, SDValue Op1, SDValue Op2,
9024                                             SDValue Op3) {
9025   SDVTList VTs = getVTList(VT);
9026   SDValue Ops[] = { Op1, Op2, Op3 };
9027   return getMachineNode(Opcode, dl, VTs, Ops);
9028 }
9029 
9030 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9031                                             EVT VT, ArrayRef<SDValue> Ops) {
9032   SDVTList VTs = getVTList(VT);
9033   return getMachineNode(Opcode, dl, VTs, Ops);
9034 }
9035 
9036 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9037                                             EVT VT1, EVT VT2, SDValue Op1,
9038                                             SDValue Op2) {
9039   SDVTList VTs = getVTList(VT1, VT2);
9040   SDValue Ops[] = { Op1, Op2 };
9041   return getMachineNode(Opcode, dl, VTs, Ops);
9042 }
9043 
9044 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9045                                             EVT VT1, EVT VT2, SDValue Op1,
9046                                             SDValue Op2, SDValue Op3) {
9047   SDVTList VTs = getVTList(VT1, VT2);
9048   SDValue Ops[] = { Op1, Op2, Op3 };
9049   return getMachineNode(Opcode, dl, VTs, Ops);
9050 }
9051 
9052 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9053                                             EVT VT1, EVT VT2,
9054                                             ArrayRef<SDValue> Ops) {
9055   SDVTList VTs = getVTList(VT1, VT2);
9056   return getMachineNode(Opcode, dl, VTs, Ops);
9057 }
9058 
9059 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9060                                             EVT VT1, EVT VT2, EVT VT3,
9061                                             SDValue Op1, SDValue Op2) {
9062   SDVTList VTs = getVTList(VT1, VT2, VT3);
9063   SDValue Ops[] = { Op1, Op2 };
9064   return getMachineNode(Opcode, dl, VTs, Ops);
9065 }
9066 
9067 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9068                                             EVT VT1, EVT VT2, EVT VT3,
9069                                             SDValue Op1, SDValue Op2,
9070                                             SDValue Op3) {
9071   SDVTList VTs = getVTList(VT1, VT2, VT3);
9072   SDValue Ops[] = { Op1, Op2, Op3 };
9073   return getMachineNode(Opcode, dl, VTs, Ops);
9074 }
9075 
9076 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9077                                             EVT VT1, EVT VT2, EVT VT3,
9078                                             ArrayRef<SDValue> Ops) {
9079   SDVTList VTs = getVTList(VT1, VT2, VT3);
9080   return getMachineNode(Opcode, dl, VTs, Ops);
9081 }
9082 
9083 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9084                                             ArrayRef<EVT> ResultTys,
9085                                             ArrayRef<SDValue> Ops) {
9086   SDVTList VTs = getVTList(ResultTys);
9087   return getMachineNode(Opcode, dl, VTs, Ops);
9088 }
9089 
9090 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9091                                             SDVTList VTs,
9092                                             ArrayRef<SDValue> Ops) {
9093   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9094   MachineSDNode *N;
9095   void *IP = nullptr;
9096 
9097   if (DoCSE) {
9098     FoldingSetNodeID ID;
9099     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9100     IP = nullptr;
9101     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9102       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9103     }
9104   }
9105 
9106   // Allocate a new MachineSDNode.
9107   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9108   createOperands(N, Ops);
9109 
9110   if (DoCSE)
9111     CSEMap.InsertNode(N, IP);
9112 
9113   InsertNode(N);
9114   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9115   return N;
9116 }
9117 
9118 /// getTargetExtractSubreg - A convenience function for creating
9119 /// TargetOpcode::EXTRACT_SUBREG nodes.
9120 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9121                                              SDValue Operand) {
9122   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9123   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9124                                   VT, Operand, SRIdxVal);
9125   return SDValue(Subreg, 0);
9126 }
9127 
9128 /// getTargetInsertSubreg - A convenience function for creating
9129 /// TargetOpcode::INSERT_SUBREG nodes.
9130 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9131                                             SDValue Operand, SDValue Subreg) {
9132   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9133   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9134                                   VT, Operand, Subreg, SRIdxVal);
9135   return SDValue(Result, 0);
9136 }
9137 
9138 /// getNodeIfExists - Get the specified node if it's already available, or
9139 /// else return NULL.
9140 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9141                                       ArrayRef<SDValue> Ops) {
9142   SDNodeFlags Flags;
9143   if (Inserter)
9144     Flags = Inserter->getFlags();
9145   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9146 }
9147 
9148 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9149                                       ArrayRef<SDValue> Ops,
9150                                       const SDNodeFlags Flags) {
9151   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9152     FoldingSetNodeID ID;
9153     AddNodeIDNode(ID, Opcode, VTList, Ops);
9154     void *IP = nullptr;
9155     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9156       E->intersectFlagsWith(Flags);
9157       return E;
9158     }
9159   }
9160   return nullptr;
9161 }
9162 
9163 /// doesNodeExist - Check if a node exists without modifying its flags.
9164 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9165                                  ArrayRef<SDValue> Ops) {
9166   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9167     FoldingSetNodeID ID;
9168     AddNodeIDNode(ID, Opcode, VTList, Ops);
9169     void *IP = nullptr;
9170     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9171       return true;
9172   }
9173   return false;
9174 }
9175 
9176 /// getDbgValue - Creates a SDDbgValue node.
9177 ///
9178 /// SDNode
9179 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9180                                       SDNode *N, unsigned R, bool IsIndirect,
9181                                       const DebugLoc &DL, unsigned O) {
9182   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9183          "Expected inlined-at fields to agree");
9184   return new (DbgInfo->getAlloc())
9185       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9186                  {}, IsIndirect, DL, O,
9187                  /*IsVariadic=*/false);
9188 }
9189 
9190 /// Constant
9191 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9192                                               DIExpression *Expr,
9193                                               const Value *C,
9194                                               const DebugLoc &DL, unsigned O) {
9195   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9196          "Expected inlined-at fields to agree");
9197   return new (DbgInfo->getAlloc())
9198       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9199                  /*IsIndirect=*/false, DL, O,
9200                  /*IsVariadic=*/false);
9201 }
9202 
9203 /// FrameIndex
9204 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9205                                                 DIExpression *Expr, unsigned FI,
9206                                                 bool IsIndirect,
9207                                                 const DebugLoc &DL,
9208                                                 unsigned O) {
9209   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9210          "Expected inlined-at fields to agree");
9211   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9212 }
9213 
9214 /// FrameIndex with dependencies
9215 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9216                                                 DIExpression *Expr, unsigned FI,
9217                                                 ArrayRef<SDNode *> Dependencies,
9218                                                 bool IsIndirect,
9219                                                 const DebugLoc &DL,
9220                                                 unsigned O) {
9221   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9222          "Expected inlined-at fields to agree");
9223   return new (DbgInfo->getAlloc())
9224       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9225                  Dependencies, IsIndirect, DL, O,
9226                  /*IsVariadic=*/false);
9227 }
9228 
9229 /// VReg
9230 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9231                                           unsigned VReg, bool IsIndirect,
9232                                           const DebugLoc &DL, unsigned O) {
9233   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9234          "Expected inlined-at fields to agree");
9235   return new (DbgInfo->getAlloc())
9236       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9237                  {}, IsIndirect, DL, O,
9238                  /*IsVariadic=*/false);
9239 }
9240 
9241 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9242                                           ArrayRef<SDDbgOperand> Locs,
9243                                           ArrayRef<SDNode *> Dependencies,
9244                                           bool IsIndirect, const DebugLoc &DL,
9245                                           unsigned O, bool IsVariadic) {
9246   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9247          "Expected inlined-at fields to agree");
9248   return new (DbgInfo->getAlloc())
9249       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9250                  DL, O, IsVariadic);
9251 }
9252 
9253 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9254                                      unsigned OffsetInBits, unsigned SizeInBits,
9255                                      bool InvalidateDbg) {
9256   SDNode *FromNode = From.getNode();
9257   SDNode *ToNode = To.getNode();
9258   assert(FromNode && ToNode && "Can't modify dbg values");
9259 
9260   // PR35338
9261   // TODO: assert(From != To && "Redundant dbg value transfer");
9262   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9263   if (From == To || FromNode == ToNode)
9264     return;
9265 
9266   if (!FromNode->getHasDebugValue())
9267     return;
9268 
9269   SDDbgOperand FromLocOp =
9270       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9271   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9272 
9273   SmallVector<SDDbgValue *, 2> ClonedDVs;
9274   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9275     if (Dbg->isInvalidated())
9276       continue;
9277 
9278     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9279 
9280     // Create a new location ops vector that is equal to the old vector, but
9281     // with each instance of FromLocOp replaced with ToLocOp.
9282     bool Changed = false;
9283     auto NewLocOps = Dbg->copyLocationOps();
9284     std::replace_if(
9285         NewLocOps.begin(), NewLocOps.end(),
9286         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9287           bool Match = Op == FromLocOp;
9288           Changed |= Match;
9289           return Match;
9290         },
9291         ToLocOp);
9292     // Ignore this SDDbgValue if we didn't find a matching location.
9293     if (!Changed)
9294       continue;
9295 
9296     DIVariable *Var = Dbg->getVariable();
9297     auto *Expr = Dbg->getExpression();
9298     // If a fragment is requested, update the expression.
9299     if (SizeInBits) {
9300       // When splitting a larger (e.g., sign-extended) value whose
9301       // lower bits are described with an SDDbgValue, do not attempt
9302       // to transfer the SDDbgValue to the upper bits.
9303       if (auto FI = Expr->getFragmentInfo())
9304         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9305           continue;
9306       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9307                                                              SizeInBits);
9308       if (!Fragment)
9309         continue;
9310       Expr = *Fragment;
9311     }
9312 
9313     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9314     // Clone the SDDbgValue and move it to To.
9315     SDDbgValue *Clone = getDbgValueList(
9316         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9317         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9318         Dbg->isVariadic());
9319     ClonedDVs.push_back(Clone);
9320 
9321     if (InvalidateDbg) {
9322       // Invalidate value and indicate the SDDbgValue should not be emitted.
9323       Dbg->setIsInvalidated();
9324       Dbg->setIsEmitted();
9325     }
9326   }
9327 
9328   for (SDDbgValue *Dbg : ClonedDVs) {
9329     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9330            "Transferred DbgValues should depend on the new SDNode");
9331     AddDbgValue(Dbg, false);
9332   }
9333 }
9334 
9335 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9336   if (!N.getHasDebugValue())
9337     return;
9338 
9339   SmallVector<SDDbgValue *, 2> ClonedDVs;
9340   for (auto DV : GetDbgValues(&N)) {
9341     if (DV->isInvalidated())
9342       continue;
9343     switch (N.getOpcode()) {
9344     default:
9345       break;
9346     case ISD::ADD:
9347       SDValue N0 = N.getOperand(0);
9348       SDValue N1 = N.getOperand(1);
9349       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9350           isConstantIntBuildVectorOrConstantInt(N1)) {
9351         uint64_t Offset = N.getConstantOperandVal(1);
9352 
9353         // Rewrite an ADD constant node into a DIExpression. Since we are
9354         // performing arithmetic to compute the variable's *value* in the
9355         // DIExpression, we need to mark the expression with a
9356         // DW_OP_stack_value.
9357         auto *DIExpr = DV->getExpression();
9358         auto NewLocOps = DV->copyLocationOps();
9359         bool Changed = false;
9360         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9361           // We're not given a ResNo to compare against because the whole
9362           // node is going away. We know that any ISD::ADD only has one
9363           // result, so we can assume any node match is using the result.
9364           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9365               NewLocOps[i].getSDNode() != &N)
9366             continue;
9367           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9368           SmallVector<uint64_t, 3> ExprOps;
9369           DIExpression::appendOffset(ExprOps, Offset);
9370           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9371           Changed = true;
9372         }
9373         (void)Changed;
9374         assert(Changed && "Salvage target doesn't use N");
9375 
9376         auto AdditionalDependencies = DV->getAdditionalDependencies();
9377         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9378                                             NewLocOps, AdditionalDependencies,
9379                                             DV->isIndirect(), DV->getDebugLoc(),
9380                                             DV->getOrder(), DV->isVariadic());
9381         ClonedDVs.push_back(Clone);
9382         DV->setIsInvalidated();
9383         DV->setIsEmitted();
9384         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9385                    N0.getNode()->dumprFull(this);
9386                    dbgs() << " into " << *DIExpr << '\n');
9387       }
9388     }
9389   }
9390 
9391   for (SDDbgValue *Dbg : ClonedDVs) {
9392     assert(!Dbg->getSDNodes().empty() &&
9393            "Salvaged DbgValue should depend on a new SDNode");
9394     AddDbgValue(Dbg, false);
9395   }
9396 }
9397 
9398 /// Creates a SDDbgLabel node.
9399 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9400                                       const DebugLoc &DL, unsigned O) {
9401   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9402          "Expected inlined-at fields to agree");
9403   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9404 }
9405 
9406 namespace {
9407 
9408 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9409 /// pointed to by a use iterator is deleted, increment the use iterator
9410 /// so that it doesn't dangle.
9411 ///
9412 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9413   SDNode::use_iterator &UI;
9414   SDNode::use_iterator &UE;
9415 
9416   void NodeDeleted(SDNode *N, SDNode *E) override {
9417     // Increment the iterator as needed.
9418     while (UI != UE && N == *UI)
9419       ++UI;
9420   }
9421 
9422 public:
9423   RAUWUpdateListener(SelectionDAG &d,
9424                      SDNode::use_iterator &ui,
9425                      SDNode::use_iterator &ue)
9426     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9427 };
9428 
9429 } // end anonymous namespace
9430 
9431 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9432 /// This can cause recursive merging of nodes in the DAG.
9433 ///
9434 /// This version assumes From has a single result value.
9435 ///
9436 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9437   SDNode *From = FromN.getNode();
9438   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9439          "Cannot replace with this method!");
9440   assert(From != To.getNode() && "Cannot replace uses of with self");
9441 
9442   // Preserve Debug Values
9443   transferDbgValues(FromN, To);
9444 
9445   // Iterate over all the existing uses of From. New uses will be added
9446   // to the beginning of the use list, which we avoid visiting.
9447   // This specifically avoids visiting uses of From that arise while the
9448   // replacement is happening, because any such uses would be the result
9449   // of CSE: If an existing node looks like From after one of its operands
9450   // is replaced by To, we don't want to replace of all its users with To
9451   // too. See PR3018 for more info.
9452   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9453   RAUWUpdateListener Listener(*this, UI, UE);
9454   while (UI != UE) {
9455     SDNode *User = *UI;
9456 
9457     // This node is about to morph, remove its old self from the CSE maps.
9458     RemoveNodeFromCSEMaps(User);
9459 
9460     // A user can appear in a use list multiple times, and when this
9461     // happens the uses are usually next to each other in the list.
9462     // To help reduce the number of CSE recomputations, process all
9463     // the uses of this user that we can find this way.
9464     do {
9465       SDUse &Use = UI.getUse();
9466       ++UI;
9467       Use.set(To);
9468       if (To->isDivergent() != From->isDivergent())
9469         updateDivergence(User);
9470     } while (UI != UE && *UI == User);
9471     // Now that we have modified User, add it back to the CSE maps.  If it
9472     // already exists there, recursively merge the results together.
9473     AddModifiedNodeToCSEMaps(User);
9474   }
9475 
9476   // If we just RAUW'd the root, take note.
9477   if (FromN == getRoot())
9478     setRoot(To);
9479 }
9480 
9481 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9482 /// This can cause recursive merging of nodes in the DAG.
9483 ///
9484 /// This version assumes that for each value of From, there is a
9485 /// corresponding value in To in the same position with the same type.
9486 ///
9487 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9488 #ifndef NDEBUG
9489   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9490     assert((!From->hasAnyUseOfValue(i) ||
9491             From->getValueType(i) == To->getValueType(i)) &&
9492            "Cannot use this version of ReplaceAllUsesWith!");
9493 #endif
9494 
9495   // Handle the trivial case.
9496   if (From == To)
9497     return;
9498 
9499   // Preserve Debug Info. Only do this if there's a use.
9500   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9501     if (From->hasAnyUseOfValue(i)) {
9502       assert((i < To->getNumValues()) && "Invalid To location");
9503       transferDbgValues(SDValue(From, i), SDValue(To, i));
9504     }
9505 
9506   // Iterate over just the existing users of From. See the comments in
9507   // the ReplaceAllUsesWith above.
9508   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9509   RAUWUpdateListener Listener(*this, UI, UE);
9510   while (UI != UE) {
9511     SDNode *User = *UI;
9512 
9513     // This node is about to morph, remove its old self from the CSE maps.
9514     RemoveNodeFromCSEMaps(User);
9515 
9516     // A user can appear in a use list multiple times, and when this
9517     // happens the uses are usually next to each other in the list.
9518     // To help reduce the number of CSE recomputations, process all
9519     // the uses of this user that we can find this way.
9520     do {
9521       SDUse &Use = UI.getUse();
9522       ++UI;
9523       Use.setNode(To);
9524       if (To->isDivergent() != From->isDivergent())
9525         updateDivergence(User);
9526     } while (UI != UE && *UI == User);
9527 
9528     // Now that we have modified User, add it back to the CSE maps.  If it
9529     // already exists there, recursively merge the results together.
9530     AddModifiedNodeToCSEMaps(User);
9531   }
9532 
9533   // If we just RAUW'd the root, take note.
9534   if (From == getRoot().getNode())
9535     setRoot(SDValue(To, getRoot().getResNo()));
9536 }
9537 
9538 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9539 /// This can cause recursive merging of nodes in the DAG.
9540 ///
9541 /// This version can replace From with any result values.  To must match the
9542 /// number and types of values returned by From.
9543 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9544   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9545     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9546 
9547   // Preserve Debug Info.
9548   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9549     transferDbgValues(SDValue(From, i), To[i]);
9550 
9551   // Iterate over just the existing users of From. See the comments in
9552   // the ReplaceAllUsesWith above.
9553   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9554   RAUWUpdateListener Listener(*this, UI, UE);
9555   while (UI != UE) {
9556     SDNode *User = *UI;
9557 
9558     // This node is about to morph, remove its old self from the CSE maps.
9559     RemoveNodeFromCSEMaps(User);
9560 
9561     // A user can appear in a use list multiple times, and when this happens the
9562     // uses are usually next to each other in the list.  To help reduce the
9563     // number of CSE and divergence recomputations, process all the uses of this
9564     // user that we can find this way.
9565     bool To_IsDivergent = false;
9566     do {
9567       SDUse &Use = UI.getUse();
9568       const SDValue &ToOp = To[Use.getResNo()];
9569       ++UI;
9570       Use.set(ToOp);
9571       To_IsDivergent |= ToOp->isDivergent();
9572     } while (UI != UE && *UI == User);
9573 
9574     if (To_IsDivergent != From->isDivergent())
9575       updateDivergence(User);
9576 
9577     // Now that we have modified User, add it back to the CSE maps.  If it
9578     // already exists there, recursively merge the results together.
9579     AddModifiedNodeToCSEMaps(User);
9580   }
9581 
9582   // If we just RAUW'd the root, take note.
9583   if (From == getRoot().getNode())
9584     setRoot(SDValue(To[getRoot().getResNo()]));
9585 }
9586 
9587 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9588 /// uses of other values produced by From.getNode() alone.  The Deleted
9589 /// vector is handled the same way as for ReplaceAllUsesWith.
9590 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9591   // Handle the really simple, really trivial case efficiently.
9592   if (From == To) return;
9593 
9594   // Handle the simple, trivial, case efficiently.
9595   if (From.getNode()->getNumValues() == 1) {
9596     ReplaceAllUsesWith(From, To);
9597     return;
9598   }
9599 
9600   // Preserve Debug Info.
9601   transferDbgValues(From, To);
9602 
9603   // Iterate over just the existing users of From. See the comments in
9604   // the ReplaceAllUsesWith above.
9605   SDNode::use_iterator UI = From.getNode()->use_begin(),
9606                        UE = From.getNode()->use_end();
9607   RAUWUpdateListener Listener(*this, UI, UE);
9608   while (UI != UE) {
9609     SDNode *User = *UI;
9610     bool UserRemovedFromCSEMaps = false;
9611 
9612     // A user can appear in a use list multiple times, and when this
9613     // happens the uses are usually next to each other in the list.
9614     // To help reduce the number of CSE recomputations, process all
9615     // the uses of this user that we can find this way.
9616     do {
9617       SDUse &Use = UI.getUse();
9618 
9619       // Skip uses of different values from the same node.
9620       if (Use.getResNo() != From.getResNo()) {
9621         ++UI;
9622         continue;
9623       }
9624 
9625       // If this node hasn't been modified yet, it's still in the CSE maps,
9626       // so remove its old self from the CSE maps.
9627       if (!UserRemovedFromCSEMaps) {
9628         RemoveNodeFromCSEMaps(User);
9629         UserRemovedFromCSEMaps = true;
9630       }
9631 
9632       ++UI;
9633       Use.set(To);
9634       if (To->isDivergent() != From->isDivergent())
9635         updateDivergence(User);
9636     } while (UI != UE && *UI == User);
9637     // We are iterating over all uses of the From node, so if a use
9638     // doesn't use the specific value, no changes are made.
9639     if (!UserRemovedFromCSEMaps)
9640       continue;
9641 
9642     // Now that we have modified User, add it back to the CSE maps.  If it
9643     // already exists there, recursively merge the results together.
9644     AddModifiedNodeToCSEMaps(User);
9645   }
9646 
9647   // If we just RAUW'd the root, take note.
9648   if (From == getRoot())
9649     setRoot(To);
9650 }
9651 
9652 namespace {
9653 
9654   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9655   /// to record information about a use.
9656   struct UseMemo {
9657     SDNode *User;
9658     unsigned Index;
9659     SDUse *Use;
9660   };
9661 
9662   /// operator< - Sort Memos by User.
9663   bool operator<(const UseMemo &L, const UseMemo &R) {
9664     return (intptr_t)L.User < (intptr_t)R.User;
9665   }
9666 
9667 } // end anonymous namespace
9668 
9669 bool SelectionDAG::calculateDivergence(SDNode *N) {
9670   if (TLI->isSDNodeAlwaysUniform(N)) {
9671     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9672            "Conflicting divergence information!");
9673     return false;
9674   }
9675   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9676     return true;
9677   for (auto &Op : N->ops()) {
9678     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9679       return true;
9680   }
9681   return false;
9682 }
9683 
9684 void SelectionDAG::updateDivergence(SDNode *N) {
9685   SmallVector<SDNode *, 16> Worklist(1, N);
9686   do {
9687     N = Worklist.pop_back_val();
9688     bool IsDivergent = calculateDivergence(N);
9689     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9690       N->SDNodeBits.IsDivergent = IsDivergent;
9691       llvm::append_range(Worklist, N->uses());
9692     }
9693   } while (!Worklist.empty());
9694 }
9695 
9696 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9697   DenseMap<SDNode *, unsigned> Degree;
9698   Order.reserve(AllNodes.size());
9699   for (auto &N : allnodes()) {
9700     unsigned NOps = N.getNumOperands();
9701     Degree[&N] = NOps;
9702     if (0 == NOps)
9703       Order.push_back(&N);
9704   }
9705   for (size_t I = 0; I != Order.size(); ++I) {
9706     SDNode *N = Order[I];
9707     for (auto U : N->uses()) {
9708       unsigned &UnsortedOps = Degree[U];
9709       if (0 == --UnsortedOps)
9710         Order.push_back(U);
9711     }
9712   }
9713 }
9714 
9715 #ifndef NDEBUG
9716 void SelectionDAG::VerifyDAGDivergence() {
9717   std::vector<SDNode *> TopoOrder;
9718   CreateTopologicalOrder(TopoOrder);
9719   for (auto *N : TopoOrder) {
9720     assert(calculateDivergence(N) == N->isDivergent() &&
9721            "Divergence bit inconsistency detected");
9722   }
9723 }
9724 #endif
9725 
9726 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9727 /// uses of other values produced by From.getNode() alone.  The same value
9728 /// may appear in both the From and To list.  The Deleted vector is
9729 /// handled the same way as for ReplaceAllUsesWith.
9730 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9731                                               const SDValue *To,
9732                                               unsigned Num){
9733   // Handle the simple, trivial case efficiently.
9734   if (Num == 1)
9735     return ReplaceAllUsesOfValueWith(*From, *To);
9736 
9737   transferDbgValues(*From, *To);
9738 
9739   // Read up all the uses and make records of them. This helps
9740   // processing new uses that are introduced during the
9741   // replacement process.
9742   SmallVector<UseMemo, 4> Uses;
9743   for (unsigned i = 0; i != Num; ++i) {
9744     unsigned FromResNo = From[i].getResNo();
9745     SDNode *FromNode = From[i].getNode();
9746     for (SDNode::use_iterator UI = FromNode->use_begin(),
9747          E = FromNode->use_end(); UI != E; ++UI) {
9748       SDUse &Use = UI.getUse();
9749       if (Use.getResNo() == FromResNo) {
9750         UseMemo Memo = { *UI, i, &Use };
9751         Uses.push_back(Memo);
9752       }
9753     }
9754   }
9755 
9756   // Sort the uses, so that all the uses from a given User are together.
9757   llvm::sort(Uses);
9758 
9759   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9760        UseIndex != UseIndexEnd; ) {
9761     // We know that this user uses some value of From.  If it is the right
9762     // value, update it.
9763     SDNode *User = Uses[UseIndex].User;
9764 
9765     // This node is about to morph, remove its old self from the CSE maps.
9766     RemoveNodeFromCSEMaps(User);
9767 
9768     // The Uses array is sorted, so all the uses for a given User
9769     // are next to each other in the list.
9770     // To help reduce the number of CSE recomputations, process all
9771     // the uses of this user that we can find this way.
9772     do {
9773       unsigned i = Uses[UseIndex].Index;
9774       SDUse &Use = *Uses[UseIndex].Use;
9775       ++UseIndex;
9776 
9777       Use.set(To[i]);
9778     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9779 
9780     // Now that we have modified User, add it back to the CSE maps.  If it
9781     // already exists there, recursively merge the results together.
9782     AddModifiedNodeToCSEMaps(User);
9783   }
9784 }
9785 
9786 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9787 /// based on their topological order. It returns the maximum id and a vector
9788 /// of the SDNodes* in assigned order by reference.
9789 unsigned SelectionDAG::AssignTopologicalOrder() {
9790   unsigned DAGSize = 0;
9791 
9792   // SortedPos tracks the progress of the algorithm. Nodes before it are
9793   // sorted, nodes after it are unsorted. When the algorithm completes
9794   // it is at the end of the list.
9795   allnodes_iterator SortedPos = allnodes_begin();
9796 
9797   // Visit all the nodes. Move nodes with no operands to the front of
9798   // the list immediately. Annotate nodes that do have operands with their
9799   // operand count. Before we do this, the Node Id fields of the nodes
9800   // may contain arbitrary values. After, the Node Id fields for nodes
9801   // before SortedPos will contain the topological sort index, and the
9802   // Node Id fields for nodes At SortedPos and after will contain the
9803   // count of outstanding operands.
9804   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
9805     checkForCycles(&N, this);
9806     unsigned Degree = N.getNumOperands();
9807     if (Degree == 0) {
9808       // A node with no uses, add it to the result array immediately.
9809       N.setNodeId(DAGSize++);
9810       allnodes_iterator Q(&N);
9811       if (Q != SortedPos)
9812         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9813       assert(SortedPos != AllNodes.end() && "Overran node list");
9814       ++SortedPos;
9815     } else {
9816       // Temporarily use the Node Id as scratch space for the degree count.
9817       N.setNodeId(Degree);
9818     }
9819   }
9820 
9821   // Visit all the nodes. As we iterate, move nodes into sorted order,
9822   // such that by the time the end is reached all nodes will be sorted.
9823   for (SDNode &Node : allnodes()) {
9824     SDNode *N = &Node;
9825     checkForCycles(N, this);
9826     // N is in sorted position, so all its uses have one less operand
9827     // that needs to be sorted.
9828     for (SDNode *P : N->uses()) {
9829       unsigned Degree = P->getNodeId();
9830       assert(Degree != 0 && "Invalid node degree");
9831       --Degree;
9832       if (Degree == 0) {
9833         // All of P's operands are sorted, so P may sorted now.
9834         P->setNodeId(DAGSize++);
9835         if (P->getIterator() != SortedPos)
9836           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9837         assert(SortedPos != AllNodes.end() && "Overran node list");
9838         ++SortedPos;
9839       } else {
9840         // Update P's outstanding operand count.
9841         P->setNodeId(Degree);
9842       }
9843     }
9844     if (Node.getIterator() == SortedPos) {
9845 #ifndef NDEBUG
9846       allnodes_iterator I(N);
9847       SDNode *S = &*++I;
9848       dbgs() << "Overran sorted position:\n";
9849       S->dumprFull(this); dbgs() << "\n";
9850       dbgs() << "Checking if this is due to cycles\n";
9851       checkForCycles(this, true);
9852 #endif
9853       llvm_unreachable(nullptr);
9854     }
9855   }
9856 
9857   assert(SortedPos == AllNodes.end() &&
9858          "Topological sort incomplete!");
9859   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9860          "First node in topological sort is not the entry token!");
9861   assert(AllNodes.front().getNodeId() == 0 &&
9862          "First node in topological sort has non-zero id!");
9863   assert(AllNodes.front().getNumOperands() == 0 &&
9864          "First node in topological sort has operands!");
9865   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9866          "Last node in topologic sort has unexpected id!");
9867   assert(AllNodes.back().use_empty() &&
9868          "Last node in topologic sort has users!");
9869   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9870   return DAGSize;
9871 }
9872 
9873 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9874 /// value is produced by SD.
9875 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9876   for (SDNode *SD : DB->getSDNodes()) {
9877     if (!SD)
9878       continue;
9879     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9880     SD->setHasDebugValue(true);
9881   }
9882   DbgInfo->add(DB, isParameter);
9883 }
9884 
9885 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9886 
9887 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9888                                                    SDValue NewMemOpChain) {
9889   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9890   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9891   // The new memory operation must have the same position as the old load in
9892   // terms of memory dependency. Create a TokenFactor for the old load and new
9893   // memory operation and update uses of the old load's output chain to use that
9894   // TokenFactor.
9895   if (OldChain == NewMemOpChain || OldChain.use_empty())
9896     return NewMemOpChain;
9897 
9898   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9899                                 OldChain, NewMemOpChain);
9900   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9901   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9902   return TokenFactor;
9903 }
9904 
9905 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9906                                                    SDValue NewMemOp) {
9907   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9908   SDValue OldChain = SDValue(OldLoad, 1);
9909   SDValue NewMemOpChain = NewMemOp.getValue(1);
9910   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9911 }
9912 
9913 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9914                                                      Function **OutFunction) {
9915   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9916 
9917   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9918   auto *Module = MF->getFunction().getParent();
9919   auto *Function = Module->getFunction(Symbol);
9920 
9921   if (OutFunction != nullptr)
9922       *OutFunction = Function;
9923 
9924   if (Function != nullptr) {
9925     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9926     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9927   }
9928 
9929   std::string ErrorStr;
9930   raw_string_ostream ErrorFormatter(ErrorStr);
9931   ErrorFormatter << "Undefined external symbol ";
9932   ErrorFormatter << '"' << Symbol << '"';
9933   report_fatal_error(Twine(ErrorFormatter.str()));
9934 }
9935 
9936 //===----------------------------------------------------------------------===//
9937 //                              SDNode Class
9938 //===----------------------------------------------------------------------===//
9939 
9940 bool llvm::isNullConstant(SDValue V) {
9941   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9942   return Const != nullptr && Const->isZero();
9943 }
9944 
9945 bool llvm::isNullFPConstant(SDValue V) {
9946   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9947   return Const != nullptr && Const->isZero() && !Const->isNegative();
9948 }
9949 
9950 bool llvm::isAllOnesConstant(SDValue V) {
9951   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9952   return Const != nullptr && Const->isAllOnes();
9953 }
9954 
9955 bool llvm::isOneConstant(SDValue V) {
9956   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9957   return Const != nullptr && Const->isOne();
9958 }
9959 
9960 SDValue llvm::peekThroughBitcasts(SDValue V) {
9961   while (V.getOpcode() == ISD::BITCAST)
9962     V = V.getOperand(0);
9963   return V;
9964 }
9965 
9966 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9967   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9968     V = V.getOperand(0);
9969   return V;
9970 }
9971 
9972 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9973   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9974     V = V.getOperand(0);
9975   return V;
9976 }
9977 
9978 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9979   if (V.getOpcode() != ISD::XOR)
9980     return false;
9981   V = peekThroughBitcasts(V.getOperand(1));
9982   unsigned NumBits = V.getScalarValueSizeInBits();
9983   ConstantSDNode *C =
9984       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9985   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9986 }
9987 
9988 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9989                                           bool AllowTruncation) {
9990   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9991     return CN;
9992 
9993   // SplatVectors can truncate their operands. Ignore that case here unless
9994   // AllowTruncation is set.
9995   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9996     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9997     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9998       EVT CVT = CN->getValueType(0);
9999       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10000       if (AllowTruncation || CVT == VecEltVT)
10001         return CN;
10002     }
10003   }
10004 
10005   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10006     BitVector UndefElements;
10007     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10008 
10009     // BuildVectors can truncate their operands. Ignore that case here unless
10010     // AllowTruncation is set.
10011     if (CN && (UndefElements.none() || AllowUndefs)) {
10012       EVT CVT = CN->getValueType(0);
10013       EVT NSVT = N.getValueType().getScalarType();
10014       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10015       if (AllowTruncation || (CVT == NSVT))
10016         return CN;
10017     }
10018   }
10019 
10020   return nullptr;
10021 }
10022 
10023 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10024                                           bool AllowUndefs,
10025                                           bool AllowTruncation) {
10026   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10027     return CN;
10028 
10029   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10030     BitVector UndefElements;
10031     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10032 
10033     // BuildVectors can truncate their operands. Ignore that case here unless
10034     // AllowTruncation is set.
10035     if (CN && (UndefElements.none() || AllowUndefs)) {
10036       EVT CVT = CN->getValueType(0);
10037       EVT NSVT = N.getValueType().getScalarType();
10038       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10039       if (AllowTruncation || (CVT == NSVT))
10040         return CN;
10041     }
10042   }
10043 
10044   return nullptr;
10045 }
10046 
10047 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10048   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10049     return CN;
10050 
10051   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10052     BitVector UndefElements;
10053     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10054     if (CN && (UndefElements.none() || AllowUndefs))
10055       return CN;
10056   }
10057 
10058   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10059     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10060       return CN;
10061 
10062   return nullptr;
10063 }
10064 
10065 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10066                                               const APInt &DemandedElts,
10067                                               bool AllowUndefs) {
10068   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10069     return CN;
10070 
10071   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10072     BitVector UndefElements;
10073     ConstantFPSDNode *CN =
10074         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10075     if (CN && (UndefElements.none() || AllowUndefs))
10076       return CN;
10077   }
10078 
10079   return nullptr;
10080 }
10081 
10082 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10083   // TODO: may want to use peekThroughBitcast() here.
10084   ConstantSDNode *C =
10085       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10086   return C && C->isZero();
10087 }
10088 
10089 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10090   // TODO: may want to use peekThroughBitcast() here.
10091   unsigned BitWidth = N.getScalarValueSizeInBits();
10092   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10093   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10094 }
10095 
10096 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10097   N = peekThroughBitcasts(N);
10098   unsigned BitWidth = N.getScalarValueSizeInBits();
10099   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10100   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10101 }
10102 
10103 HandleSDNode::~HandleSDNode() {
10104   DropOperands();
10105 }
10106 
10107 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10108                                          const DebugLoc &DL,
10109                                          const GlobalValue *GA, EVT VT,
10110                                          int64_t o, unsigned TF)
10111     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10112   TheGlobal = GA;
10113 }
10114 
10115 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10116                                          EVT VT, unsigned SrcAS,
10117                                          unsigned DestAS)
10118     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10119       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10120 
10121 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10122                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10123     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10124   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10125   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10126   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10127   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10128 
10129   // We check here that the size of the memory operand fits within the size of
10130   // the MMO. This is because the MMO might indicate only a possible address
10131   // range instead of specifying the affected memory addresses precisely.
10132   // TODO: Make MachineMemOperands aware of scalable vectors.
10133   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10134          "Size mismatch!");
10135 }
10136 
10137 /// Profile - Gather unique data for the node.
10138 ///
10139 void SDNode::Profile(FoldingSetNodeID &ID) const {
10140   AddNodeIDNode(ID, this);
10141 }
10142 
10143 namespace {
10144 
10145   struct EVTArray {
10146     std::vector<EVT> VTs;
10147 
10148     EVTArray() {
10149       VTs.reserve(MVT::VALUETYPE_SIZE);
10150       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10151         VTs.push_back(MVT((MVT::SimpleValueType)i));
10152     }
10153   };
10154 
10155 } // end anonymous namespace
10156 
10157 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10158 static ManagedStatic<EVTArray> SimpleVTArray;
10159 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10160 
10161 /// getValueTypeList - Return a pointer to the specified value type.
10162 ///
10163 const EVT *SDNode::getValueTypeList(EVT VT) {
10164   if (VT.isExtended()) {
10165     sys::SmartScopedLock<true> Lock(*VTMutex);
10166     return &(*EVTs->insert(VT).first);
10167   }
10168   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10169   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10170 }
10171 
10172 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10173 /// indicated value.  This method ignores uses of other values defined by this
10174 /// operation.
10175 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10176   assert(Value < getNumValues() && "Bad value!");
10177 
10178   // TODO: Only iterate over uses of a given value of the node
10179   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10180     if (UI.getUse().getResNo() == Value) {
10181       if (NUses == 0)
10182         return false;
10183       --NUses;
10184     }
10185   }
10186 
10187   // Found exactly the right number of uses?
10188   return NUses == 0;
10189 }
10190 
10191 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10192 /// value. This method ignores uses of other values defined by this operation.
10193 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10194   assert(Value < getNumValues() && "Bad value!");
10195 
10196   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10197     if (UI.getUse().getResNo() == Value)
10198       return true;
10199 
10200   return false;
10201 }
10202 
10203 /// isOnlyUserOf - Return true if this node is the only use of N.
10204 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10205   bool Seen = false;
10206   for (const SDNode *User : N->uses()) {
10207     if (User == this)
10208       Seen = true;
10209     else
10210       return false;
10211   }
10212 
10213   return Seen;
10214 }
10215 
10216 /// Return true if the only users of N are contained in Nodes.
10217 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10218   bool Seen = false;
10219   for (const SDNode *User : N->uses()) {
10220     if (llvm::is_contained(Nodes, User))
10221       Seen = true;
10222     else
10223       return false;
10224   }
10225 
10226   return Seen;
10227 }
10228 
10229 /// isOperand - Return true if this node is an operand of N.
10230 bool SDValue::isOperandOf(const SDNode *N) const {
10231   return is_contained(N->op_values(), *this);
10232 }
10233 
10234 bool SDNode::isOperandOf(const SDNode *N) const {
10235   return any_of(N->op_values(),
10236                 [this](SDValue Op) { return this == Op.getNode(); });
10237 }
10238 
10239 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10240 /// be a chain) reaches the specified operand without crossing any
10241 /// side-effecting instructions on any chain path.  In practice, this looks
10242 /// through token factors and non-volatile loads.  In order to remain efficient,
10243 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10244 ///
10245 /// Note that we only need to examine chains when we're searching for
10246 /// side-effects; SelectionDAG requires that all side-effects are represented
10247 /// by chains, even if another operand would force a specific ordering. This
10248 /// constraint is necessary to allow transformations like splitting loads.
10249 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10250                                              unsigned Depth) const {
10251   if (*this == Dest) return true;
10252 
10253   // Don't search too deeply, we just want to be able to see through
10254   // TokenFactor's etc.
10255   if (Depth == 0) return false;
10256 
10257   // If this is a token factor, all inputs to the TF happen in parallel.
10258   if (getOpcode() == ISD::TokenFactor) {
10259     // First, try a shallow search.
10260     if (is_contained((*this)->ops(), Dest)) {
10261       // We found the chain we want as an operand of this TokenFactor.
10262       // Essentially, we reach the chain without side-effects if we could
10263       // serialize the TokenFactor into a simple chain of operations with
10264       // Dest as the last operation. This is automatically true if the
10265       // chain has one use: there are no other ordering constraints.
10266       // If the chain has more than one use, we give up: some other
10267       // use of Dest might force a side-effect between Dest and the current
10268       // node.
10269       if (Dest.hasOneUse())
10270         return true;
10271     }
10272     // Next, try a deep search: check whether every operand of the TokenFactor
10273     // reaches Dest.
10274     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10275       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10276     });
10277   }
10278 
10279   // Loads don't have side effects, look through them.
10280   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10281     if (Ld->isUnordered())
10282       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10283   }
10284   return false;
10285 }
10286 
10287 bool SDNode::hasPredecessor(const SDNode *N) const {
10288   SmallPtrSet<const SDNode *, 32> Visited;
10289   SmallVector<const SDNode *, 16> Worklist;
10290   Worklist.push_back(this);
10291   return hasPredecessorHelper(N, Visited, Worklist);
10292 }
10293 
10294 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10295   this->Flags.intersectWith(Flags);
10296 }
10297 
10298 SDValue
10299 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10300                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10301                                   bool AllowPartials) {
10302   // The pattern must end in an extract from index 0.
10303   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10304       !isNullConstant(Extract->getOperand(1)))
10305     return SDValue();
10306 
10307   // Match against one of the candidate binary ops.
10308   SDValue Op = Extract->getOperand(0);
10309   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10310         return Op.getOpcode() == unsigned(BinOp);
10311       }))
10312     return SDValue();
10313 
10314   // Floating-point reductions may require relaxed constraints on the final step
10315   // of the reduction because they may reorder intermediate operations.
10316   unsigned CandidateBinOp = Op.getOpcode();
10317   if (Op.getValueType().isFloatingPoint()) {
10318     SDNodeFlags Flags = Op->getFlags();
10319     switch (CandidateBinOp) {
10320     case ISD::FADD:
10321       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10322         return SDValue();
10323       break;
10324     default:
10325       llvm_unreachable("Unhandled FP opcode for binop reduction");
10326     }
10327   }
10328 
10329   // Matching failed - attempt to see if we did enough stages that a partial
10330   // reduction from a subvector is possible.
10331   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10332     if (!AllowPartials || !Op)
10333       return SDValue();
10334     EVT OpVT = Op.getValueType();
10335     EVT OpSVT = OpVT.getScalarType();
10336     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10337     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10338       return SDValue();
10339     BinOp = (ISD::NodeType)CandidateBinOp;
10340     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10341                    getVectorIdxConstant(0, SDLoc(Op)));
10342   };
10343 
10344   // At each stage, we're looking for something that looks like:
10345   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10346   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10347   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10348   // %a = binop <8 x i32> %op, %s
10349   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10350   // we expect something like:
10351   // <4,5,6,7,u,u,u,u>
10352   // <2,3,u,u,u,u,u,u>
10353   // <1,u,u,u,u,u,u,u>
10354   // While a partial reduction match would be:
10355   // <2,3,u,u,u,u,u,u>
10356   // <1,u,u,u,u,u,u,u>
10357   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10358   SDValue PrevOp;
10359   for (unsigned i = 0; i < Stages; ++i) {
10360     unsigned MaskEnd = (1 << i);
10361 
10362     if (Op.getOpcode() != CandidateBinOp)
10363       return PartialReduction(PrevOp, MaskEnd);
10364 
10365     SDValue Op0 = Op.getOperand(0);
10366     SDValue Op1 = Op.getOperand(1);
10367 
10368     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10369     if (Shuffle) {
10370       Op = Op1;
10371     } else {
10372       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10373       Op = Op0;
10374     }
10375 
10376     // The first operand of the shuffle should be the same as the other operand
10377     // of the binop.
10378     if (!Shuffle || Shuffle->getOperand(0) != Op)
10379       return PartialReduction(PrevOp, MaskEnd);
10380 
10381     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10382     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10383       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10384         return PartialReduction(PrevOp, MaskEnd);
10385 
10386     PrevOp = Op;
10387   }
10388 
10389   // Handle subvector reductions, which tend to appear after the shuffle
10390   // reduction stages.
10391   while (Op.getOpcode() == CandidateBinOp) {
10392     unsigned NumElts = Op.getValueType().getVectorNumElements();
10393     SDValue Op0 = Op.getOperand(0);
10394     SDValue Op1 = Op.getOperand(1);
10395     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10396         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10397         Op0.getOperand(0) != Op1.getOperand(0))
10398       break;
10399     SDValue Src = Op0.getOperand(0);
10400     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10401     if (NumSrcElts != (2 * NumElts))
10402       break;
10403     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10404           Op1.getConstantOperandAPInt(1) == NumElts) &&
10405         !(Op1.getConstantOperandAPInt(1) == 0 &&
10406           Op0.getConstantOperandAPInt(1) == NumElts))
10407       break;
10408     Op = Src;
10409   }
10410 
10411   BinOp = (ISD::NodeType)CandidateBinOp;
10412   return Op;
10413 }
10414 
10415 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10416   assert(N->getNumValues() == 1 &&
10417          "Can't unroll a vector with multiple results!");
10418 
10419   EVT VT = N->getValueType(0);
10420   unsigned NE = VT.getVectorNumElements();
10421   EVT EltVT = VT.getVectorElementType();
10422   SDLoc dl(N);
10423 
10424   SmallVector<SDValue, 8> Scalars;
10425   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10426 
10427   // If ResNE is 0, fully unroll the vector op.
10428   if (ResNE == 0)
10429     ResNE = NE;
10430   else if (NE > ResNE)
10431     NE = ResNE;
10432 
10433   unsigned i;
10434   for (i= 0; i != NE; ++i) {
10435     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10436       SDValue Operand = N->getOperand(j);
10437       EVT OperandVT = Operand.getValueType();
10438       if (OperandVT.isVector()) {
10439         // A vector operand; extract a single element.
10440         EVT OperandEltVT = OperandVT.getVectorElementType();
10441         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10442                               Operand, getVectorIdxConstant(i, dl));
10443       } else {
10444         // A scalar operand; just use it as is.
10445         Operands[j] = Operand;
10446       }
10447     }
10448 
10449     switch (N->getOpcode()) {
10450     default: {
10451       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10452                                 N->getFlags()));
10453       break;
10454     }
10455     case ISD::VSELECT:
10456       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10457       break;
10458     case ISD::SHL:
10459     case ISD::SRA:
10460     case ISD::SRL:
10461     case ISD::ROTL:
10462     case ISD::ROTR:
10463       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10464                                getShiftAmountOperand(Operands[0].getValueType(),
10465                                                      Operands[1])));
10466       break;
10467     case ISD::SIGN_EXTEND_INREG: {
10468       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10469       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10470                                 Operands[0],
10471                                 getValueType(ExtVT)));
10472     }
10473     }
10474   }
10475 
10476   for (; i < ResNE; ++i)
10477     Scalars.push_back(getUNDEF(EltVT));
10478 
10479   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10480   return getBuildVector(VecVT, dl, Scalars);
10481 }
10482 
10483 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10484     SDNode *N, unsigned ResNE) {
10485   unsigned Opcode = N->getOpcode();
10486   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10487           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10488           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10489          "Expected an overflow opcode");
10490 
10491   EVT ResVT = N->getValueType(0);
10492   EVT OvVT = N->getValueType(1);
10493   EVT ResEltVT = ResVT.getVectorElementType();
10494   EVT OvEltVT = OvVT.getVectorElementType();
10495   SDLoc dl(N);
10496 
10497   // If ResNE is 0, fully unroll the vector op.
10498   unsigned NE = ResVT.getVectorNumElements();
10499   if (ResNE == 0)
10500     ResNE = NE;
10501   else if (NE > ResNE)
10502     NE = ResNE;
10503 
10504   SmallVector<SDValue, 8> LHSScalars;
10505   SmallVector<SDValue, 8> RHSScalars;
10506   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10507   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10508 
10509   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10510   SDVTList VTs = getVTList(ResEltVT, SVT);
10511   SmallVector<SDValue, 8> ResScalars;
10512   SmallVector<SDValue, 8> OvScalars;
10513   for (unsigned i = 0; i < NE; ++i) {
10514     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10515     SDValue Ov =
10516         getSelect(dl, OvEltVT, Res.getValue(1),
10517                   getBoolConstant(true, dl, OvEltVT, ResVT),
10518                   getConstant(0, dl, OvEltVT));
10519 
10520     ResScalars.push_back(Res);
10521     OvScalars.push_back(Ov);
10522   }
10523 
10524   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10525   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10526 
10527   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10528   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10529   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10530                         getBuildVector(NewOvVT, dl, OvScalars));
10531 }
10532 
10533 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10534                                                   LoadSDNode *Base,
10535                                                   unsigned Bytes,
10536                                                   int Dist) const {
10537   if (LD->isVolatile() || Base->isVolatile())
10538     return false;
10539   // TODO: probably too restrictive for atomics, revisit
10540   if (!LD->isSimple())
10541     return false;
10542   if (LD->isIndexed() || Base->isIndexed())
10543     return false;
10544   if (LD->getChain() != Base->getChain())
10545     return false;
10546   EVT VT = LD->getValueType(0);
10547   if (VT.getSizeInBits() / 8 != Bytes)
10548     return false;
10549 
10550   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10551   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10552 
10553   int64_t Offset = 0;
10554   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10555     return (Dist * Bytes == Offset);
10556   return false;
10557 }
10558 
10559 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10560 /// if it cannot be inferred.
10561 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10562   // If this is a GlobalAddress + cst, return the alignment.
10563   const GlobalValue *GV = nullptr;
10564   int64_t GVOffset = 0;
10565   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10566     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10567     KnownBits Known(PtrWidth);
10568     llvm::computeKnownBits(GV, Known, getDataLayout());
10569     unsigned AlignBits = Known.countMinTrailingZeros();
10570     if (AlignBits)
10571       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10572   }
10573 
10574   // If this is a direct reference to a stack slot, use information about the
10575   // stack slot's alignment.
10576   int FrameIdx = INT_MIN;
10577   int64_t FrameOffset = 0;
10578   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10579     FrameIdx = FI->getIndex();
10580   } else if (isBaseWithConstantOffset(Ptr) &&
10581              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10582     // Handle FI+Cst
10583     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10584     FrameOffset = Ptr.getConstantOperandVal(1);
10585   }
10586 
10587   if (FrameIdx != INT_MIN) {
10588     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10589     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10590   }
10591 
10592   return None;
10593 }
10594 
10595 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10596 /// which is split (or expanded) into two not necessarily identical pieces.
10597 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10598   // Currently all types are split in half.
10599   EVT LoVT, HiVT;
10600   if (!VT.isVector())
10601     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10602   else
10603     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10604 
10605   return std::make_pair(LoVT, HiVT);
10606 }
10607 
10608 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10609 /// type, dependent on an enveloping VT that has been split into two identical
10610 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10611 std::pair<EVT, EVT>
10612 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10613                                        bool *HiIsEmpty) const {
10614   EVT EltTp = VT.getVectorElementType();
10615   // Examples:
10616   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10617   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10618   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10619   //   etc.
10620   ElementCount VTNumElts = VT.getVectorElementCount();
10621   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10622   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10623          "Mixing fixed width and scalable vectors when enveloping a type");
10624   EVT LoVT, HiVT;
10625   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10626     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10627     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10628     *HiIsEmpty = false;
10629   } else {
10630     // Flag that hi type has zero storage size, but return split envelop type
10631     // (this would be easier if vector types with zero elements were allowed).
10632     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10633     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10634     *HiIsEmpty = true;
10635   }
10636   return std::make_pair(LoVT, HiVT);
10637 }
10638 
10639 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10640 /// low/high part.
10641 std::pair<SDValue, SDValue>
10642 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10643                           const EVT &HiVT) {
10644   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10645          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10646          "Splitting vector with an invalid mixture of fixed and scalable "
10647          "vector types");
10648   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10649              N.getValueType().getVectorMinNumElements() &&
10650          "More vector elements requested than available!");
10651   SDValue Lo, Hi;
10652   Lo =
10653       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10654   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10655   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10656   // IDX with the runtime scaling factor of the result vector type. For
10657   // fixed-width result vectors, that runtime scaling factor is 1.
10658   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10659                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10660   return std::make_pair(Lo, Hi);
10661 }
10662 
10663 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
10664                                                    const SDLoc &DL) {
10665   // Split the vector length parameter.
10666   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
10667   EVT VT = N.getValueType();
10668   assert(VecVT.getVectorElementCount().isKnownEven() &&
10669          "Expecting the mask to be an evenly-sized vector");
10670   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
10671   SDValue HalfNumElts =
10672       VecVT.isFixedLengthVector()
10673           ? getConstant(HalfMinNumElts, DL, VT)
10674           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
10675   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
10676   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
10677   return std::make_pair(Lo, Hi);
10678 }
10679 
10680 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10681 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10682   EVT VT = N.getValueType();
10683   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10684                                 NextPowerOf2(VT.getVectorNumElements()));
10685   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10686                  getVectorIdxConstant(0, DL));
10687 }
10688 
10689 void SelectionDAG::ExtractVectorElements(SDValue Op,
10690                                          SmallVectorImpl<SDValue> &Args,
10691                                          unsigned Start, unsigned Count,
10692                                          EVT EltVT) {
10693   EVT VT = Op.getValueType();
10694   if (Count == 0)
10695     Count = VT.getVectorNumElements();
10696   if (EltVT == EVT())
10697     EltVT = VT.getVectorElementType();
10698   SDLoc SL(Op);
10699   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10700     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10701                            getVectorIdxConstant(i, SL)));
10702   }
10703 }
10704 
10705 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10706 unsigned GlobalAddressSDNode::getAddressSpace() const {
10707   return getGlobal()->getType()->getAddressSpace();
10708 }
10709 
10710 Type *ConstantPoolSDNode::getType() const {
10711   if (isMachineConstantPoolEntry())
10712     return Val.MachineCPVal->getType();
10713   return Val.ConstVal->getType();
10714 }
10715 
10716 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10717                                         unsigned &SplatBitSize,
10718                                         bool &HasAnyUndefs,
10719                                         unsigned MinSplatBits,
10720                                         bool IsBigEndian) const {
10721   EVT VT = getValueType(0);
10722   assert(VT.isVector() && "Expected a vector type");
10723   unsigned VecWidth = VT.getSizeInBits();
10724   if (MinSplatBits > VecWidth)
10725     return false;
10726 
10727   // FIXME: The widths are based on this node's type, but build vectors can
10728   // truncate their operands.
10729   SplatValue = APInt(VecWidth, 0);
10730   SplatUndef = APInt(VecWidth, 0);
10731 
10732   // Get the bits. Bits with undefined values (when the corresponding element
10733   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10734   // in SplatValue. If any of the values are not constant, give up and return
10735   // false.
10736   unsigned int NumOps = getNumOperands();
10737   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10738   unsigned EltWidth = VT.getScalarSizeInBits();
10739 
10740   for (unsigned j = 0; j < NumOps; ++j) {
10741     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10742     SDValue OpVal = getOperand(i);
10743     unsigned BitPos = j * EltWidth;
10744 
10745     if (OpVal.isUndef())
10746       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10747     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10748       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10749     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10750       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10751     else
10752       return false;
10753   }
10754 
10755   // The build_vector is all constants or undefs. Find the smallest element
10756   // size that splats the vector.
10757   HasAnyUndefs = (SplatUndef != 0);
10758 
10759   // FIXME: This does not work for vectors with elements less than 8 bits.
10760   while (VecWidth > 8) {
10761     unsigned HalfSize = VecWidth / 2;
10762     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10763     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10764     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10765     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10766 
10767     // If the two halves do not match (ignoring undef bits), stop here.
10768     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10769         MinSplatBits > HalfSize)
10770       break;
10771 
10772     SplatValue = HighValue | LowValue;
10773     SplatUndef = HighUndef & LowUndef;
10774 
10775     VecWidth = HalfSize;
10776   }
10777 
10778   SplatBitSize = VecWidth;
10779   return true;
10780 }
10781 
10782 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10783                                          BitVector *UndefElements) const {
10784   unsigned NumOps = getNumOperands();
10785   if (UndefElements) {
10786     UndefElements->clear();
10787     UndefElements->resize(NumOps);
10788   }
10789   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10790   if (!DemandedElts)
10791     return SDValue();
10792   SDValue Splatted;
10793   for (unsigned i = 0; i != NumOps; ++i) {
10794     if (!DemandedElts[i])
10795       continue;
10796     SDValue Op = getOperand(i);
10797     if (Op.isUndef()) {
10798       if (UndefElements)
10799         (*UndefElements)[i] = true;
10800     } else if (!Splatted) {
10801       Splatted = Op;
10802     } else if (Splatted != Op) {
10803       return SDValue();
10804     }
10805   }
10806 
10807   if (!Splatted) {
10808     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10809     assert(getOperand(FirstDemandedIdx).isUndef() &&
10810            "Can only have a splat without a constant for all undefs.");
10811     return getOperand(FirstDemandedIdx);
10812   }
10813 
10814   return Splatted;
10815 }
10816 
10817 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10818   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10819   return getSplatValue(DemandedElts, UndefElements);
10820 }
10821 
10822 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10823                                             SmallVectorImpl<SDValue> &Sequence,
10824                                             BitVector *UndefElements) const {
10825   unsigned NumOps = getNumOperands();
10826   Sequence.clear();
10827   if (UndefElements) {
10828     UndefElements->clear();
10829     UndefElements->resize(NumOps);
10830   }
10831   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10832   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10833     return false;
10834 
10835   // Set the undefs even if we don't find a sequence (like getSplatValue).
10836   if (UndefElements)
10837     for (unsigned I = 0; I != NumOps; ++I)
10838       if (DemandedElts[I] && getOperand(I).isUndef())
10839         (*UndefElements)[I] = true;
10840 
10841   // Iteratively widen the sequence length looking for repetitions.
10842   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10843     Sequence.append(SeqLen, SDValue());
10844     for (unsigned I = 0; I != NumOps; ++I) {
10845       if (!DemandedElts[I])
10846         continue;
10847       SDValue &SeqOp = Sequence[I % SeqLen];
10848       SDValue Op = getOperand(I);
10849       if (Op.isUndef()) {
10850         if (!SeqOp)
10851           SeqOp = Op;
10852         continue;
10853       }
10854       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10855         Sequence.clear();
10856         break;
10857       }
10858       SeqOp = Op;
10859     }
10860     if (!Sequence.empty())
10861       return true;
10862   }
10863 
10864   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10865   return false;
10866 }
10867 
10868 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10869                                             BitVector *UndefElements) const {
10870   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10871   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10872 }
10873 
10874 ConstantSDNode *
10875 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10876                                         BitVector *UndefElements) const {
10877   return dyn_cast_or_null<ConstantSDNode>(
10878       getSplatValue(DemandedElts, UndefElements));
10879 }
10880 
10881 ConstantSDNode *
10882 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10883   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10884 }
10885 
10886 ConstantFPSDNode *
10887 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10888                                           BitVector *UndefElements) const {
10889   return dyn_cast_or_null<ConstantFPSDNode>(
10890       getSplatValue(DemandedElts, UndefElements));
10891 }
10892 
10893 ConstantFPSDNode *
10894 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10895   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10896 }
10897 
10898 int32_t
10899 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10900                                                    uint32_t BitWidth) const {
10901   if (ConstantFPSDNode *CN =
10902           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10903     bool IsExact;
10904     APSInt IntVal(BitWidth);
10905     const APFloat &APF = CN->getValueAPF();
10906     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10907             APFloat::opOK ||
10908         !IsExact)
10909       return -1;
10910 
10911     return IntVal.exactLogBase2();
10912   }
10913   return -1;
10914 }
10915 
10916 bool BuildVectorSDNode::getConstantRawBits(
10917     bool IsLittleEndian, unsigned DstEltSizeInBits,
10918     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
10919   // Early-out if this contains anything but Undef/Constant/ConstantFP.
10920   if (!isConstant())
10921     return false;
10922 
10923   unsigned NumSrcOps = getNumOperands();
10924   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
10925   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10926          "Invalid bitcast scale");
10927 
10928   // Extract raw src bits.
10929   SmallVector<APInt> SrcBitElements(NumSrcOps,
10930                                     APInt::getNullValue(SrcEltSizeInBits));
10931   BitVector SrcUndeElements(NumSrcOps, false);
10932 
10933   for (unsigned I = 0; I != NumSrcOps; ++I) {
10934     SDValue Op = getOperand(I);
10935     if (Op.isUndef()) {
10936       SrcUndeElements.set(I);
10937       continue;
10938     }
10939     auto *CInt = dyn_cast<ConstantSDNode>(Op);
10940     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
10941     assert((CInt || CFP) && "Unknown constant");
10942     SrcBitElements[I] =
10943         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
10944              : CFP->getValueAPF().bitcastToAPInt();
10945   }
10946 
10947   // Recast to dst width.
10948   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
10949                 SrcBitElements, UndefElements, SrcUndeElements);
10950   return true;
10951 }
10952 
10953 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
10954                                       unsigned DstEltSizeInBits,
10955                                       SmallVectorImpl<APInt> &DstBitElements,
10956                                       ArrayRef<APInt> SrcBitElements,
10957                                       BitVector &DstUndefElements,
10958                                       const BitVector &SrcUndefElements) {
10959   unsigned NumSrcOps = SrcBitElements.size();
10960   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
10961   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10962          "Invalid bitcast scale");
10963   assert(NumSrcOps == SrcUndefElements.size() &&
10964          "Vector size mismatch");
10965 
10966   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
10967   DstUndefElements.clear();
10968   DstUndefElements.resize(NumDstOps, false);
10969   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
10970 
10971   // Concatenate src elements constant bits together into dst element.
10972   if (SrcEltSizeInBits <= DstEltSizeInBits) {
10973     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
10974     for (unsigned I = 0; I != NumDstOps; ++I) {
10975       DstUndefElements.set(I);
10976       APInt &DstBits = DstBitElements[I];
10977       for (unsigned J = 0; J != Scale; ++J) {
10978         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10979         if (SrcUndefElements[Idx])
10980           continue;
10981         DstUndefElements.reset(I);
10982         const APInt &SrcBits = SrcBitElements[Idx];
10983         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
10984                "Illegal constant bitwidths");
10985         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
10986       }
10987     }
10988     return;
10989   }
10990 
10991   // Split src element constant bits into dst elements.
10992   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
10993   for (unsigned I = 0; I != NumSrcOps; ++I) {
10994     if (SrcUndefElements[I]) {
10995       DstUndefElements.set(I * Scale, (I + 1) * Scale);
10996       continue;
10997     }
10998     const APInt &SrcBits = SrcBitElements[I];
10999     for (unsigned J = 0; J != Scale; ++J) {
11000       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11001       APInt &DstBits = DstBitElements[Idx];
11002       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11003     }
11004   }
11005 }
11006 
11007 bool BuildVectorSDNode::isConstant() const {
11008   for (const SDValue &Op : op_values()) {
11009     unsigned Opc = Op.getOpcode();
11010     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11011       return false;
11012   }
11013   return true;
11014 }
11015 
11016 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11017   // Find the first non-undef value in the shuffle mask.
11018   unsigned i, e;
11019   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11020     /* search */;
11021 
11022   // If all elements are undefined, this shuffle can be considered a splat
11023   // (although it should eventually get simplified away completely).
11024   if (i == e)
11025     return true;
11026 
11027   // Make sure all remaining elements are either undef or the same as the first
11028   // non-undef value.
11029   for (int Idx = Mask[i]; i != e; ++i)
11030     if (Mask[i] >= 0 && Mask[i] != Idx)
11031       return false;
11032   return true;
11033 }
11034 
11035 // Returns the SDNode if it is a constant integer BuildVector
11036 // or constant integer.
11037 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11038   if (isa<ConstantSDNode>(N))
11039     return N.getNode();
11040   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11041     return N.getNode();
11042   // Treat a GlobalAddress supporting constant offset folding as a
11043   // constant integer.
11044   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11045     if (GA->getOpcode() == ISD::GlobalAddress &&
11046         TLI->isOffsetFoldingLegal(GA))
11047       return GA;
11048   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11049       isa<ConstantSDNode>(N.getOperand(0)))
11050     return N.getNode();
11051   return nullptr;
11052 }
11053 
11054 // Returns the SDNode if it is a constant float BuildVector
11055 // or constant float.
11056 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11057   if (isa<ConstantFPSDNode>(N))
11058     return N.getNode();
11059 
11060   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11061     return N.getNode();
11062 
11063   return nullptr;
11064 }
11065 
11066 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11067   assert(!Node->OperandList && "Node already has operands");
11068   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11069          "too many operands to fit into SDNode");
11070   SDUse *Ops = OperandRecycler.allocate(
11071       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11072 
11073   bool IsDivergent = false;
11074   for (unsigned I = 0; I != Vals.size(); ++I) {
11075     Ops[I].setUser(Node);
11076     Ops[I].setInitial(Vals[I]);
11077     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11078       IsDivergent |= Ops[I].getNode()->isDivergent();
11079   }
11080   Node->NumOperands = Vals.size();
11081   Node->OperandList = Ops;
11082   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11083     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11084     Node->SDNodeBits.IsDivergent = IsDivergent;
11085   }
11086   checkForCycles(Node);
11087 }
11088 
11089 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11090                                      SmallVectorImpl<SDValue> &Vals) {
11091   size_t Limit = SDNode::getMaxNumOperands();
11092   while (Vals.size() > Limit) {
11093     unsigned SliceIdx = Vals.size() - Limit;
11094     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11095     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11096     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11097     Vals.emplace_back(NewTF);
11098   }
11099   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11100 }
11101 
11102 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11103                                         EVT VT, SDNodeFlags Flags) {
11104   switch (Opcode) {
11105   default:
11106     return SDValue();
11107   case ISD::ADD:
11108   case ISD::OR:
11109   case ISD::XOR:
11110   case ISD::UMAX:
11111     return getConstant(0, DL, VT);
11112   case ISD::MUL:
11113     return getConstant(1, DL, VT);
11114   case ISD::AND:
11115   case ISD::UMIN:
11116     return getAllOnesConstant(DL, VT);
11117   case ISD::SMAX:
11118     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11119   case ISD::SMIN:
11120     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11121   case ISD::FADD:
11122     return getConstantFP(-0.0, DL, VT);
11123   case ISD::FMUL:
11124     return getConstantFP(1.0, DL, VT);
11125   case ISD::FMINNUM:
11126   case ISD::FMAXNUM: {
11127     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11128     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11129     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11130                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11131                         APFloat::getLargest(Semantics);
11132     if (Opcode == ISD::FMAXNUM)
11133       NeutralAF.changeSign();
11134 
11135     return getConstantFP(NeutralAF, DL, VT);
11136   }
11137   }
11138 }
11139 
11140 #ifndef NDEBUG
11141 static void checkForCyclesHelper(const SDNode *N,
11142                                  SmallPtrSetImpl<const SDNode*> &Visited,
11143                                  SmallPtrSetImpl<const SDNode*> &Checked,
11144                                  const llvm::SelectionDAG *DAG) {
11145   // If this node has already been checked, don't check it again.
11146   if (Checked.count(N))
11147     return;
11148 
11149   // If a node has already been visited on this depth-first walk, reject it as
11150   // a cycle.
11151   if (!Visited.insert(N).second) {
11152     errs() << "Detected cycle in SelectionDAG\n";
11153     dbgs() << "Offending node:\n";
11154     N->dumprFull(DAG); dbgs() << "\n";
11155     abort();
11156   }
11157 
11158   for (const SDValue &Op : N->op_values())
11159     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11160 
11161   Checked.insert(N);
11162   Visited.erase(N);
11163 }
11164 #endif
11165 
11166 void llvm::checkForCycles(const llvm::SDNode *N,
11167                           const llvm::SelectionDAG *DAG,
11168                           bool force) {
11169 #ifndef NDEBUG
11170   bool check = force;
11171 #ifdef EXPENSIVE_CHECKS
11172   check = true;
11173 #endif  // EXPENSIVE_CHECKS
11174   if (check) {
11175     assert(N && "Checking nonexistent SDNode");
11176     SmallPtrSet<const SDNode*, 32> visited;
11177     SmallPtrSet<const SDNode*, 32> checked;
11178     checkForCyclesHelper(N, visited, checked, DAG);
11179   }
11180 #endif  // !NDEBUG
11181 }
11182 
11183 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11184   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11185 }
11186