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/AliasAnalysis.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/CodeGen/Analysis.h"
31 #include "llvm/CodeGen/FunctionLoweringInfo.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineConstantPool.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/RuntimeLibcalls.h"
39 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
40 #include "llvm/CodeGen/SelectionDAGNodes.h"
41 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
42 #include "llvm/CodeGen/TargetFrameLowering.h"
43 #include "llvm/CodeGen/TargetLowering.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Constant.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugInfoMetadata.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/Support/Casting.h"
58 #include "llvm/Support/CodeGen.h"
59 #include "llvm/Support/Compiler.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/KnownBits.h"
63 #include "llvm/Support/MachineValueType.h"
64 #include "llvm/Support/MathExtras.h"
65 #include "llvm/Support/Mutex.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include "llvm/Target/TargetOptions.h"
69 #include "llvm/Transforms/Utils/SizeOpts.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cstdint>
73 #include <cstdlib>
74 #include <limits>
75 #include <set>
76 #include <string>
77 #include <utility>
78 #include <vector>
79 
80 using namespace llvm;
81 
82 /// makeVTList - Return an instance of the SDVTList struct initialized with the
83 /// specified members.
84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
85   SDVTList Res = {VTs, NumVTs};
86   return Res;
87 }
88 
89 // Default null implementations of the callbacks.
90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
93 
94 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
95 
96 #define DEBUG_TYPE "selectiondag"
97 
98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
99        cl::Hidden, cl::init(true),
100        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
101 
102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
103        cl::desc("Number limit for gluing ld/st of memcpy."),
104        cl::Hidden, cl::init(0));
105 
106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
107   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
108 }
109 
110 //===----------------------------------------------------------------------===//
111 //                              ConstantFPSDNode Class
112 //===----------------------------------------------------------------------===//
113 
114 /// isExactlyValue - We don't rely on operator== working on double values, as
115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
116 /// As such, this method can be used to do an exact bit-for-bit comparison of
117 /// two floating point values.
118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
119   return getValueAPF().bitwiseIsEqual(V);
120 }
121 
122 bool ConstantFPSDNode::isValueValidForType(EVT VT,
123                                            const APFloat& Val) {
124   assert(VT.isFloatingPoint() && "Can only convert between FP types");
125 
126   // convert modifies in place, so make a copy.
127   APFloat Val2 = APFloat(Val);
128   bool losesInfo;
129   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
130                       APFloat::rmNearestTiesToEven,
131                       &losesInfo);
132   return !losesInfo;
133 }
134 
135 //===----------------------------------------------------------------------===//
136 //                              ISD Namespace
137 //===----------------------------------------------------------------------===//
138 
139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
140   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
141     unsigned EltSize =
142         N->getValueType(0).getVectorElementType().getSizeInBits();
143     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
144       SplatVal = Op0->getAPIntValue().trunc(EltSize);
145       return true;
146     }
147     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
148       SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize);
149       return true;
150     }
151   }
152 
153   auto *BV = dyn_cast<BuildVectorSDNode>(N);
154   if (!BV)
155     return false;
156 
157   APInt SplatUndef;
158   unsigned SplatBitSize;
159   bool HasUndefs;
160   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
161   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
162                              EltSize) &&
163          EltSize == SplatBitSize;
164 }
165 
166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
167 // specializations of the more general isConstantSplatVector()?
168 
169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
170   // Look through a bit convert.
171   while (N->getOpcode() == ISD::BITCAST)
172     N = N->getOperand(0).getNode();
173 
174   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
175     APInt SplatVal;
176     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
177   }
178 
179   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
180 
181   unsigned i = 0, e = N->getNumOperands();
182 
183   // Skip over all of the undef values.
184   while (i != e && N->getOperand(i).isUndef())
185     ++i;
186 
187   // Do not accept an all-undef vector.
188   if (i == e) return false;
189 
190   // Do not accept build_vectors that aren't all constants or which have non-~0
191   // elements. We have to be a bit careful here, as the type of the constant
192   // may not be the same as the type of the vector elements due to type
193   // legalization (the elements are promoted to a legal type for the target and
194   // a vector of a type may be legal when the base element type is not).
195   // We only want to check enough bits to cover the vector elements, because
196   // we care if the resultant vector is all ones, not whether the individual
197   // constants are.
198   SDValue NotZero = N->getOperand(i);
199   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
200   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
201     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
202       return false;
203   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
204     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
205       return false;
206   } else
207     return false;
208 
209   // Okay, we have at least one ~0 value, check to see if the rest match or are
210   // undefs. Even with the above element type twiddling, this should be OK, as
211   // the same type legalization should have applied to all the elements.
212   for (++i; i != e; ++i)
213     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
214       return false;
215   return true;
216 }
217 
218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
219   // Look through a bit convert.
220   while (N->getOpcode() == ISD::BITCAST)
221     N = N->getOperand(0).getNode();
222 
223   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
224     APInt SplatVal;
225     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
226   }
227 
228   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
229 
230   bool IsAllUndef = true;
231   for (const SDValue &Op : N->op_values()) {
232     if (Op.isUndef())
233       continue;
234     IsAllUndef = false;
235     // Do not accept build_vectors that aren't all constants or which have non-0
236     // elements. We have to be a bit careful here, as the type of the constant
237     // may not be the same as the type of the vector elements due to type
238     // legalization (the elements are promoted to a legal type for the target
239     // and a vector of a type may be legal when the base element type is not).
240     // We only want to check enough bits to cover the vector elements, because
241     // we care if the resultant vector is all zeros, not whether the individual
242     // constants are.
243     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
244     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
245       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
246         return false;
247     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
248       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
249         return false;
250     } else
251       return false;
252   }
253 
254   // Do not accept an all-undef vector.
255   if (IsAllUndef)
256     return false;
257   return true;
258 }
259 
260 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
261   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
262 }
263 
264 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
265   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
266 }
267 
268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
269   if (N->getOpcode() != ISD::BUILD_VECTOR)
270     return false;
271 
272   for (const SDValue &Op : N->op_values()) {
273     if (Op.isUndef())
274       continue;
275     if (!isa<ConstantSDNode>(Op))
276       return false;
277   }
278   return true;
279 }
280 
281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
282   if (N->getOpcode() != ISD::BUILD_VECTOR)
283     return false;
284 
285   for (const SDValue &Op : N->op_values()) {
286     if (Op.isUndef())
287       continue;
288     if (!isa<ConstantFPSDNode>(Op))
289       return false;
290   }
291   return true;
292 }
293 
294 bool ISD::allOperandsUndef(const SDNode *N) {
295   // Return false if the node has no operands.
296   // This is "logically inconsistent" with the definition of "all" but
297   // is probably the desired behavior.
298   if (N->getNumOperands() == 0)
299     return false;
300   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
301 }
302 
303 bool ISD::matchUnaryPredicate(SDValue Op,
304                               std::function<bool(ConstantSDNode *)> Match,
305                               bool AllowUndefs) {
306   // FIXME: Add support for scalar UNDEF cases?
307   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
308     return Match(Cst);
309 
310   // FIXME: Add support for vector UNDEF cases?
311   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
312       ISD::SPLAT_VECTOR != Op.getOpcode())
313     return false;
314 
315   EVT SVT = Op.getValueType().getScalarType();
316   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
317     if (AllowUndefs && Op.getOperand(i).isUndef()) {
318       if (!Match(nullptr))
319         return false;
320       continue;
321     }
322 
323     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
324     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
325       return false;
326   }
327   return true;
328 }
329 
330 bool ISD::matchBinaryPredicate(
331     SDValue LHS, SDValue RHS,
332     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
333     bool AllowUndefs, bool AllowTypeMismatch) {
334   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
335     return false;
336 
337   // TODO: Add support for scalar UNDEF cases?
338   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
339     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
340       return Match(LHSCst, RHSCst);
341 
342   // TODO: Add support for vector UNDEF cases?
343   if (LHS.getOpcode() != RHS.getOpcode() ||
344       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
345        LHS.getOpcode() != ISD::SPLAT_VECTOR))
346     return false;
347 
348   EVT SVT = LHS.getValueType().getScalarType();
349   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
350     SDValue LHSOp = LHS.getOperand(i);
351     SDValue RHSOp = RHS.getOperand(i);
352     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
353     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
354     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
355     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
356     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
357       return false;
358     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
359                                LHSOp.getValueType() != RHSOp.getValueType()))
360       return false;
361     if (!Match(LHSCst, RHSCst))
362       return false;
363   }
364   return true;
365 }
366 
367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
368   switch (VecReduceOpcode) {
369   default:
370     llvm_unreachable("Expected VECREDUCE opcode");
371   case ISD::VECREDUCE_FADD:
372   case ISD::VECREDUCE_SEQ_FADD:
373   case ISD::VP_REDUCE_FADD:
374   case ISD::VP_REDUCE_SEQ_FADD:
375     return ISD::FADD;
376   case ISD::VECREDUCE_FMUL:
377   case ISD::VECREDUCE_SEQ_FMUL:
378   case ISD::VP_REDUCE_FMUL:
379   case ISD::VP_REDUCE_SEQ_FMUL:
380     return ISD::FMUL;
381   case ISD::VECREDUCE_ADD:
382   case ISD::VP_REDUCE_ADD:
383     return ISD::ADD;
384   case ISD::VECREDUCE_MUL:
385   case ISD::VP_REDUCE_MUL:
386     return ISD::MUL;
387   case ISD::VECREDUCE_AND:
388   case ISD::VP_REDUCE_AND:
389     return ISD::AND;
390   case ISD::VECREDUCE_OR:
391   case ISD::VP_REDUCE_OR:
392     return ISD::OR;
393   case ISD::VECREDUCE_XOR:
394   case ISD::VP_REDUCE_XOR:
395     return ISD::XOR;
396   case ISD::VECREDUCE_SMAX:
397   case ISD::VP_REDUCE_SMAX:
398     return ISD::SMAX;
399   case ISD::VECREDUCE_SMIN:
400   case ISD::VP_REDUCE_SMIN:
401     return ISD::SMIN;
402   case ISD::VECREDUCE_UMAX:
403   case ISD::VP_REDUCE_UMAX:
404     return ISD::UMAX;
405   case ISD::VECREDUCE_UMIN:
406   case ISD::VP_REDUCE_UMIN:
407     return ISD::UMIN;
408   case ISD::VECREDUCE_FMAX:
409   case ISD::VP_REDUCE_FMAX:
410     return ISD::FMAXNUM;
411   case ISD::VECREDUCE_FMIN:
412   case ISD::VP_REDUCE_FMIN:
413     return ISD::FMINNUM;
414   }
415 }
416 
417 bool ISD::isVPOpcode(unsigned Opcode) {
418   switch (Opcode) {
419   default:
420     return false;
421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
422   case ISD::VPSD:                                                              \
423     return true;
424 #include "llvm/IR/VPIntrinsics.def"
425   }
426 }
427 
428 bool ISD::isVPBinaryOp(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     break;
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_BINARYOP return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437   return false;
438 }
439 
440 bool ISD::isVPReduction(unsigned Opcode) {
441   switch (Opcode) {
442   default:
443     break;
444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
446 #define END_REGISTER_VP_SDNODE(VPSD) break;
447 #include "llvm/IR/VPIntrinsics.def"
448   }
449   return false;
450 }
451 
452 /// The operand position of the vector mask.
453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
454   switch (Opcode) {
455   default:
456     return None;
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
458   case ISD::VPSD:                                                              \
459     return MASKPOS;
460 #include "llvm/IR/VPIntrinsics.def"
461   }
462 }
463 
464 /// The operand position of the explicit vector length parameter.
465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
466   switch (Opcode) {
467   default:
468     return None;
469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
470   case ISD::VPSD:                                                              \
471     return EVLPOS;
472 #include "llvm/IR/VPIntrinsics.def"
473   }
474 }
475 
476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
477   switch (ExtType) {
478   case ISD::EXTLOAD:
479     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
480   case ISD::SEXTLOAD:
481     return ISD::SIGN_EXTEND;
482   case ISD::ZEXTLOAD:
483     return ISD::ZERO_EXTEND;
484   default:
485     break;
486   }
487 
488   llvm_unreachable("Invalid LoadExtType");
489 }
490 
491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
492   // To perform this operation, we just need to swap the L and G bits of the
493   // operation.
494   unsigned OldL = (Operation >> 2) & 1;
495   unsigned OldG = (Operation >> 1) & 1;
496   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
497                        (OldL << 1) |       // New G bit
498                        (OldG << 2));       // New L bit.
499 }
500 
501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
502   unsigned Operation = Op;
503   if (isIntegerLike)
504     Operation ^= 7;   // Flip L, G, E bits, but not U.
505   else
506     Operation ^= 15;  // Flip all of the condition bits.
507 
508   if (Operation > ISD::SETTRUE2)
509     Operation &= ~8;  // Don't let N and U bits get set.
510 
511   return ISD::CondCode(Operation);
512 }
513 
514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
515   return getSetCCInverseImpl(Op, Type.isInteger());
516 }
517 
518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
519                                                bool isIntegerLike) {
520   return getSetCCInverseImpl(Op, isIntegerLike);
521 }
522 
523 /// For an integer comparison, return 1 if the comparison is a signed operation
524 /// and 2 if the result is an unsigned comparison. Return zero if the operation
525 /// does not depend on the sign of the input (setne and seteq).
526 static int isSignedOp(ISD::CondCode Opcode) {
527   switch (Opcode) {
528   default: llvm_unreachable("Illegal integer setcc operation!");
529   case ISD::SETEQ:
530   case ISD::SETNE: return 0;
531   case ISD::SETLT:
532   case ISD::SETLE:
533   case ISD::SETGT:
534   case ISD::SETGE: return 1;
535   case ISD::SETULT:
536   case ISD::SETULE:
537   case ISD::SETUGT:
538   case ISD::SETUGE: return 2;
539   }
540 }
541 
542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
543                                        EVT Type) {
544   bool IsInteger = Type.isInteger();
545   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
546     // Cannot fold a signed integer setcc with an unsigned integer setcc.
547     return ISD::SETCC_INVALID;
548 
549   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
550 
551   // If the N and U bits get set, then the resultant comparison DOES suddenly
552   // care about orderedness, and it is true when ordered.
553   if (Op > ISD::SETTRUE2)
554     Op &= ~16;     // Clear the U bit if the N bit is set.
555 
556   // Canonicalize illegal integer setcc's.
557   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
558     Op = ISD::SETNE;
559 
560   return ISD::CondCode(Op);
561 }
562 
563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
564                                         EVT Type) {
565   bool IsInteger = Type.isInteger();
566   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
567     // Cannot fold a signed setcc with an unsigned setcc.
568     return ISD::SETCC_INVALID;
569 
570   // Combine all of the condition bits.
571   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
572 
573   // Canonicalize illegal integer setcc's.
574   if (IsInteger) {
575     switch (Result) {
576     default: break;
577     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
578     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
579     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
580     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
581     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
582     }
583   }
584 
585   return Result;
586 }
587 
588 //===----------------------------------------------------------------------===//
589 //                           SDNode Profile Support
590 //===----------------------------------------------------------------------===//
591 
592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
594   ID.AddInteger(OpC);
595 }
596 
597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
598 /// solely with their pointer.
599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
600   ID.AddPointer(VTList.VTs);
601 }
602 
603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
604 static void AddNodeIDOperands(FoldingSetNodeID &ID,
605                               ArrayRef<SDValue> Ops) {
606   for (const auto &Op : Ops) {
607     ID.AddPointer(Op.getNode());
608     ID.AddInteger(Op.getResNo());
609   }
610 }
611 
612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
613 static void AddNodeIDOperands(FoldingSetNodeID &ID,
614                               ArrayRef<SDUse> Ops) {
615   for (const auto &Op : Ops) {
616     ID.AddPointer(Op.getNode());
617     ID.AddInteger(Op.getResNo());
618   }
619 }
620 
621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
622                           SDVTList VTList, ArrayRef<SDValue> OpList) {
623   AddNodeIDOpcode(ID, OpC);
624   AddNodeIDValueTypes(ID, VTList);
625   AddNodeIDOperands(ID, OpList);
626 }
627 
628 /// If this is an SDNode with special info, add this info to the NodeID data.
629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
630   switch (N->getOpcode()) {
631   case ISD::TargetExternalSymbol:
632   case ISD::ExternalSymbol:
633   case ISD::MCSymbol:
634     llvm_unreachable("Should only be used on nodes with operands");
635   default: break;  // Normal nodes don't need extra info.
636   case ISD::TargetConstant:
637   case ISD::Constant: {
638     const ConstantSDNode *C = cast<ConstantSDNode>(N);
639     ID.AddPointer(C->getConstantIntValue());
640     ID.AddBoolean(C->isOpaque());
641     break;
642   }
643   case ISD::TargetConstantFP:
644   case ISD::ConstantFP:
645     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
646     break;
647   case ISD::TargetGlobalAddress:
648   case ISD::GlobalAddress:
649   case ISD::TargetGlobalTLSAddress:
650   case ISD::GlobalTLSAddress: {
651     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
652     ID.AddPointer(GA->getGlobal());
653     ID.AddInteger(GA->getOffset());
654     ID.AddInteger(GA->getTargetFlags());
655     break;
656   }
657   case ISD::BasicBlock:
658     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
659     break;
660   case ISD::Register:
661     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
662     break;
663   case ISD::RegisterMask:
664     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
665     break;
666   case ISD::SRCVALUE:
667     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
668     break;
669   case ISD::FrameIndex:
670   case ISD::TargetFrameIndex:
671     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
672     break;
673   case ISD::LIFETIME_START:
674   case ISD::LIFETIME_END:
675     if (cast<LifetimeSDNode>(N)->hasOffset()) {
676       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
677       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
678     }
679     break;
680   case ISD::PSEUDO_PROBE:
681     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
682     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
683     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
684     break;
685   case ISD::JumpTable:
686   case ISD::TargetJumpTable:
687     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
688     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
689     break;
690   case ISD::ConstantPool:
691   case ISD::TargetConstantPool: {
692     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
693     ID.AddInteger(CP->getAlign().value());
694     ID.AddInteger(CP->getOffset());
695     if (CP->isMachineConstantPoolEntry())
696       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
697     else
698       ID.AddPointer(CP->getConstVal());
699     ID.AddInteger(CP->getTargetFlags());
700     break;
701   }
702   case ISD::TargetIndex: {
703     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
704     ID.AddInteger(TI->getIndex());
705     ID.AddInteger(TI->getOffset());
706     ID.AddInteger(TI->getTargetFlags());
707     break;
708   }
709   case ISD::LOAD: {
710     const LoadSDNode *LD = cast<LoadSDNode>(N);
711     ID.AddInteger(LD->getMemoryVT().getRawBits());
712     ID.AddInteger(LD->getRawSubclassData());
713     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
714     ID.AddInteger(LD->getMemOperand()->getFlags());
715     break;
716   }
717   case ISD::STORE: {
718     const StoreSDNode *ST = cast<StoreSDNode>(N);
719     ID.AddInteger(ST->getMemoryVT().getRawBits());
720     ID.AddInteger(ST->getRawSubclassData());
721     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
722     ID.AddInteger(ST->getMemOperand()->getFlags());
723     break;
724   }
725   case ISD::VP_LOAD: {
726     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
727     ID.AddInteger(ELD->getMemoryVT().getRawBits());
728     ID.AddInteger(ELD->getRawSubclassData());
729     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
730     ID.AddInteger(ELD->getMemOperand()->getFlags());
731     break;
732   }
733   case ISD::VP_STORE: {
734     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735     ID.AddInteger(EST->getMemoryVT().getRawBits());
736     ID.AddInteger(EST->getRawSubclassData());
737     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738     ID.AddInteger(EST->getMemOperand()->getFlags());
739     break;
740   }
741   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
742     const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
743     ID.AddInteger(SLD->getMemoryVT().getRawBits());
744     ID.AddInteger(SLD->getRawSubclassData());
745     ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
746     break;
747   }
748   case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
749     const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
750     ID.AddInteger(SST->getMemoryVT().getRawBits());
751     ID.AddInteger(SST->getRawSubclassData());
752     ID.AddInteger(SST->getPointerInfo().getAddrSpace());
753     break;
754   }
755   case ISD::VP_GATHER: {
756     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
757     ID.AddInteger(EG->getMemoryVT().getRawBits());
758     ID.AddInteger(EG->getRawSubclassData());
759     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
760     ID.AddInteger(EG->getMemOperand()->getFlags());
761     break;
762   }
763   case ISD::VP_SCATTER: {
764     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
765     ID.AddInteger(ES->getMemoryVT().getRawBits());
766     ID.AddInteger(ES->getRawSubclassData());
767     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
768     ID.AddInteger(ES->getMemOperand()->getFlags());
769     break;
770   }
771   case ISD::MLOAD: {
772     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
773     ID.AddInteger(MLD->getMemoryVT().getRawBits());
774     ID.AddInteger(MLD->getRawSubclassData());
775     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
776     ID.AddInteger(MLD->getMemOperand()->getFlags());
777     break;
778   }
779   case ISD::MSTORE: {
780     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
781     ID.AddInteger(MST->getMemoryVT().getRawBits());
782     ID.AddInteger(MST->getRawSubclassData());
783     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
784     ID.AddInteger(MST->getMemOperand()->getFlags());
785     break;
786   }
787   case ISD::MGATHER: {
788     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
789     ID.AddInteger(MG->getMemoryVT().getRawBits());
790     ID.AddInteger(MG->getRawSubclassData());
791     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
792     ID.AddInteger(MG->getMemOperand()->getFlags());
793     break;
794   }
795   case ISD::MSCATTER: {
796     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
797     ID.AddInteger(MS->getMemoryVT().getRawBits());
798     ID.AddInteger(MS->getRawSubclassData());
799     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
800     ID.AddInteger(MS->getMemOperand()->getFlags());
801     break;
802   }
803   case ISD::ATOMIC_CMP_SWAP:
804   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
805   case ISD::ATOMIC_SWAP:
806   case ISD::ATOMIC_LOAD_ADD:
807   case ISD::ATOMIC_LOAD_SUB:
808   case ISD::ATOMIC_LOAD_AND:
809   case ISD::ATOMIC_LOAD_CLR:
810   case ISD::ATOMIC_LOAD_OR:
811   case ISD::ATOMIC_LOAD_XOR:
812   case ISD::ATOMIC_LOAD_NAND:
813   case ISD::ATOMIC_LOAD_MIN:
814   case ISD::ATOMIC_LOAD_MAX:
815   case ISD::ATOMIC_LOAD_UMIN:
816   case ISD::ATOMIC_LOAD_UMAX:
817   case ISD::ATOMIC_LOAD:
818   case ISD::ATOMIC_STORE: {
819     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
820     ID.AddInteger(AT->getMemoryVT().getRawBits());
821     ID.AddInteger(AT->getRawSubclassData());
822     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
823     ID.AddInteger(AT->getMemOperand()->getFlags());
824     break;
825   }
826   case ISD::PREFETCH: {
827     const MemSDNode *PF = cast<MemSDNode>(N);
828     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
829     ID.AddInteger(PF->getMemOperand()->getFlags());
830     break;
831   }
832   case ISD::VECTOR_SHUFFLE: {
833     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
834     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
835          i != e; ++i)
836       ID.AddInteger(SVN->getMaskElt(i));
837     break;
838   }
839   case ISD::TargetBlockAddress:
840   case ISD::BlockAddress: {
841     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
842     ID.AddPointer(BA->getBlockAddress());
843     ID.AddInteger(BA->getOffset());
844     ID.AddInteger(BA->getTargetFlags());
845     break;
846   }
847   case ISD::AssertAlign:
848     ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
849     break;
850   } // end switch (N->getOpcode())
851 
852   // Target specific memory nodes could also have address spaces and flags
853   // to check.
854   if (N->isTargetMemoryOpcode()) {
855     const MemSDNode *MN = cast<MemSDNode>(N);
856     ID.AddInteger(MN->getPointerInfo().getAddrSpace());
857     ID.AddInteger(MN->getMemOperand()->getFlags());
858   }
859 }
860 
861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
862 /// data.
863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
864   AddNodeIDOpcode(ID, N->getOpcode());
865   // Add the return value info.
866   AddNodeIDValueTypes(ID, N->getVTList());
867   // Add the operand info.
868   AddNodeIDOperands(ID, N->ops());
869 
870   // Handle SDNode leafs with special info.
871   AddNodeIDCustom(ID, N);
872 }
873 
874 //===----------------------------------------------------------------------===//
875 //                              SelectionDAG Class
876 //===----------------------------------------------------------------------===//
877 
878 /// doNotCSE - Return true if CSE should not be performed for this node.
879 static bool doNotCSE(SDNode *N) {
880   if (N->getValueType(0) == MVT::Glue)
881     return true; // Never CSE anything that produces a flag.
882 
883   switch (N->getOpcode()) {
884   default: break;
885   case ISD::HANDLENODE:
886   case ISD::EH_LABEL:
887     return true;   // Never CSE these nodes.
888   }
889 
890   // Check that remaining values produced are not flags.
891   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
892     if (N->getValueType(i) == MVT::Glue)
893       return true; // Never CSE anything that produces a flag.
894 
895   return false;
896 }
897 
898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
899 /// SelectionDAG.
900 void SelectionDAG::RemoveDeadNodes() {
901   // Create a dummy node (which is not added to allnodes), that adds a reference
902   // to the root node, preventing it from being deleted.
903   HandleSDNode Dummy(getRoot());
904 
905   SmallVector<SDNode*, 128> DeadNodes;
906 
907   // Add all obviously-dead nodes to the DeadNodes worklist.
908   for (SDNode &Node : allnodes())
909     if (Node.use_empty())
910       DeadNodes.push_back(&Node);
911 
912   RemoveDeadNodes(DeadNodes);
913 
914   // If the root changed (e.g. it was a dead load, update the root).
915   setRoot(Dummy.getValue());
916 }
917 
918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
919 /// given list, and any nodes that become unreachable as a result.
920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
921 
922   // Process the worklist, deleting the nodes and adding their uses to the
923   // worklist.
924   while (!DeadNodes.empty()) {
925     SDNode *N = DeadNodes.pop_back_val();
926     // Skip to next node if we've already managed to delete the node. This could
927     // happen if replacing a node causes a node previously added to the node to
928     // be deleted.
929     if (N->getOpcode() == ISD::DELETED_NODE)
930       continue;
931 
932     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
933       DUL->NodeDeleted(N, nullptr);
934 
935     // Take the node out of the appropriate CSE map.
936     RemoveNodeFromCSEMaps(N);
937 
938     // Next, brutally remove the operand list.  This is safe to do, as there are
939     // no cycles in the graph.
940     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
941       SDUse &Use = *I++;
942       SDNode *Operand = Use.getNode();
943       Use.set(SDValue());
944 
945       // Now that we removed this operand, see if there are no uses of it left.
946       if (Operand->use_empty())
947         DeadNodes.push_back(Operand);
948     }
949 
950     DeallocateNode(N);
951   }
952 }
953 
954 void SelectionDAG::RemoveDeadNode(SDNode *N){
955   SmallVector<SDNode*, 16> DeadNodes(1, N);
956 
957   // Create a dummy node that adds a reference to the root node, preventing
958   // it from being deleted.  (This matters if the root is an operand of the
959   // dead node.)
960   HandleSDNode Dummy(getRoot());
961 
962   RemoveDeadNodes(DeadNodes);
963 }
964 
965 void SelectionDAG::DeleteNode(SDNode *N) {
966   // First take this out of the appropriate CSE map.
967   RemoveNodeFromCSEMaps(N);
968 
969   // Finally, remove uses due to operands of this node, remove from the
970   // AllNodes list, and delete the node.
971   DeleteNodeNotInCSEMaps(N);
972 }
973 
974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
975   assert(N->getIterator() != AllNodes.begin() &&
976          "Cannot delete the entry node!");
977   assert(N->use_empty() && "Cannot delete a node that is not dead!");
978 
979   // Drop all of the operands and decrement used node's use counts.
980   N->DropOperands();
981 
982   DeallocateNode(N);
983 }
984 
985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
986   assert(!(V->isVariadic() && isParameter));
987   if (isParameter)
988     ByvalParmDbgValues.push_back(V);
989   else
990     DbgValues.push_back(V);
991   for (const SDNode *Node : V->getSDNodes())
992     if (Node)
993       DbgValMap[Node].push_back(V);
994 }
995 
996 void SDDbgInfo::erase(const SDNode *Node) {
997   DbgValMapType::iterator I = DbgValMap.find(Node);
998   if (I == DbgValMap.end())
999     return;
1000   for (auto &Val: I->second)
1001     Val->setIsInvalidated();
1002   DbgValMap.erase(I);
1003 }
1004 
1005 void SelectionDAG::DeallocateNode(SDNode *N) {
1006   // If we have operands, deallocate them.
1007   removeOperands(N);
1008 
1009   NodeAllocator.Deallocate(AllNodes.remove(N));
1010 
1011   // Set the opcode to DELETED_NODE to help catch bugs when node
1012   // memory is reallocated.
1013   // FIXME: There are places in SDag that have grown a dependency on the opcode
1014   // value in the released node.
1015   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1016   N->NodeType = ISD::DELETED_NODE;
1017 
1018   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1019   // them and forget about that node.
1020   DbgInfo->erase(N);
1021 }
1022 
1023 #ifndef NDEBUG
1024 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
1025 static void VerifySDNode(SDNode *N) {
1026   switch (N->getOpcode()) {
1027   default:
1028     break;
1029   case ISD::BUILD_PAIR: {
1030     EVT VT = N->getValueType(0);
1031     assert(N->getNumValues() == 1 && "Too many results!");
1032     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1033            "Wrong return type!");
1034     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1035     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1036            "Mismatched operand types!");
1037     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1038            "Wrong operand type!");
1039     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1040            "Wrong return type size");
1041     break;
1042   }
1043   case ISD::BUILD_VECTOR: {
1044     assert(N->getNumValues() == 1 && "Too many results!");
1045     assert(N->getValueType(0).isVector() && "Wrong return type!");
1046     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1047            "Wrong number of operands!");
1048     EVT EltVT = N->getValueType(0).getVectorElementType();
1049     for (const SDUse &Op : N->ops()) {
1050       assert((Op.getValueType() == EltVT ||
1051               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1052                EltVT.bitsLE(Op.getValueType()))) &&
1053              "Wrong operand type!");
1054       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1055              "Operands must all have the same type");
1056     }
1057     break;
1058   }
1059   }
1060 }
1061 #endif // NDEBUG
1062 
1063 /// Insert a newly allocated node into the DAG.
1064 ///
1065 /// Handles insertion into the all nodes list and CSE map, as well as
1066 /// verification and other common operations when a new node is allocated.
1067 void SelectionDAG::InsertNode(SDNode *N) {
1068   AllNodes.push_back(N);
1069 #ifndef NDEBUG
1070   N->PersistentId = NextPersistentId++;
1071   VerifySDNode(N);
1072 #endif
1073   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1074     DUL->NodeInserted(N);
1075 }
1076 
1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1078 /// correspond to it.  This is useful when we're about to delete or repurpose
1079 /// the node.  We don't want future request for structurally identical nodes
1080 /// to return N anymore.
1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1082   bool Erased = false;
1083   switch (N->getOpcode()) {
1084   case ISD::HANDLENODE: return false;  // noop.
1085   case ISD::CONDCODE:
1086     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1087            "Cond code doesn't exist!");
1088     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1089     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1090     break;
1091   case ISD::ExternalSymbol:
1092     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1093     break;
1094   case ISD::TargetExternalSymbol: {
1095     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1096     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1097         ESN->getSymbol(), ESN->getTargetFlags()));
1098     break;
1099   }
1100   case ISD::MCSymbol: {
1101     auto *MCSN = cast<MCSymbolSDNode>(N);
1102     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1103     break;
1104   }
1105   case ISD::VALUETYPE: {
1106     EVT VT = cast<VTSDNode>(N)->getVT();
1107     if (VT.isExtended()) {
1108       Erased = ExtendedValueTypeNodes.erase(VT);
1109     } else {
1110       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1111       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1112     }
1113     break;
1114   }
1115   default:
1116     // Remove it from the CSE Map.
1117     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1118     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1119     Erased = CSEMap.RemoveNode(N);
1120     break;
1121   }
1122 #ifndef NDEBUG
1123   // Verify that the node was actually in one of the CSE maps, unless it has a
1124   // flag result (which cannot be CSE'd) or is one of the special cases that are
1125   // not subject to CSE.
1126   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1127       !N->isMachineOpcode() && !doNotCSE(N)) {
1128     N->dump(this);
1129     dbgs() << "\n";
1130     llvm_unreachable("Node is not in map!");
1131   }
1132 #endif
1133   return Erased;
1134 }
1135 
1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1138 /// node already exists, in which case transfer all its users to the existing
1139 /// node. This transfer can potentially trigger recursive merging.
1140 void
1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1142   // For node types that aren't CSE'd, just act as if no identical node
1143   // already exists.
1144   if (!doNotCSE(N)) {
1145     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1146     if (Existing != N) {
1147       // If there was already an existing matching node, use ReplaceAllUsesWith
1148       // to replace the dead one with the existing one.  This can cause
1149       // recursive merging of other unrelated nodes down the line.
1150       ReplaceAllUsesWith(N, Existing);
1151 
1152       // N is now dead. Inform the listeners and delete it.
1153       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1154         DUL->NodeDeleted(N, Existing);
1155       DeleteNodeNotInCSEMaps(N);
1156       return;
1157     }
1158   }
1159 
1160   // If the node doesn't already exist, we updated it.  Inform listeners.
1161   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1162     DUL->NodeUpdated(N);
1163 }
1164 
1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1166 /// were replaced with those specified.  If this node is never memoized,
1167 /// return null, otherwise return a pointer to the slot it would take.  If a
1168 /// node already exists with these operands, the slot will be non-null.
1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1170                                            void *&InsertPos) {
1171   if (doNotCSE(N))
1172     return nullptr;
1173 
1174   SDValue Ops[] = { Op };
1175   FoldingSetNodeID ID;
1176   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1177   AddNodeIDCustom(ID, N);
1178   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1179   if (Node)
1180     Node->intersectFlagsWith(N->getFlags());
1181   return Node;
1182 }
1183 
1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1185 /// were replaced with those specified.  If this node is never memoized,
1186 /// return null, otherwise return a pointer to the slot it would take.  If a
1187 /// node already exists with these operands, the slot will be non-null.
1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1189                                            SDValue Op1, SDValue Op2,
1190                                            void *&InsertPos) {
1191   if (doNotCSE(N))
1192     return nullptr;
1193 
1194   SDValue Ops[] = { Op1, Op2 };
1195   FoldingSetNodeID ID;
1196   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1197   AddNodeIDCustom(ID, N);
1198   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1199   if (Node)
1200     Node->intersectFlagsWith(N->getFlags());
1201   return Node;
1202 }
1203 
1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1205 /// were replaced with those specified.  If this node is never memoized,
1206 /// return null, otherwise return a pointer to the slot it would take.  If a
1207 /// node already exists with these operands, the slot will be non-null.
1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1209                                            void *&InsertPos) {
1210   if (doNotCSE(N))
1211     return nullptr;
1212 
1213   FoldingSetNodeID ID;
1214   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1215   AddNodeIDCustom(ID, N);
1216   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1217   if (Node)
1218     Node->intersectFlagsWith(N->getFlags());
1219   return Node;
1220 }
1221 
1222 Align SelectionDAG::getEVTAlign(EVT VT) const {
1223   Type *Ty = VT == MVT::iPTR ?
1224                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1225                    VT.getTypeForEVT(*getContext());
1226 
1227   return getDataLayout().getABITypeAlign(Ty);
1228 }
1229 
1230 // EntryNode could meaningfully have debug info if we can find it...
1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1232     : TM(tm), OptLevel(OL),
1233       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1234       Root(getEntryNode()) {
1235   InsertNode(&EntryNode);
1236   DbgInfo = new SDDbgInfo();
1237 }
1238 
1239 void SelectionDAG::init(MachineFunction &NewMF,
1240                         OptimizationRemarkEmitter &NewORE,
1241                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1242                         LegacyDivergenceAnalysis * Divergence,
1243                         ProfileSummaryInfo *PSIin,
1244                         BlockFrequencyInfo *BFIin) {
1245   MF = &NewMF;
1246   SDAGISelPass = PassPtr;
1247   ORE = &NewORE;
1248   TLI = getSubtarget().getTargetLowering();
1249   TSI = getSubtarget().getSelectionDAGInfo();
1250   LibInfo = LibraryInfo;
1251   Context = &MF->getFunction().getContext();
1252   DA = Divergence;
1253   PSI = PSIin;
1254   BFI = BFIin;
1255 }
1256 
1257 SelectionDAG::~SelectionDAG() {
1258   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1259   allnodes_clear();
1260   OperandRecycler.clear(OperandAllocator);
1261   delete DbgInfo;
1262 }
1263 
1264 bool SelectionDAG::shouldOptForSize() const {
1265   return MF->getFunction().hasOptSize() ||
1266       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1267 }
1268 
1269 void SelectionDAG::allnodes_clear() {
1270   assert(&*AllNodes.begin() == &EntryNode);
1271   AllNodes.remove(AllNodes.begin());
1272   while (!AllNodes.empty())
1273     DeallocateNode(&AllNodes.front());
1274 #ifndef NDEBUG
1275   NextPersistentId = 0;
1276 #endif
1277 }
1278 
1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1280                                           void *&InsertPos) {
1281   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1282   if (N) {
1283     switch (N->getOpcode()) {
1284     default: break;
1285     case ISD::Constant:
1286     case ISD::ConstantFP:
1287       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1288                        "debug location.  Use another overload.");
1289     }
1290   }
1291   return N;
1292 }
1293 
1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1295                                           const SDLoc &DL, void *&InsertPos) {
1296   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1297   if (N) {
1298     switch (N->getOpcode()) {
1299     case ISD::Constant:
1300     case ISD::ConstantFP:
1301       // Erase debug location from the node if the node is used at several
1302       // different places. Do not propagate one location to all uses as it
1303       // will cause a worse single stepping debugging experience.
1304       if (N->getDebugLoc() != DL.getDebugLoc())
1305         N->setDebugLoc(DebugLoc());
1306       break;
1307     default:
1308       // When the node's point of use is located earlier in the instruction
1309       // sequence than its prior point of use, update its debug info to the
1310       // earlier location.
1311       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1312         N->setDebugLoc(DL.getDebugLoc());
1313       break;
1314     }
1315   }
1316   return N;
1317 }
1318 
1319 void SelectionDAG::clear() {
1320   allnodes_clear();
1321   OperandRecycler.clear(OperandAllocator);
1322   OperandAllocator.Reset();
1323   CSEMap.clear();
1324 
1325   ExtendedValueTypeNodes.clear();
1326   ExternalSymbols.clear();
1327   TargetExternalSymbols.clear();
1328   MCSymbols.clear();
1329   SDCallSiteDbgInfo.clear();
1330   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1331             static_cast<CondCodeSDNode*>(nullptr));
1332   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1333             static_cast<SDNode*>(nullptr));
1334 
1335   EntryNode.UseList = nullptr;
1336   InsertNode(&EntryNode);
1337   Root = getEntryNode();
1338   DbgInfo->clear();
1339 }
1340 
1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1342   return VT.bitsGT(Op.getValueType())
1343              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1344              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1345 }
1346 
1347 std::pair<SDValue, SDValue>
1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1349                                        const SDLoc &DL, EVT VT) {
1350   assert(!VT.bitsEq(Op.getValueType()) &&
1351          "Strict no-op FP extend/round not allowed.");
1352   SDValue Res =
1353       VT.bitsGT(Op.getValueType())
1354           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1355           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1356                     {Chain, Op, getIntPtrConstant(0, DL)});
1357 
1358   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1359 }
1360 
1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362   return VT.bitsGT(Op.getValueType()) ?
1363     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1364     getNode(ISD::TRUNCATE, DL, VT, Op);
1365 }
1366 
1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1368   return VT.bitsGT(Op.getValueType()) ?
1369     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1370     getNode(ISD::TRUNCATE, DL, VT, Op);
1371 }
1372 
1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1374   return VT.bitsGT(Op.getValueType()) ?
1375     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1376     getNode(ISD::TRUNCATE, DL, VT, Op);
1377 }
1378 
1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1380                                         EVT OpVT) {
1381   if (VT.bitsLE(Op.getValueType()))
1382     return getNode(ISD::TRUNCATE, SL, VT, Op);
1383 
1384   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1385   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1386 }
1387 
1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1389   EVT OpVT = Op.getValueType();
1390   assert(VT.isInteger() && OpVT.isInteger() &&
1391          "Cannot getZeroExtendInReg FP types");
1392   assert(VT.isVector() == OpVT.isVector() &&
1393          "getZeroExtendInReg type should be vector iff the operand "
1394          "type is vector!");
1395   assert((!VT.isVector() ||
1396           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1397          "Vector element counts must match in getZeroExtendInReg");
1398   assert(VT.bitsLE(OpVT) && "Not extending!");
1399   if (OpVT == VT)
1400     return Op;
1401   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1402                                    VT.getScalarSizeInBits());
1403   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1404 }
1405 
1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1407   // Only unsigned pointer semantics are supported right now. In the future this
1408   // might delegate to TLI to check pointer signedness.
1409   return getZExtOrTrunc(Op, DL, VT);
1410 }
1411 
1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1413   // Only unsigned pointer semantics are supported right now. In the future this
1414   // might delegate to TLI to check pointer signedness.
1415   return getZeroExtendInReg(Op, DL, VT);
1416 }
1417 
1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1420   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1421 }
1422 
1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1424   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1425   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1426 }
1427 
1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
1429                                       SDValue Mask, SDValue EVL, EVT VT) {
1430   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1431   return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1432 }
1433 
1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1435                                       EVT OpVT) {
1436   if (!V)
1437     return getConstant(0, DL, VT);
1438 
1439   switch (TLI->getBooleanContents(OpVT)) {
1440   case TargetLowering::ZeroOrOneBooleanContent:
1441   case TargetLowering::UndefinedBooleanContent:
1442     return getConstant(1, DL, VT);
1443   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1444     return getAllOnesConstant(DL, VT);
1445   }
1446   llvm_unreachable("Unexpected boolean content enum!");
1447 }
1448 
1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1450                                   bool isT, bool isO) {
1451   EVT EltVT = VT.getScalarType();
1452   assert((EltVT.getSizeInBits() >= 64 ||
1453           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1454          "getConstant with a uint64_t value that doesn't fit in the type!");
1455   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1456 }
1457 
1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1459                                   bool isT, bool isO) {
1460   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1461 }
1462 
1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1464                                   EVT VT, bool isT, bool isO) {
1465   assert(VT.isInteger() && "Cannot create FP integer constant!");
1466 
1467   EVT EltVT = VT.getScalarType();
1468   const ConstantInt *Elt = &Val;
1469 
1470   // In some cases the vector type is legal but the element type is illegal and
1471   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1472   // inserted value (the type does not need to match the vector element type).
1473   // Any extra bits introduced will be truncated away.
1474   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1475                            TargetLowering::TypePromoteInteger) {
1476     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1477     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1478     Elt = ConstantInt::get(*getContext(), NewVal);
1479   }
1480   // In other cases the element type is illegal and needs to be expanded, for
1481   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1482   // the value into n parts and use a vector type with n-times the elements.
1483   // Then bitcast to the type requested.
1484   // Legalizing constants too early makes the DAGCombiner's job harder so we
1485   // only legalize if the DAG tells us we must produce legal types.
1486   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1487            TLI->getTypeAction(*getContext(), EltVT) ==
1488                TargetLowering::TypeExpandInteger) {
1489     const APInt &NewVal = Elt->getValue();
1490     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1491     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1492 
1493     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1494     if (VT.isScalableVector()) {
1495       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1496              "Can only handle an even split!");
1497       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1498 
1499       SmallVector<SDValue, 2> ScalarParts;
1500       for (unsigned i = 0; i != Parts; ++i)
1501         ScalarParts.push_back(getConstant(
1502             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1503             ViaEltVT, isT, isO));
1504 
1505       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1506     }
1507 
1508     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1509     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1510 
1511     // Check the temporary vector is the correct size. If this fails then
1512     // getTypeToTransformTo() probably returned a type whose size (in bits)
1513     // isn't a power-of-2 factor of the requested type size.
1514     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1515 
1516     SmallVector<SDValue, 2> EltParts;
1517     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1518       EltParts.push_back(getConstant(
1519           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1520           ViaEltVT, isT, isO));
1521 
1522     // EltParts is currently in little endian order. If we actually want
1523     // big-endian order then reverse it now.
1524     if (getDataLayout().isBigEndian())
1525       std::reverse(EltParts.begin(), EltParts.end());
1526 
1527     // The elements must be reversed when the element order is different
1528     // to the endianness of the elements (because the BITCAST is itself a
1529     // vector shuffle in this situation). However, we do not need any code to
1530     // perform this reversal because getConstant() is producing a vector
1531     // splat.
1532     // This situation occurs in MIPS MSA.
1533 
1534     SmallVector<SDValue, 8> Ops;
1535     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1536       llvm::append_range(Ops, EltParts);
1537 
1538     SDValue V =
1539         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1540     return V;
1541   }
1542 
1543   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1544          "APInt size does not match type size!");
1545   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1546   FoldingSetNodeID ID;
1547   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1548   ID.AddPointer(Elt);
1549   ID.AddBoolean(isO);
1550   void *IP = nullptr;
1551   SDNode *N = nullptr;
1552   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1553     if (!VT.isVector())
1554       return SDValue(N, 0);
1555 
1556   if (!N) {
1557     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1558     CSEMap.InsertNode(N, IP);
1559     InsertNode(N);
1560     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1561   }
1562 
1563   SDValue Result(N, 0);
1564   if (VT.isScalableVector())
1565     Result = getSplatVector(VT, DL, Result);
1566   else if (VT.isVector())
1567     Result = getSplatBuildVector(VT, DL, Result);
1568 
1569   return Result;
1570 }
1571 
1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1573                                         bool isTarget) {
1574   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1575 }
1576 
1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1578                                              const SDLoc &DL, bool LegalTypes) {
1579   assert(VT.isInteger() && "Shift amount is not an integer type!");
1580   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1581   return getConstant(Val, DL, ShiftVT);
1582 }
1583 
1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1585                                            bool isTarget) {
1586   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1587 }
1588 
1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1590                                     bool isTarget) {
1591   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1592 }
1593 
1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1595                                     EVT VT, bool isTarget) {
1596   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1597 
1598   EVT EltVT = VT.getScalarType();
1599 
1600   // Do the map lookup using the actual bit pattern for the floating point
1601   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1602   // we don't have issues with SNANs.
1603   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1604   FoldingSetNodeID ID;
1605   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1606   ID.AddPointer(&V);
1607   void *IP = nullptr;
1608   SDNode *N = nullptr;
1609   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1610     if (!VT.isVector())
1611       return SDValue(N, 0);
1612 
1613   if (!N) {
1614     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1615     CSEMap.InsertNode(N, IP);
1616     InsertNode(N);
1617   }
1618 
1619   SDValue Result(N, 0);
1620   if (VT.isScalableVector())
1621     Result = getSplatVector(VT, DL, Result);
1622   else if (VT.isVector())
1623     Result = getSplatBuildVector(VT, DL, Result);
1624   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1625   return Result;
1626 }
1627 
1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1629                                     bool isTarget) {
1630   EVT EltVT = VT.getScalarType();
1631   if (EltVT == MVT::f32)
1632     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1633   if (EltVT == MVT::f64)
1634     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1635   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1636       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1637     bool Ignored;
1638     APFloat APF = APFloat(Val);
1639     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1640                 &Ignored);
1641     return getConstantFP(APF, DL, VT, isTarget);
1642   }
1643   llvm_unreachable("Unsupported type in getConstantFP");
1644 }
1645 
1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1647                                        EVT VT, int64_t Offset, bool isTargetGA,
1648                                        unsigned TargetFlags) {
1649   assert((TargetFlags == 0 || isTargetGA) &&
1650          "Cannot set target flags on target-independent globals");
1651 
1652   // Truncate (with sign-extension) the offset value to the pointer size.
1653   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1654   if (BitWidth < 64)
1655     Offset = SignExtend64(Offset, BitWidth);
1656 
1657   unsigned Opc;
1658   if (GV->isThreadLocal())
1659     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1660   else
1661     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1662 
1663   FoldingSetNodeID ID;
1664   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1665   ID.AddPointer(GV);
1666   ID.AddInteger(Offset);
1667   ID.AddInteger(TargetFlags);
1668   void *IP = nullptr;
1669   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1670     return SDValue(E, 0);
1671 
1672   auto *N = newSDNode<GlobalAddressSDNode>(
1673       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1674   CSEMap.InsertNode(N, IP);
1675     InsertNode(N);
1676   return SDValue(N, 0);
1677 }
1678 
1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1680   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1681   FoldingSetNodeID ID;
1682   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1683   ID.AddInteger(FI);
1684   void *IP = nullptr;
1685   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1686     return SDValue(E, 0);
1687 
1688   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1689   CSEMap.InsertNode(N, IP);
1690   InsertNode(N);
1691   return SDValue(N, 0);
1692 }
1693 
1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1695                                    unsigned TargetFlags) {
1696   assert((TargetFlags == 0 || isTarget) &&
1697          "Cannot set target flags on target-independent jump tables");
1698   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1699   FoldingSetNodeID ID;
1700   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1701   ID.AddInteger(JTI);
1702   ID.AddInteger(TargetFlags);
1703   void *IP = nullptr;
1704   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1705     return SDValue(E, 0);
1706 
1707   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1708   CSEMap.InsertNode(N, IP);
1709   InsertNode(N);
1710   return SDValue(N, 0);
1711 }
1712 
1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1714                                       MaybeAlign Alignment, int Offset,
1715                                       bool isTarget, unsigned TargetFlags) {
1716   assert((TargetFlags == 0 || isTarget) &&
1717          "Cannot set target flags on target-independent globals");
1718   if (!Alignment)
1719     Alignment = shouldOptForSize()
1720                     ? getDataLayout().getABITypeAlign(C->getType())
1721                     : getDataLayout().getPrefTypeAlign(C->getType());
1722   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1723   FoldingSetNodeID ID;
1724   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1725   ID.AddInteger(Alignment->value());
1726   ID.AddInteger(Offset);
1727   ID.AddPointer(C);
1728   ID.AddInteger(TargetFlags);
1729   void *IP = nullptr;
1730   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1731     return SDValue(E, 0);
1732 
1733   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1734                                           TargetFlags);
1735   CSEMap.InsertNode(N, IP);
1736   InsertNode(N);
1737   SDValue V = SDValue(N, 0);
1738   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1739   return V;
1740 }
1741 
1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1743                                       MaybeAlign Alignment, int Offset,
1744                                       bool isTarget, unsigned TargetFlags) {
1745   assert((TargetFlags == 0 || isTarget) &&
1746          "Cannot set target flags on target-independent globals");
1747   if (!Alignment)
1748     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1749   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1750   FoldingSetNodeID ID;
1751   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1752   ID.AddInteger(Alignment->value());
1753   ID.AddInteger(Offset);
1754   C->addSelectionDAGCSEId(ID);
1755   ID.AddInteger(TargetFlags);
1756   void *IP = nullptr;
1757   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1758     return SDValue(E, 0);
1759 
1760   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1761                                           TargetFlags);
1762   CSEMap.InsertNode(N, IP);
1763   InsertNode(N);
1764   return SDValue(N, 0);
1765 }
1766 
1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1768                                      unsigned TargetFlags) {
1769   FoldingSetNodeID ID;
1770   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1771   ID.AddInteger(Index);
1772   ID.AddInteger(Offset);
1773   ID.AddInteger(TargetFlags);
1774   void *IP = nullptr;
1775   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1776     return SDValue(E, 0);
1777 
1778   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1779   CSEMap.InsertNode(N, IP);
1780   InsertNode(N);
1781   return SDValue(N, 0);
1782 }
1783 
1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1785   FoldingSetNodeID ID;
1786   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1787   ID.AddPointer(MBB);
1788   void *IP = nullptr;
1789   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1790     return SDValue(E, 0);
1791 
1792   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1793   CSEMap.InsertNode(N, IP);
1794   InsertNode(N);
1795   return SDValue(N, 0);
1796 }
1797 
1798 SDValue SelectionDAG::getValueType(EVT VT) {
1799   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1800       ValueTypeNodes.size())
1801     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1802 
1803   SDNode *&N = VT.isExtended() ?
1804     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1805 
1806   if (N) return SDValue(N, 0);
1807   N = newSDNode<VTSDNode>(VT);
1808   InsertNode(N);
1809   return SDValue(N, 0);
1810 }
1811 
1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1813   SDNode *&N = ExternalSymbols[Sym];
1814   if (N) return SDValue(N, 0);
1815   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1816   InsertNode(N);
1817   return SDValue(N, 0);
1818 }
1819 
1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1821   SDNode *&N = MCSymbols[Sym];
1822   if (N)
1823     return SDValue(N, 0);
1824   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1825   InsertNode(N);
1826   return SDValue(N, 0);
1827 }
1828 
1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1830                                               unsigned TargetFlags) {
1831   SDNode *&N =
1832       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1833   if (N) return SDValue(N, 0);
1834   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1835   InsertNode(N);
1836   return SDValue(N, 0);
1837 }
1838 
1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1840   if ((unsigned)Cond >= CondCodeNodes.size())
1841     CondCodeNodes.resize(Cond+1);
1842 
1843   if (!CondCodeNodes[Cond]) {
1844     auto *N = newSDNode<CondCodeSDNode>(Cond);
1845     CondCodeNodes[Cond] = N;
1846     InsertNode(N);
1847   }
1848 
1849   return SDValue(CondCodeNodes[Cond], 0);
1850 }
1851 
1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1853   APInt One(ResVT.getScalarSizeInBits(), 1);
1854   return getStepVector(DL, ResVT, One);
1855 }
1856 
1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1858   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1859   if (ResVT.isScalableVector())
1860     return getNode(
1861         ISD::STEP_VECTOR, DL, ResVT,
1862         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1863 
1864   SmallVector<SDValue, 16> OpsStepConstants;
1865   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1866     OpsStepConstants.push_back(
1867         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1868   return getBuildVector(ResVT, DL, OpsStepConstants);
1869 }
1870 
1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1874   std::swap(N1, N2);
1875   ShuffleVectorSDNode::commuteMask(M);
1876 }
1877 
1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1879                                        SDValue N2, ArrayRef<int> Mask) {
1880   assert(VT.getVectorNumElements() == Mask.size() &&
1881          "Must have the same number of vector elements as mask elements!");
1882   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1883          "Invalid VECTOR_SHUFFLE");
1884 
1885   // Canonicalize shuffle undef, undef -> undef
1886   if (N1.isUndef() && N2.isUndef())
1887     return getUNDEF(VT);
1888 
1889   // Validate that all indices in Mask are within the range of the elements
1890   // input to the shuffle.
1891   int NElts = Mask.size();
1892   assert(llvm::all_of(Mask,
1893                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1894          "Index out of range");
1895 
1896   // Copy the mask so we can do any needed cleanup.
1897   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1898 
1899   // Canonicalize shuffle v, v -> v, undef
1900   if (N1 == N2) {
1901     N2 = getUNDEF(VT);
1902     for (int i = 0; i != NElts; ++i)
1903       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1904   }
1905 
1906   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1907   if (N1.isUndef())
1908     commuteShuffle(N1, N2, MaskVec);
1909 
1910   if (TLI->hasVectorBlend()) {
1911     // If shuffling a splat, try to blend the splat instead. We do this here so
1912     // that even when this arises during lowering we don't have to re-handle it.
1913     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1914       BitVector UndefElements;
1915       SDValue Splat = BV->getSplatValue(&UndefElements);
1916       if (!Splat)
1917         return;
1918 
1919       for (int i = 0; i < NElts; ++i) {
1920         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1921           continue;
1922 
1923         // If this input comes from undef, mark it as such.
1924         if (UndefElements[MaskVec[i] - Offset]) {
1925           MaskVec[i] = -1;
1926           continue;
1927         }
1928 
1929         // If we can blend a non-undef lane, use that instead.
1930         if (!UndefElements[i])
1931           MaskVec[i] = i + Offset;
1932       }
1933     };
1934     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1935       BlendSplat(N1BV, 0);
1936     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1937       BlendSplat(N2BV, NElts);
1938   }
1939 
1940   // Canonicalize all index into lhs, -> shuffle lhs, undef
1941   // Canonicalize all index into rhs, -> shuffle rhs, undef
1942   bool AllLHS = true, AllRHS = true;
1943   bool N2Undef = N2.isUndef();
1944   for (int i = 0; i != NElts; ++i) {
1945     if (MaskVec[i] >= NElts) {
1946       if (N2Undef)
1947         MaskVec[i] = -1;
1948       else
1949         AllLHS = false;
1950     } else if (MaskVec[i] >= 0) {
1951       AllRHS = false;
1952     }
1953   }
1954   if (AllLHS && AllRHS)
1955     return getUNDEF(VT);
1956   if (AllLHS && !N2Undef)
1957     N2 = getUNDEF(VT);
1958   if (AllRHS) {
1959     N1 = getUNDEF(VT);
1960     commuteShuffle(N1, N2, MaskVec);
1961   }
1962   // Reset our undef status after accounting for the mask.
1963   N2Undef = N2.isUndef();
1964   // Re-check whether both sides ended up undef.
1965   if (N1.isUndef() && N2Undef)
1966     return getUNDEF(VT);
1967 
1968   // If Identity shuffle return that node.
1969   bool Identity = true, AllSame = true;
1970   for (int i = 0; i != NElts; ++i) {
1971     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1972     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1973   }
1974   if (Identity && NElts)
1975     return N1;
1976 
1977   // Shuffling a constant splat doesn't change the result.
1978   if (N2Undef) {
1979     SDValue V = N1;
1980 
1981     // Look through any bitcasts. We check that these don't change the number
1982     // (and size) of elements and just changes their types.
1983     while (V.getOpcode() == ISD::BITCAST)
1984       V = V->getOperand(0);
1985 
1986     // A splat should always show up as a build vector node.
1987     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1988       BitVector UndefElements;
1989       SDValue Splat = BV->getSplatValue(&UndefElements);
1990       // If this is a splat of an undef, shuffling it is also undef.
1991       if (Splat && Splat.isUndef())
1992         return getUNDEF(VT);
1993 
1994       bool SameNumElts =
1995           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1996 
1997       // We only have a splat which can skip shuffles if there is a splatted
1998       // value and no undef lanes rearranged by the shuffle.
1999       if (Splat && UndefElements.none()) {
2000         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2001         // number of elements match or the value splatted is a zero constant.
2002         if (SameNumElts)
2003           return N1;
2004         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
2005           if (C->isZero())
2006             return N1;
2007       }
2008 
2009       // If the shuffle itself creates a splat, build the vector directly.
2010       if (AllSame && SameNumElts) {
2011         EVT BuildVT = BV->getValueType(0);
2012         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2013         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2014 
2015         // We may have jumped through bitcasts, so the type of the
2016         // BUILD_VECTOR may not match the type of the shuffle.
2017         if (BuildVT != VT)
2018           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2019         return NewBV;
2020       }
2021     }
2022   }
2023 
2024   FoldingSetNodeID ID;
2025   SDValue Ops[2] = { N1, N2 };
2026   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2027   for (int i = 0; i != NElts; ++i)
2028     ID.AddInteger(MaskVec[i]);
2029 
2030   void* IP = nullptr;
2031   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2032     return SDValue(E, 0);
2033 
2034   // Allocate the mask array for the node out of the BumpPtrAllocator, since
2035   // SDNode doesn't have access to it.  This memory will be "leaked" when
2036   // the node is deallocated, but recovered when the NodeAllocator is released.
2037   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2038   llvm::copy(MaskVec, MaskAlloc);
2039 
2040   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2041                                            dl.getDebugLoc(), MaskAlloc);
2042   createOperands(N, Ops);
2043 
2044   CSEMap.InsertNode(N, IP);
2045   InsertNode(N);
2046   SDValue V = SDValue(N, 0);
2047   NewSDValueDbgMsg(V, "Creating new node: ", this);
2048   return V;
2049 }
2050 
2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2052   EVT VT = SV.getValueType(0);
2053   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2054   ShuffleVectorSDNode::commuteMask(MaskVec);
2055 
2056   SDValue Op0 = SV.getOperand(0);
2057   SDValue Op1 = SV.getOperand(1);
2058   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2059 }
2060 
2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2062   FoldingSetNodeID ID;
2063   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2064   ID.AddInteger(RegNo);
2065   void *IP = nullptr;
2066   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067     return SDValue(E, 0);
2068 
2069   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2070   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2071   CSEMap.InsertNode(N, IP);
2072   InsertNode(N);
2073   return SDValue(N, 0);
2074 }
2075 
2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2077   FoldingSetNodeID ID;
2078   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2079   ID.AddPointer(RegMask);
2080   void *IP = nullptr;
2081   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2082     return SDValue(E, 0);
2083 
2084   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2085   CSEMap.InsertNode(N, IP);
2086   InsertNode(N);
2087   return SDValue(N, 0);
2088 }
2089 
2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2091                                  MCSymbol *Label) {
2092   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2093 }
2094 
2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2096                                    SDValue Root, MCSymbol *Label) {
2097   FoldingSetNodeID ID;
2098   SDValue Ops[] = { Root };
2099   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2100   ID.AddPointer(Label);
2101   void *IP = nullptr;
2102   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2103     return SDValue(E, 0);
2104 
2105   auto *N =
2106       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2107   createOperands(N, Ops);
2108 
2109   CSEMap.InsertNode(N, IP);
2110   InsertNode(N);
2111   return SDValue(N, 0);
2112 }
2113 
2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2115                                       int64_t Offset, bool isTarget,
2116                                       unsigned TargetFlags) {
2117   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2118 
2119   FoldingSetNodeID ID;
2120   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2121   ID.AddPointer(BA);
2122   ID.AddInteger(Offset);
2123   ID.AddInteger(TargetFlags);
2124   void *IP = nullptr;
2125   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2126     return SDValue(E, 0);
2127 
2128   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2129   CSEMap.InsertNode(N, IP);
2130   InsertNode(N);
2131   return SDValue(N, 0);
2132 }
2133 
2134 SDValue SelectionDAG::getSrcValue(const Value *V) {
2135   FoldingSetNodeID ID;
2136   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2137   ID.AddPointer(V);
2138 
2139   void *IP = nullptr;
2140   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2141     return SDValue(E, 0);
2142 
2143   auto *N = newSDNode<SrcValueSDNode>(V);
2144   CSEMap.InsertNode(N, IP);
2145   InsertNode(N);
2146   return SDValue(N, 0);
2147 }
2148 
2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2150   FoldingSetNodeID ID;
2151   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2152   ID.AddPointer(MD);
2153 
2154   void *IP = nullptr;
2155   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2156     return SDValue(E, 0);
2157 
2158   auto *N = newSDNode<MDNodeSDNode>(MD);
2159   CSEMap.InsertNode(N, IP);
2160   InsertNode(N);
2161   return SDValue(N, 0);
2162 }
2163 
2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2165   if (VT == V.getValueType())
2166     return V;
2167 
2168   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2169 }
2170 
2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2172                                        unsigned SrcAS, unsigned DestAS) {
2173   SDValue Ops[] = {Ptr};
2174   FoldingSetNodeID ID;
2175   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2176   ID.AddInteger(SrcAS);
2177   ID.AddInteger(DestAS);
2178 
2179   void *IP = nullptr;
2180   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2181     return SDValue(E, 0);
2182 
2183   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2184                                            VT, SrcAS, DestAS);
2185   createOperands(N, Ops);
2186 
2187   CSEMap.InsertNode(N, IP);
2188   InsertNode(N);
2189   return SDValue(N, 0);
2190 }
2191 
2192 SDValue SelectionDAG::getFreeze(SDValue V) {
2193   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2194 }
2195 
2196 /// getShiftAmountOperand - Return the specified value casted to
2197 /// the target's desired shift amount type.
2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2199   EVT OpTy = Op.getValueType();
2200   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2201   if (OpTy == ShTy || OpTy.isVector()) return Op;
2202 
2203   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2204 }
2205 
2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2207   SDLoc dl(Node);
2208   const TargetLowering &TLI = getTargetLoweringInfo();
2209   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2210   EVT VT = Node->getValueType(0);
2211   SDValue Tmp1 = Node->getOperand(0);
2212   SDValue Tmp2 = Node->getOperand(1);
2213   const MaybeAlign MA(Node->getConstantOperandVal(3));
2214 
2215   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2216                                Tmp2, MachinePointerInfo(V));
2217   SDValue VAList = VAListLoad;
2218 
2219   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2220     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2221                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2222 
2223     VAList =
2224         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2225                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2226   }
2227 
2228   // Increment the pointer, VAList, to the next vaarg
2229   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2230                  getConstant(getDataLayout().getTypeAllocSize(
2231                                                VT.getTypeForEVT(*getContext())),
2232                              dl, VAList.getValueType()));
2233   // Store the incremented VAList to the legalized pointer
2234   Tmp1 =
2235       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2236   // Load the actual argument out of the pointer VAList
2237   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2238 }
2239 
2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2241   SDLoc dl(Node);
2242   const TargetLowering &TLI = getTargetLoweringInfo();
2243   // This defaults to loading a pointer from the input and storing it to the
2244   // output, returning the chain.
2245   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2246   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2247   SDValue Tmp1 =
2248       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2249               Node->getOperand(2), MachinePointerInfo(VS));
2250   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2251                   MachinePointerInfo(VD));
2252 }
2253 
2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2255   const DataLayout &DL = getDataLayout();
2256   Type *Ty = VT.getTypeForEVT(*getContext());
2257   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2258 
2259   if (TLI->isTypeLegal(VT) || !VT.isVector())
2260     return RedAlign;
2261 
2262   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2263   const Align StackAlign = TFI->getStackAlign();
2264 
2265   // See if we can choose a smaller ABI alignment in cases where it's an
2266   // illegal vector type that will get broken down.
2267   if (RedAlign > StackAlign) {
2268     EVT IntermediateVT;
2269     MVT RegisterVT;
2270     unsigned NumIntermediates;
2271     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2272                                 NumIntermediates, RegisterVT);
2273     Ty = IntermediateVT.getTypeForEVT(*getContext());
2274     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2275     if (RedAlign2 < RedAlign)
2276       RedAlign = RedAlign2;
2277   }
2278 
2279   return RedAlign;
2280 }
2281 
2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2283   MachineFrameInfo &MFI = MF->getFrameInfo();
2284   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2285   int StackID = 0;
2286   if (Bytes.isScalable())
2287     StackID = TFI->getStackIDForScalableVectors();
2288   // The stack id gives an indication of whether the object is scalable or
2289   // not, so it's safe to pass in the minimum size here.
2290   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2291                                        false, nullptr, StackID);
2292   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2293 }
2294 
2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2296   Type *Ty = VT.getTypeForEVT(*getContext());
2297   Align StackAlign =
2298       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2299   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2300 }
2301 
2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2303   TypeSize VT1Size = VT1.getStoreSize();
2304   TypeSize VT2Size = VT2.getStoreSize();
2305   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2306          "Don't know how to choose the maximum size when creating a stack "
2307          "temporary");
2308   TypeSize Bytes =
2309       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2310 
2311   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2312   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2313   const DataLayout &DL = getDataLayout();
2314   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2315   return CreateStackTemporary(Bytes, Align);
2316 }
2317 
2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2319                                 ISD::CondCode Cond, const SDLoc &dl) {
2320   EVT OpVT = N1.getValueType();
2321 
2322   // These setcc operations always fold.
2323   switch (Cond) {
2324   default: break;
2325   case ISD::SETFALSE:
2326   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2327   case ISD::SETTRUE:
2328   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2329 
2330   case ISD::SETOEQ:
2331   case ISD::SETOGT:
2332   case ISD::SETOGE:
2333   case ISD::SETOLT:
2334   case ISD::SETOLE:
2335   case ISD::SETONE:
2336   case ISD::SETO:
2337   case ISD::SETUO:
2338   case ISD::SETUEQ:
2339   case ISD::SETUNE:
2340     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2341     break;
2342   }
2343 
2344   if (OpVT.isInteger()) {
2345     // For EQ and NE, we can always pick a value for the undef to make the
2346     // predicate pass or fail, so we can return undef.
2347     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2348     // icmp eq/ne X, undef -> undef.
2349     if ((N1.isUndef() || N2.isUndef()) &&
2350         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2351       return getUNDEF(VT);
2352 
2353     // If both operands are undef, we can return undef for int comparison.
2354     // icmp undef, undef -> undef.
2355     if (N1.isUndef() && N2.isUndef())
2356       return getUNDEF(VT);
2357 
2358     // icmp X, X -> true/false
2359     // icmp X, undef -> true/false because undef could be X.
2360     if (N1 == N2)
2361       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2362   }
2363 
2364   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2365     const APInt &C2 = N2C->getAPIntValue();
2366     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2367       const APInt &C1 = N1C->getAPIntValue();
2368 
2369       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2370                              dl, VT, OpVT);
2371     }
2372   }
2373 
2374   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2375   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2376 
2377   if (N1CFP && N2CFP) {
2378     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2379     switch (Cond) {
2380     default: break;
2381     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2382                         return getUNDEF(VT);
2383                       LLVM_FALLTHROUGH;
2384     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2385                                              OpVT);
2386     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2387                         return getUNDEF(VT);
2388                       LLVM_FALLTHROUGH;
2389     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390                                              R==APFloat::cmpLessThan, dl, VT,
2391                                              OpVT);
2392     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2393                         return getUNDEF(VT);
2394                       LLVM_FALLTHROUGH;
2395     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2396                                              OpVT);
2397     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2398                         return getUNDEF(VT);
2399                       LLVM_FALLTHROUGH;
2400     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2401                                              VT, OpVT);
2402     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2403                         return getUNDEF(VT);
2404                       LLVM_FALLTHROUGH;
2405     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2406                                              R==APFloat::cmpEqual, dl, VT,
2407                                              OpVT);
2408     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2409                         return getUNDEF(VT);
2410                       LLVM_FALLTHROUGH;
2411     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2412                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2413     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2414                                              OpVT);
2415     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2416                                              OpVT);
2417     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2418                                              R==APFloat::cmpEqual, dl, VT,
2419                                              OpVT);
2420     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2421                                              OpVT);
2422     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2423                                              R==APFloat::cmpLessThan, dl, VT,
2424                                              OpVT);
2425     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2426                                              R==APFloat::cmpUnordered, dl, VT,
2427                                              OpVT);
2428     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2429                                              VT, OpVT);
2430     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2431                                              OpVT);
2432     }
2433   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2434     // Ensure that the constant occurs on the RHS.
2435     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2436     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2437       return SDValue();
2438     return getSetCC(dl, VT, N2, N1, SwappedCond);
2439   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2440              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2441     // If an operand is known to be a nan (or undef that could be a nan), we can
2442     // fold it.
2443     // Choosing NaN for the undef will always make unordered comparison succeed
2444     // and ordered comparison fails.
2445     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2446     switch (ISD::getUnorderedFlavor(Cond)) {
2447     default:
2448       llvm_unreachable("Unknown flavor!");
2449     case 0: // Known false.
2450       return getBoolConstant(false, dl, VT, OpVT);
2451     case 1: // Known true.
2452       return getBoolConstant(true, dl, VT, OpVT);
2453     case 2: // Undefined.
2454       return getUNDEF(VT);
2455     }
2456   }
2457 
2458   // Could not fold it.
2459   return SDValue();
2460 }
2461 
2462 /// See if the specified operand can be simplified with the knowledge that only
2463 /// the bits specified by DemandedBits are used.
2464 /// TODO: really we should be making this into the DAG equivalent of
2465 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2466 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2467   EVT VT = V.getValueType();
2468 
2469   if (VT.isScalableVector())
2470     return SDValue();
2471 
2472   switch (V.getOpcode()) {
2473   default:
2474     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, *this);
2475   case ISD::Constant: {
2476     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2477     APInt NewVal = CVal & DemandedBits;
2478     if (NewVal != CVal)
2479       return getConstant(NewVal, SDLoc(V), V.getValueType());
2480     break;
2481   }
2482   case ISD::SRL:
2483     // Only look at single-use SRLs.
2484     if (!V.getNode()->hasOneUse())
2485       break;
2486     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2487       // See if we can recursively simplify the LHS.
2488       unsigned Amt = RHSC->getZExtValue();
2489 
2490       // Watch out for shift count overflow though.
2491       if (Amt >= DemandedBits.getBitWidth())
2492         break;
2493       APInt SrcDemandedBits = DemandedBits << Amt;
2494       if (SDValue SimplifyLHS = TLI->SimplifyMultipleUseDemandedBits(
2495               V.getOperand(0), SrcDemandedBits, *this))
2496         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2497                        V.getOperand(1));
2498     }
2499     break;
2500   }
2501   return SDValue();
2502 }
2503 
2504 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2505 /// use this predicate to simplify operations downstream.
2506 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2507   unsigned BitWidth = Op.getScalarValueSizeInBits();
2508   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2509 }
2510 
2511 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2512 /// this predicate to simplify operations downstream.  Mask is known to be zero
2513 /// for bits that V cannot have.
2514 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2515                                      unsigned Depth) const {
2516   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2517 }
2518 
2519 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2520 /// DemandedElts.  We use this predicate to simplify operations downstream.
2521 /// Mask is known to be zero for bits that V cannot have.
2522 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2523                                      const APInt &DemandedElts,
2524                                      unsigned Depth) const {
2525   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2526 }
2527 
2528 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2529 /// DemandedElts.  We use this predicate to simplify operations downstream.
2530 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts,
2531                                       unsigned Depth /* = 0 */) const {
2532   APInt Mask = APInt::getAllOnes(V.getScalarValueSizeInBits());
2533   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2534 }
2535 
2536 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2537 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2538                                         unsigned Depth) const {
2539   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2540 }
2541 
2542 /// isSplatValue - Return true if the vector V has the same value
2543 /// across all DemandedElts. For scalable vectors it does not make
2544 /// sense to specify which elements are demanded or undefined, therefore
2545 /// they are simply ignored.
2546 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2547                                 APInt &UndefElts, unsigned Depth) const {
2548   unsigned Opcode = V.getOpcode();
2549   EVT VT = V.getValueType();
2550   assert(VT.isVector() && "Vector type expected");
2551 
2552   if (!VT.isScalableVector() && !DemandedElts)
2553     return false; // No demanded elts, better to assume we don't know anything.
2554 
2555   if (Depth >= MaxRecursionDepth)
2556     return false; // Limit search depth.
2557 
2558   // Deal with some common cases here that work for both fixed and scalable
2559   // vector types.
2560   switch (Opcode) {
2561   case ISD::SPLAT_VECTOR:
2562     UndefElts = V.getOperand(0).isUndef()
2563                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2564                     : APInt(DemandedElts.getBitWidth(), 0);
2565     return true;
2566   case ISD::ADD:
2567   case ISD::SUB:
2568   case ISD::AND:
2569   case ISD::XOR:
2570   case ISD::OR: {
2571     APInt UndefLHS, UndefRHS;
2572     SDValue LHS = V.getOperand(0);
2573     SDValue RHS = V.getOperand(1);
2574     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2575         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2576       UndefElts = UndefLHS | UndefRHS;
2577       return true;
2578     }
2579     return false;
2580   }
2581   case ISD::ABS:
2582   case ISD::TRUNCATE:
2583   case ISD::SIGN_EXTEND:
2584   case ISD::ZERO_EXTEND:
2585     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2586   default:
2587     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2588         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2589       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2590     break;
2591 }
2592 
2593   // We don't support other cases than those above for scalable vectors at
2594   // the moment.
2595   if (VT.isScalableVector())
2596     return false;
2597 
2598   unsigned NumElts = VT.getVectorNumElements();
2599   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2600   UndefElts = APInt::getZero(NumElts);
2601 
2602   switch (Opcode) {
2603   case ISD::BUILD_VECTOR: {
2604     SDValue Scl;
2605     for (unsigned i = 0; i != NumElts; ++i) {
2606       SDValue Op = V.getOperand(i);
2607       if (Op.isUndef()) {
2608         UndefElts.setBit(i);
2609         continue;
2610       }
2611       if (!DemandedElts[i])
2612         continue;
2613       if (Scl && Scl != Op)
2614         return false;
2615       Scl = Op;
2616     }
2617     return true;
2618   }
2619   case ISD::VECTOR_SHUFFLE: {
2620     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2621     APInt DemandedLHS = APInt::getNullValue(NumElts);
2622     APInt DemandedRHS = APInt::getNullValue(NumElts);
2623     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2624     for (int i = 0; i != (int)NumElts; ++i) {
2625       int M = Mask[i];
2626       if (M < 0) {
2627         UndefElts.setBit(i);
2628         continue;
2629       }
2630       if (!DemandedElts[i])
2631         continue;
2632       if (M < (int)NumElts)
2633         DemandedLHS.setBit(M);
2634       else
2635         DemandedRHS.setBit(M - NumElts);
2636     }
2637 
2638     // If we aren't demanding either op, assume there's no splat.
2639     // If we are demanding both ops, assume there's no splat.
2640     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2641         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2642       return false;
2643 
2644     // See if the demanded elts of the source op is a splat or we only demand
2645     // one element, which should always be a splat.
2646     // TODO: Handle source ops splats with undefs.
2647     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2648       APInt SrcUndefs;
2649       return (SrcElts.countPopulation() == 1) ||
2650              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2651               (SrcElts & SrcUndefs).isZero());
2652     };
2653     if (!DemandedLHS.isZero())
2654       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2655     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2656   }
2657   case ISD::EXTRACT_SUBVECTOR: {
2658     // Offset the demanded elts by the subvector index.
2659     SDValue Src = V.getOperand(0);
2660     // We don't support scalable vectors at the moment.
2661     if (Src.getValueType().isScalableVector())
2662       return false;
2663     uint64_t Idx = V.getConstantOperandVal(1);
2664     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2665     APInt UndefSrcElts;
2666     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2667     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2668       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2669       return true;
2670     }
2671     break;
2672   }
2673   case ISD::ANY_EXTEND_VECTOR_INREG:
2674   case ISD::SIGN_EXTEND_VECTOR_INREG:
2675   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2676     // Widen the demanded elts by the src element count.
2677     SDValue Src = V.getOperand(0);
2678     // We don't support scalable vectors at the moment.
2679     if (Src.getValueType().isScalableVector())
2680       return false;
2681     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2682     APInt UndefSrcElts;
2683     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
2684     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2685       UndefElts = UndefSrcElts.trunc(NumElts);
2686       return true;
2687     }
2688     break;
2689   }
2690   case ISD::BITCAST: {
2691     SDValue Src = V.getOperand(0);
2692     EVT SrcVT = Src.getValueType();
2693     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2694     unsigned BitWidth = VT.getScalarSizeInBits();
2695 
2696     // Ignore bitcasts from unsupported types.
2697     // TODO: Add fp support?
2698     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2699       break;
2700 
2701     // Bitcast 'small element' vector to 'large element' vector.
2702     if ((BitWidth % SrcBitWidth) == 0) {
2703       // See if each sub element is a splat.
2704       unsigned Scale = BitWidth / SrcBitWidth;
2705       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2706       APInt ScaledDemandedElts =
2707           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2708       for (unsigned I = 0; I != Scale; ++I) {
2709         APInt SubUndefElts;
2710         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2711         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2712         SubDemandedElts &= ScaledDemandedElts;
2713         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2714           return false;
2715 
2716         // Here we can't do "MatchAnyBits" operation merge for undef bits.
2717         // Because some operation only use part value of the source.
2718         // Take llvm.fshl.* for example:
2719         // t1: v4i32 = Constant:i32<12>, undef:i32, Constant:i32<12>, undef:i32
2720         // t2: v2i64 = bitcast t1
2721         // t5: v2i64 = fshl t3, t4, t2
2722         // We can not convert t2 to {i64 undef, i64 undef}
2723         UndefElts |= APIntOps::ScaleBitMask(SubUndefElts, NumElts,
2724                                             /*MatchAllBits=*/true);
2725       }
2726       return true;
2727     }
2728     break;
2729   }
2730   }
2731 
2732   return false;
2733 }
2734 
2735 /// Helper wrapper to main isSplatValue function.
2736 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2737   EVT VT = V.getValueType();
2738   assert(VT.isVector() && "Vector type expected");
2739 
2740   APInt UndefElts;
2741   APInt DemandedElts;
2742 
2743   // For now we don't support this with scalable vectors.
2744   if (!VT.isScalableVector())
2745     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2746   return isSplatValue(V, DemandedElts, UndefElts) &&
2747          (AllowUndefs || !UndefElts);
2748 }
2749 
2750 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2751   V = peekThroughExtractSubvectors(V);
2752 
2753   EVT VT = V.getValueType();
2754   unsigned Opcode = V.getOpcode();
2755   switch (Opcode) {
2756   default: {
2757     APInt UndefElts;
2758     APInt DemandedElts;
2759 
2760     if (!VT.isScalableVector())
2761       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2762 
2763     if (isSplatValue(V, DemandedElts, UndefElts)) {
2764       if (VT.isScalableVector()) {
2765         // DemandedElts and UndefElts are ignored for scalable vectors, since
2766         // the only supported cases are SPLAT_VECTOR nodes.
2767         SplatIdx = 0;
2768       } else {
2769         // Handle case where all demanded elements are UNDEF.
2770         if (DemandedElts.isSubsetOf(UndefElts)) {
2771           SplatIdx = 0;
2772           return getUNDEF(VT);
2773         }
2774         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2775       }
2776       return V;
2777     }
2778     break;
2779   }
2780   case ISD::SPLAT_VECTOR:
2781     SplatIdx = 0;
2782     return V;
2783   case ISD::VECTOR_SHUFFLE: {
2784     if (VT.isScalableVector())
2785       return SDValue();
2786 
2787     // Check if this is a shuffle node doing a splat.
2788     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2789     // getTargetVShiftNode currently struggles without the splat source.
2790     auto *SVN = cast<ShuffleVectorSDNode>(V);
2791     if (!SVN->isSplat())
2792       break;
2793     int Idx = SVN->getSplatIndex();
2794     int NumElts = V.getValueType().getVectorNumElements();
2795     SplatIdx = Idx % NumElts;
2796     return V.getOperand(Idx / NumElts);
2797   }
2798   }
2799 
2800   return SDValue();
2801 }
2802 
2803 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2804   int SplatIdx;
2805   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2806     EVT SVT = SrcVector.getValueType().getScalarType();
2807     EVT LegalSVT = SVT;
2808     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2809       if (!SVT.isInteger())
2810         return SDValue();
2811       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2812       if (LegalSVT.bitsLT(SVT))
2813         return SDValue();
2814     }
2815     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2816                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2817   }
2818   return SDValue();
2819 }
2820 
2821 const APInt *
2822 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2823                                           const APInt &DemandedElts) const {
2824   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2825           V.getOpcode() == ISD::SRA) &&
2826          "Unknown shift node");
2827   unsigned BitWidth = V.getScalarValueSizeInBits();
2828   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2829     // Shifting more than the bitwidth is not valid.
2830     const APInt &ShAmt = SA->getAPIntValue();
2831     if (ShAmt.ult(BitWidth))
2832       return &ShAmt;
2833   }
2834   return nullptr;
2835 }
2836 
2837 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2838     SDValue V, const APInt &DemandedElts) const {
2839   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2840           V.getOpcode() == ISD::SRA) &&
2841          "Unknown shift node");
2842   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2843     return ValidAmt;
2844   unsigned BitWidth = V.getScalarValueSizeInBits();
2845   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2846   if (!BV)
2847     return nullptr;
2848   const APInt *MinShAmt = nullptr;
2849   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2850     if (!DemandedElts[i])
2851       continue;
2852     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2853     if (!SA)
2854       return nullptr;
2855     // Shifting more than the bitwidth is not valid.
2856     const APInt &ShAmt = SA->getAPIntValue();
2857     if (ShAmt.uge(BitWidth))
2858       return nullptr;
2859     if (MinShAmt && MinShAmt->ule(ShAmt))
2860       continue;
2861     MinShAmt = &ShAmt;
2862   }
2863   return MinShAmt;
2864 }
2865 
2866 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2867     SDValue V, const APInt &DemandedElts) const {
2868   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2869           V.getOpcode() == ISD::SRA) &&
2870          "Unknown shift node");
2871   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2872     return ValidAmt;
2873   unsigned BitWidth = V.getScalarValueSizeInBits();
2874   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2875   if (!BV)
2876     return nullptr;
2877   const APInt *MaxShAmt = nullptr;
2878   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2879     if (!DemandedElts[i])
2880       continue;
2881     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2882     if (!SA)
2883       return nullptr;
2884     // Shifting more than the bitwidth is not valid.
2885     const APInt &ShAmt = SA->getAPIntValue();
2886     if (ShAmt.uge(BitWidth))
2887       return nullptr;
2888     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2889       continue;
2890     MaxShAmt = &ShAmt;
2891   }
2892   return MaxShAmt;
2893 }
2894 
2895 /// Determine which bits of Op are known to be either zero or one and return
2896 /// them in Known. For vectors, the known bits are those that are shared by
2897 /// every vector element.
2898 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2899   EVT VT = Op.getValueType();
2900 
2901   // TOOD: Until we have a plan for how to represent demanded elements for
2902   // scalable vectors, we can just bail out for now.
2903   if (Op.getValueType().isScalableVector()) {
2904     unsigned BitWidth = Op.getScalarValueSizeInBits();
2905     return KnownBits(BitWidth);
2906   }
2907 
2908   APInt DemandedElts = VT.isVector()
2909                            ? APInt::getAllOnes(VT.getVectorNumElements())
2910                            : APInt(1, 1);
2911   return computeKnownBits(Op, DemandedElts, Depth);
2912 }
2913 
2914 /// Determine which bits of Op are known to be either zero or one and return
2915 /// them in Known. The DemandedElts argument allows us to only collect the known
2916 /// bits that are shared by the requested vector elements.
2917 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2918                                          unsigned Depth) const {
2919   unsigned BitWidth = Op.getScalarValueSizeInBits();
2920 
2921   KnownBits Known(BitWidth);   // Don't know anything.
2922 
2923   // TOOD: Until we have a plan for how to represent demanded elements for
2924   // scalable vectors, we can just bail out for now.
2925   if (Op.getValueType().isScalableVector())
2926     return Known;
2927 
2928   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2929     // We know all of the bits for a constant!
2930     return KnownBits::makeConstant(C->getAPIntValue());
2931   }
2932   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2933     // We know all of the bits for a constant fp!
2934     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2935   }
2936 
2937   if (Depth >= MaxRecursionDepth)
2938     return Known;  // Limit search depth.
2939 
2940   KnownBits Known2;
2941   unsigned NumElts = DemandedElts.getBitWidth();
2942   assert((!Op.getValueType().isVector() ||
2943           NumElts == Op.getValueType().getVectorNumElements()) &&
2944          "Unexpected vector size");
2945 
2946   if (!DemandedElts)
2947     return Known;  // No demanded elts, better to assume we don't know anything.
2948 
2949   unsigned Opcode = Op.getOpcode();
2950   switch (Opcode) {
2951   case ISD::MERGE_VALUES:
2952     return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
2953                             Depth + 1);
2954   case ISD::BUILD_VECTOR:
2955     // Collect the known bits that are shared by every demanded vector element.
2956     Known.Zero.setAllBits(); Known.One.setAllBits();
2957     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2958       if (!DemandedElts[i])
2959         continue;
2960 
2961       SDValue SrcOp = Op.getOperand(i);
2962       Known2 = computeKnownBits(SrcOp, Depth + 1);
2963 
2964       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2965       if (SrcOp.getValueSizeInBits() != BitWidth) {
2966         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2967                "Expected BUILD_VECTOR implicit truncation");
2968         Known2 = Known2.trunc(BitWidth);
2969       }
2970 
2971       // Known bits are the values that are shared by every demanded element.
2972       Known = KnownBits::commonBits(Known, Known2);
2973 
2974       // If we don't know any bits, early out.
2975       if (Known.isUnknown())
2976         break;
2977     }
2978     break;
2979   case ISD::VECTOR_SHUFFLE: {
2980     // Collect the known bits that are shared by every vector element referenced
2981     // by the shuffle.
2982     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2983     Known.Zero.setAllBits(); Known.One.setAllBits();
2984     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2985     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2986     for (unsigned i = 0; i != NumElts; ++i) {
2987       if (!DemandedElts[i])
2988         continue;
2989 
2990       int M = SVN->getMaskElt(i);
2991       if (M < 0) {
2992         // For UNDEF elements, we don't know anything about the common state of
2993         // the shuffle result.
2994         Known.resetAll();
2995         DemandedLHS.clearAllBits();
2996         DemandedRHS.clearAllBits();
2997         break;
2998       }
2999 
3000       if ((unsigned)M < NumElts)
3001         DemandedLHS.setBit((unsigned)M % NumElts);
3002       else
3003         DemandedRHS.setBit((unsigned)M % NumElts);
3004     }
3005     // Known bits are the values that are shared by every demanded element.
3006     if (!!DemandedLHS) {
3007       SDValue LHS = Op.getOperand(0);
3008       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3009       Known = KnownBits::commonBits(Known, Known2);
3010     }
3011     // If we don't know any bits, early out.
3012     if (Known.isUnknown())
3013       break;
3014     if (!!DemandedRHS) {
3015       SDValue RHS = Op.getOperand(1);
3016       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3017       Known = KnownBits::commonBits(Known, Known2);
3018     }
3019     break;
3020   }
3021   case ISD::CONCAT_VECTORS: {
3022     // Split DemandedElts and test each of the demanded subvectors.
3023     Known.Zero.setAllBits(); Known.One.setAllBits();
3024     EVT SubVectorVT = Op.getOperand(0).getValueType();
3025     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3026     unsigned NumSubVectors = Op.getNumOperands();
3027     for (unsigned i = 0; i != NumSubVectors; ++i) {
3028       APInt DemandedSub =
3029           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3030       if (!!DemandedSub) {
3031         SDValue Sub = Op.getOperand(i);
3032         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3033         Known = KnownBits::commonBits(Known, Known2);
3034       }
3035       // If we don't know any bits, early out.
3036       if (Known.isUnknown())
3037         break;
3038     }
3039     break;
3040   }
3041   case ISD::INSERT_SUBVECTOR: {
3042     // Demand any elements from the subvector and the remainder from the src its
3043     // inserted into.
3044     SDValue Src = Op.getOperand(0);
3045     SDValue Sub = Op.getOperand(1);
3046     uint64_t Idx = Op.getConstantOperandVal(2);
3047     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3048     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3049     APInt DemandedSrcElts = DemandedElts;
3050     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3051 
3052     Known.One.setAllBits();
3053     Known.Zero.setAllBits();
3054     if (!!DemandedSubElts) {
3055       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3056       if (Known.isUnknown())
3057         break; // early-out.
3058     }
3059     if (!!DemandedSrcElts) {
3060       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3061       Known = KnownBits::commonBits(Known, Known2);
3062     }
3063     break;
3064   }
3065   case ISD::EXTRACT_SUBVECTOR: {
3066     // Offset the demanded elts by the subvector index.
3067     SDValue Src = Op.getOperand(0);
3068     // Bail until we can represent demanded elements for scalable vectors.
3069     if (Src.getValueType().isScalableVector())
3070       break;
3071     uint64_t Idx = Op.getConstantOperandVal(1);
3072     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3073     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3074     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3075     break;
3076   }
3077   case ISD::SCALAR_TO_VECTOR: {
3078     // We know about scalar_to_vector as much as we know about it source,
3079     // which becomes the first element of otherwise unknown vector.
3080     if (DemandedElts != 1)
3081       break;
3082 
3083     SDValue N0 = Op.getOperand(0);
3084     Known = computeKnownBits(N0, Depth + 1);
3085     if (N0.getValueSizeInBits() != BitWidth)
3086       Known = Known.trunc(BitWidth);
3087 
3088     break;
3089   }
3090   case ISD::BITCAST: {
3091     SDValue N0 = Op.getOperand(0);
3092     EVT SubVT = N0.getValueType();
3093     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3094 
3095     // Ignore bitcasts from unsupported types.
3096     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3097       break;
3098 
3099     // Fast handling of 'identity' bitcasts.
3100     if (BitWidth == SubBitWidth) {
3101       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3102       break;
3103     }
3104 
3105     bool IsLE = getDataLayout().isLittleEndian();
3106 
3107     // Bitcast 'small element' vector to 'large element' scalar/vector.
3108     if ((BitWidth % SubBitWidth) == 0) {
3109       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3110 
3111       // Collect known bits for the (larger) output by collecting the known
3112       // bits from each set of sub elements and shift these into place.
3113       // We need to separately call computeKnownBits for each set of
3114       // sub elements as the knownbits for each is likely to be different.
3115       unsigned SubScale = BitWidth / SubBitWidth;
3116       APInt SubDemandedElts(NumElts * SubScale, 0);
3117       for (unsigned i = 0; i != NumElts; ++i)
3118         if (DemandedElts[i])
3119           SubDemandedElts.setBit(i * SubScale);
3120 
3121       for (unsigned i = 0; i != SubScale; ++i) {
3122         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3123                          Depth + 1);
3124         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3125         Known.insertBits(Known2, SubBitWidth * Shifts);
3126       }
3127     }
3128 
3129     // Bitcast 'large element' scalar/vector to 'small element' vector.
3130     if ((SubBitWidth % BitWidth) == 0) {
3131       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3132 
3133       // Collect known bits for the (smaller) output by collecting the known
3134       // bits from the overlapping larger input elements and extracting the
3135       // sub sections we actually care about.
3136       unsigned SubScale = SubBitWidth / BitWidth;
3137       APInt SubDemandedElts =
3138           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3139       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3140 
3141       Known.Zero.setAllBits(); Known.One.setAllBits();
3142       for (unsigned i = 0; i != NumElts; ++i)
3143         if (DemandedElts[i]) {
3144           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3145           unsigned Offset = (Shifts % SubScale) * BitWidth;
3146           Known = KnownBits::commonBits(Known,
3147                                         Known2.extractBits(BitWidth, Offset));
3148           // If we don't know any bits, early out.
3149           if (Known.isUnknown())
3150             break;
3151         }
3152     }
3153     break;
3154   }
3155   case ISD::AND:
3156     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3157     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3158 
3159     Known &= Known2;
3160     break;
3161   case ISD::OR:
3162     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3163     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3164 
3165     Known |= Known2;
3166     break;
3167   case ISD::XOR:
3168     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3169     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3170 
3171     Known ^= Known2;
3172     break;
3173   case ISD::MUL: {
3174     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3175     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3176     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3177     // TODO: SelfMultiply can be poison, but not undef.
3178     if (SelfMultiply)
3179       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3180           Op.getOperand(0), DemandedElts, false, Depth + 1);
3181     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3182 
3183     // If the multiplication is known not to overflow, the product of a number
3184     // with itself is non-negative. Only do this if we didn't already computed
3185     // the opposite value for the sign bit.
3186     if (Op->getFlags().hasNoSignedWrap() &&
3187         Op.getOperand(0) == Op.getOperand(1) &&
3188         !Known.isNegative())
3189       Known.makeNonNegative();
3190     break;
3191   }
3192   case ISD::MULHU: {
3193     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3194     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3195     Known = KnownBits::mulhu(Known, Known2);
3196     break;
3197   }
3198   case ISD::MULHS: {
3199     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3200     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3201     Known = KnownBits::mulhs(Known, Known2);
3202     break;
3203   }
3204   case ISD::UMUL_LOHI: {
3205     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3206     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3207     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3208     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3209     if (Op.getResNo() == 0)
3210       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3211     else
3212       Known = KnownBits::mulhu(Known, Known2);
3213     break;
3214   }
3215   case ISD::SMUL_LOHI: {
3216     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3217     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3218     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3219     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3220     if (Op.getResNo() == 0)
3221       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3222     else
3223       Known = KnownBits::mulhs(Known, Known2);
3224     break;
3225   }
3226   case ISD::AVGCEILU: {
3227     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3228     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3229     Known = Known.zext(BitWidth + 1);
3230     Known2 = Known2.zext(BitWidth + 1);
3231     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3232     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3233     Known = Known.extractBits(BitWidth, 1);
3234     break;
3235   }
3236   case ISD::SELECT:
3237   case ISD::VSELECT:
3238     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3239     // If we don't know any bits, early out.
3240     if (Known.isUnknown())
3241       break;
3242     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3243 
3244     // Only known if known in both the LHS and RHS.
3245     Known = KnownBits::commonBits(Known, Known2);
3246     break;
3247   case ISD::SELECT_CC:
3248     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3249     // If we don't know any bits, early out.
3250     if (Known.isUnknown())
3251       break;
3252     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3253 
3254     // Only known if known in both the LHS and RHS.
3255     Known = KnownBits::commonBits(Known, Known2);
3256     break;
3257   case ISD::SMULO:
3258   case ISD::UMULO:
3259     if (Op.getResNo() != 1)
3260       break;
3261     // The boolean result conforms to getBooleanContents.
3262     // If we know the result of a setcc has the top bits zero, use this info.
3263     // We know that we have an integer-based boolean since these operations
3264     // are only available for integer.
3265     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3266             TargetLowering::ZeroOrOneBooleanContent &&
3267         BitWidth > 1)
3268       Known.Zero.setBitsFrom(1);
3269     break;
3270   case ISD::SETCC:
3271   case ISD::SETCCCARRY:
3272   case ISD::STRICT_FSETCC:
3273   case ISD::STRICT_FSETCCS: {
3274     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3275     // If we know the result of a setcc has the top bits zero, use this info.
3276     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3277             TargetLowering::ZeroOrOneBooleanContent &&
3278         BitWidth > 1)
3279       Known.Zero.setBitsFrom(1);
3280     break;
3281   }
3282   case ISD::SHL:
3283     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3284     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3285     Known = KnownBits::shl(Known, Known2);
3286 
3287     // Minimum shift low bits are known zero.
3288     if (const APInt *ShMinAmt =
3289             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3290       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3291     break;
3292   case ISD::SRL:
3293     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3294     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3295     Known = KnownBits::lshr(Known, Known2);
3296 
3297     // Minimum shift high bits are known zero.
3298     if (const APInt *ShMinAmt =
3299             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3300       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3301     break;
3302   case ISD::SRA:
3303     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3304     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3305     Known = KnownBits::ashr(Known, Known2);
3306     // TODO: Add minimum shift high known sign bits.
3307     break;
3308   case ISD::FSHL:
3309   case ISD::FSHR:
3310     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3311       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3312 
3313       // For fshl, 0-shift returns the 1st arg.
3314       // For fshr, 0-shift returns the 2nd arg.
3315       if (Amt == 0) {
3316         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3317                                  DemandedElts, Depth + 1);
3318         break;
3319       }
3320 
3321       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3322       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3323       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3324       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3325       if (Opcode == ISD::FSHL) {
3326         Known.One <<= Amt;
3327         Known.Zero <<= Amt;
3328         Known2.One.lshrInPlace(BitWidth - Amt);
3329         Known2.Zero.lshrInPlace(BitWidth - Amt);
3330       } else {
3331         Known.One <<= BitWidth - Amt;
3332         Known.Zero <<= BitWidth - Amt;
3333         Known2.One.lshrInPlace(Amt);
3334         Known2.Zero.lshrInPlace(Amt);
3335       }
3336       Known.One |= Known2.One;
3337       Known.Zero |= Known2.Zero;
3338     }
3339     break;
3340   case ISD::SHL_PARTS:
3341   case ISD::SRA_PARTS:
3342   case ISD::SRL_PARTS: {
3343     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3344 
3345     // Collect lo/hi source values and concatenate.
3346     // TODO: Would a KnownBits::concatBits helper be useful?
3347     unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3348     unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3349     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3350     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3351     Known = Known.anyext(LoBits + HiBits);
3352     Known.insertBits(Known2, LoBits);
3353 
3354     // Collect shift amount.
3355     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3356 
3357     if (Opcode == ISD::SHL_PARTS)
3358       Known = KnownBits::shl(Known, Known2);
3359     else if (Opcode == ISD::SRA_PARTS)
3360       Known = KnownBits::ashr(Known, Known2);
3361     else // if (Opcode == ISD::SRL_PARTS)
3362       Known = KnownBits::lshr(Known, Known2);
3363 
3364     // TODO: Minimum shift low/high bits are known zero.
3365 
3366     if (Op.getResNo() == 0)
3367       Known = Known.extractBits(LoBits, 0);
3368     else
3369       Known = Known.extractBits(HiBits, LoBits);
3370     break;
3371   }
3372   case ISD::SIGN_EXTEND_INREG: {
3373     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3374     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3375     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3376     break;
3377   }
3378   case ISD::CTTZ:
3379   case ISD::CTTZ_ZERO_UNDEF: {
3380     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3381     // If we have a known 1, its position is our upper bound.
3382     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3383     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3384     Known.Zero.setBitsFrom(LowBits);
3385     break;
3386   }
3387   case ISD::CTLZ:
3388   case ISD::CTLZ_ZERO_UNDEF: {
3389     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3390     // If we have a known 1, its position is our upper bound.
3391     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3392     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3393     Known.Zero.setBitsFrom(LowBits);
3394     break;
3395   }
3396   case ISD::CTPOP: {
3397     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3398     // If we know some of the bits are zero, they can't be one.
3399     unsigned PossibleOnes = Known2.countMaxPopulation();
3400     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3401     break;
3402   }
3403   case ISD::PARITY: {
3404     // Parity returns 0 everywhere but the LSB.
3405     Known.Zero.setBitsFrom(1);
3406     break;
3407   }
3408   case ISD::LOAD: {
3409     LoadSDNode *LD = cast<LoadSDNode>(Op);
3410     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3411     if (ISD::isNON_EXTLoad(LD) && Cst) {
3412       // Determine any common known bits from the loaded constant pool value.
3413       Type *CstTy = Cst->getType();
3414       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3415         // If its a vector splat, then we can (quickly) reuse the scalar path.
3416         // NOTE: We assume all elements match and none are UNDEF.
3417         if (CstTy->isVectorTy()) {
3418           if (const Constant *Splat = Cst->getSplatValue()) {
3419             Cst = Splat;
3420             CstTy = Cst->getType();
3421           }
3422         }
3423         // TODO - do we need to handle different bitwidths?
3424         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3425           // Iterate across all vector elements finding common known bits.
3426           Known.One.setAllBits();
3427           Known.Zero.setAllBits();
3428           for (unsigned i = 0; i != NumElts; ++i) {
3429             if (!DemandedElts[i])
3430               continue;
3431             if (Constant *Elt = Cst->getAggregateElement(i)) {
3432               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3433                 const APInt &Value = CInt->getValue();
3434                 Known.One &= Value;
3435                 Known.Zero &= ~Value;
3436                 continue;
3437               }
3438               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3439                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3440                 Known.One &= Value;
3441                 Known.Zero &= ~Value;
3442                 continue;
3443               }
3444             }
3445             Known.One.clearAllBits();
3446             Known.Zero.clearAllBits();
3447             break;
3448           }
3449         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3450           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3451             Known = KnownBits::makeConstant(CInt->getValue());
3452           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3453             Known =
3454                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3455           }
3456         }
3457       }
3458     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3459       // If this is a ZEXTLoad and we are looking at the loaded value.
3460       EVT VT = LD->getMemoryVT();
3461       unsigned MemBits = VT.getScalarSizeInBits();
3462       Known.Zero.setBitsFrom(MemBits);
3463     } else if (const MDNode *Ranges = LD->getRanges()) {
3464       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3465         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3466     }
3467     break;
3468   }
3469   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3470     EVT InVT = Op.getOperand(0).getValueType();
3471     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3472     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3473     Known = Known.zext(BitWidth);
3474     break;
3475   }
3476   case ISD::ZERO_EXTEND: {
3477     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3478     Known = Known.zext(BitWidth);
3479     break;
3480   }
3481   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3482     EVT InVT = Op.getOperand(0).getValueType();
3483     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3484     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3485     // If the sign bit is known to be zero or one, then sext will extend
3486     // it to the top bits, else it will just zext.
3487     Known = Known.sext(BitWidth);
3488     break;
3489   }
3490   case ISD::SIGN_EXTEND: {
3491     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3492     // If the sign bit is known to be zero or one, then sext will extend
3493     // it to the top bits, else it will just zext.
3494     Known = Known.sext(BitWidth);
3495     break;
3496   }
3497   case ISD::ANY_EXTEND_VECTOR_INREG: {
3498     EVT InVT = Op.getOperand(0).getValueType();
3499     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3500     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3501     Known = Known.anyext(BitWidth);
3502     break;
3503   }
3504   case ISD::ANY_EXTEND: {
3505     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3506     Known = Known.anyext(BitWidth);
3507     break;
3508   }
3509   case ISD::TRUNCATE: {
3510     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3511     Known = Known.trunc(BitWidth);
3512     break;
3513   }
3514   case ISD::AssertZext: {
3515     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3516     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3517     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3518     Known.Zero |= (~InMask);
3519     Known.One  &= (~Known.Zero);
3520     break;
3521   }
3522   case ISD::AssertAlign: {
3523     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3524     assert(LogOfAlign != 0);
3525 
3526     // TODO: Should use maximum with source
3527     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3528     // well as clearing one bits.
3529     Known.Zero.setLowBits(LogOfAlign);
3530     Known.One.clearLowBits(LogOfAlign);
3531     break;
3532   }
3533   case ISD::FGETSIGN:
3534     // All bits are zero except the low bit.
3535     Known.Zero.setBitsFrom(1);
3536     break;
3537   case ISD::USUBO:
3538   case ISD::SSUBO:
3539   case ISD::SUBCARRY:
3540   case ISD::SSUBO_CARRY:
3541     if (Op.getResNo() == 1) {
3542       // If we know the result of a setcc has the top bits zero, use this info.
3543       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3544               TargetLowering::ZeroOrOneBooleanContent &&
3545           BitWidth > 1)
3546         Known.Zero.setBitsFrom(1);
3547       break;
3548     }
3549     LLVM_FALLTHROUGH;
3550   case ISD::SUB:
3551   case ISD::SUBC: {
3552     assert(Op.getResNo() == 0 &&
3553            "We only compute knownbits for the difference here.");
3554 
3555     // TODO: Compute influence of the carry operand.
3556     if (Opcode == ISD::SUBCARRY || Opcode == ISD::SSUBO_CARRY)
3557       break;
3558 
3559     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3560     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3561     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3562                                         Known, Known2);
3563     break;
3564   }
3565   case ISD::UADDO:
3566   case ISD::SADDO:
3567   case ISD::ADDCARRY:
3568   case ISD::SADDO_CARRY:
3569     if (Op.getResNo() == 1) {
3570       // If we know the result of a setcc has the top bits zero, use this info.
3571       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3572               TargetLowering::ZeroOrOneBooleanContent &&
3573           BitWidth > 1)
3574         Known.Zero.setBitsFrom(1);
3575       break;
3576     }
3577     LLVM_FALLTHROUGH;
3578   case ISD::ADD:
3579   case ISD::ADDC:
3580   case ISD::ADDE: {
3581     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3582 
3583     // With ADDE and ADDCARRY, a carry bit may be added in.
3584     KnownBits Carry(1);
3585     if (Opcode == ISD::ADDE)
3586       // Can't track carry from glue, set carry to unknown.
3587       Carry.resetAll();
3588     else if (Opcode == ISD::ADDCARRY || Opcode == ISD::SADDO_CARRY)
3589       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3590       // the trouble (how often will we find a known carry bit). And I haven't
3591       // tested this very much yet, but something like this might work:
3592       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3593       //   Carry = Carry.zextOrTrunc(1, false);
3594       Carry.resetAll();
3595     else
3596       Carry.setAllZero();
3597 
3598     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3599     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3600     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3601     break;
3602   }
3603   case ISD::UDIV: {
3604     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3605     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3606     Known = KnownBits::udiv(Known, Known2);
3607     break;
3608   }
3609   case ISD::SREM: {
3610     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3611     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3612     Known = KnownBits::srem(Known, Known2);
3613     break;
3614   }
3615   case ISD::UREM: {
3616     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3617     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3618     Known = KnownBits::urem(Known, Known2);
3619     break;
3620   }
3621   case ISD::EXTRACT_ELEMENT: {
3622     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3623     const unsigned Index = Op.getConstantOperandVal(1);
3624     const unsigned EltBitWidth = Op.getValueSizeInBits();
3625 
3626     // Remove low part of known bits mask
3627     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3628     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3629 
3630     // Remove high part of known bit mask
3631     Known = Known.trunc(EltBitWidth);
3632     break;
3633   }
3634   case ISD::EXTRACT_VECTOR_ELT: {
3635     SDValue InVec = Op.getOperand(0);
3636     SDValue EltNo = Op.getOperand(1);
3637     EVT VecVT = InVec.getValueType();
3638     // computeKnownBits not yet implemented for scalable vectors.
3639     if (VecVT.isScalableVector())
3640       break;
3641     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3642     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3643 
3644     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3645     // anything about the extended bits.
3646     if (BitWidth > EltBitWidth)
3647       Known = Known.trunc(EltBitWidth);
3648 
3649     // If we know the element index, just demand that vector element, else for
3650     // an unknown element index, ignore DemandedElts and demand them all.
3651     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3652     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3653     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3654       DemandedSrcElts =
3655           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3656 
3657     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3658     if (BitWidth > EltBitWidth)
3659       Known = Known.anyext(BitWidth);
3660     break;
3661   }
3662   case ISD::INSERT_VECTOR_ELT: {
3663     // If we know the element index, split the demand between the
3664     // source vector and the inserted element, otherwise assume we need
3665     // the original demanded vector elements and the value.
3666     SDValue InVec = Op.getOperand(0);
3667     SDValue InVal = Op.getOperand(1);
3668     SDValue EltNo = Op.getOperand(2);
3669     bool DemandedVal = true;
3670     APInt DemandedVecElts = DemandedElts;
3671     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3672     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3673       unsigned EltIdx = CEltNo->getZExtValue();
3674       DemandedVal = !!DemandedElts[EltIdx];
3675       DemandedVecElts.clearBit(EltIdx);
3676     }
3677     Known.One.setAllBits();
3678     Known.Zero.setAllBits();
3679     if (DemandedVal) {
3680       Known2 = computeKnownBits(InVal, Depth + 1);
3681       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3682     }
3683     if (!!DemandedVecElts) {
3684       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3685       Known = KnownBits::commonBits(Known, Known2);
3686     }
3687     break;
3688   }
3689   case ISD::BITREVERSE: {
3690     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3691     Known = Known2.reverseBits();
3692     break;
3693   }
3694   case ISD::BSWAP: {
3695     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3696     Known = Known2.byteSwap();
3697     break;
3698   }
3699   case ISD::ABS: {
3700     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3701     Known = Known2.abs();
3702     break;
3703   }
3704   case ISD::USUBSAT: {
3705     // The result of usubsat will never be larger than the LHS.
3706     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3707     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3708     break;
3709   }
3710   case ISD::UMIN: {
3711     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3712     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3713     Known = KnownBits::umin(Known, Known2);
3714     break;
3715   }
3716   case ISD::UMAX: {
3717     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3718     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3719     Known = KnownBits::umax(Known, Known2);
3720     break;
3721   }
3722   case ISD::SMIN:
3723   case ISD::SMAX: {
3724     // If we have a clamp pattern, we know that the number of sign bits will be
3725     // the minimum of the clamp min/max range.
3726     bool IsMax = (Opcode == ISD::SMAX);
3727     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3728     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3729       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3730         CstHigh =
3731             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3732     if (CstLow && CstHigh) {
3733       if (!IsMax)
3734         std::swap(CstLow, CstHigh);
3735 
3736       const APInt &ValueLow = CstLow->getAPIntValue();
3737       const APInt &ValueHigh = CstHigh->getAPIntValue();
3738       if (ValueLow.sle(ValueHigh)) {
3739         unsigned LowSignBits = ValueLow.getNumSignBits();
3740         unsigned HighSignBits = ValueHigh.getNumSignBits();
3741         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3742         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3743           Known.One.setHighBits(MinSignBits);
3744           break;
3745         }
3746         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3747           Known.Zero.setHighBits(MinSignBits);
3748           break;
3749         }
3750       }
3751     }
3752 
3753     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3754     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3755     if (IsMax)
3756       Known = KnownBits::smax(Known, Known2);
3757     else
3758       Known = KnownBits::smin(Known, Known2);
3759 
3760     // For SMAX, if CstLow is non-negative we know the result will be
3761     // non-negative and thus all sign bits are 0.
3762     // TODO: There's an equivalent of this for smin with negative constant for
3763     // known ones.
3764     if (IsMax && CstLow) {
3765       const APInt &ValueLow = CstLow->getAPIntValue();
3766       if (ValueLow.isNonNegative()) {
3767         unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3768         Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3769       }
3770     }
3771 
3772     break;
3773   }
3774   case ISD::FP_TO_UINT_SAT: {
3775     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3776     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3777     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3778     break;
3779   }
3780   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3781     if (Op.getResNo() == 1) {
3782       // The boolean result conforms to getBooleanContents.
3783       // If we know the result of a setcc has the top bits zero, use this info.
3784       // We know that we have an integer-based boolean since these operations
3785       // are only available for integer.
3786       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3787               TargetLowering::ZeroOrOneBooleanContent &&
3788           BitWidth > 1)
3789         Known.Zero.setBitsFrom(1);
3790       break;
3791     }
3792     LLVM_FALLTHROUGH;
3793   case ISD::ATOMIC_CMP_SWAP:
3794   case ISD::ATOMIC_SWAP:
3795   case ISD::ATOMIC_LOAD_ADD:
3796   case ISD::ATOMIC_LOAD_SUB:
3797   case ISD::ATOMIC_LOAD_AND:
3798   case ISD::ATOMIC_LOAD_CLR:
3799   case ISD::ATOMIC_LOAD_OR:
3800   case ISD::ATOMIC_LOAD_XOR:
3801   case ISD::ATOMIC_LOAD_NAND:
3802   case ISD::ATOMIC_LOAD_MIN:
3803   case ISD::ATOMIC_LOAD_MAX:
3804   case ISD::ATOMIC_LOAD_UMIN:
3805   case ISD::ATOMIC_LOAD_UMAX:
3806   case ISD::ATOMIC_LOAD: {
3807     unsigned MemBits =
3808         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3809     // If we are looking at the loaded value.
3810     if (Op.getResNo() == 0) {
3811       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3812         Known.Zero.setBitsFrom(MemBits);
3813     }
3814     break;
3815   }
3816   case ISD::FrameIndex:
3817   case ISD::TargetFrameIndex:
3818     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3819                                        Known, getMachineFunction());
3820     break;
3821 
3822   default:
3823     if (Opcode < ISD::BUILTIN_OP_END)
3824       break;
3825     LLVM_FALLTHROUGH;
3826   case ISD::INTRINSIC_WO_CHAIN:
3827   case ISD::INTRINSIC_W_CHAIN:
3828   case ISD::INTRINSIC_VOID:
3829     // Allow the target to implement this method for its nodes.
3830     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3831     break;
3832   }
3833 
3834   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3835   return Known;
3836 }
3837 
3838 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3839                                                              SDValue N1) const {
3840   // X + 0 never overflow
3841   if (isNullConstant(N1))
3842     return OFK_Never;
3843 
3844   KnownBits N1Known = computeKnownBits(N1);
3845   if (N1Known.Zero.getBoolValue()) {
3846     KnownBits N0Known = computeKnownBits(N0);
3847 
3848     bool overflow;
3849     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3850     if (!overflow)
3851       return OFK_Never;
3852   }
3853 
3854   // mulhi + 1 never overflow
3855   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3856       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3857     return OFK_Never;
3858 
3859   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3860     KnownBits N0Known = computeKnownBits(N0);
3861 
3862     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3863       return OFK_Never;
3864   }
3865 
3866   return OFK_Sometime;
3867 }
3868 
3869 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3870   EVT OpVT = Val.getValueType();
3871   unsigned BitWidth = OpVT.getScalarSizeInBits();
3872 
3873   // Is the constant a known power of 2?
3874   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3875     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3876 
3877   // A left-shift of a constant one will have exactly one bit set because
3878   // shifting the bit off the end is undefined.
3879   if (Val.getOpcode() == ISD::SHL) {
3880     auto *C = isConstOrConstSplat(Val.getOperand(0));
3881     if (C && C->getAPIntValue() == 1)
3882       return true;
3883   }
3884 
3885   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3886   // one bit set.
3887   if (Val.getOpcode() == ISD::SRL) {
3888     auto *C = isConstOrConstSplat(Val.getOperand(0));
3889     if (C && C->getAPIntValue().isSignMask())
3890       return true;
3891   }
3892 
3893   // Are all operands of a build vector constant powers of two?
3894   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3895     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3896           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3897             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3898           return false;
3899         }))
3900       return true;
3901 
3902   // Is the operand of a splat vector a constant power of two?
3903   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3904     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3905       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3906         return true;
3907 
3908   // vscale(power-of-two) is a power-of-two for some targets
3909   if (Val.getOpcode() == ISD::VSCALE &&
3910       getTargetLoweringInfo().isVScaleKnownToBeAPowerOfTwo() &&
3911       isKnownToBeAPowerOfTwo(Val.getOperand(0)))
3912     return true;
3913 
3914   // More could be done here, though the above checks are enough
3915   // to handle some common cases.
3916 
3917   // Fall back to computeKnownBits to catch other known cases.
3918   KnownBits Known = computeKnownBits(Val);
3919   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3920 }
3921 
3922 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3923   EVT VT = Op.getValueType();
3924 
3925   // TODO: Assume we don't know anything for now.
3926   if (VT.isScalableVector())
3927     return 1;
3928 
3929   APInt DemandedElts = VT.isVector()
3930                            ? APInt::getAllOnes(VT.getVectorNumElements())
3931                            : APInt(1, 1);
3932   return ComputeNumSignBits(Op, DemandedElts, Depth);
3933 }
3934 
3935 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3936                                           unsigned Depth) const {
3937   EVT VT = Op.getValueType();
3938   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3939   unsigned VTBits = VT.getScalarSizeInBits();
3940   unsigned NumElts = DemandedElts.getBitWidth();
3941   unsigned Tmp, Tmp2;
3942   unsigned FirstAnswer = 1;
3943 
3944   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3945     const APInt &Val = C->getAPIntValue();
3946     return Val.getNumSignBits();
3947   }
3948 
3949   if (Depth >= MaxRecursionDepth)
3950     return 1;  // Limit search depth.
3951 
3952   if (!DemandedElts || VT.isScalableVector())
3953     return 1;  // No demanded elts, better to assume we don't know anything.
3954 
3955   unsigned Opcode = Op.getOpcode();
3956   switch (Opcode) {
3957   default: break;
3958   case ISD::AssertSext:
3959     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3960     return VTBits-Tmp+1;
3961   case ISD::AssertZext:
3962     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3963     return VTBits-Tmp;
3964   case ISD::MERGE_VALUES:
3965     return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
3966                               Depth + 1);
3967   case ISD::BUILD_VECTOR:
3968     Tmp = VTBits;
3969     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3970       if (!DemandedElts[i])
3971         continue;
3972 
3973       SDValue SrcOp = Op.getOperand(i);
3974       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3975 
3976       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3977       if (SrcOp.getValueSizeInBits() != VTBits) {
3978         assert(SrcOp.getValueSizeInBits() > VTBits &&
3979                "Expected BUILD_VECTOR implicit truncation");
3980         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3981         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3982       }
3983       Tmp = std::min(Tmp, Tmp2);
3984     }
3985     return Tmp;
3986 
3987   case ISD::VECTOR_SHUFFLE: {
3988     // Collect the minimum number of sign bits that are shared by every vector
3989     // element referenced by the shuffle.
3990     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3991     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3992     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3993     for (unsigned i = 0; i != NumElts; ++i) {
3994       int M = SVN->getMaskElt(i);
3995       if (!DemandedElts[i])
3996         continue;
3997       // For UNDEF elements, we don't know anything about the common state of
3998       // the shuffle result.
3999       if (M < 0)
4000         return 1;
4001       if ((unsigned)M < NumElts)
4002         DemandedLHS.setBit((unsigned)M % NumElts);
4003       else
4004         DemandedRHS.setBit((unsigned)M % NumElts);
4005     }
4006     Tmp = std::numeric_limits<unsigned>::max();
4007     if (!!DemandedLHS)
4008       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
4009     if (!!DemandedRHS) {
4010       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
4011       Tmp = std::min(Tmp, Tmp2);
4012     }
4013     // If we don't know anything, early out and try computeKnownBits fall-back.
4014     if (Tmp == 1)
4015       break;
4016     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4017     return Tmp;
4018   }
4019 
4020   case ISD::BITCAST: {
4021     SDValue N0 = Op.getOperand(0);
4022     EVT SrcVT = N0.getValueType();
4023     unsigned SrcBits = SrcVT.getScalarSizeInBits();
4024 
4025     // Ignore bitcasts from unsupported types..
4026     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
4027       break;
4028 
4029     // Fast handling of 'identity' bitcasts.
4030     if (VTBits == SrcBits)
4031       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
4032 
4033     bool IsLE = getDataLayout().isLittleEndian();
4034 
4035     // Bitcast 'large element' scalar/vector to 'small element' vector.
4036     if ((SrcBits % VTBits) == 0) {
4037       assert(VT.isVector() && "Expected bitcast to vector");
4038 
4039       unsigned Scale = SrcBits / VTBits;
4040       APInt SrcDemandedElts =
4041           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
4042 
4043       // Fast case - sign splat can be simply split across the small elements.
4044       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
4045       if (Tmp == SrcBits)
4046         return VTBits;
4047 
4048       // Slow case - determine how far the sign extends into each sub-element.
4049       Tmp2 = VTBits;
4050       for (unsigned i = 0; i != NumElts; ++i)
4051         if (DemandedElts[i]) {
4052           unsigned SubOffset = i % Scale;
4053           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
4054           SubOffset = SubOffset * VTBits;
4055           if (Tmp <= SubOffset)
4056             return 1;
4057           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
4058         }
4059       return Tmp2;
4060     }
4061     break;
4062   }
4063 
4064   case ISD::FP_TO_SINT_SAT:
4065     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4066     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4067     return VTBits - Tmp + 1;
4068   case ISD::SIGN_EXTEND:
4069     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4070     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4071   case ISD::SIGN_EXTEND_INREG:
4072     // Max of the input and what this extends.
4073     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4074     Tmp = VTBits-Tmp+1;
4075     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4076     return std::max(Tmp, Tmp2);
4077   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4078     SDValue Src = Op.getOperand(0);
4079     EVT SrcVT = Src.getValueType();
4080     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4081     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4082     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4083   }
4084   case ISD::SRA:
4085     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4086     // SRA X, C -> adds C sign bits.
4087     if (const APInt *ShAmt =
4088             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4089       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4090     return Tmp;
4091   case ISD::SHL:
4092     if (const APInt *ShAmt =
4093             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4094       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4095       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4096       if (ShAmt->ult(Tmp))
4097         return Tmp - ShAmt->getZExtValue();
4098     }
4099     break;
4100   case ISD::AND:
4101   case ISD::OR:
4102   case ISD::XOR:    // NOT is handled here.
4103     // Logical binary ops preserve the number of sign bits at the worst.
4104     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4105     if (Tmp != 1) {
4106       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4107       FirstAnswer = std::min(Tmp, Tmp2);
4108       // We computed what we know about the sign bits as our first
4109       // answer. Now proceed to the generic code that uses
4110       // computeKnownBits, and pick whichever answer is better.
4111     }
4112     break;
4113 
4114   case ISD::SELECT:
4115   case ISD::VSELECT:
4116     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4117     if (Tmp == 1) return 1;  // Early out.
4118     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4119     return std::min(Tmp, Tmp2);
4120   case ISD::SELECT_CC:
4121     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4122     if (Tmp == 1) return 1;  // Early out.
4123     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4124     return std::min(Tmp, Tmp2);
4125 
4126   case ISD::SMIN:
4127   case ISD::SMAX: {
4128     // If we have a clamp pattern, we know that the number of sign bits will be
4129     // the minimum of the clamp min/max range.
4130     bool IsMax = (Opcode == ISD::SMAX);
4131     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4132     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4133       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4134         CstHigh =
4135             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4136     if (CstLow && CstHigh) {
4137       if (!IsMax)
4138         std::swap(CstLow, CstHigh);
4139       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4140         Tmp = CstLow->getAPIntValue().getNumSignBits();
4141         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4142         return std::min(Tmp, Tmp2);
4143       }
4144     }
4145 
4146     // Fallback - just get the minimum number of sign bits of the operands.
4147     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4148     if (Tmp == 1)
4149       return 1;  // Early out.
4150     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4151     return std::min(Tmp, Tmp2);
4152   }
4153   case ISD::UMIN:
4154   case ISD::UMAX:
4155     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4156     if (Tmp == 1)
4157       return 1;  // Early out.
4158     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4159     return std::min(Tmp, Tmp2);
4160   case ISD::SADDO:
4161   case ISD::UADDO:
4162   case ISD::SADDO_CARRY:
4163   case ISD::ADDCARRY:
4164   case ISD::SSUBO:
4165   case ISD::USUBO:
4166   case ISD::SSUBO_CARRY:
4167   case ISD::SUBCARRY:
4168   case ISD::SMULO:
4169   case ISD::UMULO:
4170     if (Op.getResNo() != 1)
4171       break;
4172     // The boolean result conforms to getBooleanContents.  Fall through.
4173     // If setcc returns 0/-1, all bits are sign bits.
4174     // We know that we have an integer-based boolean since these operations
4175     // are only available for integer.
4176     if (TLI->getBooleanContents(VT.isVector(), false) ==
4177         TargetLowering::ZeroOrNegativeOneBooleanContent)
4178       return VTBits;
4179     break;
4180   case ISD::SETCC:
4181   case ISD::SETCCCARRY:
4182   case ISD::STRICT_FSETCC:
4183   case ISD::STRICT_FSETCCS: {
4184     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4185     // If setcc returns 0/-1, all bits are sign bits.
4186     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4187         TargetLowering::ZeroOrNegativeOneBooleanContent)
4188       return VTBits;
4189     break;
4190   }
4191   case ISD::ROTL:
4192   case ISD::ROTR:
4193     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4194 
4195     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4196     if (Tmp == VTBits)
4197       return VTBits;
4198 
4199     if (ConstantSDNode *C =
4200             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4201       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4202 
4203       // Handle rotate right by N like a rotate left by 32-N.
4204       if (Opcode == ISD::ROTR)
4205         RotAmt = (VTBits - RotAmt) % VTBits;
4206 
4207       // If we aren't rotating out all of the known-in sign bits, return the
4208       // number that are left.  This handles rotl(sext(x), 1) for example.
4209       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4210     }
4211     break;
4212   case ISD::ADD:
4213   case ISD::ADDC:
4214     // Add can have at most one carry bit.  Thus we know that the output
4215     // is, at worst, one more bit than the inputs.
4216     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4217     if (Tmp == 1) return 1; // Early out.
4218 
4219     // Special case decrementing a value (ADD X, -1):
4220     if (ConstantSDNode *CRHS =
4221             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4222       if (CRHS->isAllOnes()) {
4223         KnownBits Known =
4224             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4225 
4226         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4227         // sign bits set.
4228         if ((Known.Zero | 1).isAllOnes())
4229           return VTBits;
4230 
4231         // If we are subtracting one from a positive number, there is no carry
4232         // out of the result.
4233         if (Known.isNonNegative())
4234           return Tmp;
4235       }
4236 
4237     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4238     if (Tmp2 == 1) return 1; // Early out.
4239     return std::min(Tmp, Tmp2) - 1;
4240   case ISD::SUB:
4241     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4242     if (Tmp2 == 1) return 1; // Early out.
4243 
4244     // Handle NEG.
4245     if (ConstantSDNode *CLHS =
4246             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4247       if (CLHS->isZero()) {
4248         KnownBits Known =
4249             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4250         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4251         // sign bits set.
4252         if ((Known.Zero | 1).isAllOnes())
4253           return VTBits;
4254 
4255         // If the input is known to be positive (the sign bit is known clear),
4256         // the output of the NEG has the same number of sign bits as the input.
4257         if (Known.isNonNegative())
4258           return Tmp2;
4259 
4260         // Otherwise, we treat this like a SUB.
4261       }
4262 
4263     // Sub can have at most one carry bit.  Thus we know that the output
4264     // is, at worst, one more bit than the inputs.
4265     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4266     if (Tmp == 1) return 1; // Early out.
4267     return std::min(Tmp, Tmp2) - 1;
4268   case ISD::MUL: {
4269     // The output of the Mul can be at most twice the valid bits in the inputs.
4270     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4271     if (SignBitsOp0 == 1)
4272       break;
4273     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4274     if (SignBitsOp1 == 1)
4275       break;
4276     unsigned OutValidBits =
4277         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4278     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4279   }
4280   case ISD::SREM:
4281     // The sign bit is the LHS's sign bit, except when the result of the
4282     // remainder is zero. The magnitude of the result should be less than or
4283     // equal to the magnitude of the LHS. Therefore, the result should have
4284     // at least as many sign bits as the left hand side.
4285     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4286   case ISD::TRUNCATE: {
4287     // Check if the sign bits of source go down as far as the truncated value.
4288     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4289     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4290     if (NumSrcSignBits > (NumSrcBits - VTBits))
4291       return NumSrcSignBits - (NumSrcBits - VTBits);
4292     break;
4293   }
4294   case ISD::EXTRACT_ELEMENT: {
4295     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4296     const int BitWidth = Op.getValueSizeInBits();
4297     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4298 
4299     // Get reverse index (starting from 1), Op1 value indexes elements from
4300     // little end. Sign starts at big end.
4301     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4302 
4303     // If the sign portion ends in our element the subtraction gives correct
4304     // result. Otherwise it gives either negative or > bitwidth result
4305     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4306   }
4307   case ISD::INSERT_VECTOR_ELT: {
4308     // If we know the element index, split the demand between the
4309     // source vector and the inserted element, otherwise assume we need
4310     // the original demanded vector elements and the value.
4311     SDValue InVec = Op.getOperand(0);
4312     SDValue InVal = Op.getOperand(1);
4313     SDValue EltNo = Op.getOperand(2);
4314     bool DemandedVal = true;
4315     APInt DemandedVecElts = DemandedElts;
4316     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4317     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4318       unsigned EltIdx = CEltNo->getZExtValue();
4319       DemandedVal = !!DemandedElts[EltIdx];
4320       DemandedVecElts.clearBit(EltIdx);
4321     }
4322     Tmp = std::numeric_limits<unsigned>::max();
4323     if (DemandedVal) {
4324       // TODO - handle implicit truncation of inserted elements.
4325       if (InVal.getScalarValueSizeInBits() != VTBits)
4326         break;
4327       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4328       Tmp = std::min(Tmp, Tmp2);
4329     }
4330     if (!!DemandedVecElts) {
4331       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4332       Tmp = std::min(Tmp, Tmp2);
4333     }
4334     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4335     return Tmp;
4336   }
4337   case ISD::EXTRACT_VECTOR_ELT: {
4338     SDValue InVec = Op.getOperand(0);
4339     SDValue EltNo = Op.getOperand(1);
4340     EVT VecVT = InVec.getValueType();
4341     // ComputeNumSignBits not yet implemented for scalable vectors.
4342     if (VecVT.isScalableVector())
4343       break;
4344     const unsigned BitWidth = Op.getValueSizeInBits();
4345     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4346     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4347 
4348     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4349     // anything about sign bits. But if the sizes match we can derive knowledge
4350     // about sign bits from the vector operand.
4351     if (BitWidth != EltBitWidth)
4352       break;
4353 
4354     // If we know the element index, just demand that vector element, else for
4355     // an unknown element index, ignore DemandedElts and demand them all.
4356     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4357     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4358     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4359       DemandedSrcElts =
4360           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4361 
4362     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4363   }
4364   case ISD::EXTRACT_SUBVECTOR: {
4365     // Offset the demanded elts by the subvector index.
4366     SDValue Src = Op.getOperand(0);
4367     // Bail until we can represent demanded elements for scalable vectors.
4368     if (Src.getValueType().isScalableVector())
4369       break;
4370     uint64_t Idx = Op.getConstantOperandVal(1);
4371     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4372     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4373     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4374   }
4375   case ISD::CONCAT_VECTORS: {
4376     // Determine the minimum number of sign bits across all demanded
4377     // elts of the input vectors. Early out if the result is already 1.
4378     Tmp = std::numeric_limits<unsigned>::max();
4379     EVT SubVectorVT = Op.getOperand(0).getValueType();
4380     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4381     unsigned NumSubVectors = Op.getNumOperands();
4382     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4383       APInt DemandedSub =
4384           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4385       if (!DemandedSub)
4386         continue;
4387       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4388       Tmp = std::min(Tmp, Tmp2);
4389     }
4390     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4391     return Tmp;
4392   }
4393   case ISD::INSERT_SUBVECTOR: {
4394     // Demand any elements from the subvector and the remainder from the src its
4395     // inserted into.
4396     SDValue Src = Op.getOperand(0);
4397     SDValue Sub = Op.getOperand(1);
4398     uint64_t Idx = Op.getConstantOperandVal(2);
4399     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4400     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4401     APInt DemandedSrcElts = DemandedElts;
4402     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4403 
4404     Tmp = std::numeric_limits<unsigned>::max();
4405     if (!!DemandedSubElts) {
4406       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4407       if (Tmp == 1)
4408         return 1; // early-out
4409     }
4410     if (!!DemandedSrcElts) {
4411       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4412       Tmp = std::min(Tmp, Tmp2);
4413     }
4414     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4415     return Tmp;
4416   }
4417   case ISD::ATOMIC_CMP_SWAP:
4418   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4419   case ISD::ATOMIC_SWAP:
4420   case ISD::ATOMIC_LOAD_ADD:
4421   case ISD::ATOMIC_LOAD_SUB:
4422   case ISD::ATOMIC_LOAD_AND:
4423   case ISD::ATOMIC_LOAD_CLR:
4424   case ISD::ATOMIC_LOAD_OR:
4425   case ISD::ATOMIC_LOAD_XOR:
4426   case ISD::ATOMIC_LOAD_NAND:
4427   case ISD::ATOMIC_LOAD_MIN:
4428   case ISD::ATOMIC_LOAD_MAX:
4429   case ISD::ATOMIC_LOAD_UMIN:
4430   case ISD::ATOMIC_LOAD_UMAX:
4431   case ISD::ATOMIC_LOAD: {
4432     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4433     // If we are looking at the loaded value.
4434     if (Op.getResNo() == 0) {
4435       if (Tmp == VTBits)
4436         return 1; // early-out
4437       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4438         return VTBits - Tmp + 1;
4439       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4440         return VTBits - Tmp;
4441     }
4442     break;
4443   }
4444   }
4445 
4446   // If we are looking at the loaded value of the SDNode.
4447   if (Op.getResNo() == 0) {
4448     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4449     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4450       unsigned ExtType = LD->getExtensionType();
4451       switch (ExtType) {
4452       default: break;
4453       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4454         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4455         return VTBits - Tmp + 1;
4456       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4457         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4458         return VTBits - Tmp;
4459       case ISD::NON_EXTLOAD:
4460         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4461           // We only need to handle vectors - computeKnownBits should handle
4462           // scalar cases.
4463           Type *CstTy = Cst->getType();
4464           if (CstTy->isVectorTy() &&
4465               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4466               VTBits == CstTy->getScalarSizeInBits()) {
4467             Tmp = VTBits;
4468             for (unsigned i = 0; i != NumElts; ++i) {
4469               if (!DemandedElts[i])
4470                 continue;
4471               if (Constant *Elt = Cst->getAggregateElement(i)) {
4472                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4473                   const APInt &Value = CInt->getValue();
4474                   Tmp = std::min(Tmp, Value.getNumSignBits());
4475                   continue;
4476                 }
4477                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4478                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4479                   Tmp = std::min(Tmp, Value.getNumSignBits());
4480                   continue;
4481                 }
4482               }
4483               // Unknown type. Conservatively assume no bits match sign bit.
4484               return 1;
4485             }
4486             return Tmp;
4487           }
4488         }
4489         break;
4490       }
4491     }
4492   }
4493 
4494   // Allow the target to implement this method for its nodes.
4495   if (Opcode >= ISD::BUILTIN_OP_END ||
4496       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4497       Opcode == ISD::INTRINSIC_W_CHAIN ||
4498       Opcode == ISD::INTRINSIC_VOID) {
4499     unsigned NumBits =
4500         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4501     if (NumBits > 1)
4502       FirstAnswer = std::max(FirstAnswer, NumBits);
4503   }
4504 
4505   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4506   // use this information.
4507   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4508   return std::max(FirstAnswer, Known.countMinSignBits());
4509 }
4510 
4511 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4512                                                  unsigned Depth) const {
4513   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4514   return Op.getScalarValueSizeInBits() - SignBits + 1;
4515 }
4516 
4517 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4518                                                  const APInt &DemandedElts,
4519                                                  unsigned Depth) const {
4520   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4521   return Op.getScalarValueSizeInBits() - SignBits + 1;
4522 }
4523 
4524 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4525                                                     unsigned Depth) const {
4526   // Early out for FREEZE.
4527   if (Op.getOpcode() == ISD::FREEZE)
4528     return true;
4529 
4530   // TODO: Assume we don't know anything for now.
4531   EVT VT = Op.getValueType();
4532   if (VT.isScalableVector())
4533     return false;
4534 
4535   APInt DemandedElts = VT.isVector()
4536                            ? APInt::getAllOnes(VT.getVectorNumElements())
4537                            : APInt(1, 1);
4538   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4539 }
4540 
4541 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4542                                                     const APInt &DemandedElts,
4543                                                     bool PoisonOnly,
4544                                                     unsigned Depth) const {
4545   unsigned Opcode = Op.getOpcode();
4546 
4547   // Early out for FREEZE.
4548   if (Opcode == ISD::FREEZE)
4549     return true;
4550 
4551   if (Depth >= MaxRecursionDepth)
4552     return false; // Limit search depth.
4553 
4554   if (isIntOrFPConstant(Op))
4555     return true;
4556 
4557   switch (Opcode) {
4558   case ISD::UNDEF:
4559     return PoisonOnly;
4560 
4561   case ISD::BUILD_VECTOR:
4562     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4563     // this shouldn't affect the result.
4564     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4565       if (!DemandedElts[i])
4566         continue;
4567       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4568                                             Depth + 1))
4569         return false;
4570     }
4571     return true;
4572 
4573   // TODO: Search for noundef attributes from library functions.
4574 
4575   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4576 
4577   default:
4578     // Allow the target to implement this method for its nodes.
4579     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4580         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4581       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4582           Op, DemandedElts, *this, PoisonOnly, Depth);
4583     break;
4584   }
4585 
4586   return false;
4587 }
4588 
4589 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4590   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4591       !isa<ConstantSDNode>(Op.getOperand(1)))
4592     return false;
4593 
4594   if (Op.getOpcode() == ISD::OR &&
4595       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4596     return false;
4597 
4598   return true;
4599 }
4600 
4601 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4602   // If we're told that NaNs won't happen, assume they won't.
4603   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4604     return true;
4605 
4606   if (Depth >= MaxRecursionDepth)
4607     return false; // Limit search depth.
4608 
4609   // TODO: Handle vectors.
4610   // If the value is a constant, we can obviously see if it is a NaN or not.
4611   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4612     return !C->getValueAPF().isNaN() ||
4613            (SNaN && !C->getValueAPF().isSignaling());
4614   }
4615 
4616   unsigned Opcode = Op.getOpcode();
4617   switch (Opcode) {
4618   case ISD::FADD:
4619   case ISD::FSUB:
4620   case ISD::FMUL:
4621   case ISD::FDIV:
4622   case ISD::FREM:
4623   case ISD::FSIN:
4624   case ISD::FCOS: {
4625     if (SNaN)
4626       return true;
4627     // TODO: Need isKnownNeverInfinity
4628     return false;
4629   }
4630   case ISD::FCANONICALIZE:
4631   case ISD::FEXP:
4632   case ISD::FEXP2:
4633   case ISD::FTRUNC:
4634   case ISD::FFLOOR:
4635   case ISD::FCEIL:
4636   case ISD::FROUND:
4637   case ISD::FROUNDEVEN:
4638   case ISD::FRINT:
4639   case ISD::FNEARBYINT: {
4640     if (SNaN)
4641       return true;
4642     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4643   }
4644   case ISD::FABS:
4645   case ISD::FNEG:
4646   case ISD::FCOPYSIGN: {
4647     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4648   }
4649   case ISD::SELECT:
4650     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4651            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4652   case ISD::FP_EXTEND:
4653   case ISD::FP_ROUND: {
4654     if (SNaN)
4655       return true;
4656     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4657   }
4658   case ISD::SINT_TO_FP:
4659   case ISD::UINT_TO_FP:
4660     return true;
4661   case ISD::FMA:
4662   case ISD::FMAD: {
4663     if (SNaN)
4664       return true;
4665     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4666            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4667            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4668   }
4669   case ISD::FSQRT: // Need is known positive
4670   case ISD::FLOG:
4671   case ISD::FLOG2:
4672   case ISD::FLOG10:
4673   case ISD::FPOWI:
4674   case ISD::FPOW: {
4675     if (SNaN)
4676       return true;
4677     // TODO: Refine on operand
4678     return false;
4679   }
4680   case ISD::FMINNUM:
4681   case ISD::FMAXNUM: {
4682     // Only one needs to be known not-nan, since it will be returned if the
4683     // other ends up being one.
4684     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4685            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4686   }
4687   case ISD::FMINNUM_IEEE:
4688   case ISD::FMAXNUM_IEEE: {
4689     if (SNaN)
4690       return true;
4691     // This can return a NaN if either operand is an sNaN, or if both operands
4692     // are NaN.
4693     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4694             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4695            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4696             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4697   }
4698   case ISD::FMINIMUM:
4699   case ISD::FMAXIMUM: {
4700     // TODO: Does this quiet or return the origina NaN as-is?
4701     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4702            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4703   }
4704   case ISD::EXTRACT_VECTOR_ELT: {
4705     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4706   }
4707   default:
4708     if (Opcode >= ISD::BUILTIN_OP_END ||
4709         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4710         Opcode == ISD::INTRINSIC_W_CHAIN ||
4711         Opcode == ISD::INTRINSIC_VOID) {
4712       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4713     }
4714 
4715     return false;
4716   }
4717 }
4718 
4719 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4720   assert(Op.getValueType().isFloatingPoint() &&
4721          "Floating point type expected");
4722 
4723   // If the value is a constant, we can obviously see if it is a zero or not.
4724   // TODO: Add BuildVector support.
4725   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4726     return !C->isZero();
4727   return false;
4728 }
4729 
4730 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4731   assert(!Op.getValueType().isFloatingPoint() &&
4732          "Floating point types unsupported - use isKnownNeverZeroFloat");
4733 
4734   // If the value is a constant, we can obviously see if it is a zero or not.
4735   if (ISD::matchUnaryPredicate(Op,
4736                                [](ConstantSDNode *C) { return !C->isZero(); }))
4737     return true;
4738 
4739   // TODO: Recognize more cases here.
4740   switch (Op.getOpcode()) {
4741   default: break;
4742   case ISD::OR:
4743     if (isKnownNeverZero(Op.getOperand(1)) ||
4744         isKnownNeverZero(Op.getOperand(0)))
4745       return true;
4746     break;
4747   }
4748 
4749   return false;
4750 }
4751 
4752 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4753   // Check the obvious case.
4754   if (A == B) return true;
4755 
4756   // For for negative and positive zero.
4757   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4758     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4759       if (CA->isZero() && CB->isZero()) return true;
4760 
4761   // Otherwise they may not be equal.
4762   return false;
4763 }
4764 
4765 // Only bits set in Mask must be negated, other bits may be arbitrary.
4766 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4767   if (isBitwiseNot(V, AllowUndefs))
4768     return V.getOperand(0);
4769 
4770   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4771   // bits in the non-extended part.
4772   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4773   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4774     return SDValue();
4775   SDValue ExtArg = V.getOperand(0);
4776   if (ExtArg.getScalarValueSizeInBits() >=
4777           MaskC->getAPIntValue().getActiveBits() &&
4778       isBitwiseNot(ExtArg, AllowUndefs) &&
4779       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4780       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4781     return ExtArg.getOperand(0).getOperand(0);
4782   return SDValue();
4783 }
4784 
4785 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4786   // Match masked merge pattern (X & ~M) op (Y & M)
4787   // Including degenerate case (X & ~M) op M
4788   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4789                                       SDValue Other) {
4790     if (SDValue NotOperand =
4791             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4792       if (Other == NotOperand)
4793         return true;
4794       if (Other->getOpcode() == ISD::AND)
4795         return NotOperand == Other->getOperand(0) ||
4796                NotOperand == Other->getOperand(1);
4797     }
4798     return false;
4799   };
4800   if (A->getOpcode() == ISD::AND)
4801     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4802            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4803   return false;
4804 }
4805 
4806 // FIXME: unify with llvm::haveNoCommonBitsSet.
4807 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4808   assert(A.getValueType() == B.getValueType() &&
4809          "Values must have the same type");
4810   if (haveNoCommonBitsSetCommutative(A, B) ||
4811       haveNoCommonBitsSetCommutative(B, A))
4812     return true;
4813   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4814                                         computeKnownBits(B));
4815 }
4816 
4817 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4818                                SelectionDAG &DAG) {
4819   if (cast<ConstantSDNode>(Step)->isZero())
4820     return DAG.getConstant(0, DL, VT);
4821 
4822   return SDValue();
4823 }
4824 
4825 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4826                                 ArrayRef<SDValue> Ops,
4827                                 SelectionDAG &DAG) {
4828   int NumOps = Ops.size();
4829   assert(NumOps != 0 && "Can't build an empty vector!");
4830   assert(!VT.isScalableVector() &&
4831          "BUILD_VECTOR cannot be used with scalable types");
4832   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4833          "Incorrect element count in BUILD_VECTOR!");
4834 
4835   // BUILD_VECTOR of UNDEFs is UNDEF.
4836   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4837     return DAG.getUNDEF(VT);
4838 
4839   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4840   SDValue IdentitySrc;
4841   bool IsIdentity = true;
4842   for (int i = 0; i != NumOps; ++i) {
4843     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4844         Ops[i].getOperand(0).getValueType() != VT ||
4845         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4846         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4847         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4848       IsIdentity = false;
4849       break;
4850     }
4851     IdentitySrc = Ops[i].getOperand(0);
4852   }
4853   if (IsIdentity)
4854     return IdentitySrc;
4855 
4856   return SDValue();
4857 }
4858 
4859 /// Try to simplify vector concatenation to an input value, undef, or build
4860 /// vector.
4861 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4862                                   ArrayRef<SDValue> Ops,
4863                                   SelectionDAG &DAG) {
4864   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4865   assert(llvm::all_of(Ops,
4866                       [Ops](SDValue Op) {
4867                         return Ops[0].getValueType() == Op.getValueType();
4868                       }) &&
4869          "Concatenation of vectors with inconsistent value types!");
4870   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4871              VT.getVectorElementCount() &&
4872          "Incorrect element count in vector concatenation!");
4873 
4874   if (Ops.size() == 1)
4875     return Ops[0];
4876 
4877   // Concat of UNDEFs is UNDEF.
4878   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4879     return DAG.getUNDEF(VT);
4880 
4881   // Scan the operands and look for extract operations from a single source
4882   // that correspond to insertion at the same location via this concatenation:
4883   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4884   SDValue IdentitySrc;
4885   bool IsIdentity = true;
4886   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4887     SDValue Op = Ops[i];
4888     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4889     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4890         Op.getOperand(0).getValueType() != VT ||
4891         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4892         Op.getConstantOperandVal(1) != IdentityIndex) {
4893       IsIdentity = false;
4894       break;
4895     }
4896     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4897            "Unexpected identity source vector for concat of extracts");
4898     IdentitySrc = Op.getOperand(0);
4899   }
4900   if (IsIdentity) {
4901     assert(IdentitySrc && "Failed to set source vector of extracts");
4902     return IdentitySrc;
4903   }
4904 
4905   // The code below this point is only designed to work for fixed width
4906   // vectors, so we bail out for now.
4907   if (VT.isScalableVector())
4908     return SDValue();
4909 
4910   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4911   // simplified to one big BUILD_VECTOR.
4912   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4913   EVT SVT = VT.getScalarType();
4914   SmallVector<SDValue, 16> Elts;
4915   for (SDValue Op : Ops) {
4916     EVT OpVT = Op.getValueType();
4917     if (Op.isUndef())
4918       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4919     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4920       Elts.append(Op->op_begin(), Op->op_end());
4921     else
4922       return SDValue();
4923   }
4924 
4925   // BUILD_VECTOR requires all inputs to be of the same type, find the
4926   // maximum type and extend them all.
4927   for (SDValue Op : Elts)
4928     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4929 
4930   if (SVT.bitsGT(VT.getScalarType())) {
4931     for (SDValue &Op : Elts) {
4932       if (Op.isUndef())
4933         Op = DAG.getUNDEF(SVT);
4934       else
4935         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4936                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4937                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4938     }
4939   }
4940 
4941   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4942   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4943   return V;
4944 }
4945 
4946 /// Gets or creates the specified node.
4947 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4948   FoldingSetNodeID ID;
4949   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4950   void *IP = nullptr;
4951   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4952     return SDValue(E, 0);
4953 
4954   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4955                               getVTList(VT));
4956   CSEMap.InsertNode(N, IP);
4957 
4958   InsertNode(N);
4959   SDValue V = SDValue(N, 0);
4960   NewSDValueDbgMsg(V, "Creating new node: ", this);
4961   return V;
4962 }
4963 
4964 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4965                               SDValue Operand) {
4966   SDNodeFlags Flags;
4967   if (Inserter)
4968     Flags = Inserter->getFlags();
4969   return getNode(Opcode, DL, VT, Operand, Flags);
4970 }
4971 
4972 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4973                               SDValue Operand, const SDNodeFlags Flags) {
4974   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4975          "Operand is DELETED_NODE!");
4976   // Constant fold unary operations with an integer constant operand. Even
4977   // opaque constant will be folded, because the folding of unary operations
4978   // doesn't create new constants with different values. Nevertheless, the
4979   // opaque flag is preserved during folding to prevent future folding with
4980   // other constants.
4981   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4982     const APInt &Val = C->getAPIntValue();
4983     switch (Opcode) {
4984     default: break;
4985     case ISD::SIGN_EXTEND:
4986       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4987                          C->isTargetOpcode(), C->isOpaque());
4988     case ISD::TRUNCATE:
4989       if (C->isOpaque())
4990         break;
4991       LLVM_FALLTHROUGH;
4992     case ISD::ZERO_EXTEND:
4993       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4994                          C->isTargetOpcode(), C->isOpaque());
4995     case ISD::ANY_EXTEND:
4996       // Some targets like RISCV prefer to sign extend some types.
4997       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4998         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4999                            C->isTargetOpcode(), C->isOpaque());
5000       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
5001                          C->isTargetOpcode(), C->isOpaque());
5002     case ISD::UINT_TO_FP:
5003     case ISD::SINT_TO_FP: {
5004       APFloat apf(EVTToAPFloatSemantics(VT),
5005                   APInt::getZero(VT.getSizeInBits()));
5006       (void)apf.convertFromAPInt(Val,
5007                                  Opcode==ISD::SINT_TO_FP,
5008                                  APFloat::rmNearestTiesToEven);
5009       return getConstantFP(apf, DL, VT);
5010     }
5011     case ISD::BITCAST:
5012       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
5013         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
5014       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
5015         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
5016       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
5017         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
5018       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
5019         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
5020       break;
5021     case ISD::ABS:
5022       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
5023                          C->isOpaque());
5024     case ISD::BITREVERSE:
5025       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
5026                          C->isOpaque());
5027     case ISD::BSWAP:
5028       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
5029                          C->isOpaque());
5030     case ISD::CTPOP:
5031       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
5032                          C->isOpaque());
5033     case ISD::CTLZ:
5034     case ISD::CTLZ_ZERO_UNDEF:
5035       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
5036                          C->isOpaque());
5037     case ISD::CTTZ:
5038     case ISD::CTTZ_ZERO_UNDEF:
5039       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
5040                          C->isOpaque());
5041     case ISD::FP16_TO_FP:
5042     case ISD::BF16_TO_FP: {
5043       bool Ignored;
5044       APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
5045                                             : APFloat::BFloat(),
5046                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
5047 
5048       // This can return overflow, underflow, or inexact; we don't care.
5049       // FIXME need to be more flexible about rounding mode.
5050       (void)FPV.convert(EVTToAPFloatSemantics(VT),
5051                         APFloat::rmNearestTiesToEven, &Ignored);
5052       return getConstantFP(FPV, DL, VT);
5053     }
5054     case ISD::STEP_VECTOR: {
5055       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
5056         return V;
5057       break;
5058     }
5059     }
5060   }
5061 
5062   // Constant fold unary operations with a floating point constant operand.
5063   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
5064     APFloat V = C->getValueAPF();    // make copy
5065     switch (Opcode) {
5066     case ISD::FNEG:
5067       V.changeSign();
5068       return getConstantFP(V, DL, VT);
5069     case ISD::FABS:
5070       V.clearSign();
5071       return getConstantFP(V, DL, VT);
5072     case ISD::FCEIL: {
5073       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5074       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5075         return getConstantFP(V, DL, VT);
5076       break;
5077     }
5078     case ISD::FTRUNC: {
5079       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5080       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5081         return getConstantFP(V, DL, VT);
5082       break;
5083     }
5084     case ISD::FFLOOR: {
5085       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5086       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5087         return getConstantFP(V, DL, VT);
5088       break;
5089     }
5090     case ISD::FP_EXTEND: {
5091       bool ignored;
5092       // This can return overflow, underflow, or inexact; we don't care.
5093       // FIXME need to be more flexible about rounding mode.
5094       (void)V.convert(EVTToAPFloatSemantics(VT),
5095                       APFloat::rmNearestTiesToEven, &ignored);
5096       return getConstantFP(V, DL, VT);
5097     }
5098     case ISD::FP_TO_SINT:
5099     case ISD::FP_TO_UINT: {
5100       bool ignored;
5101       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5102       // FIXME need to be more flexible about rounding mode.
5103       APFloat::opStatus s =
5104           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5105       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5106         break;
5107       return getConstant(IntVal, DL, VT);
5108     }
5109     case ISD::BITCAST:
5110       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5111         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5112       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5113         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5114       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5115         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5116       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5117         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5118       break;
5119     case ISD::FP_TO_FP16:
5120     case ISD::FP_TO_BF16: {
5121       bool Ignored;
5122       // This can return overflow, underflow, or inexact; we don't care.
5123       // FIXME need to be more flexible about rounding mode.
5124       (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
5125                                                 : APFloat::BFloat(),
5126                       APFloat::rmNearestTiesToEven, &Ignored);
5127       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5128     }
5129     }
5130   }
5131 
5132   // Constant fold unary operations with a vector integer or float operand.
5133   switch (Opcode) {
5134   default:
5135     // FIXME: Entirely reasonable to perform folding of other unary
5136     // operations here as the need arises.
5137     break;
5138   case ISD::FNEG:
5139   case ISD::FABS:
5140   case ISD::FCEIL:
5141   case ISD::FTRUNC:
5142   case ISD::FFLOOR:
5143   case ISD::FP_EXTEND:
5144   case ISD::FP_TO_SINT:
5145   case ISD::FP_TO_UINT:
5146   case ISD::TRUNCATE:
5147   case ISD::ANY_EXTEND:
5148   case ISD::ZERO_EXTEND:
5149   case ISD::SIGN_EXTEND:
5150   case ISD::UINT_TO_FP:
5151   case ISD::SINT_TO_FP:
5152   case ISD::ABS:
5153   case ISD::BITREVERSE:
5154   case ISD::BSWAP:
5155   case ISD::CTLZ:
5156   case ISD::CTLZ_ZERO_UNDEF:
5157   case ISD::CTTZ:
5158   case ISD::CTTZ_ZERO_UNDEF:
5159   case ISD::CTPOP: {
5160     SDValue Ops = {Operand};
5161     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5162       return Fold;
5163   }
5164   }
5165 
5166   unsigned OpOpcode = Operand.getNode()->getOpcode();
5167   switch (Opcode) {
5168   case ISD::STEP_VECTOR:
5169     assert(VT.isScalableVector() &&
5170            "STEP_VECTOR can only be used with scalable types");
5171     assert(OpOpcode == ISD::TargetConstant &&
5172            VT.getVectorElementType() == Operand.getValueType() &&
5173            "Unexpected step operand");
5174     break;
5175   case ISD::FREEZE:
5176     assert(VT == Operand.getValueType() && "Unexpected VT!");
5177     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5178       return Operand;
5179     break;
5180   case ISD::TokenFactor:
5181   case ISD::MERGE_VALUES:
5182   case ISD::CONCAT_VECTORS:
5183     return Operand;         // Factor, merge or concat of one node?  No need.
5184   case ISD::BUILD_VECTOR: {
5185     // Attempt to simplify BUILD_VECTOR.
5186     SDValue Ops[] = {Operand};
5187     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5188       return V;
5189     break;
5190   }
5191   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5192   case ISD::FP_EXTEND:
5193     assert(VT.isFloatingPoint() &&
5194            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5195     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5196     assert((!VT.isVector() ||
5197             VT.getVectorElementCount() ==
5198             Operand.getValueType().getVectorElementCount()) &&
5199            "Vector element count mismatch!");
5200     assert(Operand.getValueType().bitsLT(VT) &&
5201            "Invalid fpext node, dst < src!");
5202     if (Operand.isUndef())
5203       return getUNDEF(VT);
5204     break;
5205   case ISD::FP_TO_SINT:
5206   case ISD::FP_TO_UINT:
5207     if (Operand.isUndef())
5208       return getUNDEF(VT);
5209     break;
5210   case ISD::SINT_TO_FP:
5211   case ISD::UINT_TO_FP:
5212     // [us]itofp(undef) = 0, because the result value is bounded.
5213     if (Operand.isUndef())
5214       return getConstantFP(0.0, DL, VT);
5215     break;
5216   case ISD::SIGN_EXTEND:
5217     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5218            "Invalid SIGN_EXTEND!");
5219     assert(VT.isVector() == Operand.getValueType().isVector() &&
5220            "SIGN_EXTEND result type type should be vector iff the operand "
5221            "type is vector!");
5222     if (Operand.getValueType() == VT) return Operand;   // noop extension
5223     assert((!VT.isVector() ||
5224             VT.getVectorElementCount() ==
5225                 Operand.getValueType().getVectorElementCount()) &&
5226            "Vector element count mismatch!");
5227     assert(Operand.getValueType().bitsLT(VT) &&
5228            "Invalid sext node, dst < src!");
5229     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5230       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5231     if (OpOpcode == ISD::UNDEF)
5232       // sext(undef) = 0, because the top bits will all be the same.
5233       return getConstant(0, DL, VT);
5234     break;
5235   case ISD::ZERO_EXTEND:
5236     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5237            "Invalid ZERO_EXTEND!");
5238     assert(VT.isVector() == Operand.getValueType().isVector() &&
5239            "ZERO_EXTEND result type type should be vector iff the operand "
5240            "type is vector!");
5241     if (Operand.getValueType() == VT) return Operand;   // noop extension
5242     assert((!VT.isVector() ||
5243             VT.getVectorElementCount() ==
5244                 Operand.getValueType().getVectorElementCount()) &&
5245            "Vector element count mismatch!");
5246     assert(Operand.getValueType().bitsLT(VT) &&
5247            "Invalid zext node, dst < src!");
5248     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5249       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5250     if (OpOpcode == ISD::UNDEF)
5251       // zext(undef) = 0, because the top bits will be zero.
5252       return getConstant(0, DL, VT);
5253     break;
5254   case ISD::ANY_EXTEND:
5255     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5256            "Invalid ANY_EXTEND!");
5257     assert(VT.isVector() == Operand.getValueType().isVector() &&
5258            "ANY_EXTEND result type type should be vector iff the operand "
5259            "type is vector!");
5260     if (Operand.getValueType() == VT) return Operand;   // noop extension
5261     assert((!VT.isVector() ||
5262             VT.getVectorElementCount() ==
5263                 Operand.getValueType().getVectorElementCount()) &&
5264            "Vector element count mismatch!");
5265     assert(Operand.getValueType().bitsLT(VT) &&
5266            "Invalid anyext node, dst < src!");
5267 
5268     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5269         OpOpcode == ISD::ANY_EXTEND)
5270       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5271       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5272     if (OpOpcode == ISD::UNDEF)
5273       return getUNDEF(VT);
5274 
5275     // (ext (trunc x)) -> x
5276     if (OpOpcode == ISD::TRUNCATE) {
5277       SDValue OpOp = Operand.getOperand(0);
5278       if (OpOp.getValueType() == VT) {
5279         transferDbgValues(Operand, OpOp);
5280         return OpOp;
5281       }
5282     }
5283     break;
5284   case ISD::TRUNCATE:
5285     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5286            "Invalid TRUNCATE!");
5287     assert(VT.isVector() == Operand.getValueType().isVector() &&
5288            "TRUNCATE result type type should be vector iff the operand "
5289            "type is vector!");
5290     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5291     assert((!VT.isVector() ||
5292             VT.getVectorElementCount() ==
5293                 Operand.getValueType().getVectorElementCount()) &&
5294            "Vector element count mismatch!");
5295     assert(Operand.getValueType().bitsGT(VT) &&
5296            "Invalid truncate node, src < dst!");
5297     if (OpOpcode == ISD::TRUNCATE)
5298       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5299     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5300         OpOpcode == ISD::ANY_EXTEND) {
5301       // If the source is smaller than the dest, we still need an extend.
5302       if (Operand.getOperand(0).getValueType().getScalarType()
5303             .bitsLT(VT.getScalarType()))
5304         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5305       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5306         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5307       return Operand.getOperand(0);
5308     }
5309     if (OpOpcode == ISD::UNDEF)
5310       return getUNDEF(VT);
5311     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5312       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5313     break;
5314   case ISD::ANY_EXTEND_VECTOR_INREG:
5315   case ISD::ZERO_EXTEND_VECTOR_INREG:
5316   case ISD::SIGN_EXTEND_VECTOR_INREG:
5317     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5318     assert(Operand.getValueType().bitsLE(VT) &&
5319            "The input must be the same size or smaller than the result.");
5320     assert(VT.getVectorMinNumElements() <
5321                Operand.getValueType().getVectorMinNumElements() &&
5322            "The destination vector type must have fewer lanes than the input.");
5323     break;
5324   case ISD::ABS:
5325     assert(VT.isInteger() && VT == Operand.getValueType() &&
5326            "Invalid ABS!");
5327     if (OpOpcode == ISD::UNDEF)
5328       return getConstant(0, DL, VT);
5329     break;
5330   case ISD::BSWAP:
5331     assert(VT.isInteger() && VT == Operand.getValueType() &&
5332            "Invalid BSWAP!");
5333     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5334            "BSWAP types must be a multiple of 16 bits!");
5335     if (OpOpcode == ISD::UNDEF)
5336       return getUNDEF(VT);
5337     // bswap(bswap(X)) -> X.
5338     if (OpOpcode == ISD::BSWAP)
5339       return Operand.getOperand(0);
5340     break;
5341   case ISD::BITREVERSE:
5342     assert(VT.isInteger() && VT == Operand.getValueType() &&
5343            "Invalid BITREVERSE!");
5344     if (OpOpcode == ISD::UNDEF)
5345       return getUNDEF(VT);
5346     break;
5347   case ISD::BITCAST:
5348     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5349            "Cannot BITCAST between types of different sizes!");
5350     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5351     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5352       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5353     if (OpOpcode == ISD::UNDEF)
5354       return getUNDEF(VT);
5355     break;
5356   case ISD::SCALAR_TO_VECTOR:
5357     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5358            (VT.getVectorElementType() == Operand.getValueType() ||
5359             (VT.getVectorElementType().isInteger() &&
5360              Operand.getValueType().isInteger() &&
5361              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5362            "Illegal SCALAR_TO_VECTOR node!");
5363     if (OpOpcode == ISD::UNDEF)
5364       return getUNDEF(VT);
5365     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5366     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5367         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5368         Operand.getConstantOperandVal(1) == 0 &&
5369         Operand.getOperand(0).getValueType() == VT)
5370       return Operand.getOperand(0);
5371     break;
5372   case ISD::FNEG:
5373     // Negation of an unknown bag of bits is still completely undefined.
5374     if (OpOpcode == ISD::UNDEF)
5375       return getUNDEF(VT);
5376 
5377     if (OpOpcode == ISD::FNEG)  // --X -> X
5378       return Operand.getOperand(0);
5379     break;
5380   case ISD::FABS:
5381     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5382       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5383     break;
5384   case ISD::VSCALE:
5385     assert(VT == Operand.getValueType() && "Unexpected VT!");
5386     break;
5387   case ISD::CTPOP:
5388     if (Operand.getValueType().getScalarType() == MVT::i1)
5389       return Operand;
5390     break;
5391   case ISD::CTLZ:
5392   case ISD::CTTZ:
5393     if (Operand.getValueType().getScalarType() == MVT::i1)
5394       return getNOT(DL, Operand, Operand.getValueType());
5395     break;
5396   case ISD::VECREDUCE_ADD:
5397     if (Operand.getValueType().getScalarType() == MVT::i1)
5398       return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
5399     break;
5400   case ISD::VECREDUCE_SMIN:
5401   case ISD::VECREDUCE_UMAX:
5402     if (Operand.getValueType().getScalarType() == MVT::i1)
5403       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5404     break;
5405   case ISD::VECREDUCE_SMAX:
5406   case ISD::VECREDUCE_UMIN:
5407     if (Operand.getValueType().getScalarType() == MVT::i1)
5408       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5409     break;
5410   }
5411 
5412   SDNode *N;
5413   SDVTList VTs = getVTList(VT);
5414   SDValue Ops[] = {Operand};
5415   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5416     FoldingSetNodeID ID;
5417     AddNodeIDNode(ID, Opcode, VTs, Ops);
5418     void *IP = nullptr;
5419     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5420       E->intersectFlagsWith(Flags);
5421       return SDValue(E, 0);
5422     }
5423 
5424     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5425     N->setFlags(Flags);
5426     createOperands(N, Ops);
5427     CSEMap.InsertNode(N, IP);
5428   } else {
5429     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5430     createOperands(N, Ops);
5431   }
5432 
5433   InsertNode(N);
5434   SDValue V = SDValue(N, 0);
5435   NewSDValueDbgMsg(V, "Creating new node: ", this);
5436   return V;
5437 }
5438 
5439 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5440                                        const APInt &C2) {
5441   switch (Opcode) {
5442   case ISD::ADD:  return C1 + C2;
5443   case ISD::SUB:  return C1 - C2;
5444   case ISD::MUL:  return C1 * C2;
5445   case ISD::AND:  return C1 & C2;
5446   case ISD::OR:   return C1 | C2;
5447   case ISD::XOR:  return C1 ^ C2;
5448   case ISD::SHL:  return C1 << C2;
5449   case ISD::SRL:  return C1.lshr(C2);
5450   case ISD::SRA:  return C1.ashr(C2);
5451   case ISD::ROTL: return C1.rotl(C2);
5452   case ISD::ROTR: return C1.rotr(C2);
5453   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5454   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5455   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5456   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5457   case ISD::SADDSAT: return C1.sadd_sat(C2);
5458   case ISD::UADDSAT: return C1.uadd_sat(C2);
5459   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5460   case ISD::USUBSAT: return C1.usub_sat(C2);
5461   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5462   case ISD::USHLSAT: return C1.ushl_sat(C2);
5463   case ISD::UDIV:
5464     if (!C2.getBoolValue())
5465       break;
5466     return C1.udiv(C2);
5467   case ISD::UREM:
5468     if (!C2.getBoolValue())
5469       break;
5470     return C1.urem(C2);
5471   case ISD::SDIV:
5472     if (!C2.getBoolValue())
5473       break;
5474     return C1.sdiv(C2);
5475   case ISD::SREM:
5476     if (!C2.getBoolValue())
5477       break;
5478     return C1.srem(C2);
5479   case ISD::MULHS: {
5480     unsigned FullWidth = C1.getBitWidth() * 2;
5481     APInt C1Ext = C1.sext(FullWidth);
5482     APInt C2Ext = C2.sext(FullWidth);
5483     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5484   }
5485   case ISD::MULHU: {
5486     unsigned FullWidth = C1.getBitWidth() * 2;
5487     APInt C1Ext = C1.zext(FullWidth);
5488     APInt C2Ext = C2.zext(FullWidth);
5489     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5490   }
5491   case ISD::AVGFLOORS: {
5492     unsigned FullWidth = C1.getBitWidth() + 1;
5493     APInt C1Ext = C1.sext(FullWidth);
5494     APInt C2Ext = C2.sext(FullWidth);
5495     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5496   }
5497   case ISD::AVGFLOORU: {
5498     unsigned FullWidth = C1.getBitWidth() + 1;
5499     APInt C1Ext = C1.zext(FullWidth);
5500     APInt C2Ext = C2.zext(FullWidth);
5501     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5502   }
5503   case ISD::AVGCEILS: {
5504     unsigned FullWidth = C1.getBitWidth() + 1;
5505     APInt C1Ext = C1.sext(FullWidth);
5506     APInt C2Ext = C2.sext(FullWidth);
5507     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5508   }
5509   case ISD::AVGCEILU: {
5510     unsigned FullWidth = C1.getBitWidth() + 1;
5511     APInt C1Ext = C1.zext(FullWidth);
5512     APInt C2Ext = C2.zext(FullWidth);
5513     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5514   }
5515   }
5516   return llvm::None;
5517 }
5518 
5519 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5520                                        const GlobalAddressSDNode *GA,
5521                                        const SDNode *N2) {
5522   if (GA->getOpcode() != ISD::GlobalAddress)
5523     return SDValue();
5524   if (!TLI->isOffsetFoldingLegal(GA))
5525     return SDValue();
5526   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5527   if (!C2)
5528     return SDValue();
5529   int64_t Offset = C2->getSExtValue();
5530   switch (Opcode) {
5531   case ISD::ADD: break;
5532   case ISD::SUB: Offset = -uint64_t(Offset); break;
5533   default: return SDValue();
5534   }
5535   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5536                           GA->getOffset() + uint64_t(Offset));
5537 }
5538 
5539 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5540   switch (Opcode) {
5541   case ISD::SDIV:
5542   case ISD::UDIV:
5543   case ISD::SREM:
5544   case ISD::UREM: {
5545     // If a divisor is zero/undef or any element of a divisor vector is
5546     // zero/undef, the whole op is undef.
5547     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5548     SDValue Divisor = Ops[1];
5549     if (Divisor.isUndef() || isNullConstant(Divisor))
5550       return true;
5551 
5552     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5553            llvm::any_of(Divisor->op_values(),
5554                         [](SDValue V) { return V.isUndef() ||
5555                                         isNullConstant(V); });
5556     // TODO: Handle signed overflow.
5557   }
5558   // TODO: Handle oversized shifts.
5559   default:
5560     return false;
5561   }
5562 }
5563 
5564 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5565                                              EVT VT, ArrayRef<SDValue> Ops) {
5566   // If the opcode is a target-specific ISD node, there's nothing we can
5567   // do here and the operand rules may not line up with the below, so
5568   // bail early.
5569   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5570   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5571   // foldCONCAT_VECTORS in getNode before this is called.
5572   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5573     return SDValue();
5574 
5575   unsigned NumOps = Ops.size();
5576   if (NumOps == 0)
5577     return SDValue();
5578 
5579   if (isUndef(Opcode, Ops))
5580     return getUNDEF(VT);
5581 
5582   // Handle binops special cases.
5583   if (NumOps == 2) {
5584     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5585       return CFP;
5586 
5587     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5588       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5589         if (C1->isOpaque() || C2->isOpaque())
5590           return SDValue();
5591 
5592         Optional<APInt> FoldAttempt =
5593             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5594         if (!FoldAttempt)
5595           return SDValue();
5596 
5597         SDValue Folded = getConstant(*FoldAttempt, DL, VT);
5598         assert((!Folded || !VT.isVector()) &&
5599                "Can't fold vectors ops with scalar operands");
5600         return Folded;
5601       }
5602     }
5603 
5604     // fold (add Sym, c) -> Sym+c
5605     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5606       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5607     if (TLI->isCommutativeBinOp(Opcode))
5608       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5609         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5610   }
5611 
5612   // This is for vector folding only from here on.
5613   if (!VT.isVector())
5614     return SDValue();
5615 
5616   ElementCount NumElts = VT.getVectorElementCount();
5617 
5618   // See if we can fold through bitcasted integer ops.
5619   // TODO: Can we handle undef elements?
5620   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5621       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5622       Ops[0].getOpcode() == ISD::BITCAST &&
5623       Ops[1].getOpcode() == ISD::BITCAST) {
5624     SDValue N1 = peekThroughBitcasts(Ops[0]);
5625     SDValue N2 = peekThroughBitcasts(Ops[1]);
5626     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5627     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5628     EVT BVVT = N1.getValueType();
5629     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5630       bool IsLE = getDataLayout().isLittleEndian();
5631       unsigned EltBits = VT.getScalarSizeInBits();
5632       SmallVector<APInt> RawBits1, RawBits2;
5633       BitVector UndefElts1, UndefElts2;
5634       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5635           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5636           UndefElts1.none() && UndefElts2.none()) {
5637         SmallVector<APInt> RawBits;
5638         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5639           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5640           if (!Fold)
5641             break;
5642           RawBits.push_back(*Fold);
5643         }
5644         if (RawBits.size() == NumElts.getFixedValue()) {
5645           // We have constant folded, but we need to cast this again back to
5646           // the original (possibly legalized) type.
5647           SmallVector<APInt> DstBits;
5648           BitVector DstUndefs;
5649           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5650                                            DstBits, RawBits, DstUndefs,
5651                                            BitVector(RawBits.size(), false));
5652           EVT BVEltVT = BV1->getOperand(0).getValueType();
5653           unsigned BVEltBits = BVEltVT.getSizeInBits();
5654           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5655           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5656             if (DstUndefs[I])
5657               continue;
5658             Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
5659           }
5660           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5661         }
5662       }
5663     }
5664   }
5665 
5666   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5667   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5668   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5669       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5670     APInt RHSVal;
5671     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5672       APInt NewStep = Opcode == ISD::MUL
5673                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5674                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5675       return getStepVector(DL, VT, NewStep);
5676     }
5677   }
5678 
5679   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5680     return !Op.getValueType().isVector() ||
5681            Op.getValueType().getVectorElementCount() == NumElts;
5682   };
5683 
5684   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5685     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5686            Op.getOpcode() == ISD::BUILD_VECTOR ||
5687            Op.getOpcode() == ISD::SPLAT_VECTOR;
5688   };
5689 
5690   // All operands must be vector types with the same number of elements as
5691   // the result type and must be either UNDEF or a build/splat vector
5692   // or UNDEF scalars.
5693   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5694       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5695     return SDValue();
5696 
5697   // If we are comparing vectors, then the result needs to be a i1 boolean that
5698   // is then extended back to the legal result type depending on how booleans
5699   // are represented.
5700   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5701   ISD::NodeType ExtendCode =
5702       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5703           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5704           : ISD::SIGN_EXTEND;
5705 
5706   // Find legal integer scalar type for constant promotion and
5707   // ensure that its scalar size is at least as large as source.
5708   EVT LegalSVT = VT.getScalarType();
5709   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5710     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5711     if (LegalSVT.bitsLT(VT.getScalarType()))
5712       return SDValue();
5713   }
5714 
5715   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5716   // only have one operand to check. For fixed-length vector types we may have
5717   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5718   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5719 
5720   // Constant fold each scalar lane separately.
5721   SmallVector<SDValue, 4> ScalarResults;
5722   for (unsigned I = 0; I != NumVectorElts; I++) {
5723     SmallVector<SDValue, 4> ScalarOps;
5724     for (SDValue Op : Ops) {
5725       EVT InSVT = Op.getValueType().getScalarType();
5726       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5727           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5728         if (Op.isUndef())
5729           ScalarOps.push_back(getUNDEF(InSVT));
5730         else
5731           ScalarOps.push_back(Op);
5732         continue;
5733       }
5734 
5735       SDValue ScalarOp =
5736           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5737       EVT ScalarVT = ScalarOp.getValueType();
5738 
5739       // Build vector (integer) scalar operands may need implicit
5740       // truncation - do this before constant folding.
5741       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5742         // Don't create illegally-typed nodes unless they're constants or undef
5743         // - if we fail to constant fold we can't guarantee the (dead) nodes
5744         // we're creating will be cleaned up before being visited for
5745         // legalization.
5746         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5747             !isa<ConstantSDNode>(ScalarOp) &&
5748             TLI->getTypeAction(*getContext(), InSVT) !=
5749                 TargetLowering::TypeLegal)
5750           return SDValue();
5751         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5752       }
5753 
5754       ScalarOps.push_back(ScalarOp);
5755     }
5756 
5757     // Constant fold the scalar operands.
5758     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5759 
5760     // Legalize the (integer) scalar constant if necessary.
5761     if (LegalSVT != SVT)
5762       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5763 
5764     // Scalar folding only succeeded if the result is a constant or UNDEF.
5765     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5766         ScalarResult.getOpcode() != ISD::ConstantFP)
5767       return SDValue();
5768     ScalarResults.push_back(ScalarResult);
5769   }
5770 
5771   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5772                                    : getBuildVector(VT, DL, ScalarResults);
5773   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5774   return V;
5775 }
5776 
5777 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5778                                          EVT VT, SDValue N1, SDValue N2) {
5779   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5780   //       should. That will require dealing with a potentially non-default
5781   //       rounding mode, checking the "opStatus" return value from the APFloat
5782   //       math calculations, and possibly other variations.
5783   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5784   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5785   if (N1CFP && N2CFP) {
5786     APFloat C1 = N1CFP->getValueAPF(); // make copy
5787     const APFloat &C2 = N2CFP->getValueAPF();
5788     switch (Opcode) {
5789     case ISD::FADD:
5790       C1.add(C2, APFloat::rmNearestTiesToEven);
5791       return getConstantFP(C1, DL, VT);
5792     case ISD::FSUB:
5793       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5794       return getConstantFP(C1, DL, VT);
5795     case ISD::FMUL:
5796       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5797       return getConstantFP(C1, DL, VT);
5798     case ISD::FDIV:
5799       C1.divide(C2, APFloat::rmNearestTiesToEven);
5800       return getConstantFP(C1, DL, VT);
5801     case ISD::FREM:
5802       C1.mod(C2);
5803       return getConstantFP(C1, DL, VT);
5804     case ISD::FCOPYSIGN:
5805       C1.copySign(C2);
5806       return getConstantFP(C1, DL, VT);
5807     case ISD::FMINNUM:
5808       return getConstantFP(minnum(C1, C2), DL, VT);
5809     case ISD::FMAXNUM:
5810       return getConstantFP(maxnum(C1, C2), DL, VT);
5811     case ISD::FMINIMUM:
5812       return getConstantFP(minimum(C1, C2), DL, VT);
5813     case ISD::FMAXIMUM:
5814       return getConstantFP(maximum(C1, C2), DL, VT);
5815     default: break;
5816     }
5817   }
5818   if (N1CFP && Opcode == ISD::FP_ROUND) {
5819     APFloat C1 = N1CFP->getValueAPF();    // make copy
5820     bool Unused;
5821     // This can return overflow, underflow, or inexact; we don't care.
5822     // FIXME need to be more flexible about rounding mode.
5823     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5824                       &Unused);
5825     return getConstantFP(C1, DL, VT);
5826   }
5827 
5828   switch (Opcode) {
5829   case ISD::FSUB:
5830     // -0.0 - undef --> undef (consistent with "fneg undef")
5831     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5832       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5833         return getUNDEF(VT);
5834     LLVM_FALLTHROUGH;
5835 
5836   case ISD::FADD:
5837   case ISD::FMUL:
5838   case ISD::FDIV:
5839   case ISD::FREM:
5840     // If both operands are undef, the result is undef. If 1 operand is undef,
5841     // the result is NaN. This should match the behavior of the IR optimizer.
5842     if (N1.isUndef() && N2.isUndef())
5843       return getUNDEF(VT);
5844     if (N1.isUndef() || N2.isUndef())
5845       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5846   }
5847   return SDValue();
5848 }
5849 
5850 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5851   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5852 
5853   // There's no need to assert on a byte-aligned pointer. All pointers are at
5854   // least byte aligned.
5855   if (A == Align(1))
5856     return Val;
5857 
5858   FoldingSetNodeID ID;
5859   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5860   ID.AddInteger(A.value());
5861 
5862   void *IP = nullptr;
5863   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5864     return SDValue(E, 0);
5865 
5866   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5867                                          Val.getValueType(), A);
5868   createOperands(N, {Val});
5869 
5870   CSEMap.InsertNode(N, IP);
5871   InsertNode(N);
5872 
5873   SDValue V(N, 0);
5874   NewSDValueDbgMsg(V, "Creating new node: ", this);
5875   return V;
5876 }
5877 
5878 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5879                               SDValue N1, SDValue N2) {
5880   SDNodeFlags Flags;
5881   if (Inserter)
5882     Flags = Inserter->getFlags();
5883   return getNode(Opcode, DL, VT, N1, N2, Flags);
5884 }
5885 
5886 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5887                                                 SDValue &N2) const {
5888   if (!TLI->isCommutativeBinOp(Opcode))
5889     return;
5890 
5891   // Canonicalize:
5892   //   binop(const, nonconst) -> binop(nonconst, const)
5893   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5894   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5895   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5896   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5897   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5898     std::swap(N1, N2);
5899 
5900   // Canonicalize:
5901   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5902   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5903            N2.getOpcode() == ISD::STEP_VECTOR)
5904     std::swap(N1, N2);
5905 }
5906 
5907 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5908                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5909   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5910          N2.getOpcode() != ISD::DELETED_NODE &&
5911          "Operand is DELETED_NODE!");
5912 
5913   canonicalizeCommutativeBinop(Opcode, N1, N2);
5914 
5915   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5916   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5917 
5918   // Don't allow undefs in vector splats - we might be returning N2 when folding
5919   // to zero etc.
5920   ConstantSDNode *N2CV =
5921       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5922 
5923   switch (Opcode) {
5924   default: break;
5925   case ISD::TokenFactor:
5926     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5927            N2.getValueType() == MVT::Other && "Invalid token factor!");
5928     // Fold trivial token factors.
5929     if (N1.getOpcode() == ISD::EntryToken) return N2;
5930     if (N2.getOpcode() == ISD::EntryToken) return N1;
5931     if (N1 == N2) return N1;
5932     break;
5933   case ISD::BUILD_VECTOR: {
5934     // Attempt to simplify BUILD_VECTOR.
5935     SDValue Ops[] = {N1, N2};
5936     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5937       return V;
5938     break;
5939   }
5940   case ISD::CONCAT_VECTORS: {
5941     SDValue Ops[] = {N1, N2};
5942     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5943       return V;
5944     break;
5945   }
5946   case ISD::AND:
5947     assert(VT.isInteger() && "This operator does not apply to FP types!");
5948     assert(N1.getValueType() == N2.getValueType() &&
5949            N1.getValueType() == VT && "Binary operator types must match!");
5950     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5951     // worth handling here.
5952     if (N2CV && N2CV->isZero())
5953       return N2;
5954     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5955       return N1;
5956     break;
5957   case ISD::OR:
5958   case ISD::XOR:
5959   case ISD::ADD:
5960   case ISD::SUB:
5961     assert(VT.isInteger() && "This operator does not apply to FP types!");
5962     assert(N1.getValueType() == N2.getValueType() &&
5963            N1.getValueType() == VT && "Binary operator types must match!");
5964     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5965     // it's worth handling here.
5966     if (N2CV && N2CV->isZero())
5967       return N1;
5968     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5969         VT.getVectorElementType() == MVT::i1)
5970       return getNode(ISD::XOR, DL, VT, N1, N2);
5971     break;
5972   case ISD::MUL:
5973     assert(VT.isInteger() && "This operator does not apply to FP types!");
5974     assert(N1.getValueType() == N2.getValueType() &&
5975            N1.getValueType() == VT && "Binary operator types must match!");
5976     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5977       return getNode(ISD::AND, DL, VT, N1, N2);
5978     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5979       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5980       const APInt &N2CImm = N2C->getAPIntValue();
5981       return getVScale(DL, VT, MulImm * N2CImm);
5982     }
5983     break;
5984   case ISD::UDIV:
5985   case ISD::UREM:
5986   case ISD::MULHU:
5987   case ISD::MULHS:
5988   case ISD::SDIV:
5989   case ISD::SREM:
5990   case ISD::SADDSAT:
5991   case ISD::SSUBSAT:
5992   case ISD::UADDSAT:
5993   case ISD::USUBSAT:
5994     assert(VT.isInteger() && "This operator does not apply to FP types!");
5995     assert(N1.getValueType() == N2.getValueType() &&
5996            N1.getValueType() == VT && "Binary operator types must match!");
5997     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5998       // fold (add_sat x, y) -> (or x, y) for bool types.
5999       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
6000         return getNode(ISD::OR, DL, VT, N1, N2);
6001       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
6002       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
6003         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
6004     }
6005     break;
6006   case ISD::SMIN:
6007   case ISD::UMAX:
6008     assert(VT.isInteger() && "This operator does not apply to FP types!");
6009     assert(N1.getValueType() == N2.getValueType() &&
6010            N1.getValueType() == VT && "Binary operator types must match!");
6011     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
6012       return getNode(ISD::OR, DL, VT, N1, N2);
6013     break;
6014   case ISD::SMAX:
6015   case ISD::UMIN:
6016     assert(VT.isInteger() && "This operator does not apply to FP types!");
6017     assert(N1.getValueType() == N2.getValueType() &&
6018            N1.getValueType() == VT && "Binary operator types must match!");
6019     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
6020       return getNode(ISD::AND, DL, VT, N1, N2);
6021     break;
6022   case ISD::FADD:
6023   case ISD::FSUB:
6024   case ISD::FMUL:
6025   case ISD::FDIV:
6026   case ISD::FREM:
6027     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6028     assert(N1.getValueType() == N2.getValueType() &&
6029            N1.getValueType() == VT && "Binary operator types must match!");
6030     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
6031       return V;
6032     break;
6033   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
6034     assert(N1.getValueType() == VT &&
6035            N1.getValueType().isFloatingPoint() &&
6036            N2.getValueType().isFloatingPoint() &&
6037            "Invalid FCOPYSIGN!");
6038     break;
6039   case ISD::SHL:
6040     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
6041       const APInt &MulImm = N1->getConstantOperandAPInt(0);
6042       const APInt &ShiftImm = N2C->getAPIntValue();
6043       return getVScale(DL, VT, MulImm << ShiftImm);
6044     }
6045     LLVM_FALLTHROUGH;
6046   case ISD::SRA:
6047   case ISD::SRL:
6048     if (SDValue V = simplifyShift(N1, N2))
6049       return V;
6050     LLVM_FALLTHROUGH;
6051   case ISD::ROTL:
6052   case ISD::ROTR:
6053     assert(VT == N1.getValueType() &&
6054            "Shift operators return type must be the same as their first arg");
6055     assert(VT.isInteger() && N2.getValueType().isInteger() &&
6056            "Shifts only work on integers");
6057     assert((!VT.isVector() || VT == N2.getValueType()) &&
6058            "Vector shift amounts must be in the same as their first arg");
6059     // Verify that the shift amount VT is big enough to hold valid shift
6060     // amounts.  This catches things like trying to shift an i1024 value by an
6061     // i8, which is easy to fall into in generic code that uses
6062     // TLI.getShiftAmount().
6063     assert(N2.getValueType().getScalarSizeInBits() >=
6064                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
6065            "Invalid use of small shift amount with oversized value!");
6066 
6067     // Always fold shifts of i1 values so the code generator doesn't need to
6068     // handle them.  Since we know the size of the shift has to be less than the
6069     // size of the value, the shift/rotate count is guaranteed to be zero.
6070     if (VT == MVT::i1)
6071       return N1;
6072     if (N2CV && N2CV->isZero())
6073       return N1;
6074     break;
6075   case ISD::FP_ROUND:
6076     assert(VT.isFloatingPoint() &&
6077            N1.getValueType().isFloatingPoint() &&
6078            VT.bitsLE(N1.getValueType()) &&
6079            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6080            "Invalid FP_ROUND!");
6081     if (N1.getValueType() == VT) return N1;  // noop conversion.
6082     break;
6083   case ISD::AssertSext:
6084   case ISD::AssertZext: {
6085     EVT EVT = cast<VTSDNode>(N2)->getVT();
6086     assert(VT == N1.getValueType() && "Not an inreg extend!");
6087     assert(VT.isInteger() && EVT.isInteger() &&
6088            "Cannot *_EXTEND_INREG FP types");
6089     assert(!EVT.isVector() &&
6090            "AssertSExt/AssertZExt type should be the vector element type "
6091            "rather than the vector type!");
6092     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6093     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6094     break;
6095   }
6096   case ISD::SIGN_EXTEND_INREG: {
6097     EVT EVT = cast<VTSDNode>(N2)->getVT();
6098     assert(VT == N1.getValueType() && "Not an inreg extend!");
6099     assert(VT.isInteger() && EVT.isInteger() &&
6100            "Cannot *_EXTEND_INREG FP types");
6101     assert(EVT.isVector() == VT.isVector() &&
6102            "SIGN_EXTEND_INREG type should be vector iff the operand "
6103            "type is vector!");
6104     assert((!EVT.isVector() ||
6105             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6106            "Vector element counts must match in SIGN_EXTEND_INREG");
6107     assert(EVT.bitsLE(VT) && "Not extending!");
6108     if (EVT == VT) return N1;  // Not actually extending
6109 
6110     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6111       unsigned FromBits = EVT.getScalarSizeInBits();
6112       Val <<= Val.getBitWidth() - FromBits;
6113       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6114       return getConstant(Val, DL, ConstantVT);
6115     };
6116 
6117     if (N1C) {
6118       const APInt &Val = N1C->getAPIntValue();
6119       return SignExtendInReg(Val, VT);
6120     }
6121 
6122     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6123       SmallVector<SDValue, 8> Ops;
6124       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6125       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6126         SDValue Op = N1.getOperand(i);
6127         if (Op.isUndef()) {
6128           Ops.push_back(getUNDEF(OpVT));
6129           continue;
6130         }
6131         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6132         APInt Val = C->getAPIntValue();
6133         Ops.push_back(SignExtendInReg(Val, OpVT));
6134       }
6135       return getBuildVector(VT, DL, Ops);
6136     }
6137     break;
6138   }
6139   case ISD::FP_TO_SINT_SAT:
6140   case ISD::FP_TO_UINT_SAT: {
6141     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6142            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6143     assert(N1.getValueType().isVector() == VT.isVector() &&
6144            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6145            "vector!");
6146     assert((!VT.isVector() || VT.getVectorElementCount() ==
6147                                   N1.getValueType().getVectorElementCount()) &&
6148            "Vector element counts must match in FP_TO_*INT_SAT");
6149     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6150            "Type to saturate to must be a scalar.");
6151     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6152            "Not extending!");
6153     break;
6154   }
6155   case ISD::EXTRACT_VECTOR_ELT:
6156     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6157            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6158              element type of the vector.");
6159 
6160     // Extract from an undefined value or using an undefined index is undefined.
6161     if (N1.isUndef() || N2.isUndef())
6162       return getUNDEF(VT);
6163 
6164     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6165     // vectors. For scalable vectors we will provide appropriate support for
6166     // dealing with arbitrary indices.
6167     if (N2C && N1.getValueType().isFixedLengthVector() &&
6168         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6169       return getUNDEF(VT);
6170 
6171     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6172     // expanding copies of large vectors from registers. This only works for
6173     // fixed length vectors, since we need to know the exact number of
6174     // elements.
6175     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6176         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6177       unsigned Factor =
6178         N1.getOperand(0).getValueType().getVectorNumElements();
6179       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6180                      N1.getOperand(N2C->getZExtValue() / Factor),
6181                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6182     }
6183 
6184     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6185     // lowering is expanding large vector constants.
6186     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6187                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6188       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6189               N1.getValueType().isFixedLengthVector()) &&
6190              "BUILD_VECTOR used for scalable vectors");
6191       unsigned Index =
6192           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6193       SDValue Elt = N1.getOperand(Index);
6194 
6195       if (VT != Elt.getValueType())
6196         // If the vector element type is not legal, the BUILD_VECTOR operands
6197         // are promoted and implicitly truncated, and the result implicitly
6198         // extended. Make that explicit here.
6199         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6200 
6201       return Elt;
6202     }
6203 
6204     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6205     // operations are lowered to scalars.
6206     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6207       // If the indices are the same, return the inserted element else
6208       // if the indices are known different, extract the element from
6209       // the original vector.
6210       SDValue N1Op2 = N1.getOperand(2);
6211       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6212 
6213       if (N1Op2C && N2C) {
6214         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6215           if (VT == N1.getOperand(1).getValueType())
6216             return N1.getOperand(1);
6217           if (VT.isFloatingPoint()) {
6218             assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits());
6219             return getFPExtendOrRound(N1.getOperand(1), DL, VT);
6220           }
6221           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6222         }
6223         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6224       }
6225     }
6226 
6227     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6228     // when vector types are scalarized and v1iX is legal.
6229     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6230     // Here we are completely ignoring the extract element index (N2),
6231     // which is fine for fixed width vectors, since any index other than 0
6232     // is undefined anyway. However, this cannot be ignored for scalable
6233     // vectors - in theory we could support this, but we don't want to do this
6234     // without a profitability check.
6235     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6236         N1.getValueType().isFixedLengthVector() &&
6237         N1.getValueType().getVectorNumElements() == 1) {
6238       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6239                      N1.getOperand(1));
6240     }
6241     break;
6242   case ISD::EXTRACT_ELEMENT:
6243     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6244     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6245            (N1.getValueType().isInteger() == VT.isInteger()) &&
6246            N1.getValueType() != VT &&
6247            "Wrong types for EXTRACT_ELEMENT!");
6248 
6249     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6250     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6251     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6252     if (N1.getOpcode() == ISD::BUILD_PAIR)
6253       return N1.getOperand(N2C->getZExtValue());
6254 
6255     // EXTRACT_ELEMENT of a constant int is also very common.
6256     if (N1C) {
6257       unsigned ElementSize = VT.getSizeInBits();
6258       unsigned Shift = ElementSize * N2C->getZExtValue();
6259       const APInt &Val = N1C->getAPIntValue();
6260       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6261     }
6262     break;
6263   case ISD::EXTRACT_SUBVECTOR: {
6264     EVT N1VT = N1.getValueType();
6265     assert(VT.isVector() && N1VT.isVector() &&
6266            "Extract subvector VTs must be vectors!");
6267     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6268            "Extract subvector VTs must have the same element type!");
6269     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6270            "Cannot extract a scalable vector from a fixed length vector!");
6271     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6272             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6273            "Extract subvector must be from larger vector to smaller vector!");
6274     assert(N2C && "Extract subvector index must be a constant");
6275     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6276             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6277                 N1VT.getVectorMinNumElements()) &&
6278            "Extract subvector overflow!");
6279     assert(N2C->getAPIntValue().getBitWidth() ==
6280                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6281            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6282 
6283     // Trivial extraction.
6284     if (VT == N1VT)
6285       return N1;
6286 
6287     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6288     if (N1.isUndef())
6289       return getUNDEF(VT);
6290 
6291     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6292     // the concat have the same type as the extract.
6293     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6294         VT == N1.getOperand(0).getValueType()) {
6295       unsigned Factor = VT.getVectorMinNumElements();
6296       return N1.getOperand(N2C->getZExtValue() / Factor);
6297     }
6298 
6299     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6300     // during shuffle legalization.
6301     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6302         VT == N1.getOperand(1).getValueType())
6303       return N1.getOperand(1);
6304     break;
6305   }
6306   }
6307 
6308   // Perform trivial constant folding.
6309   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6310     return SV;
6311 
6312   // Canonicalize an UNDEF to the RHS, even over a constant.
6313   if (N1.isUndef()) {
6314     if (TLI->isCommutativeBinOp(Opcode)) {
6315       std::swap(N1, N2);
6316     } else {
6317       switch (Opcode) {
6318       case ISD::SUB:
6319         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6320       case ISD::SIGN_EXTEND_INREG:
6321       case ISD::UDIV:
6322       case ISD::SDIV:
6323       case ISD::UREM:
6324       case ISD::SREM:
6325       case ISD::SSUBSAT:
6326       case ISD::USUBSAT:
6327         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6328       }
6329     }
6330   }
6331 
6332   // Fold a bunch of operators when the RHS is undef.
6333   if (N2.isUndef()) {
6334     switch (Opcode) {
6335     case ISD::XOR:
6336       if (N1.isUndef())
6337         // Handle undef ^ undef -> 0 special case. This is a common
6338         // idiom (misuse).
6339         return getConstant(0, DL, VT);
6340       LLVM_FALLTHROUGH;
6341     case ISD::ADD:
6342     case ISD::SUB:
6343     case ISD::UDIV:
6344     case ISD::SDIV:
6345     case ISD::UREM:
6346     case ISD::SREM:
6347       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6348     case ISD::MUL:
6349     case ISD::AND:
6350     case ISD::SSUBSAT:
6351     case ISD::USUBSAT:
6352       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6353     case ISD::OR:
6354     case ISD::SADDSAT:
6355     case ISD::UADDSAT:
6356       return getAllOnesConstant(DL, VT);
6357     }
6358   }
6359 
6360   // Memoize this node if possible.
6361   SDNode *N;
6362   SDVTList VTs = getVTList(VT);
6363   SDValue Ops[] = {N1, N2};
6364   if (VT != MVT::Glue) {
6365     FoldingSetNodeID ID;
6366     AddNodeIDNode(ID, Opcode, VTs, Ops);
6367     void *IP = nullptr;
6368     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6369       E->intersectFlagsWith(Flags);
6370       return SDValue(E, 0);
6371     }
6372 
6373     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6374     N->setFlags(Flags);
6375     createOperands(N, Ops);
6376     CSEMap.InsertNode(N, IP);
6377   } else {
6378     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6379     createOperands(N, Ops);
6380   }
6381 
6382   InsertNode(N);
6383   SDValue V = SDValue(N, 0);
6384   NewSDValueDbgMsg(V, "Creating new node: ", this);
6385   return V;
6386 }
6387 
6388 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6389                               SDValue N1, SDValue N2, SDValue N3) {
6390   SDNodeFlags Flags;
6391   if (Inserter)
6392     Flags = Inserter->getFlags();
6393   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6394 }
6395 
6396 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6397                               SDValue N1, SDValue N2, SDValue N3,
6398                               const SDNodeFlags Flags) {
6399   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6400          N2.getOpcode() != ISD::DELETED_NODE &&
6401          N3.getOpcode() != ISD::DELETED_NODE &&
6402          "Operand is DELETED_NODE!");
6403   // Perform various simplifications.
6404   switch (Opcode) {
6405   case ISD::FMA: {
6406     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6407     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6408            N3.getValueType() == VT && "FMA types must match!");
6409     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6410     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6411     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6412     if (N1CFP && N2CFP && N3CFP) {
6413       APFloat  V1 = N1CFP->getValueAPF();
6414       const APFloat &V2 = N2CFP->getValueAPF();
6415       const APFloat &V3 = N3CFP->getValueAPF();
6416       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6417       return getConstantFP(V1, DL, VT);
6418     }
6419     break;
6420   }
6421   case ISD::BUILD_VECTOR: {
6422     // Attempt to simplify BUILD_VECTOR.
6423     SDValue Ops[] = {N1, N2, N3};
6424     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6425       return V;
6426     break;
6427   }
6428   case ISD::CONCAT_VECTORS: {
6429     SDValue Ops[] = {N1, N2, N3};
6430     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6431       return V;
6432     break;
6433   }
6434   case ISD::SETCC: {
6435     assert(VT.isInteger() && "SETCC result type must be an integer!");
6436     assert(N1.getValueType() == N2.getValueType() &&
6437            "SETCC operands must have the same type!");
6438     assert(VT.isVector() == N1.getValueType().isVector() &&
6439            "SETCC type should be vector iff the operand type is vector!");
6440     assert((!VT.isVector() || VT.getVectorElementCount() ==
6441                                   N1.getValueType().getVectorElementCount()) &&
6442            "SETCC vector element counts must match!");
6443     // Use FoldSetCC to simplify SETCC's.
6444     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6445       return V;
6446     // Vector constant folding.
6447     SDValue Ops[] = {N1, N2, N3};
6448     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6449       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6450       return V;
6451     }
6452     break;
6453   }
6454   case ISD::SELECT:
6455   case ISD::VSELECT:
6456     if (SDValue V = simplifySelect(N1, N2, N3))
6457       return V;
6458     break;
6459   case ISD::VECTOR_SHUFFLE:
6460     llvm_unreachable("should use getVectorShuffle constructor!");
6461   case ISD::VECTOR_SPLICE: {
6462     if (cast<ConstantSDNode>(N3)->isNullValue())
6463       return N1;
6464     break;
6465   }
6466   case ISD::INSERT_VECTOR_ELT: {
6467     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6468     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6469     // for scalable vectors where we will generate appropriate code to
6470     // deal with out-of-bounds cases correctly.
6471     if (N3C && N1.getValueType().isFixedLengthVector() &&
6472         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6473       return getUNDEF(VT);
6474 
6475     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6476     if (N3.isUndef())
6477       return getUNDEF(VT);
6478 
6479     // If the inserted element is an UNDEF, just use the input vector.
6480     if (N2.isUndef())
6481       return N1;
6482 
6483     break;
6484   }
6485   case ISD::INSERT_SUBVECTOR: {
6486     // Inserting undef into undef is still undef.
6487     if (N1.isUndef() && N2.isUndef())
6488       return getUNDEF(VT);
6489 
6490     EVT N2VT = N2.getValueType();
6491     assert(VT == N1.getValueType() &&
6492            "Dest and insert subvector source types must match!");
6493     assert(VT.isVector() && N2VT.isVector() &&
6494            "Insert subvector VTs must be vectors!");
6495     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6496            "Cannot insert a scalable vector into a fixed length vector!");
6497     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6498             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6499            "Insert subvector must be from smaller vector to larger vector!");
6500     assert(isa<ConstantSDNode>(N3) &&
6501            "Insert subvector index must be constant");
6502     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6503             (N2VT.getVectorMinNumElements() +
6504              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6505                 VT.getVectorMinNumElements()) &&
6506            "Insert subvector overflow!");
6507     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6508                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6509            "Constant index for INSERT_SUBVECTOR has an invalid size");
6510 
6511     // Trivial insertion.
6512     if (VT == N2VT)
6513       return N2;
6514 
6515     // If this is an insert of an extracted vector into an undef vector, we
6516     // can just use the input to the extract.
6517     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6518         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6519       return N2.getOperand(0);
6520     break;
6521   }
6522   case ISD::BITCAST:
6523     // Fold bit_convert nodes from a type to themselves.
6524     if (N1.getValueType() == VT)
6525       return N1;
6526     break;
6527   }
6528 
6529   // Memoize node if it doesn't produce a flag.
6530   SDNode *N;
6531   SDVTList VTs = getVTList(VT);
6532   SDValue Ops[] = {N1, N2, N3};
6533   if (VT != MVT::Glue) {
6534     FoldingSetNodeID ID;
6535     AddNodeIDNode(ID, Opcode, VTs, Ops);
6536     void *IP = nullptr;
6537     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6538       E->intersectFlagsWith(Flags);
6539       return SDValue(E, 0);
6540     }
6541 
6542     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6543     N->setFlags(Flags);
6544     createOperands(N, Ops);
6545     CSEMap.InsertNode(N, IP);
6546   } else {
6547     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6548     createOperands(N, Ops);
6549   }
6550 
6551   InsertNode(N);
6552   SDValue V = SDValue(N, 0);
6553   NewSDValueDbgMsg(V, "Creating new node: ", this);
6554   return V;
6555 }
6556 
6557 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6558                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6559   SDValue Ops[] = { N1, N2, N3, N4 };
6560   return getNode(Opcode, DL, VT, Ops);
6561 }
6562 
6563 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6564                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6565                               SDValue N5) {
6566   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6567   return getNode(Opcode, DL, VT, Ops);
6568 }
6569 
6570 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6571 /// the incoming stack arguments to be loaded from the stack.
6572 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6573   SmallVector<SDValue, 8> ArgChains;
6574 
6575   // Include the original chain at the beginning of the list. When this is
6576   // used by target LowerCall hooks, this helps legalize find the
6577   // CALLSEQ_BEGIN node.
6578   ArgChains.push_back(Chain);
6579 
6580   // Add a chain value for each stack argument.
6581   for (SDNode *U : getEntryNode().getNode()->uses())
6582     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6583       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6584         if (FI->getIndex() < 0)
6585           ArgChains.push_back(SDValue(L, 1));
6586 
6587   // Build a tokenfactor for all the chains.
6588   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6589 }
6590 
6591 /// getMemsetValue - Vectorized representation of the memset value
6592 /// operand.
6593 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6594                               const SDLoc &dl) {
6595   assert(!Value.isUndef());
6596 
6597   unsigned NumBits = VT.getScalarSizeInBits();
6598   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6599     assert(C->getAPIntValue().getBitWidth() == 8);
6600     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6601     if (VT.isInteger()) {
6602       bool IsOpaque = VT.getSizeInBits() > 64 ||
6603           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6604       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6605     }
6606     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6607                              VT);
6608   }
6609 
6610   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6611   EVT IntVT = VT.getScalarType();
6612   if (!IntVT.isInteger())
6613     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6614 
6615   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6616   if (NumBits > 8) {
6617     // Use a multiplication with 0x010101... to extend the input to the
6618     // required length.
6619     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6620     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6621                         DAG.getConstant(Magic, dl, IntVT));
6622   }
6623 
6624   if (VT != Value.getValueType() && !VT.isInteger())
6625     Value = DAG.getBitcast(VT.getScalarType(), Value);
6626   if (VT != Value.getValueType())
6627     Value = DAG.getSplatBuildVector(VT, dl, Value);
6628 
6629   return Value;
6630 }
6631 
6632 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6633 /// used when a memcpy is turned into a memset when the source is a constant
6634 /// string ptr.
6635 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6636                                   const TargetLowering &TLI,
6637                                   const ConstantDataArraySlice &Slice) {
6638   // Handle vector with all elements zero.
6639   if (Slice.Array == nullptr) {
6640     if (VT.isInteger())
6641       return DAG.getConstant(0, dl, VT);
6642     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6643       return DAG.getConstantFP(0.0, dl, VT);
6644     if (VT.isVector()) {
6645       unsigned NumElts = VT.getVectorNumElements();
6646       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6647       return DAG.getNode(ISD::BITCAST, dl, VT,
6648                          DAG.getConstant(0, dl,
6649                                          EVT::getVectorVT(*DAG.getContext(),
6650                                                           EltVT, NumElts)));
6651     }
6652     llvm_unreachable("Expected type!");
6653   }
6654 
6655   assert(!VT.isVector() && "Can't handle vector type here!");
6656   unsigned NumVTBits = VT.getSizeInBits();
6657   unsigned NumVTBytes = NumVTBits / 8;
6658   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6659 
6660   APInt Val(NumVTBits, 0);
6661   if (DAG.getDataLayout().isLittleEndian()) {
6662     for (unsigned i = 0; i != NumBytes; ++i)
6663       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6664   } else {
6665     for (unsigned i = 0; i != NumBytes; ++i)
6666       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6667   }
6668 
6669   // If the "cost" of materializing the integer immediate is less than the cost
6670   // of a load, then it is cost effective to turn the load into the immediate.
6671   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6672   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6673     return DAG.getConstant(Val, dl, VT);
6674   return SDValue();
6675 }
6676 
6677 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6678                                            const SDLoc &DL,
6679                                            const SDNodeFlags Flags) {
6680   EVT VT = Base.getValueType();
6681   SDValue Index;
6682 
6683   if (Offset.isScalable())
6684     Index = getVScale(DL, Base.getValueType(),
6685                       APInt(Base.getValueSizeInBits().getFixedSize(),
6686                             Offset.getKnownMinSize()));
6687   else
6688     Index = getConstant(Offset.getFixedSize(), DL, VT);
6689 
6690   return getMemBasePlusOffset(Base, Index, DL, Flags);
6691 }
6692 
6693 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6694                                            const SDLoc &DL,
6695                                            const SDNodeFlags Flags) {
6696   assert(Offset.getValueType().isInteger());
6697   EVT BasePtrVT = Ptr.getValueType();
6698   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6699 }
6700 
6701 /// Returns true if memcpy source is constant data.
6702 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6703   uint64_t SrcDelta = 0;
6704   GlobalAddressSDNode *G = nullptr;
6705   if (Src.getOpcode() == ISD::GlobalAddress)
6706     G = cast<GlobalAddressSDNode>(Src);
6707   else if (Src.getOpcode() == ISD::ADD &&
6708            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6709            Src.getOperand(1).getOpcode() == ISD::Constant) {
6710     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6711     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6712   }
6713   if (!G)
6714     return false;
6715 
6716   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6717                                   SrcDelta + G->getOffset());
6718 }
6719 
6720 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6721                                       SelectionDAG &DAG) {
6722   // On Darwin, -Os means optimize for size without hurting performance, so
6723   // only really optimize for size when -Oz (MinSize) is used.
6724   if (MF.getTarget().getTargetTriple().isOSDarwin())
6725     return MF.getFunction().hasMinSize();
6726   return DAG.shouldOptForSize();
6727 }
6728 
6729 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6730                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6731                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6732                           SmallVector<SDValue, 16> &OutStoreChains) {
6733   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6734   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6735   SmallVector<SDValue, 16> GluedLoadChains;
6736   for (unsigned i = From; i < To; ++i) {
6737     OutChains.push_back(OutLoadChains[i]);
6738     GluedLoadChains.push_back(OutLoadChains[i]);
6739   }
6740 
6741   // Chain for all loads.
6742   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6743                                   GluedLoadChains);
6744 
6745   for (unsigned i = From; i < To; ++i) {
6746     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6747     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6748                                   ST->getBasePtr(), ST->getMemoryVT(),
6749                                   ST->getMemOperand());
6750     OutChains.push_back(NewStore);
6751   }
6752 }
6753 
6754 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6755                                        SDValue Chain, SDValue Dst, SDValue Src,
6756                                        uint64_t Size, Align Alignment,
6757                                        bool isVol, bool AlwaysInline,
6758                                        MachinePointerInfo DstPtrInfo,
6759                                        MachinePointerInfo SrcPtrInfo,
6760                                        const AAMDNodes &AAInfo, AAResults *AA) {
6761   // Turn a memcpy of undef to nop.
6762   // FIXME: We need to honor volatile even is Src is undef.
6763   if (Src.isUndef())
6764     return Chain;
6765 
6766   // Expand memcpy to a series of load and store ops if the size operand falls
6767   // below a certain threshold.
6768   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6769   // rather than maybe a humongous number of loads and stores.
6770   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6771   const DataLayout &DL = DAG.getDataLayout();
6772   LLVMContext &C = *DAG.getContext();
6773   std::vector<EVT> MemOps;
6774   bool DstAlignCanChange = false;
6775   MachineFunction &MF = DAG.getMachineFunction();
6776   MachineFrameInfo &MFI = MF.getFrameInfo();
6777   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6778   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6779   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6780     DstAlignCanChange = true;
6781   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6782   if (!SrcAlign || Alignment > *SrcAlign)
6783     SrcAlign = Alignment;
6784   assert(SrcAlign && "SrcAlign must be set");
6785   ConstantDataArraySlice Slice;
6786   // If marked as volatile, perform a copy even when marked as constant.
6787   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6788   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6789   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6790   const MemOp Op = isZeroConstant
6791                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6792                                     /*IsZeroMemset*/ true, isVol)
6793                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6794                                      *SrcAlign, isVol, CopyFromConstant);
6795   if (!TLI.findOptimalMemOpLowering(
6796           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6797           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6798     return SDValue();
6799 
6800   if (DstAlignCanChange) {
6801     Type *Ty = MemOps[0].getTypeForEVT(C);
6802     Align NewAlign = DL.getABITypeAlign(Ty);
6803 
6804     // Don't promote to an alignment that would require dynamic stack
6805     // realignment.
6806     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6807     if (!TRI->hasStackRealignment(MF))
6808       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6809         NewAlign = NewAlign.previous();
6810 
6811     if (NewAlign > Alignment) {
6812       // Give the stack frame object a larger alignment if needed.
6813       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6814         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6815       Alignment = NewAlign;
6816     }
6817   }
6818 
6819   // Prepare AAInfo for loads/stores after lowering this memcpy.
6820   AAMDNodes NewAAInfo = AAInfo;
6821   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6822 
6823   const Value *SrcVal = SrcPtrInfo.V.dyn_cast<const Value *>();
6824   bool isConstant =
6825       AA && SrcVal &&
6826       AA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
6827 
6828   MachineMemOperand::Flags MMOFlags =
6829       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6830   SmallVector<SDValue, 16> OutLoadChains;
6831   SmallVector<SDValue, 16> OutStoreChains;
6832   SmallVector<SDValue, 32> OutChains;
6833   unsigned NumMemOps = MemOps.size();
6834   uint64_t SrcOff = 0, DstOff = 0;
6835   for (unsigned i = 0; i != NumMemOps; ++i) {
6836     EVT VT = MemOps[i];
6837     unsigned VTSize = VT.getSizeInBits() / 8;
6838     SDValue Value, Store;
6839 
6840     if (VTSize > Size) {
6841       // Issuing an unaligned load / store pair  that overlaps with the previous
6842       // pair. Adjust the offset accordingly.
6843       assert(i == NumMemOps-1 && i != 0);
6844       SrcOff -= VTSize - Size;
6845       DstOff -= VTSize - Size;
6846     }
6847 
6848     if (CopyFromConstant &&
6849         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6850       // It's unlikely a store of a vector immediate can be done in a single
6851       // instruction. It would require a load from a constantpool first.
6852       // We only handle zero vectors here.
6853       // FIXME: Handle other cases where store of vector immediate is done in
6854       // a single instruction.
6855       ConstantDataArraySlice SubSlice;
6856       if (SrcOff < Slice.Length) {
6857         SubSlice = Slice;
6858         SubSlice.move(SrcOff);
6859       } else {
6860         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6861         SubSlice.Array = nullptr;
6862         SubSlice.Offset = 0;
6863         SubSlice.Length = VTSize;
6864       }
6865       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6866       if (Value.getNode()) {
6867         Store = DAG.getStore(
6868             Chain, dl, Value,
6869             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6870             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6871         OutChains.push_back(Store);
6872       }
6873     }
6874 
6875     if (!Store.getNode()) {
6876       // The type might not be legal for the target.  This should only happen
6877       // if the type is smaller than a legal type, as on PPC, so the right
6878       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6879       // to Load/Store if NVT==VT.
6880       // FIXME does the case above also need this?
6881       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6882       assert(NVT.bitsGE(VT));
6883 
6884       bool isDereferenceable =
6885         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6886       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6887       if (isDereferenceable)
6888         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6889       if (isConstant)
6890         SrcMMOFlags |= MachineMemOperand::MOInvariant;
6891 
6892       Value = DAG.getExtLoad(
6893           ISD::EXTLOAD, dl, NVT, Chain,
6894           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6895           SrcPtrInfo.getWithOffset(SrcOff), VT,
6896           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6897       OutLoadChains.push_back(Value.getValue(1));
6898 
6899       Store = DAG.getTruncStore(
6900           Chain, dl, Value,
6901           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6902           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6903       OutStoreChains.push_back(Store);
6904     }
6905     SrcOff += VTSize;
6906     DstOff += VTSize;
6907     Size -= VTSize;
6908   }
6909 
6910   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6911                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6912   unsigned NumLdStInMemcpy = OutStoreChains.size();
6913 
6914   if (NumLdStInMemcpy) {
6915     // It may be that memcpy might be converted to memset if it's memcpy
6916     // of constants. In such a case, we won't have loads and stores, but
6917     // just stores. In the absence of loads, there is nothing to gang up.
6918     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6919       // If target does not care, just leave as it.
6920       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6921         OutChains.push_back(OutLoadChains[i]);
6922         OutChains.push_back(OutStoreChains[i]);
6923       }
6924     } else {
6925       // Ld/St less than/equal limit set by target.
6926       if (NumLdStInMemcpy <= GluedLdStLimit) {
6927           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6928                                         NumLdStInMemcpy, OutLoadChains,
6929                                         OutStoreChains);
6930       } else {
6931         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6932         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6933         unsigned GlueIter = 0;
6934 
6935         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6936           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6937           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6938 
6939           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6940                                        OutLoadChains, OutStoreChains);
6941           GlueIter += GluedLdStLimit;
6942         }
6943 
6944         // Residual ld/st.
6945         if (RemainingLdStInMemcpy) {
6946           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6947                                         RemainingLdStInMemcpy, OutLoadChains,
6948                                         OutStoreChains);
6949         }
6950       }
6951     }
6952   }
6953   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6954 }
6955 
6956 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6957                                         SDValue Chain, SDValue Dst, SDValue Src,
6958                                         uint64_t Size, Align Alignment,
6959                                         bool isVol, bool AlwaysInline,
6960                                         MachinePointerInfo DstPtrInfo,
6961                                         MachinePointerInfo SrcPtrInfo,
6962                                         const AAMDNodes &AAInfo) {
6963   // Turn a memmove of undef to nop.
6964   // FIXME: We need to honor volatile even is Src is undef.
6965   if (Src.isUndef())
6966     return Chain;
6967 
6968   // Expand memmove to a series of load and store ops if the size operand falls
6969   // below a certain threshold.
6970   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6971   const DataLayout &DL = DAG.getDataLayout();
6972   LLVMContext &C = *DAG.getContext();
6973   std::vector<EVT> MemOps;
6974   bool DstAlignCanChange = false;
6975   MachineFunction &MF = DAG.getMachineFunction();
6976   MachineFrameInfo &MFI = MF.getFrameInfo();
6977   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6978   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6979   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6980     DstAlignCanChange = true;
6981   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6982   if (!SrcAlign || Alignment > *SrcAlign)
6983     SrcAlign = Alignment;
6984   assert(SrcAlign && "SrcAlign must be set");
6985   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6986   if (!TLI.findOptimalMemOpLowering(
6987           MemOps, Limit,
6988           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6989                       /*IsVolatile*/ true),
6990           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6991           MF.getFunction().getAttributes()))
6992     return SDValue();
6993 
6994   if (DstAlignCanChange) {
6995     Type *Ty = MemOps[0].getTypeForEVT(C);
6996     Align NewAlign = DL.getABITypeAlign(Ty);
6997     if (NewAlign > Alignment) {
6998       // Give the stack frame object a larger alignment if needed.
6999       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7000         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7001       Alignment = NewAlign;
7002     }
7003   }
7004 
7005   // Prepare AAInfo for loads/stores after lowering this memmove.
7006   AAMDNodes NewAAInfo = AAInfo;
7007   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7008 
7009   MachineMemOperand::Flags MMOFlags =
7010       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
7011   uint64_t SrcOff = 0, DstOff = 0;
7012   SmallVector<SDValue, 8> LoadValues;
7013   SmallVector<SDValue, 8> LoadChains;
7014   SmallVector<SDValue, 8> OutChains;
7015   unsigned NumMemOps = MemOps.size();
7016   for (unsigned i = 0; i < NumMemOps; i++) {
7017     EVT VT = MemOps[i];
7018     unsigned VTSize = VT.getSizeInBits() / 8;
7019     SDValue Value;
7020 
7021     bool isDereferenceable =
7022       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
7023     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
7024     if (isDereferenceable)
7025       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
7026 
7027     Value = DAG.getLoad(
7028         VT, dl, Chain,
7029         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
7030         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
7031     LoadValues.push_back(Value);
7032     LoadChains.push_back(Value.getValue(1));
7033     SrcOff += VTSize;
7034   }
7035   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
7036   OutChains.clear();
7037   for (unsigned i = 0; i < NumMemOps; i++) {
7038     EVT VT = MemOps[i];
7039     unsigned VTSize = VT.getSizeInBits() / 8;
7040     SDValue Store;
7041 
7042     Store = DAG.getStore(
7043         Chain, dl, LoadValues[i],
7044         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7045         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
7046     OutChains.push_back(Store);
7047     DstOff += VTSize;
7048   }
7049 
7050   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7051 }
7052 
7053 /// Lower the call to 'memset' intrinsic function into a series of store
7054 /// operations.
7055 ///
7056 /// \param DAG Selection DAG where lowered code is placed.
7057 /// \param dl Link to corresponding IR location.
7058 /// \param Chain Control flow dependency.
7059 /// \param Dst Pointer to destination memory location.
7060 /// \param Src Value of byte to write into the memory.
7061 /// \param Size Number of bytes to write.
7062 /// \param Alignment Alignment of the destination in bytes.
7063 /// \param isVol True if destination is volatile.
7064 /// \param AlwaysInline Makes sure no function call is generated.
7065 /// \param DstPtrInfo IR information on the memory pointer.
7066 /// \returns New head in the control flow, if lowering was successful, empty
7067 /// SDValue otherwise.
7068 ///
7069 /// The function tries to replace 'llvm.memset' intrinsic with several store
7070 /// operations and value calculation code. This is usually profitable for small
7071 /// memory size or when the semantic requires inlining.
7072 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
7073                                SDValue Chain, SDValue Dst, SDValue Src,
7074                                uint64_t Size, Align Alignment, bool isVol,
7075                                bool AlwaysInline, MachinePointerInfo DstPtrInfo,
7076                                const AAMDNodes &AAInfo) {
7077   // Turn a memset of undef to nop.
7078   // FIXME: We need to honor volatile even is Src is undef.
7079   if (Src.isUndef())
7080     return Chain;
7081 
7082   // Expand memset to a series of load/store ops if the size operand
7083   // falls below a certain threshold.
7084   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7085   std::vector<EVT> MemOps;
7086   bool DstAlignCanChange = false;
7087   MachineFunction &MF = DAG.getMachineFunction();
7088   MachineFrameInfo &MFI = MF.getFrameInfo();
7089   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7090   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7091   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7092     DstAlignCanChange = true;
7093   bool IsZeroVal =
7094       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
7095   unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
7096 
7097   if (!TLI.findOptimalMemOpLowering(
7098           MemOps, Limit,
7099           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7100           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7101     return SDValue();
7102 
7103   if (DstAlignCanChange) {
7104     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7105     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7106     if (NewAlign > Alignment) {
7107       // Give the stack frame object a larger alignment if needed.
7108       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7109         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7110       Alignment = NewAlign;
7111     }
7112   }
7113 
7114   SmallVector<SDValue, 8> OutChains;
7115   uint64_t DstOff = 0;
7116   unsigned NumMemOps = MemOps.size();
7117 
7118   // Find the largest store and generate the bit pattern for it.
7119   EVT LargestVT = MemOps[0];
7120   for (unsigned i = 1; i < NumMemOps; i++)
7121     if (MemOps[i].bitsGT(LargestVT))
7122       LargestVT = MemOps[i];
7123   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7124 
7125   // Prepare AAInfo for loads/stores after lowering this memset.
7126   AAMDNodes NewAAInfo = AAInfo;
7127   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7128 
7129   for (unsigned i = 0; i < NumMemOps; i++) {
7130     EVT VT = MemOps[i];
7131     unsigned VTSize = VT.getSizeInBits() / 8;
7132     if (VTSize > Size) {
7133       // Issuing an unaligned load / store pair  that overlaps with the previous
7134       // pair. Adjust the offset accordingly.
7135       assert(i == NumMemOps-1 && i != 0);
7136       DstOff -= VTSize - Size;
7137     }
7138 
7139     // If this store is smaller than the largest store see whether we can get
7140     // the smaller value for free with a truncate.
7141     SDValue Value = MemSetValue;
7142     if (VT.bitsLT(LargestVT)) {
7143       if (!LargestVT.isVector() && !VT.isVector() &&
7144           TLI.isTruncateFree(LargestVT, VT))
7145         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7146       else
7147         Value = getMemsetValue(Src, VT, DAG, dl);
7148     }
7149     assert(Value.getValueType() == VT && "Value with wrong type.");
7150     SDValue Store = DAG.getStore(
7151         Chain, dl, Value,
7152         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7153         DstPtrInfo.getWithOffset(DstOff), Alignment,
7154         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7155         NewAAInfo);
7156     OutChains.push_back(Store);
7157     DstOff += VT.getSizeInBits() / 8;
7158     Size -= VTSize;
7159   }
7160 
7161   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7162 }
7163 
7164 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7165                                             unsigned AS) {
7166   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7167   // pointer operands can be losslessly bitcasted to pointers of address space 0
7168   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7169     report_fatal_error("cannot lower memory intrinsic in address space " +
7170                        Twine(AS));
7171   }
7172 }
7173 
7174 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7175                                 SDValue Src, SDValue Size, Align Alignment,
7176                                 bool isVol, bool AlwaysInline, bool isTailCall,
7177                                 MachinePointerInfo DstPtrInfo,
7178                                 MachinePointerInfo SrcPtrInfo,
7179                                 const AAMDNodes &AAInfo, AAResults *AA) {
7180   // Check to see if we should lower the memcpy to loads and stores first.
7181   // For cases within the target-specified limits, this is the best choice.
7182   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7183   if (ConstantSize) {
7184     // Memcpy with size zero? Just return the original chain.
7185     if (ConstantSize->isZero())
7186       return Chain;
7187 
7188     SDValue Result = getMemcpyLoadsAndStores(
7189         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7190         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, AA);
7191     if (Result.getNode())
7192       return Result;
7193   }
7194 
7195   // Then check to see if we should lower the memcpy with target-specific
7196   // code. If the target chooses to do this, this is the next best.
7197   if (TSI) {
7198     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7199         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7200         DstPtrInfo, SrcPtrInfo);
7201     if (Result.getNode())
7202       return Result;
7203   }
7204 
7205   // If we really need inline code and the target declined to provide it,
7206   // use a (potentially long) sequence of loads and stores.
7207   if (AlwaysInline) {
7208     assert(ConstantSize && "AlwaysInline requires a constant size!");
7209     return getMemcpyLoadsAndStores(
7210         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7211         isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, AA);
7212   }
7213 
7214   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7215   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7216 
7217   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7218   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7219   // respect volatile, so they may do things like read or write memory
7220   // beyond the given memory regions. But fixing this isn't easy, and most
7221   // people don't care.
7222 
7223   // Emit a library call.
7224   TargetLowering::ArgListTy Args;
7225   TargetLowering::ArgListEntry Entry;
7226   Entry.Ty = Type::getInt8PtrTy(*getContext());
7227   Entry.Node = Dst; Args.push_back(Entry);
7228   Entry.Node = Src; Args.push_back(Entry);
7229 
7230   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7231   Entry.Node = Size; Args.push_back(Entry);
7232   // FIXME: pass in SDLoc
7233   TargetLowering::CallLoweringInfo CLI(*this);
7234   CLI.setDebugLoc(dl)
7235       .setChain(Chain)
7236       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7237                     Dst.getValueType().getTypeForEVT(*getContext()),
7238                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7239                                       TLI->getPointerTy(getDataLayout())),
7240                     std::move(Args))
7241       .setDiscardResult()
7242       .setTailCall(isTailCall);
7243 
7244   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7245   return CallResult.second;
7246 }
7247 
7248 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7249                                       SDValue Dst, SDValue Src, SDValue Size,
7250                                       Type *SizeTy, unsigned ElemSz,
7251                                       bool isTailCall,
7252                                       MachinePointerInfo DstPtrInfo,
7253                                       MachinePointerInfo SrcPtrInfo) {
7254   // Emit a library call.
7255   TargetLowering::ArgListTy Args;
7256   TargetLowering::ArgListEntry Entry;
7257   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7258   Entry.Node = Dst;
7259   Args.push_back(Entry);
7260 
7261   Entry.Node = Src;
7262   Args.push_back(Entry);
7263 
7264   Entry.Ty = SizeTy;
7265   Entry.Node = Size;
7266   Args.push_back(Entry);
7267 
7268   RTLIB::Libcall LibraryCall =
7269       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7270   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7271     report_fatal_error("Unsupported element size");
7272 
7273   TargetLowering::CallLoweringInfo CLI(*this);
7274   CLI.setDebugLoc(dl)
7275       .setChain(Chain)
7276       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7277                     Type::getVoidTy(*getContext()),
7278                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7279                                       TLI->getPointerTy(getDataLayout())),
7280                     std::move(Args))
7281       .setDiscardResult()
7282       .setTailCall(isTailCall);
7283 
7284   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7285   return CallResult.second;
7286 }
7287 
7288 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7289                                  SDValue Src, SDValue Size, Align Alignment,
7290                                  bool isVol, bool isTailCall,
7291                                  MachinePointerInfo DstPtrInfo,
7292                                  MachinePointerInfo SrcPtrInfo,
7293                                  const AAMDNodes &AAInfo, AAResults *AA) {
7294   // Check to see if we should lower the memmove to loads and stores first.
7295   // For cases within the target-specified limits, this is the best choice.
7296   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7297   if (ConstantSize) {
7298     // Memmove with size zero? Just return the original chain.
7299     if (ConstantSize->isZero())
7300       return Chain;
7301 
7302     SDValue Result = getMemmoveLoadsAndStores(
7303         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7304         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7305     if (Result.getNode())
7306       return Result;
7307   }
7308 
7309   // Then check to see if we should lower the memmove with target-specific
7310   // code. If the target chooses to do this, this is the next best.
7311   if (TSI) {
7312     SDValue Result =
7313         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7314                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7315     if (Result.getNode())
7316       return Result;
7317   }
7318 
7319   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7320   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7321 
7322   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7323   // not be safe.  See memcpy above for more details.
7324 
7325   // Emit a library call.
7326   TargetLowering::ArgListTy Args;
7327   TargetLowering::ArgListEntry Entry;
7328   Entry.Ty = Type::getInt8PtrTy(*getContext());
7329   Entry.Node = Dst; Args.push_back(Entry);
7330   Entry.Node = Src; Args.push_back(Entry);
7331 
7332   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7333   Entry.Node = Size; Args.push_back(Entry);
7334   // FIXME:  pass in SDLoc
7335   TargetLowering::CallLoweringInfo CLI(*this);
7336   CLI.setDebugLoc(dl)
7337       .setChain(Chain)
7338       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7339                     Dst.getValueType().getTypeForEVT(*getContext()),
7340                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7341                                       TLI->getPointerTy(getDataLayout())),
7342                     std::move(Args))
7343       .setDiscardResult()
7344       .setTailCall(isTailCall);
7345 
7346   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7347   return CallResult.second;
7348 }
7349 
7350 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7351                                        SDValue Dst, SDValue Src, SDValue Size,
7352                                        Type *SizeTy, unsigned ElemSz,
7353                                        bool isTailCall,
7354                                        MachinePointerInfo DstPtrInfo,
7355                                        MachinePointerInfo SrcPtrInfo) {
7356   // Emit a library call.
7357   TargetLowering::ArgListTy Args;
7358   TargetLowering::ArgListEntry Entry;
7359   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7360   Entry.Node = Dst;
7361   Args.push_back(Entry);
7362 
7363   Entry.Node = Src;
7364   Args.push_back(Entry);
7365 
7366   Entry.Ty = SizeTy;
7367   Entry.Node = Size;
7368   Args.push_back(Entry);
7369 
7370   RTLIB::Libcall LibraryCall =
7371       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7372   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7373     report_fatal_error("Unsupported element size");
7374 
7375   TargetLowering::CallLoweringInfo CLI(*this);
7376   CLI.setDebugLoc(dl)
7377       .setChain(Chain)
7378       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7379                     Type::getVoidTy(*getContext()),
7380                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7381                                       TLI->getPointerTy(getDataLayout())),
7382                     std::move(Args))
7383       .setDiscardResult()
7384       .setTailCall(isTailCall);
7385 
7386   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7387   return CallResult.second;
7388 }
7389 
7390 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7391                                 SDValue Src, SDValue Size, Align Alignment,
7392                                 bool isVol, bool AlwaysInline, bool isTailCall,
7393                                 MachinePointerInfo DstPtrInfo,
7394                                 const AAMDNodes &AAInfo) {
7395   // Check to see if we should lower the memset to stores first.
7396   // For cases within the target-specified limits, this is the best choice.
7397   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7398   if (ConstantSize) {
7399     // Memset with size zero? Just return the original chain.
7400     if (ConstantSize->isZero())
7401       return Chain;
7402 
7403     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7404                                      ConstantSize->getZExtValue(), Alignment,
7405                                      isVol, false, DstPtrInfo, AAInfo);
7406 
7407     if (Result.getNode())
7408       return Result;
7409   }
7410 
7411   // Then check to see if we should lower the memset with target-specific
7412   // code. If the target chooses to do this, this is the next best.
7413   if (TSI) {
7414     SDValue Result = TSI->EmitTargetCodeForMemset(
7415         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
7416     if (Result.getNode())
7417       return Result;
7418   }
7419 
7420   // If we really need inline code and the target declined to provide it,
7421   // use a (potentially long) sequence of loads and stores.
7422   if (AlwaysInline) {
7423     assert(ConstantSize && "AlwaysInline requires a constant size!");
7424     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7425                                      ConstantSize->getZExtValue(), Alignment,
7426                                      isVol, true, DstPtrInfo, AAInfo);
7427     assert(Result &&
7428            "getMemsetStores must return a valid sequence when AlwaysInline");
7429     return Result;
7430   }
7431 
7432   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7433 
7434   // Emit a library call.
7435   auto &Ctx = *getContext();
7436   const auto& DL = getDataLayout();
7437 
7438   TargetLowering::CallLoweringInfo CLI(*this);
7439   // FIXME: pass in SDLoc
7440   CLI.setDebugLoc(dl).setChain(Chain);
7441 
7442   ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src);
7443   const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero();
7444   const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO);
7445 
7446   // Helper function to create an Entry from Node and Type.
7447   const auto CreateEntry = [](SDValue Node, Type *Ty) {
7448     TargetLowering::ArgListEntry Entry;
7449     Entry.Node = Node;
7450     Entry.Ty = Ty;
7451     return Entry;
7452   };
7453 
7454   // If zeroing out and bzero is present, use it.
7455   if (SrcIsZero && BzeroName) {
7456     TargetLowering::ArgListTy Args;
7457     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7458     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7459     CLI.setLibCallee(
7460         TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx),
7461         getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args));
7462   } else {
7463     TargetLowering::ArgListTy Args;
7464     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7465     Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx)));
7466     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7467     CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7468                      Dst.getValueType().getTypeForEVT(Ctx),
7469                      getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7470                                        TLI->getPointerTy(DL)),
7471                      std::move(Args));
7472   }
7473 
7474   CLI.setDiscardResult().setTailCall(isTailCall);
7475 
7476   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7477   return CallResult.second;
7478 }
7479 
7480 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7481                                       SDValue Dst, SDValue Value, SDValue Size,
7482                                       Type *SizeTy, unsigned ElemSz,
7483                                       bool isTailCall,
7484                                       MachinePointerInfo DstPtrInfo) {
7485   // Emit a library call.
7486   TargetLowering::ArgListTy Args;
7487   TargetLowering::ArgListEntry Entry;
7488   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7489   Entry.Node = Dst;
7490   Args.push_back(Entry);
7491 
7492   Entry.Ty = Type::getInt8Ty(*getContext());
7493   Entry.Node = Value;
7494   Args.push_back(Entry);
7495 
7496   Entry.Ty = SizeTy;
7497   Entry.Node = Size;
7498   Args.push_back(Entry);
7499 
7500   RTLIB::Libcall LibraryCall =
7501       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7502   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7503     report_fatal_error("Unsupported element size");
7504 
7505   TargetLowering::CallLoweringInfo CLI(*this);
7506   CLI.setDebugLoc(dl)
7507       .setChain(Chain)
7508       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7509                     Type::getVoidTy(*getContext()),
7510                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7511                                       TLI->getPointerTy(getDataLayout())),
7512                     std::move(Args))
7513       .setDiscardResult()
7514       .setTailCall(isTailCall);
7515 
7516   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7517   return CallResult.second;
7518 }
7519 
7520 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7521                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7522                                 MachineMemOperand *MMO) {
7523   FoldingSetNodeID ID;
7524   ID.AddInteger(MemVT.getRawBits());
7525   AddNodeIDNode(ID, Opcode, VTList, Ops);
7526   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7527   ID.AddInteger(MMO->getFlags());
7528   void* IP = nullptr;
7529   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7530     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7531     return SDValue(E, 0);
7532   }
7533 
7534   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7535                                     VTList, MemVT, MMO);
7536   createOperands(N, Ops);
7537 
7538   CSEMap.InsertNode(N, IP);
7539   InsertNode(N);
7540   return SDValue(N, 0);
7541 }
7542 
7543 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7544                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7545                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7546                                        MachineMemOperand *MMO) {
7547   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7548          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7549   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7550 
7551   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7552   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7553 }
7554 
7555 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7556                                 SDValue Chain, SDValue Ptr, SDValue Val,
7557                                 MachineMemOperand *MMO) {
7558   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7559           Opcode == ISD::ATOMIC_LOAD_SUB ||
7560           Opcode == ISD::ATOMIC_LOAD_AND ||
7561           Opcode == ISD::ATOMIC_LOAD_CLR ||
7562           Opcode == ISD::ATOMIC_LOAD_OR ||
7563           Opcode == ISD::ATOMIC_LOAD_XOR ||
7564           Opcode == ISD::ATOMIC_LOAD_NAND ||
7565           Opcode == ISD::ATOMIC_LOAD_MIN ||
7566           Opcode == ISD::ATOMIC_LOAD_MAX ||
7567           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7568           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7569           Opcode == ISD::ATOMIC_LOAD_FADD ||
7570           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7571           Opcode == ISD::ATOMIC_LOAD_FMAX ||
7572           Opcode == ISD::ATOMIC_LOAD_FMIN ||
7573           Opcode == ISD::ATOMIC_SWAP ||
7574           Opcode == ISD::ATOMIC_STORE) &&
7575          "Invalid Atomic Op");
7576 
7577   EVT VT = Val.getValueType();
7578 
7579   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7580                                                getVTList(VT, MVT::Other);
7581   SDValue Ops[] = {Chain, Ptr, Val};
7582   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7583 }
7584 
7585 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7586                                 EVT VT, SDValue Chain, SDValue Ptr,
7587                                 MachineMemOperand *MMO) {
7588   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7589 
7590   SDVTList VTs = getVTList(VT, MVT::Other);
7591   SDValue Ops[] = {Chain, Ptr};
7592   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7593 }
7594 
7595 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7596 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7597   if (Ops.size() == 1)
7598     return Ops[0];
7599 
7600   SmallVector<EVT, 4> VTs;
7601   VTs.reserve(Ops.size());
7602   for (const SDValue &Op : Ops)
7603     VTs.push_back(Op.getValueType());
7604   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7605 }
7606 
7607 SDValue SelectionDAG::getMemIntrinsicNode(
7608     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7609     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7610     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7611   if (!Size && MemVT.isScalableVector())
7612     Size = MemoryLocation::UnknownSize;
7613   else if (!Size)
7614     Size = MemVT.getStoreSize();
7615 
7616   MachineFunction &MF = getMachineFunction();
7617   MachineMemOperand *MMO =
7618       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7619 
7620   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7621 }
7622 
7623 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7624                                           SDVTList VTList,
7625                                           ArrayRef<SDValue> Ops, EVT MemVT,
7626                                           MachineMemOperand *MMO) {
7627   assert((Opcode == ISD::INTRINSIC_VOID ||
7628           Opcode == ISD::INTRINSIC_W_CHAIN ||
7629           Opcode == ISD::PREFETCH ||
7630           ((int)Opcode <= std::numeric_limits<int>::max() &&
7631            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7632          "Opcode is not a memory-accessing opcode!");
7633 
7634   // Memoize the node unless it returns a flag.
7635   MemIntrinsicSDNode *N;
7636   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7637     FoldingSetNodeID ID;
7638     AddNodeIDNode(ID, Opcode, VTList, Ops);
7639     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7640         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7641     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7642     ID.AddInteger(MMO->getFlags());
7643     void *IP = nullptr;
7644     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7645       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7646       return SDValue(E, 0);
7647     }
7648 
7649     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7650                                       VTList, MemVT, MMO);
7651     createOperands(N, Ops);
7652 
7653   CSEMap.InsertNode(N, IP);
7654   } else {
7655     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7656                                       VTList, MemVT, MMO);
7657     createOperands(N, Ops);
7658   }
7659   InsertNode(N);
7660   SDValue V(N, 0);
7661   NewSDValueDbgMsg(V, "Creating new node: ", this);
7662   return V;
7663 }
7664 
7665 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7666                                       SDValue Chain, int FrameIndex,
7667                                       int64_t Size, int64_t Offset) {
7668   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7669   const auto VTs = getVTList(MVT::Other);
7670   SDValue Ops[2] = {
7671       Chain,
7672       getFrameIndex(FrameIndex,
7673                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7674                     true)};
7675 
7676   FoldingSetNodeID ID;
7677   AddNodeIDNode(ID, Opcode, VTs, Ops);
7678   ID.AddInteger(FrameIndex);
7679   ID.AddInteger(Size);
7680   ID.AddInteger(Offset);
7681   void *IP = nullptr;
7682   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7683     return SDValue(E, 0);
7684 
7685   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7686       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7687   createOperands(N, Ops);
7688   CSEMap.InsertNode(N, IP);
7689   InsertNode(N);
7690   SDValue V(N, 0);
7691   NewSDValueDbgMsg(V, "Creating new node: ", this);
7692   return V;
7693 }
7694 
7695 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7696                                          uint64_t Guid, uint64_t Index,
7697                                          uint32_t Attr) {
7698   const unsigned Opcode = ISD::PSEUDO_PROBE;
7699   const auto VTs = getVTList(MVT::Other);
7700   SDValue Ops[] = {Chain};
7701   FoldingSetNodeID ID;
7702   AddNodeIDNode(ID, Opcode, VTs, Ops);
7703   ID.AddInteger(Guid);
7704   ID.AddInteger(Index);
7705   void *IP = nullptr;
7706   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7707     return SDValue(E, 0);
7708 
7709   auto *N = newSDNode<PseudoProbeSDNode>(
7710       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7711   createOperands(N, Ops);
7712   CSEMap.InsertNode(N, IP);
7713   InsertNode(N);
7714   SDValue V(N, 0);
7715   NewSDValueDbgMsg(V, "Creating new node: ", this);
7716   return V;
7717 }
7718 
7719 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7720 /// MachinePointerInfo record from it.  This is particularly useful because the
7721 /// code generator has many cases where it doesn't bother passing in a
7722 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7723 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7724                                            SelectionDAG &DAG, SDValue Ptr,
7725                                            int64_t Offset = 0) {
7726   // If this is FI+Offset, we can model it.
7727   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7728     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7729                                              FI->getIndex(), Offset);
7730 
7731   // If this is (FI+Offset1)+Offset2, we can model it.
7732   if (Ptr.getOpcode() != ISD::ADD ||
7733       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7734       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7735     return Info;
7736 
7737   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7738   return MachinePointerInfo::getFixedStack(
7739       DAG.getMachineFunction(), FI,
7740       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7741 }
7742 
7743 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7744 /// MachinePointerInfo record from it.  This is particularly useful because the
7745 /// code generator has many cases where it doesn't bother passing in a
7746 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7747 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7748                                            SelectionDAG &DAG, SDValue Ptr,
7749                                            SDValue OffsetOp) {
7750   // If the 'Offset' value isn't a constant, we can't handle this.
7751   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7752     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7753   if (OffsetOp.isUndef())
7754     return InferPointerInfo(Info, DAG, Ptr);
7755   return Info;
7756 }
7757 
7758 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7759                               EVT VT, const SDLoc &dl, SDValue Chain,
7760                               SDValue Ptr, SDValue Offset,
7761                               MachinePointerInfo PtrInfo, EVT MemVT,
7762                               Align Alignment,
7763                               MachineMemOperand::Flags MMOFlags,
7764                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7765   assert(Chain.getValueType() == MVT::Other &&
7766         "Invalid chain type");
7767 
7768   MMOFlags |= MachineMemOperand::MOLoad;
7769   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7770   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7771   // clients.
7772   if (PtrInfo.V.isNull())
7773     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7774 
7775   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7776   MachineFunction &MF = getMachineFunction();
7777   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7778                                                    Alignment, AAInfo, Ranges);
7779   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7780 }
7781 
7782 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7783                               EVT VT, const SDLoc &dl, SDValue Chain,
7784                               SDValue Ptr, SDValue Offset, EVT MemVT,
7785                               MachineMemOperand *MMO) {
7786   if (VT == MemVT) {
7787     ExtType = ISD::NON_EXTLOAD;
7788   } else if (ExtType == ISD::NON_EXTLOAD) {
7789     assert(VT == MemVT && "Non-extending load from different memory type!");
7790   } else {
7791     // Extending load.
7792     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7793            "Should only be an extending load, not truncating!");
7794     assert(VT.isInteger() == MemVT.isInteger() &&
7795            "Cannot convert from FP to Int or Int -> FP!");
7796     assert(VT.isVector() == MemVT.isVector() &&
7797            "Cannot use an ext load to convert to or from a vector!");
7798     assert((!VT.isVector() ||
7799             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7800            "Cannot use an ext load to change the number of vector elements!");
7801   }
7802 
7803   bool Indexed = AM != ISD::UNINDEXED;
7804   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7805 
7806   SDVTList VTs = Indexed ?
7807     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7808   SDValue Ops[] = { Chain, Ptr, Offset };
7809   FoldingSetNodeID ID;
7810   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7811   ID.AddInteger(MemVT.getRawBits());
7812   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7813       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7814   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7815   ID.AddInteger(MMO->getFlags());
7816   void *IP = nullptr;
7817   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7818     cast<LoadSDNode>(E)->refineAlignment(MMO);
7819     return SDValue(E, 0);
7820   }
7821   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7822                                   ExtType, MemVT, MMO);
7823   createOperands(N, Ops);
7824 
7825   CSEMap.InsertNode(N, IP);
7826   InsertNode(N);
7827   SDValue V(N, 0);
7828   NewSDValueDbgMsg(V, "Creating new node: ", this);
7829   return V;
7830 }
7831 
7832 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7833                               SDValue Ptr, MachinePointerInfo PtrInfo,
7834                               MaybeAlign Alignment,
7835                               MachineMemOperand::Flags MMOFlags,
7836                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7837   SDValue Undef = getUNDEF(Ptr.getValueType());
7838   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7839                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7840 }
7841 
7842 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7843                               SDValue Ptr, MachineMemOperand *MMO) {
7844   SDValue Undef = getUNDEF(Ptr.getValueType());
7845   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7846                  VT, MMO);
7847 }
7848 
7849 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7850                                  EVT VT, SDValue Chain, SDValue Ptr,
7851                                  MachinePointerInfo PtrInfo, EVT MemVT,
7852                                  MaybeAlign Alignment,
7853                                  MachineMemOperand::Flags MMOFlags,
7854                                  const AAMDNodes &AAInfo) {
7855   SDValue Undef = getUNDEF(Ptr.getValueType());
7856   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7857                  MemVT, Alignment, MMOFlags, AAInfo);
7858 }
7859 
7860 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7861                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7862                                  MachineMemOperand *MMO) {
7863   SDValue Undef = getUNDEF(Ptr.getValueType());
7864   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7865                  MemVT, MMO);
7866 }
7867 
7868 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7869                                      SDValue Base, SDValue Offset,
7870                                      ISD::MemIndexedMode AM) {
7871   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7872   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7873   // Don't propagate the invariant or dereferenceable flags.
7874   auto MMOFlags =
7875       LD->getMemOperand()->getFlags() &
7876       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7877   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7878                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7879                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7880 }
7881 
7882 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7883                                SDValue Ptr, MachinePointerInfo PtrInfo,
7884                                Align Alignment,
7885                                MachineMemOperand::Flags MMOFlags,
7886                                const AAMDNodes &AAInfo) {
7887   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7888 
7889   MMOFlags |= MachineMemOperand::MOStore;
7890   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7891 
7892   if (PtrInfo.V.isNull())
7893     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7894 
7895   MachineFunction &MF = getMachineFunction();
7896   uint64_t Size =
7897       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7898   MachineMemOperand *MMO =
7899       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7900   return getStore(Chain, dl, Val, Ptr, MMO);
7901 }
7902 
7903 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7904                                SDValue Ptr, MachineMemOperand *MMO) {
7905   assert(Chain.getValueType() == MVT::Other &&
7906         "Invalid chain type");
7907   EVT VT = Val.getValueType();
7908   SDVTList VTs = getVTList(MVT::Other);
7909   SDValue Undef = getUNDEF(Ptr.getValueType());
7910   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7911   FoldingSetNodeID ID;
7912   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7913   ID.AddInteger(VT.getRawBits());
7914   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7915       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7916   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7917   ID.AddInteger(MMO->getFlags());
7918   void *IP = nullptr;
7919   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7920     cast<StoreSDNode>(E)->refineAlignment(MMO);
7921     return SDValue(E, 0);
7922   }
7923   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7924                                    ISD::UNINDEXED, false, VT, MMO);
7925   createOperands(N, Ops);
7926 
7927   CSEMap.InsertNode(N, IP);
7928   InsertNode(N);
7929   SDValue V(N, 0);
7930   NewSDValueDbgMsg(V, "Creating new node: ", this);
7931   return V;
7932 }
7933 
7934 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7935                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7936                                     EVT SVT, Align Alignment,
7937                                     MachineMemOperand::Flags MMOFlags,
7938                                     const AAMDNodes &AAInfo) {
7939   assert(Chain.getValueType() == MVT::Other &&
7940         "Invalid chain type");
7941 
7942   MMOFlags |= MachineMemOperand::MOStore;
7943   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7944 
7945   if (PtrInfo.V.isNull())
7946     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7947 
7948   MachineFunction &MF = getMachineFunction();
7949   MachineMemOperand *MMO = MF.getMachineMemOperand(
7950       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7951       Alignment, AAInfo);
7952   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7953 }
7954 
7955 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7956                                     SDValue Ptr, EVT SVT,
7957                                     MachineMemOperand *MMO) {
7958   EVT VT = Val.getValueType();
7959 
7960   assert(Chain.getValueType() == MVT::Other &&
7961         "Invalid chain type");
7962   if (VT == SVT)
7963     return getStore(Chain, dl, Val, Ptr, MMO);
7964 
7965   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7966          "Should only be a truncating store, not extending!");
7967   assert(VT.isInteger() == SVT.isInteger() &&
7968          "Can't do FP-INT conversion!");
7969   assert(VT.isVector() == SVT.isVector() &&
7970          "Cannot use trunc store to convert to or from a vector!");
7971   assert((!VT.isVector() ||
7972           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7973          "Cannot use trunc store to change the number of vector elements!");
7974 
7975   SDVTList VTs = getVTList(MVT::Other);
7976   SDValue Undef = getUNDEF(Ptr.getValueType());
7977   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7978   FoldingSetNodeID ID;
7979   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7980   ID.AddInteger(SVT.getRawBits());
7981   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7982       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7983   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7984   ID.AddInteger(MMO->getFlags());
7985   void *IP = nullptr;
7986   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7987     cast<StoreSDNode>(E)->refineAlignment(MMO);
7988     return SDValue(E, 0);
7989   }
7990   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7991                                    ISD::UNINDEXED, true, SVT, MMO);
7992   createOperands(N, Ops);
7993 
7994   CSEMap.InsertNode(N, IP);
7995   InsertNode(N);
7996   SDValue V(N, 0);
7997   NewSDValueDbgMsg(V, "Creating new node: ", this);
7998   return V;
7999 }
8000 
8001 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
8002                                       SDValue Base, SDValue Offset,
8003                                       ISD::MemIndexedMode AM) {
8004   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
8005   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
8006   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8007   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
8008   FoldingSetNodeID ID;
8009   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
8010   ID.AddInteger(ST->getMemoryVT().getRawBits());
8011   ID.AddInteger(ST->getRawSubclassData());
8012   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8013   ID.AddInteger(ST->getMemOperand()->getFlags());
8014   void *IP = nullptr;
8015   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8016     return SDValue(E, 0);
8017 
8018   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8019                                    ST->isTruncatingStore(), ST->getMemoryVT(),
8020                                    ST->getMemOperand());
8021   createOperands(N, Ops);
8022 
8023   CSEMap.InsertNode(N, IP);
8024   InsertNode(N);
8025   SDValue V(N, 0);
8026   NewSDValueDbgMsg(V, "Creating new node: ", this);
8027   return V;
8028 }
8029 
8030 SDValue SelectionDAG::getLoadVP(
8031     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
8032     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
8033     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8034     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8035     const MDNode *Ranges, bool IsExpanding) {
8036   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8037 
8038   MMOFlags |= MachineMemOperand::MOLoad;
8039   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8040   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8041   // clients.
8042   if (PtrInfo.V.isNull())
8043     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8044 
8045   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
8046   MachineFunction &MF = getMachineFunction();
8047   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8048                                                    Alignment, AAInfo, Ranges);
8049   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
8050                    MMO, IsExpanding);
8051 }
8052 
8053 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
8054                                 ISD::LoadExtType ExtType, EVT VT,
8055                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
8056                                 SDValue Offset, SDValue Mask, SDValue EVL,
8057                                 EVT MemVT, MachineMemOperand *MMO,
8058                                 bool IsExpanding) {
8059   bool Indexed = AM != ISD::UNINDEXED;
8060   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8061 
8062   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8063                          : getVTList(VT, MVT::Other);
8064   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
8065   FoldingSetNodeID ID;
8066   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
8067   ID.AddInteger(VT.getRawBits());
8068   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
8069       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8070   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8071   ID.AddInteger(MMO->getFlags());
8072   void *IP = nullptr;
8073   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8074     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
8075     return SDValue(E, 0);
8076   }
8077   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8078                                     ExtType, IsExpanding, MemVT, MMO);
8079   createOperands(N, Ops);
8080 
8081   CSEMap.InsertNode(N, IP);
8082   InsertNode(N);
8083   SDValue V(N, 0);
8084   NewSDValueDbgMsg(V, "Creating new node: ", this);
8085   return V;
8086 }
8087 
8088 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8089                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8090                                 MachinePointerInfo PtrInfo,
8091                                 MaybeAlign Alignment,
8092                                 MachineMemOperand::Flags MMOFlags,
8093                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
8094                                 bool IsExpanding) {
8095   SDValue Undef = getUNDEF(Ptr.getValueType());
8096   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8097                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
8098                    IsExpanding);
8099 }
8100 
8101 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8102                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8103                                 MachineMemOperand *MMO, bool IsExpanding) {
8104   SDValue Undef = getUNDEF(Ptr.getValueType());
8105   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8106                    Mask, EVL, VT, MMO, IsExpanding);
8107 }
8108 
8109 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8110                                    EVT VT, SDValue Chain, SDValue Ptr,
8111                                    SDValue Mask, SDValue EVL,
8112                                    MachinePointerInfo PtrInfo, EVT MemVT,
8113                                    MaybeAlign Alignment,
8114                                    MachineMemOperand::Flags MMOFlags,
8115                                    const AAMDNodes &AAInfo, bool IsExpanding) {
8116   SDValue Undef = getUNDEF(Ptr.getValueType());
8117   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8118                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8119                    IsExpanding);
8120 }
8121 
8122 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8123                                    EVT VT, SDValue Chain, SDValue Ptr,
8124                                    SDValue Mask, SDValue EVL, EVT MemVT,
8125                                    MachineMemOperand *MMO, bool IsExpanding) {
8126   SDValue Undef = getUNDEF(Ptr.getValueType());
8127   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8128                    EVL, MemVT, MMO, IsExpanding);
8129 }
8130 
8131 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8132                                        SDValue Base, SDValue Offset,
8133                                        ISD::MemIndexedMode AM) {
8134   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8135   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8136   // Don't propagate the invariant or dereferenceable flags.
8137   auto MMOFlags =
8138       LD->getMemOperand()->getFlags() &
8139       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8140   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8141                    LD->getChain(), Base, Offset, LD->getMask(),
8142                    LD->getVectorLength(), LD->getPointerInfo(),
8143                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8144                    nullptr, LD->isExpandingLoad());
8145 }
8146 
8147 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8148                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8149                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8150                                  ISD::MemIndexedMode AM, bool IsTruncating,
8151                                  bool IsCompressing) {
8152   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8153   bool Indexed = AM != ISD::UNINDEXED;
8154   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8155   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8156                          : getVTList(MVT::Other);
8157   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8158   FoldingSetNodeID ID;
8159   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8160   ID.AddInteger(MemVT.getRawBits());
8161   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8162       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8163   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8164   ID.AddInteger(MMO->getFlags());
8165   void *IP = nullptr;
8166   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8167     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8168     return SDValue(E, 0);
8169   }
8170   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8171                                      IsTruncating, IsCompressing, MemVT, MMO);
8172   createOperands(N, Ops);
8173 
8174   CSEMap.InsertNode(N, IP);
8175   InsertNode(N);
8176   SDValue V(N, 0);
8177   NewSDValueDbgMsg(V, "Creating new node: ", this);
8178   return V;
8179 }
8180 
8181 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8182                                       SDValue Val, SDValue Ptr, SDValue Mask,
8183                                       SDValue EVL, MachinePointerInfo PtrInfo,
8184                                       EVT SVT, Align Alignment,
8185                                       MachineMemOperand::Flags MMOFlags,
8186                                       const AAMDNodes &AAInfo,
8187                                       bool IsCompressing) {
8188   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8189 
8190   MMOFlags |= MachineMemOperand::MOStore;
8191   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8192 
8193   if (PtrInfo.V.isNull())
8194     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8195 
8196   MachineFunction &MF = getMachineFunction();
8197   MachineMemOperand *MMO = MF.getMachineMemOperand(
8198       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8199       Alignment, AAInfo);
8200   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8201                          IsCompressing);
8202 }
8203 
8204 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8205                                       SDValue Val, SDValue Ptr, SDValue Mask,
8206                                       SDValue EVL, EVT SVT,
8207                                       MachineMemOperand *MMO,
8208                                       bool IsCompressing) {
8209   EVT VT = Val.getValueType();
8210 
8211   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8212   if (VT == SVT)
8213     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8214                       EVL, VT, MMO, ISD::UNINDEXED,
8215                       /*IsTruncating*/ false, IsCompressing);
8216 
8217   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8218          "Should only be a truncating store, not extending!");
8219   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8220   assert(VT.isVector() == SVT.isVector() &&
8221          "Cannot use trunc store to convert to or from a vector!");
8222   assert((!VT.isVector() ||
8223           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8224          "Cannot use trunc store to change the number of vector elements!");
8225 
8226   SDVTList VTs = getVTList(MVT::Other);
8227   SDValue Undef = getUNDEF(Ptr.getValueType());
8228   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8229   FoldingSetNodeID ID;
8230   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8231   ID.AddInteger(SVT.getRawBits());
8232   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8233       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8234   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8235   ID.AddInteger(MMO->getFlags());
8236   void *IP = nullptr;
8237   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8238     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8239     return SDValue(E, 0);
8240   }
8241   auto *N =
8242       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8243                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8244   createOperands(N, Ops);
8245 
8246   CSEMap.InsertNode(N, IP);
8247   InsertNode(N);
8248   SDValue V(N, 0);
8249   NewSDValueDbgMsg(V, "Creating new node: ", this);
8250   return V;
8251 }
8252 
8253 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8254                                         SDValue Base, SDValue Offset,
8255                                         ISD::MemIndexedMode AM) {
8256   auto *ST = cast<VPStoreSDNode>(OrigStore);
8257   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8258   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8259   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8260                    Offset,         ST->getMask(),  ST->getVectorLength()};
8261   FoldingSetNodeID ID;
8262   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8263   ID.AddInteger(ST->getMemoryVT().getRawBits());
8264   ID.AddInteger(ST->getRawSubclassData());
8265   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8266   ID.AddInteger(ST->getMemOperand()->getFlags());
8267   void *IP = nullptr;
8268   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8269     return SDValue(E, 0);
8270 
8271   auto *N = newSDNode<VPStoreSDNode>(
8272       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8273       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8274   createOperands(N, Ops);
8275 
8276   CSEMap.InsertNode(N, IP);
8277   InsertNode(N);
8278   SDValue V(N, 0);
8279   NewSDValueDbgMsg(V, "Creating new node: ", this);
8280   return V;
8281 }
8282 
8283 SDValue SelectionDAG::getStridedLoadVP(
8284     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8285     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8286     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8287     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8288     const MDNode *Ranges, bool IsExpanding) {
8289   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8290 
8291   MMOFlags |= MachineMemOperand::MOLoad;
8292   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8293   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8294   // clients.
8295   if (PtrInfo.V.isNull())
8296     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8297 
8298   uint64_t Size = MemoryLocation::UnknownSize;
8299   MachineFunction &MF = getMachineFunction();
8300   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8301                                                    Alignment, AAInfo, Ranges);
8302   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8303                           EVL, MemVT, MMO, IsExpanding);
8304 }
8305 
8306 SDValue SelectionDAG::getStridedLoadVP(
8307     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8308     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8309     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8310   bool Indexed = AM != ISD::UNINDEXED;
8311   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8312 
8313   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8314   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8315                          : getVTList(VT, MVT::Other);
8316   FoldingSetNodeID ID;
8317   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8318   ID.AddInteger(VT.getRawBits());
8319   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8320       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8321   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8322 
8323   void *IP = nullptr;
8324   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8325     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8326     return SDValue(E, 0);
8327   }
8328 
8329   auto *N =
8330       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8331                                      ExtType, IsExpanding, MemVT, MMO);
8332   createOperands(N, Ops);
8333   CSEMap.InsertNode(N, IP);
8334   InsertNode(N);
8335   SDValue V(N, 0);
8336   NewSDValueDbgMsg(V, "Creating new node: ", this);
8337   return V;
8338 }
8339 
8340 SDValue SelectionDAG::getStridedLoadVP(
8341     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8342     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8343     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8344     const MDNode *Ranges, bool IsExpanding) {
8345   SDValue Undef = getUNDEF(Ptr.getValueType());
8346   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8347                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8348                           MMOFlags, AAInfo, Ranges, IsExpanding);
8349 }
8350 
8351 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8352                                        SDValue Ptr, SDValue Stride,
8353                                        SDValue Mask, SDValue EVL,
8354                                        MachineMemOperand *MMO,
8355                                        bool IsExpanding) {
8356   SDValue Undef = getUNDEF(Ptr.getValueType());
8357   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8358                           Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8359 }
8360 
8361 SDValue SelectionDAG::getExtStridedLoadVP(
8362     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8363     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8364     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8365     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8366     bool IsExpanding) {
8367   SDValue Undef = getUNDEF(Ptr.getValueType());
8368   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8369                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8370                           MMOFlags, AAInfo, nullptr, IsExpanding);
8371 }
8372 
8373 SDValue SelectionDAG::getExtStridedLoadVP(
8374     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8375     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8376     MachineMemOperand *MMO, bool IsExpanding) {
8377   SDValue Undef = getUNDEF(Ptr.getValueType());
8378   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8379                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8380 }
8381 
8382 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8383                                               SDValue Base, SDValue Offset,
8384                                               ISD::MemIndexedMode AM) {
8385   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8386   assert(SLD->getOffset().isUndef() &&
8387          "Strided load is already a indexed load!");
8388   // Don't propagate the invariant or dereferenceable flags.
8389   auto MMOFlags =
8390       SLD->getMemOperand()->getFlags() &
8391       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8392   return getStridedLoadVP(
8393       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8394       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8395       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8396       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8397 }
8398 
8399 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8400                                         SDValue Val, SDValue Ptr,
8401                                         SDValue Offset, SDValue Stride,
8402                                         SDValue Mask, SDValue EVL, EVT MemVT,
8403                                         MachineMemOperand *MMO,
8404                                         ISD::MemIndexedMode AM,
8405                                         bool IsTruncating, bool IsCompressing) {
8406   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8407   bool Indexed = AM != ISD::UNINDEXED;
8408   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8409   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8410                          : getVTList(MVT::Other);
8411   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8412   FoldingSetNodeID ID;
8413   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8414   ID.AddInteger(MemVT.getRawBits());
8415   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8416       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8417   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8418   void *IP = nullptr;
8419   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8420     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8421     return SDValue(E, 0);
8422   }
8423   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8424                                             VTs, AM, IsTruncating,
8425                                             IsCompressing, MemVT, MMO);
8426   createOperands(N, Ops);
8427 
8428   CSEMap.InsertNode(N, IP);
8429   InsertNode(N);
8430   SDValue V(N, 0);
8431   NewSDValueDbgMsg(V, "Creating new node: ", this);
8432   return V;
8433 }
8434 
8435 SDValue SelectionDAG::getTruncStridedStoreVP(
8436     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8437     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8438     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8439     bool IsCompressing) {
8440   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8441 
8442   MMOFlags |= MachineMemOperand::MOStore;
8443   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8444 
8445   if (PtrInfo.V.isNull())
8446     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8447 
8448   MachineFunction &MF = getMachineFunction();
8449   MachineMemOperand *MMO = MF.getMachineMemOperand(
8450       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8451   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8452                                 MMO, IsCompressing);
8453 }
8454 
8455 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8456                                              SDValue Val, SDValue Ptr,
8457                                              SDValue Stride, SDValue Mask,
8458                                              SDValue EVL, EVT SVT,
8459                                              MachineMemOperand *MMO,
8460                                              bool IsCompressing) {
8461   EVT VT = Val.getValueType();
8462 
8463   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8464   if (VT == SVT)
8465     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8466                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8467                              /*IsTruncating*/ false, IsCompressing);
8468 
8469   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8470          "Should only be a truncating store, not extending!");
8471   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8472   assert(VT.isVector() == SVT.isVector() &&
8473          "Cannot use trunc store to convert to or from a vector!");
8474   assert((!VT.isVector() ||
8475           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8476          "Cannot use trunc store to change the number of vector elements!");
8477 
8478   SDVTList VTs = getVTList(MVT::Other);
8479   SDValue Undef = getUNDEF(Ptr.getValueType());
8480   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8481   FoldingSetNodeID ID;
8482   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8483   ID.AddInteger(SVT.getRawBits());
8484   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8485       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8486   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8487   void *IP = nullptr;
8488   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8489     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8490     return SDValue(E, 0);
8491   }
8492   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8493                                             VTs, ISD::UNINDEXED, true,
8494                                             IsCompressing, SVT, MMO);
8495   createOperands(N, Ops);
8496 
8497   CSEMap.InsertNode(N, IP);
8498   InsertNode(N);
8499   SDValue V(N, 0);
8500   NewSDValueDbgMsg(V, "Creating new node: ", this);
8501   return V;
8502 }
8503 
8504 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8505                                                const SDLoc &DL, SDValue Base,
8506                                                SDValue Offset,
8507                                                ISD::MemIndexedMode AM) {
8508   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8509   assert(SST->getOffset().isUndef() &&
8510          "Strided store is already an indexed store!");
8511   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8512   SDValue Ops[] = {
8513       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8514       SST->getMask(),  SST->getVectorLength()};
8515   FoldingSetNodeID ID;
8516   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8517   ID.AddInteger(SST->getMemoryVT().getRawBits());
8518   ID.AddInteger(SST->getRawSubclassData());
8519   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8520   void *IP = nullptr;
8521   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8522     return SDValue(E, 0);
8523 
8524   auto *N = newSDNode<VPStridedStoreSDNode>(
8525       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8526       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8527   createOperands(N, Ops);
8528 
8529   CSEMap.InsertNode(N, IP);
8530   InsertNode(N);
8531   SDValue V(N, 0);
8532   NewSDValueDbgMsg(V, "Creating new node: ", this);
8533   return V;
8534 }
8535 
8536 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8537                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8538                                   ISD::MemIndexType IndexType) {
8539   assert(Ops.size() == 6 && "Incompatible number of operands");
8540 
8541   FoldingSetNodeID ID;
8542   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8543   ID.AddInteger(VT.getRawBits());
8544   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8545       dl.getIROrder(), VTs, VT, MMO, IndexType));
8546   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8547   ID.AddInteger(MMO->getFlags());
8548   void *IP = nullptr;
8549   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8550     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8551     return SDValue(E, 0);
8552   }
8553 
8554   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8555                                       VT, MMO, IndexType);
8556   createOperands(N, Ops);
8557 
8558   assert(N->getMask().getValueType().getVectorElementCount() ==
8559              N->getValueType(0).getVectorElementCount() &&
8560          "Vector width mismatch between mask and data");
8561   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8562              N->getValueType(0).getVectorElementCount().isScalable() &&
8563          "Scalable flags of index and data do not match");
8564   assert(ElementCount::isKnownGE(
8565              N->getIndex().getValueType().getVectorElementCount(),
8566              N->getValueType(0).getVectorElementCount()) &&
8567          "Vector width mismatch between index and data");
8568   assert(isa<ConstantSDNode>(N->getScale()) &&
8569          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8570          "Scale should be a constant power of 2");
8571 
8572   CSEMap.InsertNode(N, IP);
8573   InsertNode(N);
8574   SDValue V(N, 0);
8575   NewSDValueDbgMsg(V, "Creating new node: ", this);
8576   return V;
8577 }
8578 
8579 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8580                                    ArrayRef<SDValue> Ops,
8581                                    MachineMemOperand *MMO,
8582                                    ISD::MemIndexType IndexType) {
8583   assert(Ops.size() == 7 && "Incompatible number of operands");
8584 
8585   FoldingSetNodeID ID;
8586   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8587   ID.AddInteger(VT.getRawBits());
8588   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8589       dl.getIROrder(), VTs, VT, MMO, IndexType));
8590   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8591   ID.AddInteger(MMO->getFlags());
8592   void *IP = nullptr;
8593   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8594     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8595     return SDValue(E, 0);
8596   }
8597   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8598                                        VT, MMO, IndexType);
8599   createOperands(N, Ops);
8600 
8601   assert(N->getMask().getValueType().getVectorElementCount() ==
8602              N->getValue().getValueType().getVectorElementCount() &&
8603          "Vector width mismatch between mask and data");
8604   assert(
8605       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8606           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8607       "Scalable flags of index and data do not match");
8608   assert(ElementCount::isKnownGE(
8609              N->getIndex().getValueType().getVectorElementCount(),
8610              N->getValue().getValueType().getVectorElementCount()) &&
8611          "Vector width mismatch between index and data");
8612   assert(isa<ConstantSDNode>(N->getScale()) &&
8613          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8614          "Scale should be a constant power of 2");
8615 
8616   CSEMap.InsertNode(N, IP);
8617   InsertNode(N);
8618   SDValue V(N, 0);
8619   NewSDValueDbgMsg(V, "Creating new node: ", this);
8620   return V;
8621 }
8622 
8623 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8624                                     SDValue Base, SDValue Offset, SDValue Mask,
8625                                     SDValue PassThru, EVT MemVT,
8626                                     MachineMemOperand *MMO,
8627                                     ISD::MemIndexedMode AM,
8628                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8629   bool Indexed = AM != ISD::UNINDEXED;
8630   assert((Indexed || Offset.isUndef()) &&
8631          "Unindexed masked load with an offset!");
8632   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8633                          : getVTList(VT, MVT::Other);
8634   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8635   FoldingSetNodeID ID;
8636   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8637   ID.AddInteger(MemVT.getRawBits());
8638   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8639       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8640   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8641   ID.AddInteger(MMO->getFlags());
8642   void *IP = nullptr;
8643   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8644     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8645     return SDValue(E, 0);
8646   }
8647   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8648                                         AM, ExtTy, isExpanding, MemVT, MMO);
8649   createOperands(N, Ops);
8650 
8651   CSEMap.InsertNode(N, IP);
8652   InsertNode(N);
8653   SDValue V(N, 0);
8654   NewSDValueDbgMsg(V, "Creating new node: ", this);
8655   return V;
8656 }
8657 
8658 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8659                                            SDValue Base, SDValue Offset,
8660                                            ISD::MemIndexedMode AM) {
8661   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8662   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8663   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8664                        Offset, LD->getMask(), LD->getPassThru(),
8665                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8666                        LD->getExtensionType(), LD->isExpandingLoad());
8667 }
8668 
8669 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8670                                      SDValue Val, SDValue Base, SDValue Offset,
8671                                      SDValue Mask, EVT MemVT,
8672                                      MachineMemOperand *MMO,
8673                                      ISD::MemIndexedMode AM, bool IsTruncating,
8674                                      bool IsCompressing) {
8675   assert(Chain.getValueType() == MVT::Other &&
8676         "Invalid chain type");
8677   bool Indexed = AM != ISD::UNINDEXED;
8678   assert((Indexed || Offset.isUndef()) &&
8679          "Unindexed masked store with an offset!");
8680   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8681                          : getVTList(MVT::Other);
8682   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8683   FoldingSetNodeID ID;
8684   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8685   ID.AddInteger(MemVT.getRawBits());
8686   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8687       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8688   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8689   ID.AddInteger(MMO->getFlags());
8690   void *IP = nullptr;
8691   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8692     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8693     return SDValue(E, 0);
8694   }
8695   auto *N =
8696       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8697                                    IsTruncating, IsCompressing, MemVT, MMO);
8698   createOperands(N, Ops);
8699 
8700   CSEMap.InsertNode(N, IP);
8701   InsertNode(N);
8702   SDValue V(N, 0);
8703   NewSDValueDbgMsg(V, "Creating new node: ", this);
8704   return V;
8705 }
8706 
8707 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8708                                             SDValue Base, SDValue Offset,
8709                                             ISD::MemIndexedMode AM) {
8710   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8711   assert(ST->getOffset().isUndef() &&
8712          "Masked store is already a indexed store!");
8713   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8714                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8715                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8716 }
8717 
8718 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8719                                       ArrayRef<SDValue> Ops,
8720                                       MachineMemOperand *MMO,
8721                                       ISD::MemIndexType IndexType,
8722                                       ISD::LoadExtType ExtTy) {
8723   assert(Ops.size() == 6 && "Incompatible number of operands");
8724 
8725   FoldingSetNodeID ID;
8726   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8727   ID.AddInteger(MemVT.getRawBits());
8728   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8729       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8730   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8731   ID.AddInteger(MMO->getFlags());
8732   void *IP = nullptr;
8733   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8734     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8735     return SDValue(E, 0);
8736   }
8737 
8738   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8739                                           VTs, MemVT, MMO, IndexType, ExtTy);
8740   createOperands(N, Ops);
8741 
8742   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8743          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8744   assert(N->getMask().getValueType().getVectorElementCount() ==
8745              N->getValueType(0).getVectorElementCount() &&
8746          "Vector width mismatch between mask and data");
8747   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8748              N->getValueType(0).getVectorElementCount().isScalable() &&
8749          "Scalable flags of index and data do not match");
8750   assert(ElementCount::isKnownGE(
8751              N->getIndex().getValueType().getVectorElementCount(),
8752              N->getValueType(0).getVectorElementCount()) &&
8753          "Vector width mismatch between index and data");
8754   assert(isa<ConstantSDNode>(N->getScale()) &&
8755          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8756          "Scale should be a constant power of 2");
8757 
8758   CSEMap.InsertNode(N, IP);
8759   InsertNode(N);
8760   SDValue V(N, 0);
8761   NewSDValueDbgMsg(V, "Creating new node: ", this);
8762   return V;
8763 }
8764 
8765 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8766                                        ArrayRef<SDValue> Ops,
8767                                        MachineMemOperand *MMO,
8768                                        ISD::MemIndexType IndexType,
8769                                        bool IsTrunc) {
8770   assert(Ops.size() == 6 && "Incompatible number of operands");
8771 
8772   FoldingSetNodeID ID;
8773   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8774   ID.AddInteger(MemVT.getRawBits());
8775   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8776       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8777   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8778   ID.AddInteger(MMO->getFlags());
8779   void *IP = nullptr;
8780   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8781     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8782     return SDValue(E, 0);
8783   }
8784 
8785   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8786                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8787   createOperands(N, Ops);
8788 
8789   assert(N->getMask().getValueType().getVectorElementCount() ==
8790              N->getValue().getValueType().getVectorElementCount() &&
8791          "Vector width mismatch between mask and data");
8792   assert(
8793       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8794           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8795       "Scalable flags of index and data do not match");
8796   assert(ElementCount::isKnownGE(
8797              N->getIndex().getValueType().getVectorElementCount(),
8798              N->getValue().getValueType().getVectorElementCount()) &&
8799          "Vector width mismatch between index and data");
8800   assert(isa<ConstantSDNode>(N->getScale()) &&
8801          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8802          "Scale should be a constant power of 2");
8803 
8804   CSEMap.InsertNode(N, IP);
8805   InsertNode(N);
8806   SDValue V(N, 0);
8807   NewSDValueDbgMsg(V, "Creating new node: ", this);
8808   return V;
8809 }
8810 
8811 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8812   // select undef, T, F --> T (if T is a constant), otherwise F
8813   // select, ?, undef, F --> F
8814   // select, ?, T, undef --> T
8815   if (Cond.isUndef())
8816     return isConstantValueOfAnyType(T) ? T : F;
8817   if (T.isUndef())
8818     return F;
8819   if (F.isUndef())
8820     return T;
8821 
8822   // select true, T, F --> T
8823   // select false, T, F --> F
8824   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8825     return CondC->isZero() ? F : T;
8826 
8827   // TODO: This should simplify VSELECT with constant condition using something
8828   // like this (but check boolean contents to be complete?):
8829   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8830   //    return T;
8831   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8832   //    return F;
8833 
8834   // select ?, T, T --> T
8835   if (T == F)
8836     return T;
8837 
8838   return SDValue();
8839 }
8840 
8841 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8842   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8843   if (X.isUndef())
8844     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8845   // shift X, undef --> undef (because it may shift by the bitwidth)
8846   if (Y.isUndef())
8847     return getUNDEF(X.getValueType());
8848 
8849   // shift 0, Y --> 0
8850   // shift X, 0 --> X
8851   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8852     return X;
8853 
8854   // shift X, C >= bitwidth(X) --> undef
8855   // All vector elements must be too big (or undef) to avoid partial undefs.
8856   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8857     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8858   };
8859   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8860     return getUNDEF(X.getValueType());
8861 
8862   return SDValue();
8863 }
8864 
8865 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8866                                       SDNodeFlags Flags) {
8867   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8868   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8869   // operation is poison. That result can be relaxed to undef.
8870   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8871   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8872   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8873                 (YC && YC->getValueAPF().isNaN());
8874   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8875                 (YC && YC->getValueAPF().isInfinity());
8876 
8877   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8878     return getUNDEF(X.getValueType());
8879 
8880   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8881     return getUNDEF(X.getValueType());
8882 
8883   if (!YC)
8884     return SDValue();
8885 
8886   // X + -0.0 --> X
8887   if (Opcode == ISD::FADD)
8888     if (YC->getValueAPF().isNegZero())
8889       return X;
8890 
8891   // X - +0.0 --> X
8892   if (Opcode == ISD::FSUB)
8893     if (YC->getValueAPF().isPosZero())
8894       return X;
8895 
8896   // X * 1.0 --> X
8897   // X / 1.0 --> X
8898   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8899     if (YC->getValueAPF().isExactlyValue(1.0))
8900       return X;
8901 
8902   // X * 0.0 --> 0.0
8903   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8904     if (YC->getValueAPF().isZero())
8905       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8906 
8907   return SDValue();
8908 }
8909 
8910 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8911                                SDValue Ptr, SDValue SV, unsigned Align) {
8912   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8913   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8914 }
8915 
8916 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8917                               ArrayRef<SDUse> Ops) {
8918   switch (Ops.size()) {
8919   case 0: return getNode(Opcode, DL, VT);
8920   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8921   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8922   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8923   default: break;
8924   }
8925 
8926   // Copy from an SDUse array into an SDValue array for use with
8927   // the regular getNode logic.
8928   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8929   return getNode(Opcode, DL, VT, NewOps);
8930 }
8931 
8932 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8933                               ArrayRef<SDValue> Ops) {
8934   SDNodeFlags Flags;
8935   if (Inserter)
8936     Flags = Inserter->getFlags();
8937   return getNode(Opcode, DL, VT, Ops, Flags);
8938 }
8939 
8940 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8941                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8942   unsigned NumOps = Ops.size();
8943   switch (NumOps) {
8944   case 0: return getNode(Opcode, DL, VT);
8945   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8946   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8947   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8948   default: break;
8949   }
8950 
8951 #ifndef NDEBUG
8952   for (const auto &Op : Ops)
8953     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8954            "Operand is DELETED_NODE!");
8955 #endif
8956 
8957   switch (Opcode) {
8958   default: break;
8959   case ISD::BUILD_VECTOR:
8960     // Attempt to simplify BUILD_VECTOR.
8961     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8962       return V;
8963     break;
8964   case ISD::CONCAT_VECTORS:
8965     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8966       return V;
8967     break;
8968   case ISD::SELECT_CC:
8969     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8970     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8971            "LHS and RHS of condition must have same type!");
8972     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8973            "True and False arms of SelectCC must have same type!");
8974     assert(Ops[2].getValueType() == VT &&
8975            "select_cc node must be of same type as true and false value!");
8976     assert((!Ops[0].getValueType().isVector() ||
8977             Ops[0].getValueType().getVectorElementCount() ==
8978                 VT.getVectorElementCount()) &&
8979            "Expected select_cc with vector result to have the same sized "
8980            "comparison type!");
8981     break;
8982   case ISD::BR_CC:
8983     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8984     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8985            "LHS/RHS of comparison should match types!");
8986     break;
8987   case ISD::VP_ADD:
8988   case ISD::VP_SUB:
8989     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8990     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8991       Opcode = ISD::VP_XOR;
8992     break;
8993   case ISD::VP_MUL:
8994     // If it is VP_MUL mask operation then turn it to VP_AND
8995     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8996       Opcode = ISD::VP_AND;
8997     break;
8998   case ISD::VP_REDUCE_MUL:
8999     // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
9000     if (VT == MVT::i1)
9001       Opcode = ISD::VP_REDUCE_AND;
9002     break;
9003   case ISD::VP_REDUCE_ADD:
9004     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
9005     if (VT == MVT::i1)
9006       Opcode = ISD::VP_REDUCE_XOR;
9007     break;
9008   case ISD::VP_REDUCE_SMAX:
9009   case ISD::VP_REDUCE_UMIN:
9010     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
9011     // VP_REDUCE_AND.
9012     if (VT == MVT::i1)
9013       Opcode = ISD::VP_REDUCE_AND;
9014     break;
9015   case ISD::VP_REDUCE_SMIN:
9016   case ISD::VP_REDUCE_UMAX:
9017     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
9018     // VP_REDUCE_OR.
9019     if (VT == MVT::i1)
9020       Opcode = ISD::VP_REDUCE_OR;
9021     break;
9022   }
9023 
9024   // Memoize nodes.
9025   SDNode *N;
9026   SDVTList VTs = getVTList(VT);
9027 
9028   if (VT != MVT::Glue) {
9029     FoldingSetNodeID ID;
9030     AddNodeIDNode(ID, Opcode, VTs, Ops);
9031     void *IP = nullptr;
9032 
9033     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9034       return SDValue(E, 0);
9035 
9036     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9037     createOperands(N, Ops);
9038 
9039     CSEMap.InsertNode(N, IP);
9040   } else {
9041     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9042     createOperands(N, Ops);
9043   }
9044 
9045   N->setFlags(Flags);
9046   InsertNode(N);
9047   SDValue V(N, 0);
9048   NewSDValueDbgMsg(V, "Creating new node: ", this);
9049   return V;
9050 }
9051 
9052 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9053                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
9054   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
9055 }
9056 
9057 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9058                               ArrayRef<SDValue> Ops) {
9059   SDNodeFlags Flags;
9060   if (Inserter)
9061     Flags = Inserter->getFlags();
9062   return getNode(Opcode, DL, VTList, Ops, Flags);
9063 }
9064 
9065 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9066                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
9067   if (VTList.NumVTs == 1)
9068     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
9069 
9070 #ifndef NDEBUG
9071   for (const auto &Op : Ops)
9072     assert(Op.getOpcode() != ISD::DELETED_NODE &&
9073            "Operand is DELETED_NODE!");
9074 #endif
9075 
9076   switch (Opcode) {
9077   case ISD::SADDO:
9078   case ISD::UADDO:
9079   case ISD::SSUBO:
9080   case ISD::USUBO: {
9081     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9082            "Invalid add/sub overflow op!");
9083     assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
9084            Ops[0].getValueType() == Ops[1].getValueType() &&
9085            Ops[0].getValueType() == VTList.VTs[0] &&
9086            "Binary operator types must match!");
9087     SDValue N1 = Ops[0], N2 = Ops[1];
9088     canonicalizeCommutativeBinop(Opcode, N1, N2);
9089 
9090     // (X +- 0) -> X with zero-overflow.
9091     ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
9092                                                /*AllowTruncation*/ true);
9093     if (N2CV && N2CV->isZero()) {
9094       SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
9095       return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
9096     }
9097     break;
9098   }
9099   case ISD::STRICT_FP_EXTEND:
9100     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9101            "Invalid STRICT_FP_EXTEND!");
9102     assert(VTList.VTs[0].isFloatingPoint() &&
9103            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
9104     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9105            "STRICT_FP_EXTEND result type should be vector iff the operand "
9106            "type is vector!");
9107     assert((!VTList.VTs[0].isVector() ||
9108             VTList.VTs[0].getVectorNumElements() ==
9109             Ops[1].getValueType().getVectorNumElements()) &&
9110            "Vector element count mismatch!");
9111     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
9112            "Invalid fpext node, dst <= src!");
9113     break;
9114   case ISD::STRICT_FP_ROUND:
9115     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
9116     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9117            "STRICT_FP_ROUND result type should be vector iff the operand "
9118            "type is vector!");
9119     assert((!VTList.VTs[0].isVector() ||
9120             VTList.VTs[0].getVectorNumElements() ==
9121             Ops[1].getValueType().getVectorNumElements()) &&
9122            "Vector element count mismatch!");
9123     assert(VTList.VTs[0].isFloatingPoint() &&
9124            Ops[1].getValueType().isFloatingPoint() &&
9125            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
9126            isa<ConstantSDNode>(Ops[2]) &&
9127            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
9128             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
9129            "Invalid STRICT_FP_ROUND!");
9130     break;
9131 #if 0
9132   // FIXME: figure out how to safely handle things like
9133   // int foo(int x) { return 1 << (x & 255); }
9134   // int bar() { return foo(256); }
9135   case ISD::SRA_PARTS:
9136   case ISD::SRL_PARTS:
9137   case ISD::SHL_PARTS:
9138     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
9139         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
9140       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9141     else if (N3.getOpcode() == ISD::AND)
9142       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9143         // If the and is only masking out bits that cannot effect the shift,
9144         // eliminate the and.
9145         unsigned NumBits = VT.getScalarSizeInBits()*2;
9146         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9147           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9148       }
9149     break;
9150 #endif
9151   }
9152 
9153   // Memoize the node unless it returns a flag.
9154   SDNode *N;
9155   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9156     FoldingSetNodeID ID;
9157     AddNodeIDNode(ID, Opcode, VTList, Ops);
9158     void *IP = nullptr;
9159     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9160       return SDValue(E, 0);
9161 
9162     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9163     createOperands(N, Ops);
9164     CSEMap.InsertNode(N, IP);
9165   } else {
9166     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9167     createOperands(N, Ops);
9168   }
9169 
9170   N->setFlags(Flags);
9171   InsertNode(N);
9172   SDValue V(N, 0);
9173   NewSDValueDbgMsg(V, "Creating new node: ", this);
9174   return V;
9175 }
9176 
9177 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9178                               SDVTList VTList) {
9179   return getNode(Opcode, DL, VTList, None);
9180 }
9181 
9182 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9183                               SDValue N1) {
9184   SDValue Ops[] = { N1 };
9185   return getNode(Opcode, DL, VTList, Ops);
9186 }
9187 
9188 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9189                               SDValue N1, SDValue N2) {
9190   SDValue Ops[] = { N1, N2 };
9191   return getNode(Opcode, DL, VTList, Ops);
9192 }
9193 
9194 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9195                               SDValue N1, SDValue N2, SDValue N3) {
9196   SDValue Ops[] = { N1, N2, N3 };
9197   return getNode(Opcode, DL, VTList, Ops);
9198 }
9199 
9200 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9201                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9202   SDValue Ops[] = { N1, N2, N3, N4 };
9203   return getNode(Opcode, DL, VTList, Ops);
9204 }
9205 
9206 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9207                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9208                               SDValue N5) {
9209   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9210   return getNode(Opcode, DL, VTList, Ops);
9211 }
9212 
9213 SDVTList SelectionDAG::getVTList(EVT VT) {
9214   return makeVTList(SDNode::getValueTypeList(VT), 1);
9215 }
9216 
9217 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9218   FoldingSetNodeID ID;
9219   ID.AddInteger(2U);
9220   ID.AddInteger(VT1.getRawBits());
9221   ID.AddInteger(VT2.getRawBits());
9222 
9223   void *IP = nullptr;
9224   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9225   if (!Result) {
9226     EVT *Array = Allocator.Allocate<EVT>(2);
9227     Array[0] = VT1;
9228     Array[1] = VT2;
9229     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9230     VTListMap.InsertNode(Result, IP);
9231   }
9232   return Result->getSDVTList();
9233 }
9234 
9235 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9236   FoldingSetNodeID ID;
9237   ID.AddInteger(3U);
9238   ID.AddInteger(VT1.getRawBits());
9239   ID.AddInteger(VT2.getRawBits());
9240   ID.AddInteger(VT3.getRawBits());
9241 
9242   void *IP = nullptr;
9243   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9244   if (!Result) {
9245     EVT *Array = Allocator.Allocate<EVT>(3);
9246     Array[0] = VT1;
9247     Array[1] = VT2;
9248     Array[2] = VT3;
9249     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9250     VTListMap.InsertNode(Result, IP);
9251   }
9252   return Result->getSDVTList();
9253 }
9254 
9255 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9256   FoldingSetNodeID ID;
9257   ID.AddInteger(4U);
9258   ID.AddInteger(VT1.getRawBits());
9259   ID.AddInteger(VT2.getRawBits());
9260   ID.AddInteger(VT3.getRawBits());
9261   ID.AddInteger(VT4.getRawBits());
9262 
9263   void *IP = nullptr;
9264   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9265   if (!Result) {
9266     EVT *Array = Allocator.Allocate<EVT>(4);
9267     Array[0] = VT1;
9268     Array[1] = VT2;
9269     Array[2] = VT3;
9270     Array[3] = VT4;
9271     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9272     VTListMap.InsertNode(Result, IP);
9273   }
9274   return Result->getSDVTList();
9275 }
9276 
9277 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9278   unsigned NumVTs = VTs.size();
9279   FoldingSetNodeID ID;
9280   ID.AddInteger(NumVTs);
9281   for (unsigned index = 0; index < NumVTs; index++) {
9282     ID.AddInteger(VTs[index].getRawBits());
9283   }
9284 
9285   void *IP = nullptr;
9286   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9287   if (!Result) {
9288     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9289     llvm::copy(VTs, Array);
9290     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9291     VTListMap.InsertNode(Result, IP);
9292   }
9293   return Result->getSDVTList();
9294 }
9295 
9296 
9297 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9298 /// specified operands.  If the resultant node already exists in the DAG,
9299 /// this does not modify the specified node, instead it returns the node that
9300 /// already exists.  If the resultant node does not exist in the DAG, the
9301 /// input node is returned.  As a degenerate case, if you specify the same
9302 /// input operands as the node already has, the input node is returned.
9303 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9304   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9305 
9306   // Check to see if there is no change.
9307   if (Op == N->getOperand(0)) return N;
9308 
9309   // See if the modified node already exists.
9310   void *InsertPos = nullptr;
9311   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9312     return Existing;
9313 
9314   // Nope it doesn't.  Remove the node from its current place in the maps.
9315   if (InsertPos)
9316     if (!RemoveNodeFromCSEMaps(N))
9317       InsertPos = nullptr;
9318 
9319   // Now we update the operands.
9320   N->OperandList[0].set(Op);
9321 
9322   updateDivergence(N);
9323   // If this gets put into a CSE map, add it.
9324   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9325   return N;
9326 }
9327 
9328 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9329   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9330 
9331   // Check to see if there is no change.
9332   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9333     return N;   // No operands changed, just return the input node.
9334 
9335   // See if the modified node already exists.
9336   void *InsertPos = nullptr;
9337   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9338     return Existing;
9339 
9340   // Nope it doesn't.  Remove the node from its current place in the maps.
9341   if (InsertPos)
9342     if (!RemoveNodeFromCSEMaps(N))
9343       InsertPos = nullptr;
9344 
9345   // Now we update the operands.
9346   if (N->OperandList[0] != Op1)
9347     N->OperandList[0].set(Op1);
9348   if (N->OperandList[1] != Op2)
9349     N->OperandList[1].set(Op2);
9350 
9351   updateDivergence(N);
9352   // If this gets put into a CSE map, add it.
9353   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9354   return N;
9355 }
9356 
9357 SDNode *SelectionDAG::
9358 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9359   SDValue Ops[] = { Op1, Op2, Op3 };
9360   return UpdateNodeOperands(N, Ops);
9361 }
9362 
9363 SDNode *SelectionDAG::
9364 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9365                    SDValue Op3, SDValue Op4) {
9366   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9367   return UpdateNodeOperands(N, Ops);
9368 }
9369 
9370 SDNode *SelectionDAG::
9371 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9372                    SDValue Op3, SDValue Op4, SDValue Op5) {
9373   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9374   return UpdateNodeOperands(N, Ops);
9375 }
9376 
9377 SDNode *SelectionDAG::
9378 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9379   unsigned NumOps = Ops.size();
9380   assert(N->getNumOperands() == NumOps &&
9381          "Update with wrong number of operands");
9382 
9383   // If no operands changed just return the input node.
9384   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9385     return N;
9386 
9387   // See if the modified node already exists.
9388   void *InsertPos = nullptr;
9389   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9390     return Existing;
9391 
9392   // Nope it doesn't.  Remove the node from its current place in the maps.
9393   if (InsertPos)
9394     if (!RemoveNodeFromCSEMaps(N))
9395       InsertPos = nullptr;
9396 
9397   // Now we update the operands.
9398   for (unsigned i = 0; i != NumOps; ++i)
9399     if (N->OperandList[i] != Ops[i])
9400       N->OperandList[i].set(Ops[i]);
9401 
9402   updateDivergence(N);
9403   // If this gets put into a CSE map, add it.
9404   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9405   return N;
9406 }
9407 
9408 /// DropOperands - Release the operands and set this node to have
9409 /// zero operands.
9410 void SDNode::DropOperands() {
9411   // Unlike the code in MorphNodeTo that does this, we don't need to
9412   // watch for dead nodes here.
9413   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9414     SDUse &Use = *I++;
9415     Use.set(SDValue());
9416   }
9417 }
9418 
9419 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9420                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9421   if (NewMemRefs.empty()) {
9422     N->clearMemRefs();
9423     return;
9424   }
9425 
9426   // Check if we can avoid allocating by storing a single reference directly.
9427   if (NewMemRefs.size() == 1) {
9428     N->MemRefs = NewMemRefs[0];
9429     N->NumMemRefs = 1;
9430     return;
9431   }
9432 
9433   MachineMemOperand **MemRefsBuffer =
9434       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9435   llvm::copy(NewMemRefs, MemRefsBuffer);
9436   N->MemRefs = MemRefsBuffer;
9437   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9438 }
9439 
9440 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9441 /// machine opcode.
9442 ///
9443 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9444                                    EVT VT) {
9445   SDVTList VTs = getVTList(VT);
9446   return SelectNodeTo(N, MachineOpc, VTs, None);
9447 }
9448 
9449 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9450                                    EVT VT, SDValue Op1) {
9451   SDVTList VTs = getVTList(VT);
9452   SDValue Ops[] = { Op1 };
9453   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9454 }
9455 
9456 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9457                                    EVT VT, SDValue Op1,
9458                                    SDValue Op2) {
9459   SDVTList VTs = getVTList(VT);
9460   SDValue Ops[] = { Op1, Op2 };
9461   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9462 }
9463 
9464 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9465                                    EVT VT, SDValue Op1,
9466                                    SDValue Op2, SDValue Op3) {
9467   SDVTList VTs = getVTList(VT);
9468   SDValue Ops[] = { Op1, Op2, Op3 };
9469   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9470 }
9471 
9472 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9473                                    EVT VT, ArrayRef<SDValue> Ops) {
9474   SDVTList VTs = getVTList(VT);
9475   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9476 }
9477 
9478 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9479                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9480   SDVTList VTs = getVTList(VT1, VT2);
9481   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9482 }
9483 
9484 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9485                                    EVT VT1, EVT VT2) {
9486   SDVTList VTs = getVTList(VT1, VT2);
9487   return SelectNodeTo(N, MachineOpc, VTs, None);
9488 }
9489 
9490 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9491                                    EVT VT1, EVT VT2, EVT VT3,
9492                                    ArrayRef<SDValue> Ops) {
9493   SDVTList VTs = getVTList(VT1, VT2, VT3);
9494   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9495 }
9496 
9497 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9498                                    EVT VT1, EVT VT2,
9499                                    SDValue Op1, SDValue Op2) {
9500   SDVTList VTs = getVTList(VT1, VT2);
9501   SDValue Ops[] = { Op1, Op2 };
9502   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9503 }
9504 
9505 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9506                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9507   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9508   // Reset the NodeID to -1.
9509   New->setNodeId(-1);
9510   if (New != N) {
9511     ReplaceAllUsesWith(N, New);
9512     RemoveDeadNode(N);
9513   }
9514   return New;
9515 }
9516 
9517 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9518 /// the line number information on the merged node since it is not possible to
9519 /// preserve the information that operation is associated with multiple lines.
9520 /// This will make the debugger working better at -O0, were there is a higher
9521 /// probability having other instructions associated with that line.
9522 ///
9523 /// For IROrder, we keep the smaller of the two
9524 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9525   DebugLoc NLoc = N->getDebugLoc();
9526   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9527     N->setDebugLoc(DebugLoc());
9528   }
9529   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9530   N->setIROrder(Order);
9531   return N;
9532 }
9533 
9534 /// MorphNodeTo - This *mutates* the specified node to have the specified
9535 /// return type, opcode, and operands.
9536 ///
9537 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9538 /// node of the specified opcode and operands, it returns that node instead of
9539 /// the current one.  Note that the SDLoc need not be the same.
9540 ///
9541 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9542 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9543 /// node, and because it doesn't require CSE recalculation for any of
9544 /// the node's users.
9545 ///
9546 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9547 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9548 /// the legalizer which maintain worklists that would need to be updated when
9549 /// deleting things.
9550 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9551                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9552   // If an identical node already exists, use it.
9553   void *IP = nullptr;
9554   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9555     FoldingSetNodeID ID;
9556     AddNodeIDNode(ID, Opc, VTs, Ops);
9557     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9558       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9559   }
9560 
9561   if (!RemoveNodeFromCSEMaps(N))
9562     IP = nullptr;
9563 
9564   // Start the morphing.
9565   N->NodeType = Opc;
9566   N->ValueList = VTs.VTs;
9567   N->NumValues = VTs.NumVTs;
9568 
9569   // Clear the operands list, updating used nodes to remove this from their
9570   // use list.  Keep track of any operands that become dead as a result.
9571   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9572   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9573     SDUse &Use = *I++;
9574     SDNode *Used = Use.getNode();
9575     Use.set(SDValue());
9576     if (Used->use_empty())
9577       DeadNodeSet.insert(Used);
9578   }
9579 
9580   // For MachineNode, initialize the memory references information.
9581   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9582     MN->clearMemRefs();
9583 
9584   // Swap for an appropriately sized array from the recycler.
9585   removeOperands(N);
9586   createOperands(N, Ops);
9587 
9588   // Delete any nodes that are still dead after adding the uses for the
9589   // new operands.
9590   if (!DeadNodeSet.empty()) {
9591     SmallVector<SDNode *, 16> DeadNodes;
9592     for (SDNode *N : DeadNodeSet)
9593       if (N->use_empty())
9594         DeadNodes.push_back(N);
9595     RemoveDeadNodes(DeadNodes);
9596   }
9597 
9598   if (IP)
9599     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9600   return N;
9601 }
9602 
9603 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9604   unsigned OrigOpc = Node->getOpcode();
9605   unsigned NewOpc;
9606   switch (OrigOpc) {
9607   default:
9608     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9609 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9610   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9611 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9612   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9613 #include "llvm/IR/ConstrainedOps.def"
9614   }
9615 
9616   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9617 
9618   // We're taking this node out of the chain, so we need to re-link things.
9619   SDValue InputChain = Node->getOperand(0);
9620   SDValue OutputChain = SDValue(Node, 1);
9621   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9622 
9623   SmallVector<SDValue, 3> Ops;
9624   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9625     Ops.push_back(Node->getOperand(i));
9626 
9627   SDVTList VTs = getVTList(Node->getValueType(0));
9628   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9629 
9630   // MorphNodeTo can operate in two ways: if an existing node with the
9631   // specified operands exists, it can just return it.  Otherwise, it
9632   // updates the node in place to have the requested operands.
9633   if (Res == Node) {
9634     // If we updated the node in place, reset the node ID.  To the isel,
9635     // this should be just like a newly allocated machine node.
9636     Res->setNodeId(-1);
9637   } else {
9638     ReplaceAllUsesWith(Node, Res);
9639     RemoveDeadNode(Node);
9640   }
9641 
9642   return Res;
9643 }
9644 
9645 /// getMachineNode - These are used for target selectors to create a new node
9646 /// with specified return type(s), MachineInstr opcode, and operands.
9647 ///
9648 /// Note that getMachineNode returns the resultant node.  If there is already a
9649 /// node of the specified opcode and operands, it returns that node instead of
9650 /// the current one.
9651 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9652                                             EVT VT) {
9653   SDVTList VTs = getVTList(VT);
9654   return getMachineNode(Opcode, dl, VTs, None);
9655 }
9656 
9657 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9658                                             EVT VT, SDValue Op1) {
9659   SDVTList VTs = getVTList(VT);
9660   SDValue Ops[] = { Op1 };
9661   return getMachineNode(Opcode, dl, VTs, Ops);
9662 }
9663 
9664 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9665                                             EVT VT, SDValue Op1, SDValue Op2) {
9666   SDVTList VTs = getVTList(VT);
9667   SDValue Ops[] = { Op1, Op2 };
9668   return getMachineNode(Opcode, dl, VTs, Ops);
9669 }
9670 
9671 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9672                                             EVT VT, SDValue Op1, SDValue Op2,
9673                                             SDValue Op3) {
9674   SDVTList VTs = getVTList(VT);
9675   SDValue Ops[] = { Op1, Op2, Op3 };
9676   return getMachineNode(Opcode, dl, VTs, Ops);
9677 }
9678 
9679 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9680                                             EVT VT, ArrayRef<SDValue> Ops) {
9681   SDVTList VTs = getVTList(VT);
9682   return getMachineNode(Opcode, dl, VTs, Ops);
9683 }
9684 
9685 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9686                                             EVT VT1, EVT VT2, SDValue Op1,
9687                                             SDValue Op2) {
9688   SDVTList VTs = getVTList(VT1, VT2);
9689   SDValue Ops[] = { Op1, Op2 };
9690   return getMachineNode(Opcode, dl, VTs, Ops);
9691 }
9692 
9693 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9694                                             EVT VT1, EVT VT2, SDValue Op1,
9695                                             SDValue Op2, SDValue Op3) {
9696   SDVTList VTs = getVTList(VT1, VT2);
9697   SDValue Ops[] = { Op1, Op2, Op3 };
9698   return getMachineNode(Opcode, dl, VTs, Ops);
9699 }
9700 
9701 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9702                                             EVT VT1, EVT VT2,
9703                                             ArrayRef<SDValue> Ops) {
9704   SDVTList VTs = getVTList(VT1, VT2);
9705   return getMachineNode(Opcode, dl, VTs, Ops);
9706 }
9707 
9708 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9709                                             EVT VT1, EVT VT2, EVT VT3,
9710                                             SDValue Op1, SDValue Op2) {
9711   SDVTList VTs = getVTList(VT1, VT2, VT3);
9712   SDValue Ops[] = { Op1, Op2 };
9713   return getMachineNode(Opcode, dl, VTs, Ops);
9714 }
9715 
9716 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9717                                             EVT VT1, EVT VT2, EVT VT3,
9718                                             SDValue Op1, SDValue Op2,
9719                                             SDValue Op3) {
9720   SDVTList VTs = getVTList(VT1, VT2, VT3);
9721   SDValue Ops[] = { Op1, Op2, Op3 };
9722   return getMachineNode(Opcode, dl, VTs, Ops);
9723 }
9724 
9725 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9726                                             EVT VT1, EVT VT2, EVT VT3,
9727                                             ArrayRef<SDValue> Ops) {
9728   SDVTList VTs = getVTList(VT1, VT2, VT3);
9729   return getMachineNode(Opcode, dl, VTs, Ops);
9730 }
9731 
9732 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9733                                             ArrayRef<EVT> ResultTys,
9734                                             ArrayRef<SDValue> Ops) {
9735   SDVTList VTs = getVTList(ResultTys);
9736   return getMachineNode(Opcode, dl, VTs, Ops);
9737 }
9738 
9739 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9740                                             SDVTList VTs,
9741                                             ArrayRef<SDValue> Ops) {
9742   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9743   MachineSDNode *N;
9744   void *IP = nullptr;
9745 
9746   if (DoCSE) {
9747     FoldingSetNodeID ID;
9748     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9749     IP = nullptr;
9750     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9751       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9752     }
9753   }
9754 
9755   // Allocate a new MachineSDNode.
9756   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9757   createOperands(N, Ops);
9758 
9759   if (DoCSE)
9760     CSEMap.InsertNode(N, IP);
9761 
9762   InsertNode(N);
9763   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9764   return N;
9765 }
9766 
9767 /// getTargetExtractSubreg - A convenience function for creating
9768 /// TargetOpcode::EXTRACT_SUBREG nodes.
9769 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9770                                              SDValue Operand) {
9771   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9772   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9773                                   VT, Operand, SRIdxVal);
9774   return SDValue(Subreg, 0);
9775 }
9776 
9777 /// getTargetInsertSubreg - A convenience function for creating
9778 /// TargetOpcode::INSERT_SUBREG nodes.
9779 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9780                                             SDValue Operand, SDValue Subreg) {
9781   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9782   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9783                                   VT, Operand, Subreg, SRIdxVal);
9784   return SDValue(Result, 0);
9785 }
9786 
9787 /// getNodeIfExists - Get the specified node if it's already available, or
9788 /// else return NULL.
9789 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9790                                       ArrayRef<SDValue> Ops) {
9791   SDNodeFlags Flags;
9792   if (Inserter)
9793     Flags = Inserter->getFlags();
9794   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9795 }
9796 
9797 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9798                                       ArrayRef<SDValue> Ops,
9799                                       const SDNodeFlags Flags) {
9800   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9801     FoldingSetNodeID ID;
9802     AddNodeIDNode(ID, Opcode, VTList, Ops);
9803     void *IP = nullptr;
9804     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9805       E->intersectFlagsWith(Flags);
9806       return E;
9807     }
9808   }
9809   return nullptr;
9810 }
9811 
9812 /// doesNodeExist - Check if a node exists without modifying its flags.
9813 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9814                                  ArrayRef<SDValue> Ops) {
9815   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9816     FoldingSetNodeID ID;
9817     AddNodeIDNode(ID, Opcode, VTList, Ops);
9818     void *IP = nullptr;
9819     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9820       return true;
9821   }
9822   return false;
9823 }
9824 
9825 /// getDbgValue - Creates a SDDbgValue node.
9826 ///
9827 /// SDNode
9828 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9829                                       SDNode *N, unsigned R, bool IsIndirect,
9830                                       const DebugLoc &DL, unsigned O) {
9831   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9832          "Expected inlined-at fields to agree");
9833   return new (DbgInfo->getAlloc())
9834       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9835                  {}, IsIndirect, DL, O,
9836                  /*IsVariadic=*/false);
9837 }
9838 
9839 /// Constant
9840 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9841                                               DIExpression *Expr,
9842                                               const Value *C,
9843                                               const DebugLoc &DL, unsigned O) {
9844   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9845          "Expected inlined-at fields to agree");
9846   return new (DbgInfo->getAlloc())
9847       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9848                  /*IsIndirect=*/false, DL, O,
9849                  /*IsVariadic=*/false);
9850 }
9851 
9852 /// FrameIndex
9853 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9854                                                 DIExpression *Expr, unsigned FI,
9855                                                 bool IsIndirect,
9856                                                 const DebugLoc &DL,
9857                                                 unsigned O) {
9858   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9859          "Expected inlined-at fields to agree");
9860   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9861 }
9862 
9863 /// FrameIndex with dependencies
9864 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9865                                                 DIExpression *Expr, unsigned FI,
9866                                                 ArrayRef<SDNode *> Dependencies,
9867                                                 bool IsIndirect,
9868                                                 const DebugLoc &DL,
9869                                                 unsigned O) {
9870   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9871          "Expected inlined-at fields to agree");
9872   return new (DbgInfo->getAlloc())
9873       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9874                  Dependencies, IsIndirect, DL, O,
9875                  /*IsVariadic=*/false);
9876 }
9877 
9878 /// VReg
9879 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9880                                           unsigned VReg, bool IsIndirect,
9881                                           const DebugLoc &DL, unsigned O) {
9882   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9883          "Expected inlined-at fields to agree");
9884   return new (DbgInfo->getAlloc())
9885       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9886                  {}, IsIndirect, DL, O,
9887                  /*IsVariadic=*/false);
9888 }
9889 
9890 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9891                                           ArrayRef<SDDbgOperand> Locs,
9892                                           ArrayRef<SDNode *> Dependencies,
9893                                           bool IsIndirect, const DebugLoc &DL,
9894                                           unsigned O, bool IsVariadic) {
9895   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9896          "Expected inlined-at fields to agree");
9897   return new (DbgInfo->getAlloc())
9898       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9899                  DL, O, IsVariadic);
9900 }
9901 
9902 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9903                                      unsigned OffsetInBits, unsigned SizeInBits,
9904                                      bool InvalidateDbg) {
9905   SDNode *FromNode = From.getNode();
9906   SDNode *ToNode = To.getNode();
9907   assert(FromNode && ToNode && "Can't modify dbg values");
9908 
9909   // PR35338
9910   // TODO: assert(From != To && "Redundant dbg value transfer");
9911   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9912   if (From == To || FromNode == ToNode)
9913     return;
9914 
9915   if (!FromNode->getHasDebugValue())
9916     return;
9917 
9918   SDDbgOperand FromLocOp =
9919       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9920   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9921 
9922   SmallVector<SDDbgValue *, 2> ClonedDVs;
9923   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9924     if (Dbg->isInvalidated())
9925       continue;
9926 
9927     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9928 
9929     // Create a new location ops vector that is equal to the old vector, but
9930     // with each instance of FromLocOp replaced with ToLocOp.
9931     bool Changed = false;
9932     auto NewLocOps = Dbg->copyLocationOps();
9933     std::replace_if(
9934         NewLocOps.begin(), NewLocOps.end(),
9935         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9936           bool Match = Op == FromLocOp;
9937           Changed |= Match;
9938           return Match;
9939         },
9940         ToLocOp);
9941     // Ignore this SDDbgValue if we didn't find a matching location.
9942     if (!Changed)
9943       continue;
9944 
9945     DIVariable *Var = Dbg->getVariable();
9946     auto *Expr = Dbg->getExpression();
9947     // If a fragment is requested, update the expression.
9948     if (SizeInBits) {
9949       // When splitting a larger (e.g., sign-extended) value whose
9950       // lower bits are described with an SDDbgValue, do not attempt
9951       // to transfer the SDDbgValue to the upper bits.
9952       if (auto FI = Expr->getFragmentInfo())
9953         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9954           continue;
9955       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9956                                                              SizeInBits);
9957       if (!Fragment)
9958         continue;
9959       Expr = *Fragment;
9960     }
9961 
9962     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9963     // Clone the SDDbgValue and move it to To.
9964     SDDbgValue *Clone = getDbgValueList(
9965         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9966         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9967         Dbg->isVariadic());
9968     ClonedDVs.push_back(Clone);
9969 
9970     if (InvalidateDbg) {
9971       // Invalidate value and indicate the SDDbgValue should not be emitted.
9972       Dbg->setIsInvalidated();
9973       Dbg->setIsEmitted();
9974     }
9975   }
9976 
9977   for (SDDbgValue *Dbg : ClonedDVs) {
9978     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9979            "Transferred DbgValues should depend on the new SDNode");
9980     AddDbgValue(Dbg, false);
9981   }
9982 }
9983 
9984 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9985   if (!N.getHasDebugValue())
9986     return;
9987 
9988   SmallVector<SDDbgValue *, 2> ClonedDVs;
9989   for (auto *DV : GetDbgValues(&N)) {
9990     if (DV->isInvalidated())
9991       continue;
9992     switch (N.getOpcode()) {
9993     default:
9994       break;
9995     case ISD::ADD:
9996       SDValue N0 = N.getOperand(0);
9997       SDValue N1 = N.getOperand(1);
9998       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9999           isConstantIntBuildVectorOrConstantInt(N1)) {
10000         uint64_t Offset = N.getConstantOperandVal(1);
10001 
10002         // Rewrite an ADD constant node into a DIExpression. Since we are
10003         // performing arithmetic to compute the variable's *value* in the
10004         // DIExpression, we need to mark the expression with a
10005         // DW_OP_stack_value.
10006         auto *DIExpr = DV->getExpression();
10007         auto NewLocOps = DV->copyLocationOps();
10008         bool Changed = false;
10009         for (size_t i = 0; i < NewLocOps.size(); ++i) {
10010           // We're not given a ResNo to compare against because the whole
10011           // node is going away. We know that any ISD::ADD only has one
10012           // result, so we can assume any node match is using the result.
10013           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
10014               NewLocOps[i].getSDNode() != &N)
10015             continue;
10016           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
10017           SmallVector<uint64_t, 3> ExprOps;
10018           DIExpression::appendOffset(ExprOps, Offset);
10019           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
10020           Changed = true;
10021         }
10022         (void)Changed;
10023         assert(Changed && "Salvage target doesn't use N");
10024 
10025         auto AdditionalDependencies = DV->getAdditionalDependencies();
10026         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
10027                                             NewLocOps, AdditionalDependencies,
10028                                             DV->isIndirect(), DV->getDebugLoc(),
10029                                             DV->getOrder(), DV->isVariadic());
10030         ClonedDVs.push_back(Clone);
10031         DV->setIsInvalidated();
10032         DV->setIsEmitted();
10033         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
10034                    N0.getNode()->dumprFull(this);
10035                    dbgs() << " into " << *DIExpr << '\n');
10036       }
10037     }
10038   }
10039 
10040   for (SDDbgValue *Dbg : ClonedDVs) {
10041     assert(!Dbg->getSDNodes().empty() &&
10042            "Salvaged DbgValue should depend on a new SDNode");
10043     AddDbgValue(Dbg, false);
10044   }
10045 }
10046 
10047 /// Creates a SDDbgLabel node.
10048 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
10049                                       const DebugLoc &DL, unsigned O) {
10050   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
10051          "Expected inlined-at fields to agree");
10052   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
10053 }
10054 
10055 namespace {
10056 
10057 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
10058 /// pointed to by a use iterator is deleted, increment the use iterator
10059 /// so that it doesn't dangle.
10060 ///
10061 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
10062   SDNode::use_iterator &UI;
10063   SDNode::use_iterator &UE;
10064 
10065   void NodeDeleted(SDNode *N, SDNode *E) override {
10066     // Increment the iterator as needed.
10067     while (UI != UE && N == *UI)
10068       ++UI;
10069   }
10070 
10071 public:
10072   RAUWUpdateListener(SelectionDAG &d,
10073                      SDNode::use_iterator &ui,
10074                      SDNode::use_iterator &ue)
10075     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
10076 };
10077 
10078 } // end anonymous namespace
10079 
10080 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10081 /// This can cause recursive merging of nodes in the DAG.
10082 ///
10083 /// This version assumes From has a single result value.
10084 ///
10085 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
10086   SDNode *From = FromN.getNode();
10087   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
10088          "Cannot replace with this method!");
10089   assert(From != To.getNode() && "Cannot replace uses of with self");
10090 
10091   // Preserve Debug Values
10092   transferDbgValues(FromN, To);
10093 
10094   // Iterate over all the existing uses of From. New uses will be added
10095   // to the beginning of the use list, which we avoid visiting.
10096   // This specifically avoids visiting uses of From that arise while the
10097   // replacement is happening, because any such uses would be the result
10098   // of CSE: If an existing node looks like From after one of its operands
10099   // is replaced by To, we don't want to replace of all its users with To
10100   // too. See PR3018 for more info.
10101   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10102   RAUWUpdateListener Listener(*this, UI, UE);
10103   while (UI != UE) {
10104     SDNode *User = *UI;
10105 
10106     // This node is about to morph, remove its old self from the CSE maps.
10107     RemoveNodeFromCSEMaps(User);
10108 
10109     // A user can appear in a use list multiple times, and when this
10110     // happens the uses are usually next to each other in the list.
10111     // To help reduce the number of CSE recomputations, process all
10112     // the uses of this user that we can find this way.
10113     do {
10114       SDUse &Use = UI.getUse();
10115       ++UI;
10116       Use.set(To);
10117       if (To->isDivergent() != From->isDivergent())
10118         updateDivergence(User);
10119     } while (UI != UE && *UI == User);
10120     // Now that we have modified User, add it back to the CSE maps.  If it
10121     // already exists there, recursively merge the results together.
10122     AddModifiedNodeToCSEMaps(User);
10123   }
10124 
10125   // If we just RAUW'd the root, take note.
10126   if (FromN == getRoot())
10127     setRoot(To);
10128 }
10129 
10130 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10131 /// This can cause recursive merging of nodes in the DAG.
10132 ///
10133 /// This version assumes that for each value of From, there is a
10134 /// corresponding value in To in the same position with the same type.
10135 ///
10136 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
10137 #ifndef NDEBUG
10138   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10139     assert((!From->hasAnyUseOfValue(i) ||
10140             From->getValueType(i) == To->getValueType(i)) &&
10141            "Cannot use this version of ReplaceAllUsesWith!");
10142 #endif
10143 
10144   // Handle the trivial case.
10145   if (From == To)
10146     return;
10147 
10148   // Preserve Debug Info. Only do this if there's a use.
10149   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10150     if (From->hasAnyUseOfValue(i)) {
10151       assert((i < To->getNumValues()) && "Invalid To location");
10152       transferDbgValues(SDValue(From, i), SDValue(To, i));
10153     }
10154 
10155   // Iterate over just the existing users of From. See the comments in
10156   // the ReplaceAllUsesWith above.
10157   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10158   RAUWUpdateListener Listener(*this, UI, UE);
10159   while (UI != UE) {
10160     SDNode *User = *UI;
10161 
10162     // This node is about to morph, remove its old self from the CSE maps.
10163     RemoveNodeFromCSEMaps(User);
10164 
10165     // A user can appear in a use list multiple times, and when this
10166     // happens the uses are usually next to each other in the list.
10167     // To help reduce the number of CSE recomputations, process all
10168     // the uses of this user that we can find this way.
10169     do {
10170       SDUse &Use = UI.getUse();
10171       ++UI;
10172       Use.setNode(To);
10173       if (To->isDivergent() != From->isDivergent())
10174         updateDivergence(User);
10175     } while (UI != UE && *UI == User);
10176 
10177     // Now that we have modified User, add it back to the CSE maps.  If it
10178     // already exists there, recursively merge the results together.
10179     AddModifiedNodeToCSEMaps(User);
10180   }
10181 
10182   // If we just RAUW'd the root, take note.
10183   if (From == getRoot().getNode())
10184     setRoot(SDValue(To, getRoot().getResNo()));
10185 }
10186 
10187 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10188 /// This can cause recursive merging of nodes in the DAG.
10189 ///
10190 /// This version can replace From with any result values.  To must match the
10191 /// number and types of values returned by From.
10192 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10193   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10194     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10195 
10196   // Preserve Debug Info.
10197   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10198     transferDbgValues(SDValue(From, i), To[i]);
10199 
10200   // Iterate over just the existing users of From. See the comments in
10201   // the ReplaceAllUsesWith above.
10202   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10203   RAUWUpdateListener Listener(*this, UI, UE);
10204   while (UI != UE) {
10205     SDNode *User = *UI;
10206 
10207     // This node is about to morph, remove its old self from the CSE maps.
10208     RemoveNodeFromCSEMaps(User);
10209 
10210     // A user can appear in a use list multiple times, and when this happens the
10211     // uses are usually next to each other in the list.  To help reduce the
10212     // number of CSE and divergence recomputations, process all the uses of this
10213     // user that we can find this way.
10214     bool To_IsDivergent = false;
10215     do {
10216       SDUse &Use = UI.getUse();
10217       const SDValue &ToOp = To[Use.getResNo()];
10218       ++UI;
10219       Use.set(ToOp);
10220       To_IsDivergent |= ToOp->isDivergent();
10221     } while (UI != UE && *UI == User);
10222 
10223     if (To_IsDivergent != From->isDivergent())
10224       updateDivergence(User);
10225 
10226     // Now that we have modified User, add it back to the CSE maps.  If it
10227     // already exists there, recursively merge the results together.
10228     AddModifiedNodeToCSEMaps(User);
10229   }
10230 
10231   // If we just RAUW'd the root, take note.
10232   if (From == getRoot().getNode())
10233     setRoot(SDValue(To[getRoot().getResNo()]));
10234 }
10235 
10236 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10237 /// uses of other values produced by From.getNode() alone.  The Deleted
10238 /// vector is handled the same way as for ReplaceAllUsesWith.
10239 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10240   // Handle the really simple, really trivial case efficiently.
10241   if (From == To) return;
10242 
10243   // Handle the simple, trivial, case efficiently.
10244   if (From.getNode()->getNumValues() == 1) {
10245     ReplaceAllUsesWith(From, To);
10246     return;
10247   }
10248 
10249   // Preserve Debug Info.
10250   transferDbgValues(From, To);
10251 
10252   // Iterate over just the existing users of From. See the comments in
10253   // the ReplaceAllUsesWith above.
10254   SDNode::use_iterator UI = From.getNode()->use_begin(),
10255                        UE = From.getNode()->use_end();
10256   RAUWUpdateListener Listener(*this, UI, UE);
10257   while (UI != UE) {
10258     SDNode *User = *UI;
10259     bool UserRemovedFromCSEMaps = false;
10260 
10261     // A user can appear in a use list multiple times, and when this
10262     // happens the uses are usually next to each other in the list.
10263     // To help reduce the number of CSE recomputations, process all
10264     // the uses of this user that we can find this way.
10265     do {
10266       SDUse &Use = UI.getUse();
10267 
10268       // Skip uses of different values from the same node.
10269       if (Use.getResNo() != From.getResNo()) {
10270         ++UI;
10271         continue;
10272       }
10273 
10274       // If this node hasn't been modified yet, it's still in the CSE maps,
10275       // so remove its old self from the CSE maps.
10276       if (!UserRemovedFromCSEMaps) {
10277         RemoveNodeFromCSEMaps(User);
10278         UserRemovedFromCSEMaps = true;
10279       }
10280 
10281       ++UI;
10282       Use.set(To);
10283       if (To->isDivergent() != From->isDivergent())
10284         updateDivergence(User);
10285     } while (UI != UE && *UI == User);
10286     // We are iterating over all uses of the From node, so if a use
10287     // doesn't use the specific value, no changes are made.
10288     if (!UserRemovedFromCSEMaps)
10289       continue;
10290 
10291     // Now that we have modified User, add it back to the CSE maps.  If it
10292     // already exists there, recursively merge the results together.
10293     AddModifiedNodeToCSEMaps(User);
10294   }
10295 
10296   // If we just RAUW'd the root, take note.
10297   if (From == getRoot())
10298     setRoot(To);
10299 }
10300 
10301 namespace {
10302 
10303 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10304 /// to record information about a use.
10305 struct UseMemo {
10306   SDNode *User;
10307   unsigned Index;
10308   SDUse *Use;
10309 };
10310 
10311 /// operator< - Sort Memos by User.
10312 bool operator<(const UseMemo &L, const UseMemo &R) {
10313   return (intptr_t)L.User < (intptr_t)R.User;
10314 }
10315 
10316 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10317 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10318 /// the node already has been taken care of recursively.
10319 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10320   SmallVector<UseMemo, 4> &Uses;
10321 
10322   void NodeDeleted(SDNode *N, SDNode *E) override {
10323     for (UseMemo &Memo : Uses)
10324       if (Memo.User == N)
10325         Memo.User = nullptr;
10326   }
10327 
10328 public:
10329   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10330       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10331 };
10332 
10333 } // end anonymous namespace
10334 
10335 bool SelectionDAG::calculateDivergence(SDNode *N) {
10336   if (TLI->isSDNodeAlwaysUniform(N)) {
10337     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10338            "Conflicting divergence information!");
10339     return false;
10340   }
10341   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10342     return true;
10343   for (const auto &Op : N->ops()) {
10344     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10345       return true;
10346   }
10347   return false;
10348 }
10349 
10350 void SelectionDAG::updateDivergence(SDNode *N) {
10351   SmallVector<SDNode *, 16> Worklist(1, N);
10352   do {
10353     N = Worklist.pop_back_val();
10354     bool IsDivergent = calculateDivergence(N);
10355     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10356       N->SDNodeBits.IsDivergent = IsDivergent;
10357       llvm::append_range(Worklist, N->uses());
10358     }
10359   } while (!Worklist.empty());
10360 }
10361 
10362 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10363   DenseMap<SDNode *, unsigned> Degree;
10364   Order.reserve(AllNodes.size());
10365   for (auto &N : allnodes()) {
10366     unsigned NOps = N.getNumOperands();
10367     Degree[&N] = NOps;
10368     if (0 == NOps)
10369       Order.push_back(&N);
10370   }
10371   for (size_t I = 0; I != Order.size(); ++I) {
10372     SDNode *N = Order[I];
10373     for (auto *U : N->uses()) {
10374       unsigned &UnsortedOps = Degree[U];
10375       if (0 == --UnsortedOps)
10376         Order.push_back(U);
10377     }
10378   }
10379 }
10380 
10381 #ifndef NDEBUG
10382 void SelectionDAG::VerifyDAGDivergence() {
10383   std::vector<SDNode *> TopoOrder;
10384   CreateTopologicalOrder(TopoOrder);
10385   for (auto *N : TopoOrder) {
10386     assert(calculateDivergence(N) == N->isDivergent() &&
10387            "Divergence bit inconsistency detected");
10388   }
10389 }
10390 #endif
10391 
10392 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10393 /// uses of other values produced by From.getNode() alone.  The same value
10394 /// may appear in both the From and To list.  The Deleted vector is
10395 /// handled the same way as for ReplaceAllUsesWith.
10396 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10397                                               const SDValue *To,
10398                                               unsigned Num){
10399   // Handle the simple, trivial case efficiently.
10400   if (Num == 1)
10401     return ReplaceAllUsesOfValueWith(*From, *To);
10402 
10403   transferDbgValues(*From, *To);
10404 
10405   // Read up all the uses and make records of them. This helps
10406   // processing new uses that are introduced during the
10407   // replacement process.
10408   SmallVector<UseMemo, 4> Uses;
10409   for (unsigned i = 0; i != Num; ++i) {
10410     unsigned FromResNo = From[i].getResNo();
10411     SDNode *FromNode = From[i].getNode();
10412     for (SDNode::use_iterator UI = FromNode->use_begin(),
10413          E = FromNode->use_end(); UI != E; ++UI) {
10414       SDUse &Use = UI.getUse();
10415       if (Use.getResNo() == FromResNo) {
10416         UseMemo Memo = { *UI, i, &Use };
10417         Uses.push_back(Memo);
10418       }
10419     }
10420   }
10421 
10422   // Sort the uses, so that all the uses from a given User are together.
10423   llvm::sort(Uses);
10424   RAUOVWUpdateListener Listener(*this, Uses);
10425 
10426   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10427        UseIndex != UseIndexEnd; ) {
10428     // We know that this user uses some value of From.  If it is the right
10429     // value, update it.
10430     SDNode *User = Uses[UseIndex].User;
10431     // If the node has been deleted by recursive CSE updates when updating
10432     // another node, then just skip this entry.
10433     if (User == nullptr) {
10434       ++UseIndex;
10435       continue;
10436     }
10437 
10438     // This node is about to morph, remove its old self from the CSE maps.
10439     RemoveNodeFromCSEMaps(User);
10440 
10441     // The Uses array is sorted, so all the uses for a given User
10442     // are next to each other in the list.
10443     // To help reduce the number of CSE recomputations, process all
10444     // the uses of this user that we can find this way.
10445     do {
10446       unsigned i = Uses[UseIndex].Index;
10447       SDUse &Use = *Uses[UseIndex].Use;
10448       ++UseIndex;
10449 
10450       Use.set(To[i]);
10451     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10452 
10453     // Now that we have modified User, add it back to the CSE maps.  If it
10454     // already exists there, recursively merge the results together.
10455     AddModifiedNodeToCSEMaps(User);
10456   }
10457 }
10458 
10459 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10460 /// based on their topological order. It returns the maximum id and a vector
10461 /// of the SDNodes* in assigned order by reference.
10462 unsigned SelectionDAG::AssignTopologicalOrder() {
10463   unsigned DAGSize = 0;
10464 
10465   // SortedPos tracks the progress of the algorithm. Nodes before it are
10466   // sorted, nodes after it are unsorted. When the algorithm completes
10467   // it is at the end of the list.
10468   allnodes_iterator SortedPos = allnodes_begin();
10469 
10470   // Visit all the nodes. Move nodes with no operands to the front of
10471   // the list immediately. Annotate nodes that do have operands with their
10472   // operand count. Before we do this, the Node Id fields of the nodes
10473   // may contain arbitrary values. After, the Node Id fields for nodes
10474   // before SortedPos will contain the topological sort index, and the
10475   // Node Id fields for nodes At SortedPos and after will contain the
10476   // count of outstanding operands.
10477   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10478     checkForCycles(&N, this);
10479     unsigned Degree = N.getNumOperands();
10480     if (Degree == 0) {
10481       // A node with no uses, add it to the result array immediately.
10482       N.setNodeId(DAGSize++);
10483       allnodes_iterator Q(&N);
10484       if (Q != SortedPos)
10485         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10486       assert(SortedPos != AllNodes.end() && "Overran node list");
10487       ++SortedPos;
10488     } else {
10489       // Temporarily use the Node Id as scratch space for the degree count.
10490       N.setNodeId(Degree);
10491     }
10492   }
10493 
10494   // Visit all the nodes. As we iterate, move nodes into sorted order,
10495   // such that by the time the end is reached all nodes will be sorted.
10496   for (SDNode &Node : allnodes()) {
10497     SDNode *N = &Node;
10498     checkForCycles(N, this);
10499     // N is in sorted position, so all its uses have one less operand
10500     // that needs to be sorted.
10501     for (SDNode *P : N->uses()) {
10502       unsigned Degree = P->getNodeId();
10503       assert(Degree != 0 && "Invalid node degree");
10504       --Degree;
10505       if (Degree == 0) {
10506         // All of P's operands are sorted, so P may sorted now.
10507         P->setNodeId(DAGSize++);
10508         if (P->getIterator() != SortedPos)
10509           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10510         assert(SortedPos != AllNodes.end() && "Overran node list");
10511         ++SortedPos;
10512       } else {
10513         // Update P's outstanding operand count.
10514         P->setNodeId(Degree);
10515       }
10516     }
10517     if (Node.getIterator() == SortedPos) {
10518 #ifndef NDEBUG
10519       allnodes_iterator I(N);
10520       SDNode *S = &*++I;
10521       dbgs() << "Overran sorted position:\n";
10522       S->dumprFull(this); dbgs() << "\n";
10523       dbgs() << "Checking if this is due to cycles\n";
10524       checkForCycles(this, true);
10525 #endif
10526       llvm_unreachable(nullptr);
10527     }
10528   }
10529 
10530   assert(SortedPos == AllNodes.end() &&
10531          "Topological sort incomplete!");
10532   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10533          "First node in topological sort is not the entry token!");
10534   assert(AllNodes.front().getNodeId() == 0 &&
10535          "First node in topological sort has non-zero id!");
10536   assert(AllNodes.front().getNumOperands() == 0 &&
10537          "First node in topological sort has operands!");
10538   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10539          "Last node in topologic sort has unexpected id!");
10540   assert(AllNodes.back().use_empty() &&
10541          "Last node in topologic sort has users!");
10542   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10543   return DAGSize;
10544 }
10545 
10546 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10547 /// value is produced by SD.
10548 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10549   for (SDNode *SD : DB->getSDNodes()) {
10550     if (!SD)
10551       continue;
10552     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10553     SD->setHasDebugValue(true);
10554   }
10555   DbgInfo->add(DB, isParameter);
10556 }
10557 
10558 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10559 
10560 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10561                                                    SDValue NewMemOpChain) {
10562   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10563   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10564   // The new memory operation must have the same position as the old load in
10565   // terms of memory dependency. Create a TokenFactor for the old load and new
10566   // memory operation and update uses of the old load's output chain to use that
10567   // TokenFactor.
10568   if (OldChain == NewMemOpChain || OldChain.use_empty())
10569     return NewMemOpChain;
10570 
10571   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10572                                 OldChain, NewMemOpChain);
10573   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10574   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10575   return TokenFactor;
10576 }
10577 
10578 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10579                                                    SDValue NewMemOp) {
10580   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10581   SDValue OldChain = SDValue(OldLoad, 1);
10582   SDValue NewMemOpChain = NewMemOp.getValue(1);
10583   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10584 }
10585 
10586 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10587                                                      Function **OutFunction) {
10588   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10589 
10590   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10591   auto *Module = MF->getFunction().getParent();
10592   auto *Function = Module->getFunction(Symbol);
10593 
10594   if (OutFunction != nullptr)
10595       *OutFunction = Function;
10596 
10597   if (Function != nullptr) {
10598     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10599     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10600   }
10601 
10602   std::string ErrorStr;
10603   raw_string_ostream ErrorFormatter(ErrorStr);
10604   ErrorFormatter << "Undefined external symbol ";
10605   ErrorFormatter << '"' << Symbol << '"';
10606   report_fatal_error(Twine(ErrorFormatter.str()));
10607 }
10608 
10609 //===----------------------------------------------------------------------===//
10610 //                              SDNode Class
10611 //===----------------------------------------------------------------------===//
10612 
10613 bool llvm::isNullConstant(SDValue V) {
10614   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10615   return Const != nullptr && Const->isZero();
10616 }
10617 
10618 bool llvm::isNullFPConstant(SDValue V) {
10619   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10620   return Const != nullptr && Const->isZero() && !Const->isNegative();
10621 }
10622 
10623 bool llvm::isAllOnesConstant(SDValue V) {
10624   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10625   return Const != nullptr && Const->isAllOnes();
10626 }
10627 
10628 bool llvm::isOneConstant(SDValue V) {
10629   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10630   return Const != nullptr && Const->isOne();
10631 }
10632 
10633 bool llvm::isMinSignedConstant(SDValue V) {
10634   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10635   return Const != nullptr && Const->isMinSignedValue();
10636 }
10637 
10638 SDValue llvm::peekThroughBitcasts(SDValue V) {
10639   while (V.getOpcode() == ISD::BITCAST)
10640     V = V.getOperand(0);
10641   return V;
10642 }
10643 
10644 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10645   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10646     V = V.getOperand(0);
10647   return V;
10648 }
10649 
10650 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10651   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10652     V = V.getOperand(0);
10653   return V;
10654 }
10655 
10656 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10657   if (V.getOpcode() != ISD::XOR)
10658     return false;
10659   V = peekThroughBitcasts(V.getOperand(1));
10660   unsigned NumBits = V.getScalarValueSizeInBits();
10661   ConstantSDNode *C =
10662       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10663   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10664 }
10665 
10666 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10667                                           bool AllowTruncation) {
10668   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10669     return CN;
10670 
10671   // SplatVectors can truncate their operands. Ignore that case here unless
10672   // AllowTruncation is set.
10673   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10674     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10675     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10676       EVT CVT = CN->getValueType(0);
10677       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10678       if (AllowTruncation || CVT == VecEltVT)
10679         return CN;
10680     }
10681   }
10682 
10683   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10684     BitVector UndefElements;
10685     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10686 
10687     // BuildVectors can truncate their operands. Ignore that case here unless
10688     // AllowTruncation is set.
10689     if (CN && (UndefElements.none() || AllowUndefs)) {
10690       EVT CVT = CN->getValueType(0);
10691       EVT NSVT = N.getValueType().getScalarType();
10692       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10693       if (AllowTruncation || (CVT == NSVT))
10694         return CN;
10695     }
10696   }
10697 
10698   return nullptr;
10699 }
10700 
10701 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10702                                           bool AllowUndefs,
10703                                           bool AllowTruncation) {
10704   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10705     return CN;
10706 
10707   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10708     BitVector UndefElements;
10709     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10710 
10711     // BuildVectors can truncate their operands. Ignore that case here unless
10712     // AllowTruncation is set.
10713     if (CN && (UndefElements.none() || AllowUndefs)) {
10714       EVT CVT = CN->getValueType(0);
10715       EVT NSVT = N.getValueType().getScalarType();
10716       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10717       if (AllowTruncation || (CVT == NSVT))
10718         return CN;
10719     }
10720   }
10721 
10722   return nullptr;
10723 }
10724 
10725 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10726   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10727     return CN;
10728 
10729   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10730     BitVector UndefElements;
10731     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10732     if (CN && (UndefElements.none() || AllowUndefs))
10733       return CN;
10734   }
10735 
10736   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10737     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10738       return CN;
10739 
10740   return nullptr;
10741 }
10742 
10743 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10744                                               const APInt &DemandedElts,
10745                                               bool AllowUndefs) {
10746   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10747     return CN;
10748 
10749   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10750     BitVector UndefElements;
10751     ConstantFPSDNode *CN =
10752         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10753     if (CN && (UndefElements.none() || AllowUndefs))
10754       return CN;
10755   }
10756 
10757   return nullptr;
10758 }
10759 
10760 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10761   // TODO: may want to use peekThroughBitcast() here.
10762   ConstantSDNode *C =
10763       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10764   return C && C->isZero();
10765 }
10766 
10767 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10768   ConstantSDNode *C =
10769       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
10770   return C && C->isOne();
10771 }
10772 
10773 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10774   N = peekThroughBitcasts(N);
10775   unsigned BitWidth = N.getScalarValueSizeInBits();
10776   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10777   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10778 }
10779 
10780 HandleSDNode::~HandleSDNode() {
10781   DropOperands();
10782 }
10783 
10784 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10785                                          const DebugLoc &DL,
10786                                          const GlobalValue *GA, EVT VT,
10787                                          int64_t o, unsigned TF)
10788     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10789   TheGlobal = GA;
10790 }
10791 
10792 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10793                                          EVT VT, unsigned SrcAS,
10794                                          unsigned DestAS)
10795     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10796       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10797 
10798 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10799                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10800     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10801   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10802   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10803   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10804   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10805 
10806   // We check here that the size of the memory operand fits within the size of
10807   // the MMO. This is because the MMO might indicate only a possible address
10808   // range instead of specifying the affected memory addresses precisely.
10809   // TODO: Make MachineMemOperands aware of scalable vectors.
10810   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10811          "Size mismatch!");
10812 }
10813 
10814 /// Profile - Gather unique data for the node.
10815 ///
10816 void SDNode::Profile(FoldingSetNodeID &ID) const {
10817   AddNodeIDNode(ID, this);
10818 }
10819 
10820 namespace {
10821 
10822   struct EVTArray {
10823     std::vector<EVT> VTs;
10824 
10825     EVTArray() {
10826       VTs.reserve(MVT::VALUETYPE_SIZE);
10827       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10828         VTs.push_back(MVT((MVT::SimpleValueType)i));
10829     }
10830   };
10831 
10832 } // end anonymous namespace
10833 
10834 /// getValueTypeList - Return a pointer to the specified value type.
10835 ///
10836 const EVT *SDNode::getValueTypeList(EVT VT) {
10837   static std::set<EVT, EVT::compareRawBits> EVTs;
10838   static EVTArray SimpleVTArray;
10839   static sys::SmartMutex<true> VTMutex;
10840 
10841   if (VT.isExtended()) {
10842     sys::SmartScopedLock<true> Lock(VTMutex);
10843     return &(*EVTs.insert(VT).first);
10844   }
10845   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10846   return &SimpleVTArray.VTs[VT.getSimpleVT().SimpleTy];
10847 }
10848 
10849 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10850 /// indicated value.  This method ignores uses of other values defined by this
10851 /// operation.
10852 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10853   assert(Value < getNumValues() && "Bad value!");
10854 
10855   // TODO: Only iterate over uses of a given value of the node
10856   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10857     if (UI.getUse().getResNo() == Value) {
10858       if (NUses == 0)
10859         return false;
10860       --NUses;
10861     }
10862   }
10863 
10864   // Found exactly the right number of uses?
10865   return NUses == 0;
10866 }
10867 
10868 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10869 /// value. This method ignores uses of other values defined by this operation.
10870 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10871   assert(Value < getNumValues() && "Bad value!");
10872 
10873   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10874     if (UI.getUse().getResNo() == Value)
10875       return true;
10876 
10877   return false;
10878 }
10879 
10880 /// isOnlyUserOf - Return true if this node is the only use of N.
10881 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10882   bool Seen = false;
10883   for (const SDNode *User : N->uses()) {
10884     if (User == this)
10885       Seen = true;
10886     else
10887       return false;
10888   }
10889 
10890   return Seen;
10891 }
10892 
10893 /// Return true if the only users of N are contained in Nodes.
10894 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10895   bool Seen = false;
10896   for (const SDNode *User : N->uses()) {
10897     if (llvm::is_contained(Nodes, User))
10898       Seen = true;
10899     else
10900       return false;
10901   }
10902 
10903   return Seen;
10904 }
10905 
10906 /// isOperand - Return true if this node is an operand of N.
10907 bool SDValue::isOperandOf(const SDNode *N) const {
10908   return is_contained(N->op_values(), *this);
10909 }
10910 
10911 bool SDNode::isOperandOf(const SDNode *N) const {
10912   return any_of(N->op_values(),
10913                 [this](SDValue Op) { return this == Op.getNode(); });
10914 }
10915 
10916 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10917 /// be a chain) reaches the specified operand without crossing any
10918 /// side-effecting instructions on any chain path.  In practice, this looks
10919 /// through token factors and non-volatile loads.  In order to remain efficient,
10920 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10921 ///
10922 /// Note that we only need to examine chains when we're searching for
10923 /// side-effects; SelectionDAG requires that all side-effects are represented
10924 /// by chains, even if another operand would force a specific ordering. This
10925 /// constraint is necessary to allow transformations like splitting loads.
10926 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10927                                              unsigned Depth) const {
10928   if (*this == Dest) return true;
10929 
10930   // Don't search too deeply, we just want to be able to see through
10931   // TokenFactor's etc.
10932   if (Depth == 0) return false;
10933 
10934   // If this is a token factor, all inputs to the TF happen in parallel.
10935   if (getOpcode() == ISD::TokenFactor) {
10936     // First, try a shallow search.
10937     if (is_contained((*this)->ops(), Dest)) {
10938       // We found the chain we want as an operand of this TokenFactor.
10939       // Essentially, we reach the chain without side-effects if we could
10940       // serialize the TokenFactor into a simple chain of operations with
10941       // Dest as the last operation. This is automatically true if the
10942       // chain has one use: there are no other ordering constraints.
10943       // If the chain has more than one use, we give up: some other
10944       // use of Dest might force a side-effect between Dest and the current
10945       // node.
10946       if (Dest.hasOneUse())
10947         return true;
10948     }
10949     // Next, try a deep search: check whether every operand of the TokenFactor
10950     // reaches Dest.
10951     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10952       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10953     });
10954   }
10955 
10956   // Loads don't have side effects, look through them.
10957   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10958     if (Ld->isUnordered())
10959       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10960   }
10961   return false;
10962 }
10963 
10964 bool SDNode::hasPredecessor(const SDNode *N) const {
10965   SmallPtrSet<const SDNode *, 32> Visited;
10966   SmallVector<const SDNode *, 16> Worklist;
10967   Worklist.push_back(this);
10968   return hasPredecessorHelper(N, Visited, Worklist);
10969 }
10970 
10971 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10972   this->Flags.intersectWith(Flags);
10973 }
10974 
10975 SDValue
10976 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10977                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10978                                   bool AllowPartials) {
10979   // The pattern must end in an extract from index 0.
10980   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10981       !isNullConstant(Extract->getOperand(1)))
10982     return SDValue();
10983 
10984   // Match against one of the candidate binary ops.
10985   SDValue Op = Extract->getOperand(0);
10986   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10987         return Op.getOpcode() == unsigned(BinOp);
10988       }))
10989     return SDValue();
10990 
10991   // Floating-point reductions may require relaxed constraints on the final step
10992   // of the reduction because they may reorder intermediate operations.
10993   unsigned CandidateBinOp = Op.getOpcode();
10994   if (Op.getValueType().isFloatingPoint()) {
10995     SDNodeFlags Flags = Op->getFlags();
10996     switch (CandidateBinOp) {
10997     case ISD::FADD:
10998       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10999         return SDValue();
11000       break;
11001     default:
11002       llvm_unreachable("Unhandled FP opcode for binop reduction");
11003     }
11004   }
11005 
11006   // Matching failed - attempt to see if we did enough stages that a partial
11007   // reduction from a subvector is possible.
11008   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
11009     if (!AllowPartials || !Op)
11010       return SDValue();
11011     EVT OpVT = Op.getValueType();
11012     EVT OpSVT = OpVT.getScalarType();
11013     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
11014     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
11015       return SDValue();
11016     BinOp = (ISD::NodeType)CandidateBinOp;
11017     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
11018                    getVectorIdxConstant(0, SDLoc(Op)));
11019   };
11020 
11021   // At each stage, we're looking for something that looks like:
11022   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
11023   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
11024   //                               i32 undef, i32 undef, i32 undef, i32 undef>
11025   // %a = binop <8 x i32> %op, %s
11026   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
11027   // we expect something like:
11028   // <4,5,6,7,u,u,u,u>
11029   // <2,3,u,u,u,u,u,u>
11030   // <1,u,u,u,u,u,u,u>
11031   // While a partial reduction match would be:
11032   // <2,3,u,u,u,u,u,u>
11033   // <1,u,u,u,u,u,u,u>
11034   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
11035   SDValue PrevOp;
11036   for (unsigned i = 0; i < Stages; ++i) {
11037     unsigned MaskEnd = (1 << i);
11038 
11039     if (Op.getOpcode() != CandidateBinOp)
11040       return PartialReduction(PrevOp, MaskEnd);
11041 
11042     SDValue Op0 = Op.getOperand(0);
11043     SDValue Op1 = Op.getOperand(1);
11044 
11045     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
11046     if (Shuffle) {
11047       Op = Op1;
11048     } else {
11049       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
11050       Op = Op0;
11051     }
11052 
11053     // The first operand of the shuffle should be the same as the other operand
11054     // of the binop.
11055     if (!Shuffle || Shuffle->getOperand(0) != Op)
11056       return PartialReduction(PrevOp, MaskEnd);
11057 
11058     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
11059     for (int Index = 0; Index < (int)MaskEnd; ++Index)
11060       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
11061         return PartialReduction(PrevOp, MaskEnd);
11062 
11063     PrevOp = Op;
11064   }
11065 
11066   // Handle subvector reductions, which tend to appear after the shuffle
11067   // reduction stages.
11068   while (Op.getOpcode() == CandidateBinOp) {
11069     unsigned NumElts = Op.getValueType().getVectorNumElements();
11070     SDValue Op0 = Op.getOperand(0);
11071     SDValue Op1 = Op.getOperand(1);
11072     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
11073         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
11074         Op0.getOperand(0) != Op1.getOperand(0))
11075       break;
11076     SDValue Src = Op0.getOperand(0);
11077     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
11078     if (NumSrcElts != (2 * NumElts))
11079       break;
11080     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
11081           Op1.getConstantOperandAPInt(1) == NumElts) &&
11082         !(Op1.getConstantOperandAPInt(1) == 0 &&
11083           Op0.getConstantOperandAPInt(1) == NumElts))
11084       break;
11085     Op = Src;
11086   }
11087 
11088   BinOp = (ISD::NodeType)CandidateBinOp;
11089   return Op;
11090 }
11091 
11092 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
11093   assert(N->getNumValues() == 1 &&
11094          "Can't unroll a vector with multiple results!");
11095 
11096   EVT VT = N->getValueType(0);
11097   unsigned NE = VT.getVectorNumElements();
11098   EVT EltVT = VT.getVectorElementType();
11099   SDLoc dl(N);
11100 
11101   SmallVector<SDValue, 8> Scalars;
11102   SmallVector<SDValue, 4> Operands(N->getNumOperands());
11103 
11104   // If ResNE is 0, fully unroll the vector op.
11105   if (ResNE == 0)
11106     ResNE = NE;
11107   else if (NE > ResNE)
11108     NE = ResNE;
11109 
11110   unsigned i;
11111   for (i= 0; i != NE; ++i) {
11112     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
11113       SDValue Operand = N->getOperand(j);
11114       EVT OperandVT = Operand.getValueType();
11115       if (OperandVT.isVector()) {
11116         // A vector operand; extract a single element.
11117         EVT OperandEltVT = OperandVT.getVectorElementType();
11118         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
11119                               Operand, getVectorIdxConstant(i, dl));
11120       } else {
11121         // A scalar operand; just use it as is.
11122         Operands[j] = Operand;
11123       }
11124     }
11125 
11126     switch (N->getOpcode()) {
11127     default: {
11128       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
11129                                 N->getFlags()));
11130       break;
11131     }
11132     case ISD::VSELECT:
11133       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
11134       break;
11135     case ISD::SHL:
11136     case ISD::SRA:
11137     case ISD::SRL:
11138     case ISD::ROTL:
11139     case ISD::ROTR:
11140       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11141                                getShiftAmountOperand(Operands[0].getValueType(),
11142                                                      Operands[1])));
11143       break;
11144     case ISD::SIGN_EXTEND_INREG: {
11145       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11146       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11147                                 Operands[0],
11148                                 getValueType(ExtVT)));
11149     }
11150     }
11151   }
11152 
11153   for (; i < ResNE; ++i)
11154     Scalars.push_back(getUNDEF(EltVT));
11155 
11156   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11157   return getBuildVector(VecVT, dl, Scalars);
11158 }
11159 
11160 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11161     SDNode *N, unsigned ResNE) {
11162   unsigned Opcode = N->getOpcode();
11163   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11164           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11165           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11166          "Expected an overflow opcode");
11167 
11168   EVT ResVT = N->getValueType(0);
11169   EVT OvVT = N->getValueType(1);
11170   EVT ResEltVT = ResVT.getVectorElementType();
11171   EVT OvEltVT = OvVT.getVectorElementType();
11172   SDLoc dl(N);
11173 
11174   // If ResNE is 0, fully unroll the vector op.
11175   unsigned NE = ResVT.getVectorNumElements();
11176   if (ResNE == 0)
11177     ResNE = NE;
11178   else if (NE > ResNE)
11179     NE = ResNE;
11180 
11181   SmallVector<SDValue, 8> LHSScalars;
11182   SmallVector<SDValue, 8> RHSScalars;
11183   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11184   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11185 
11186   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11187   SDVTList VTs = getVTList(ResEltVT, SVT);
11188   SmallVector<SDValue, 8> ResScalars;
11189   SmallVector<SDValue, 8> OvScalars;
11190   for (unsigned i = 0; i < NE; ++i) {
11191     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11192     SDValue Ov =
11193         getSelect(dl, OvEltVT, Res.getValue(1),
11194                   getBoolConstant(true, dl, OvEltVT, ResVT),
11195                   getConstant(0, dl, OvEltVT));
11196 
11197     ResScalars.push_back(Res);
11198     OvScalars.push_back(Ov);
11199   }
11200 
11201   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11202   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11203 
11204   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11205   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11206   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11207                         getBuildVector(NewOvVT, dl, OvScalars));
11208 }
11209 
11210 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11211                                                   LoadSDNode *Base,
11212                                                   unsigned Bytes,
11213                                                   int Dist) const {
11214   if (LD->isVolatile() || Base->isVolatile())
11215     return false;
11216   // TODO: probably too restrictive for atomics, revisit
11217   if (!LD->isSimple())
11218     return false;
11219   if (LD->isIndexed() || Base->isIndexed())
11220     return false;
11221   if (LD->getChain() != Base->getChain())
11222     return false;
11223   EVT VT = LD->getValueType(0);
11224   if (VT.getSizeInBits() / 8 != Bytes)
11225     return false;
11226 
11227   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11228   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11229 
11230   int64_t Offset = 0;
11231   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11232     return (Dist * Bytes == Offset);
11233   return false;
11234 }
11235 
11236 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11237 /// if it cannot be inferred.
11238 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11239   // If this is a GlobalAddress + cst, return the alignment.
11240   const GlobalValue *GV = nullptr;
11241   int64_t GVOffset = 0;
11242   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11243     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11244     KnownBits Known(PtrWidth);
11245     llvm::computeKnownBits(GV, Known, getDataLayout());
11246     unsigned AlignBits = Known.countMinTrailingZeros();
11247     if (AlignBits)
11248       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11249   }
11250 
11251   // If this is a direct reference to a stack slot, use information about the
11252   // stack slot's alignment.
11253   int FrameIdx = INT_MIN;
11254   int64_t FrameOffset = 0;
11255   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11256     FrameIdx = FI->getIndex();
11257   } else if (isBaseWithConstantOffset(Ptr) &&
11258              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11259     // Handle FI+Cst
11260     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11261     FrameOffset = Ptr.getConstantOperandVal(1);
11262   }
11263 
11264   if (FrameIdx != INT_MIN) {
11265     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11266     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11267   }
11268 
11269   return None;
11270 }
11271 
11272 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11273 /// which is split (or expanded) into two not necessarily identical pieces.
11274 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11275   // Currently all types are split in half.
11276   EVT LoVT, HiVT;
11277   if (!VT.isVector())
11278     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11279   else
11280     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11281 
11282   return std::make_pair(LoVT, HiVT);
11283 }
11284 
11285 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11286 /// type, dependent on an enveloping VT that has been split into two identical
11287 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11288 std::pair<EVT, EVT>
11289 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11290                                        bool *HiIsEmpty) const {
11291   EVT EltTp = VT.getVectorElementType();
11292   // Examples:
11293   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11294   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11295   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11296   //   etc.
11297   ElementCount VTNumElts = VT.getVectorElementCount();
11298   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11299   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11300          "Mixing fixed width and scalable vectors when enveloping a type");
11301   EVT LoVT, HiVT;
11302   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11303     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11304     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11305     *HiIsEmpty = false;
11306   } else {
11307     // Flag that hi type has zero storage size, but return split envelop type
11308     // (this would be easier if vector types with zero elements were allowed).
11309     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11310     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11311     *HiIsEmpty = true;
11312   }
11313   return std::make_pair(LoVT, HiVT);
11314 }
11315 
11316 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11317 /// low/high part.
11318 std::pair<SDValue, SDValue>
11319 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11320                           const EVT &HiVT) {
11321   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11322          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11323          "Splitting vector with an invalid mixture of fixed and scalable "
11324          "vector types");
11325   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11326              N.getValueType().getVectorMinNumElements() &&
11327          "More vector elements requested than available!");
11328   SDValue Lo, Hi;
11329   Lo =
11330       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11331   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11332   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11333   // IDX with the runtime scaling factor of the result vector type. For
11334   // fixed-width result vectors, that runtime scaling factor is 1.
11335   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11336                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11337   return std::make_pair(Lo, Hi);
11338 }
11339 
11340 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11341                                                    const SDLoc &DL) {
11342   // Split the vector length parameter.
11343   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11344   EVT VT = N.getValueType();
11345   assert(VecVT.getVectorElementCount().isKnownEven() &&
11346          "Expecting the mask to be an evenly-sized vector");
11347   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11348   SDValue HalfNumElts =
11349       VecVT.isFixedLengthVector()
11350           ? getConstant(HalfMinNumElts, DL, VT)
11351           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11352   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11353   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11354   return std::make_pair(Lo, Hi);
11355 }
11356 
11357 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11358 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11359   EVT VT = N.getValueType();
11360   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11361                                 NextPowerOf2(VT.getVectorNumElements()));
11362   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11363                  getVectorIdxConstant(0, DL));
11364 }
11365 
11366 void SelectionDAG::ExtractVectorElements(SDValue Op,
11367                                          SmallVectorImpl<SDValue> &Args,
11368                                          unsigned Start, unsigned Count,
11369                                          EVT EltVT) {
11370   EVT VT = Op.getValueType();
11371   if (Count == 0)
11372     Count = VT.getVectorNumElements();
11373   if (EltVT == EVT())
11374     EltVT = VT.getVectorElementType();
11375   SDLoc SL(Op);
11376   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11377     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11378                            getVectorIdxConstant(i, SL)));
11379   }
11380 }
11381 
11382 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11383 unsigned GlobalAddressSDNode::getAddressSpace() const {
11384   return getGlobal()->getType()->getAddressSpace();
11385 }
11386 
11387 Type *ConstantPoolSDNode::getType() const {
11388   if (isMachineConstantPoolEntry())
11389     return Val.MachineCPVal->getType();
11390   return Val.ConstVal->getType();
11391 }
11392 
11393 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11394                                         unsigned &SplatBitSize,
11395                                         bool &HasAnyUndefs,
11396                                         unsigned MinSplatBits,
11397                                         bool IsBigEndian) const {
11398   EVT VT = getValueType(0);
11399   assert(VT.isVector() && "Expected a vector type");
11400   unsigned VecWidth = VT.getSizeInBits();
11401   if (MinSplatBits > VecWidth)
11402     return false;
11403 
11404   // FIXME: The widths are based on this node's type, but build vectors can
11405   // truncate their operands.
11406   SplatValue = APInt(VecWidth, 0);
11407   SplatUndef = APInt(VecWidth, 0);
11408 
11409   // Get the bits. Bits with undefined values (when the corresponding element
11410   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11411   // in SplatValue. If any of the values are not constant, give up and return
11412   // false.
11413   unsigned int NumOps = getNumOperands();
11414   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11415   unsigned EltWidth = VT.getScalarSizeInBits();
11416 
11417   for (unsigned j = 0; j < NumOps; ++j) {
11418     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11419     SDValue OpVal = getOperand(i);
11420     unsigned BitPos = j * EltWidth;
11421 
11422     if (OpVal.isUndef())
11423       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11424     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11425       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11426     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11427       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11428     else
11429       return false;
11430   }
11431 
11432   // The build_vector is all constants or undefs. Find the smallest element
11433   // size that splats the vector.
11434   HasAnyUndefs = (SplatUndef != 0);
11435 
11436   // FIXME: This does not work for vectors with elements less than 8 bits.
11437   while (VecWidth > 8) {
11438     unsigned HalfSize = VecWidth / 2;
11439     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11440     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11441     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11442     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11443 
11444     // If the two halves do not match (ignoring undef bits), stop here.
11445     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11446         MinSplatBits > HalfSize)
11447       break;
11448 
11449     SplatValue = HighValue | LowValue;
11450     SplatUndef = HighUndef & LowUndef;
11451 
11452     VecWidth = HalfSize;
11453   }
11454 
11455   SplatBitSize = VecWidth;
11456   return true;
11457 }
11458 
11459 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11460                                          BitVector *UndefElements) const {
11461   unsigned NumOps = getNumOperands();
11462   if (UndefElements) {
11463     UndefElements->clear();
11464     UndefElements->resize(NumOps);
11465   }
11466   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11467   if (!DemandedElts)
11468     return SDValue();
11469   SDValue Splatted;
11470   for (unsigned i = 0; i != NumOps; ++i) {
11471     if (!DemandedElts[i])
11472       continue;
11473     SDValue Op = getOperand(i);
11474     if (Op.isUndef()) {
11475       if (UndefElements)
11476         (*UndefElements)[i] = true;
11477     } else if (!Splatted) {
11478       Splatted = Op;
11479     } else if (Splatted != Op) {
11480       return SDValue();
11481     }
11482   }
11483 
11484   if (!Splatted) {
11485     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11486     assert(getOperand(FirstDemandedIdx).isUndef() &&
11487            "Can only have a splat without a constant for all undefs.");
11488     return getOperand(FirstDemandedIdx);
11489   }
11490 
11491   return Splatted;
11492 }
11493 
11494 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11495   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11496   return getSplatValue(DemandedElts, UndefElements);
11497 }
11498 
11499 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11500                                             SmallVectorImpl<SDValue> &Sequence,
11501                                             BitVector *UndefElements) const {
11502   unsigned NumOps = getNumOperands();
11503   Sequence.clear();
11504   if (UndefElements) {
11505     UndefElements->clear();
11506     UndefElements->resize(NumOps);
11507   }
11508   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11509   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11510     return false;
11511 
11512   // Set the undefs even if we don't find a sequence (like getSplatValue).
11513   if (UndefElements)
11514     for (unsigned I = 0; I != NumOps; ++I)
11515       if (DemandedElts[I] && getOperand(I).isUndef())
11516         (*UndefElements)[I] = true;
11517 
11518   // Iteratively widen the sequence length looking for repetitions.
11519   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11520     Sequence.append(SeqLen, SDValue());
11521     for (unsigned I = 0; I != NumOps; ++I) {
11522       if (!DemandedElts[I])
11523         continue;
11524       SDValue &SeqOp = Sequence[I % SeqLen];
11525       SDValue Op = getOperand(I);
11526       if (Op.isUndef()) {
11527         if (!SeqOp)
11528           SeqOp = Op;
11529         continue;
11530       }
11531       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11532         Sequence.clear();
11533         break;
11534       }
11535       SeqOp = Op;
11536     }
11537     if (!Sequence.empty())
11538       return true;
11539   }
11540 
11541   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11542   return false;
11543 }
11544 
11545 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11546                                             BitVector *UndefElements) const {
11547   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11548   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11549 }
11550 
11551 ConstantSDNode *
11552 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11553                                         BitVector *UndefElements) const {
11554   return dyn_cast_or_null<ConstantSDNode>(
11555       getSplatValue(DemandedElts, UndefElements));
11556 }
11557 
11558 ConstantSDNode *
11559 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11560   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11561 }
11562 
11563 ConstantFPSDNode *
11564 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11565                                           BitVector *UndefElements) const {
11566   return dyn_cast_or_null<ConstantFPSDNode>(
11567       getSplatValue(DemandedElts, UndefElements));
11568 }
11569 
11570 ConstantFPSDNode *
11571 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11572   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11573 }
11574 
11575 int32_t
11576 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11577                                                    uint32_t BitWidth) const {
11578   if (ConstantFPSDNode *CN =
11579           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11580     bool IsExact;
11581     APSInt IntVal(BitWidth);
11582     const APFloat &APF = CN->getValueAPF();
11583     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11584             APFloat::opOK ||
11585         !IsExact)
11586       return -1;
11587 
11588     return IntVal.exactLogBase2();
11589   }
11590   return -1;
11591 }
11592 
11593 bool BuildVectorSDNode::getConstantRawBits(
11594     bool IsLittleEndian, unsigned DstEltSizeInBits,
11595     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11596   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11597   if (!isConstant())
11598     return false;
11599 
11600   unsigned NumSrcOps = getNumOperands();
11601   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11602   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11603          "Invalid bitcast scale");
11604 
11605   // Extract raw src bits.
11606   SmallVector<APInt> SrcBitElements(NumSrcOps,
11607                                     APInt::getNullValue(SrcEltSizeInBits));
11608   BitVector SrcUndeElements(NumSrcOps, false);
11609 
11610   for (unsigned I = 0; I != NumSrcOps; ++I) {
11611     SDValue Op = getOperand(I);
11612     if (Op.isUndef()) {
11613       SrcUndeElements.set(I);
11614       continue;
11615     }
11616     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11617     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11618     assert((CInt || CFP) && "Unknown constant");
11619     SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
11620                              : CFP->getValueAPF().bitcastToAPInt();
11621   }
11622 
11623   // Recast to dst width.
11624   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11625                 SrcBitElements, UndefElements, SrcUndeElements);
11626   return true;
11627 }
11628 
11629 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11630                                       unsigned DstEltSizeInBits,
11631                                       SmallVectorImpl<APInt> &DstBitElements,
11632                                       ArrayRef<APInt> SrcBitElements,
11633                                       BitVector &DstUndefElements,
11634                                       const BitVector &SrcUndefElements) {
11635   unsigned NumSrcOps = SrcBitElements.size();
11636   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11637   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11638          "Invalid bitcast scale");
11639   assert(NumSrcOps == SrcUndefElements.size() &&
11640          "Vector size mismatch");
11641 
11642   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11643   DstUndefElements.clear();
11644   DstUndefElements.resize(NumDstOps, false);
11645   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11646 
11647   // Concatenate src elements constant bits together into dst element.
11648   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11649     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11650     for (unsigned I = 0; I != NumDstOps; ++I) {
11651       DstUndefElements.set(I);
11652       APInt &DstBits = DstBitElements[I];
11653       for (unsigned J = 0; J != Scale; ++J) {
11654         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11655         if (SrcUndefElements[Idx])
11656           continue;
11657         DstUndefElements.reset(I);
11658         const APInt &SrcBits = SrcBitElements[Idx];
11659         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11660                "Illegal constant bitwidths");
11661         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11662       }
11663     }
11664     return;
11665   }
11666 
11667   // Split src element constant bits into dst elements.
11668   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11669   for (unsigned I = 0; I != NumSrcOps; ++I) {
11670     if (SrcUndefElements[I]) {
11671       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11672       continue;
11673     }
11674     const APInt &SrcBits = SrcBitElements[I];
11675     for (unsigned J = 0; J != Scale; ++J) {
11676       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11677       APInt &DstBits = DstBitElements[Idx];
11678       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11679     }
11680   }
11681 }
11682 
11683 bool BuildVectorSDNode::isConstant() const {
11684   for (const SDValue &Op : op_values()) {
11685     unsigned Opc = Op.getOpcode();
11686     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11687       return false;
11688   }
11689   return true;
11690 }
11691 
11692 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11693   // Find the first non-undef value in the shuffle mask.
11694   unsigned i, e;
11695   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11696     /* search */;
11697 
11698   // If all elements are undefined, this shuffle can be considered a splat
11699   // (although it should eventually get simplified away completely).
11700   if (i == e)
11701     return true;
11702 
11703   // Make sure all remaining elements are either undef or the same as the first
11704   // non-undef value.
11705   for (int Idx = Mask[i]; i != e; ++i)
11706     if (Mask[i] >= 0 && Mask[i] != Idx)
11707       return false;
11708   return true;
11709 }
11710 
11711 // Returns the SDNode if it is a constant integer BuildVector
11712 // or constant integer.
11713 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11714   if (isa<ConstantSDNode>(N))
11715     return N.getNode();
11716   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11717     return N.getNode();
11718   // Treat a GlobalAddress supporting constant offset folding as a
11719   // constant integer.
11720   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11721     if (GA->getOpcode() == ISD::GlobalAddress &&
11722         TLI->isOffsetFoldingLegal(GA))
11723       return GA;
11724   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11725       isa<ConstantSDNode>(N.getOperand(0)))
11726     return N.getNode();
11727   return nullptr;
11728 }
11729 
11730 // Returns the SDNode if it is a constant float BuildVector
11731 // or constant float.
11732 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11733   if (isa<ConstantFPSDNode>(N))
11734     return N.getNode();
11735 
11736   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11737     return N.getNode();
11738 
11739   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11740       isa<ConstantFPSDNode>(N.getOperand(0)))
11741     return N.getNode();
11742 
11743   return nullptr;
11744 }
11745 
11746 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11747   assert(!Node->OperandList && "Node already has operands");
11748   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11749          "too many operands to fit into SDNode");
11750   SDUse *Ops = OperandRecycler.allocate(
11751       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11752 
11753   bool IsDivergent = false;
11754   for (unsigned I = 0; I != Vals.size(); ++I) {
11755     Ops[I].setUser(Node);
11756     Ops[I].setInitial(Vals[I]);
11757     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11758       IsDivergent |= Ops[I].getNode()->isDivergent();
11759   }
11760   Node->NumOperands = Vals.size();
11761   Node->OperandList = Ops;
11762   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11763     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11764     Node->SDNodeBits.IsDivergent = IsDivergent;
11765   }
11766   checkForCycles(Node);
11767 }
11768 
11769 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11770                                      SmallVectorImpl<SDValue> &Vals) {
11771   size_t Limit = SDNode::getMaxNumOperands();
11772   while (Vals.size() > Limit) {
11773     unsigned SliceIdx = Vals.size() - Limit;
11774     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11775     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11776     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11777     Vals.emplace_back(NewTF);
11778   }
11779   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11780 }
11781 
11782 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11783                                         EVT VT, SDNodeFlags Flags) {
11784   switch (Opcode) {
11785   default:
11786     return SDValue();
11787   case ISD::ADD:
11788   case ISD::OR:
11789   case ISD::XOR:
11790   case ISD::UMAX:
11791     return getConstant(0, DL, VT);
11792   case ISD::MUL:
11793     return getConstant(1, DL, VT);
11794   case ISD::AND:
11795   case ISD::UMIN:
11796     return getAllOnesConstant(DL, VT);
11797   case ISD::SMAX:
11798     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11799   case ISD::SMIN:
11800     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11801   case ISD::FADD:
11802     return getConstantFP(-0.0, DL, VT);
11803   case ISD::FMUL:
11804     return getConstantFP(1.0, DL, VT);
11805   case ISD::FMINNUM:
11806   case ISD::FMAXNUM: {
11807     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11808     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11809     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11810                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11811                         APFloat::getLargest(Semantics);
11812     if (Opcode == ISD::FMAXNUM)
11813       NeutralAF.changeSign();
11814 
11815     return getConstantFP(NeutralAF, DL, VT);
11816   }
11817   }
11818 }
11819 
11820 #ifndef NDEBUG
11821 static void checkForCyclesHelper(const SDNode *N,
11822                                  SmallPtrSetImpl<const SDNode*> &Visited,
11823                                  SmallPtrSetImpl<const SDNode*> &Checked,
11824                                  const llvm::SelectionDAG *DAG) {
11825   // If this node has already been checked, don't check it again.
11826   if (Checked.count(N))
11827     return;
11828 
11829   // If a node has already been visited on this depth-first walk, reject it as
11830   // a cycle.
11831   if (!Visited.insert(N).second) {
11832     errs() << "Detected cycle in SelectionDAG\n";
11833     dbgs() << "Offending node:\n";
11834     N->dumprFull(DAG); dbgs() << "\n";
11835     abort();
11836   }
11837 
11838   for (const SDValue &Op : N->op_values())
11839     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11840 
11841   Checked.insert(N);
11842   Visited.erase(N);
11843 }
11844 #endif
11845 
11846 void llvm::checkForCycles(const llvm::SDNode *N,
11847                           const llvm::SelectionDAG *DAG,
11848                           bool force) {
11849 #ifndef NDEBUG
11850   bool check = force;
11851 #ifdef EXPENSIVE_CHECKS
11852   check = true;
11853 #endif  // EXPENSIVE_CHECKS
11854   if (check) {
11855     assert(N && "Checking nonexistent SDNode");
11856     SmallPtrSet<const SDNode*, 32> visited;
11857     SmallPtrSet<const SDNode*, 32> checked;
11858     checkForCyclesHelper(N, visited, checked, DAG);
11859   }
11860 #endif  // !NDEBUG
11861 }
11862 
11863 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11864   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11865 }
11866