1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/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/IR/Value.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CodeGen.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/KnownBits.h"
64 #include "llvm/Support/MachineValueType.h"
65 #include "llvm/Support/ManagedStatic.h"
66 #include "llvm/Support/MathExtras.h"
67 #include "llvm/Support/Mutex.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include "llvm/Target/TargetOptions.h"
71 #include "llvm/Transforms/Utils/SizeOpts.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstdint>
75 #include <cstdlib>
76 #include <limits>
77 #include <set>
78 #include <string>
79 #include <utility>
80 #include <vector>
81 
82 using namespace llvm;
83 
84 /// makeVTList - Return an instance of the SDVTList struct initialized with the
85 /// specified members.
86 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
87   SDVTList Res = {VTs, NumVTs};
88   return Res;
89 }
90 
91 // Default null implementations of the callbacks.
92 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
93 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
94 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
95 
96 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
97 
98 #define DEBUG_TYPE "selectiondag"
99 
100 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
101        cl::Hidden, cl::init(true),
102        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
103 
104 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
105        cl::desc("Number limit for gluing ld/st of memcpy."),
106        cl::Hidden, cl::init(0));
107 
108 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
109   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
110 }
111 
112 //===----------------------------------------------------------------------===//
113 //                              ConstantFPSDNode Class
114 //===----------------------------------------------------------------------===//
115 
116 /// isExactlyValue - We don't rely on operator== working on double values, as
117 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
118 /// As such, this method can be used to do an exact bit-for-bit comparison of
119 /// two floating point values.
120 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
121   return getValueAPF().bitwiseIsEqual(V);
122 }
123 
124 bool ConstantFPSDNode::isValueValidForType(EVT VT,
125                                            const APFloat& Val) {
126   assert(VT.isFloatingPoint() && "Can only convert between FP types");
127 
128   // convert modifies in place, so make a copy.
129   APFloat Val2 = APFloat(Val);
130   bool losesInfo;
131   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
132                       APFloat::rmNearestTiesToEven,
133                       &losesInfo);
134   return !losesInfo;
135 }
136 
137 //===----------------------------------------------------------------------===//
138 //                              ISD Namespace
139 //===----------------------------------------------------------------------===//
140 
141 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
142   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
143     unsigned EltSize =
144         N->getValueType(0).getVectorElementType().getSizeInBits();
145     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
146       SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
147       return true;
148     }
149     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
150       SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
151       return true;
152     }
153   }
154 
155   auto *BV = dyn_cast<BuildVectorSDNode>(N);
156   if (!BV)
157     return false;
158 
159   APInt SplatUndef;
160   unsigned SplatBitSize;
161   bool HasUndefs;
162   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
163   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
164                              EltSize) &&
165          EltSize == SplatBitSize;
166 }
167 
168 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
169 // specializations of the more general isConstantSplatVector()?
170 
171 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
172   // Look through a bit convert.
173   while (N->getOpcode() == ISD::BITCAST)
174     N = N->getOperand(0).getNode();
175 
176   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
177     APInt SplatVal;
178     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnesValue();
179   }
180 
181   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
182 
183   unsigned i = 0, e = N->getNumOperands();
184 
185   // Skip over all of the undef values.
186   while (i != e && N->getOperand(i).isUndef())
187     ++i;
188 
189   // Do not accept an all-undef vector.
190   if (i == e) return false;
191 
192   // Do not accept build_vectors that aren't all constants or which have non-~0
193   // elements. We have to be a bit careful here, as the type of the constant
194   // may not be the same as the type of the vector elements due to type
195   // legalization (the elements are promoted to a legal type for the target and
196   // a vector of a type may be legal when the base element type is not).
197   // We only want to check enough bits to cover the vector elements, because
198   // we care if the resultant vector is all ones, not whether the individual
199   // constants are.
200   SDValue NotZero = N->getOperand(i);
201   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
202   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
203     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
204       return false;
205   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
206     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
207       return false;
208   } else
209     return false;
210 
211   // Okay, we have at least one ~0 value, check to see if the rest match or are
212   // undefs. Even with the above element type twiddling, this should be OK, as
213   // the same type legalization should have applied to all the elements.
214   for (++i; i != e; ++i)
215     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
216       return false;
217   return true;
218 }
219 
220 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
221   // Look through a bit convert.
222   while (N->getOpcode() == ISD::BITCAST)
223     N = N->getOperand(0).getNode();
224 
225   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
226     APInt SplatVal;
227     return isConstantSplatVector(N, SplatVal) && SplatVal.isNullValue();
228   }
229 
230   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
231 
232   bool IsAllUndef = true;
233   for (const SDValue &Op : N->op_values()) {
234     if (Op.isUndef())
235       continue;
236     IsAllUndef = false;
237     // Do not accept build_vectors that aren't all constants or which have non-0
238     // elements. We have to be a bit careful here, as the type of the constant
239     // may not be the same as the type of the vector elements due to type
240     // legalization (the elements are promoted to a legal type for the target
241     // and a vector of a type may be legal when the base element type is not).
242     // We only want to check enough bits to cover the vector elements, because
243     // we care if the resultant vector is all zeros, not whether the individual
244     // constants are.
245     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
246     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
247       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
248         return false;
249     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
250       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
251         return false;
252     } else
253       return false;
254   }
255 
256   // Do not accept an all-undef vector.
257   if (IsAllUndef)
258     return false;
259   return true;
260 }
261 
262 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
263   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
264 }
265 
266 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
267   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
268 }
269 
270 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
271   if (N->getOpcode() != ISD::BUILD_VECTOR)
272     return false;
273 
274   for (const SDValue &Op : N->op_values()) {
275     if (Op.isUndef())
276       continue;
277     if (!isa<ConstantSDNode>(Op))
278       return false;
279   }
280   return true;
281 }
282 
283 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
284   if (N->getOpcode() != ISD::BUILD_VECTOR)
285     return false;
286 
287   for (const SDValue &Op : N->op_values()) {
288     if (Op.isUndef())
289       continue;
290     if (!isa<ConstantFPSDNode>(Op))
291       return false;
292   }
293   return true;
294 }
295 
296 bool ISD::allOperandsUndef(const SDNode *N) {
297   // Return false if the node has no operands.
298   // This is "logically inconsistent" with the definition of "all" but
299   // is probably the desired behavior.
300   if (N->getNumOperands() == 0)
301     return false;
302   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
303 }
304 
305 bool ISD::matchUnaryPredicate(SDValue Op,
306                               std::function<bool(ConstantSDNode *)> Match,
307                               bool AllowUndefs) {
308   // FIXME: Add support for scalar UNDEF cases?
309   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
310     return Match(Cst);
311 
312   // FIXME: Add support for vector UNDEF cases?
313   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
314       ISD::SPLAT_VECTOR != Op.getOpcode())
315     return false;
316 
317   EVT SVT = Op.getValueType().getScalarType();
318   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
319     if (AllowUndefs && Op.getOperand(i).isUndef()) {
320       if (!Match(nullptr))
321         return false;
322       continue;
323     }
324 
325     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
326     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
327       return false;
328   }
329   return true;
330 }
331 
332 bool ISD::matchBinaryPredicate(
333     SDValue LHS, SDValue RHS,
334     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
335     bool AllowUndefs, bool AllowTypeMismatch) {
336   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
337     return false;
338 
339   // TODO: Add support for scalar UNDEF cases?
340   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
341     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
342       return Match(LHSCst, RHSCst);
343 
344   // TODO: Add support for vector UNDEF cases?
345   if (LHS.getOpcode() != RHS.getOpcode() ||
346       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
347        LHS.getOpcode() != ISD::SPLAT_VECTOR))
348     return false;
349 
350   EVT SVT = LHS.getValueType().getScalarType();
351   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
352     SDValue LHSOp = LHS.getOperand(i);
353     SDValue RHSOp = RHS.getOperand(i);
354     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
355     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
356     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
357     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
358     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
359       return false;
360     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
361                                LHSOp.getValueType() != RHSOp.getValueType()))
362       return false;
363     if (!Match(LHSCst, RHSCst))
364       return false;
365   }
366   return true;
367 }
368 
369 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
370   switch (VecReduceOpcode) {
371   default:
372     llvm_unreachable("Expected VECREDUCE opcode");
373   case ISD::VECREDUCE_FADD:
374   case ISD::VECREDUCE_SEQ_FADD:
375     return ISD::FADD;
376   case ISD::VECREDUCE_FMUL:
377   case ISD::VECREDUCE_SEQ_FMUL:
378     return ISD::FMUL;
379   case ISD::VECREDUCE_ADD:
380     return ISD::ADD;
381   case ISD::VECREDUCE_MUL:
382     return ISD::MUL;
383   case ISD::VECREDUCE_AND:
384     return ISD::AND;
385   case ISD::VECREDUCE_OR:
386     return ISD::OR;
387   case ISD::VECREDUCE_XOR:
388     return ISD::XOR;
389   case ISD::VECREDUCE_SMAX:
390     return ISD::SMAX;
391   case ISD::VECREDUCE_SMIN:
392     return ISD::SMIN;
393   case ISD::VECREDUCE_UMAX:
394     return ISD::UMAX;
395   case ISD::VECREDUCE_UMIN:
396     return ISD::UMIN;
397   case ISD::VECREDUCE_FMAX:
398     return ISD::FMAXNUM;
399   case ISD::VECREDUCE_FMIN:
400     return ISD::FMINNUM;
401   }
402 }
403 
404 bool ISD::isVPOpcode(unsigned Opcode) {
405   switch (Opcode) {
406   default:
407     return false;
408 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
409   case ISD::SDOPC:                                                             \
410     return true;
411 #include "llvm/IR/VPIntrinsics.def"
412   }
413 }
414 
415 /// The operand position of the vector mask.
416 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
417   switch (Opcode) {
418   default:
419     return None;
420 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...)        \
421   case ISD::SDOPC:                                                             \
422     return MASKPOS;
423 #include "llvm/IR/VPIntrinsics.def"
424   }
425 }
426 
427 /// The operand position of the explicit vector length parameter.
428 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     return None;
432 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS)     \
433   case ISD::SDOPC:                                                             \
434     return EVLPOS;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437 }
438 
439 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
440   switch (ExtType) {
441   case ISD::EXTLOAD:
442     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
443   case ISD::SEXTLOAD:
444     return ISD::SIGN_EXTEND;
445   case ISD::ZEXTLOAD:
446     return ISD::ZERO_EXTEND;
447   default:
448     break;
449   }
450 
451   llvm_unreachable("Invalid LoadExtType");
452 }
453 
454 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
455   // To perform this operation, we just need to swap the L and G bits of the
456   // operation.
457   unsigned OldL = (Operation >> 2) & 1;
458   unsigned OldG = (Operation >> 1) & 1;
459   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
460                        (OldL << 1) |       // New G bit
461                        (OldG << 2));       // New L bit.
462 }
463 
464 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
465   unsigned Operation = Op;
466   if (isIntegerLike)
467     Operation ^= 7;   // Flip L, G, E bits, but not U.
468   else
469     Operation ^= 15;  // Flip all of the condition bits.
470 
471   if (Operation > ISD::SETTRUE2)
472     Operation &= ~8;  // Don't let N and U bits get set.
473 
474   return ISD::CondCode(Operation);
475 }
476 
477 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
478   return getSetCCInverseImpl(Op, Type.isInteger());
479 }
480 
481 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
482                                                bool isIntegerLike) {
483   return getSetCCInverseImpl(Op, isIntegerLike);
484 }
485 
486 /// For an integer comparison, return 1 if the comparison is a signed operation
487 /// and 2 if the result is an unsigned comparison. Return zero if the operation
488 /// does not depend on the sign of the input (setne and seteq).
489 static int isSignedOp(ISD::CondCode Opcode) {
490   switch (Opcode) {
491   default: llvm_unreachable("Illegal integer setcc operation!");
492   case ISD::SETEQ:
493   case ISD::SETNE: return 0;
494   case ISD::SETLT:
495   case ISD::SETLE:
496   case ISD::SETGT:
497   case ISD::SETGE: return 1;
498   case ISD::SETULT:
499   case ISD::SETULE:
500   case ISD::SETUGT:
501   case ISD::SETUGE: return 2;
502   }
503 }
504 
505 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
506                                        EVT Type) {
507   bool IsInteger = Type.isInteger();
508   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
509     // Cannot fold a signed integer setcc with an unsigned integer setcc.
510     return ISD::SETCC_INVALID;
511 
512   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
513 
514   // If the N and U bits get set, then the resultant comparison DOES suddenly
515   // care about orderedness, and it is true when ordered.
516   if (Op > ISD::SETTRUE2)
517     Op &= ~16;     // Clear the U bit if the N bit is set.
518 
519   // Canonicalize illegal integer setcc's.
520   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
521     Op = ISD::SETNE;
522 
523   return ISD::CondCode(Op);
524 }
525 
526 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
527                                         EVT Type) {
528   bool IsInteger = Type.isInteger();
529   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
530     // Cannot fold a signed setcc with an unsigned setcc.
531     return ISD::SETCC_INVALID;
532 
533   // Combine all of the condition bits.
534   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
535 
536   // Canonicalize illegal integer setcc's.
537   if (IsInteger) {
538     switch (Result) {
539     default: break;
540     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
541     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
542     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
543     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
544     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
545     }
546   }
547 
548   return Result;
549 }
550 
551 //===----------------------------------------------------------------------===//
552 //                           SDNode Profile Support
553 //===----------------------------------------------------------------------===//
554 
555 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
556 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
557   ID.AddInteger(OpC);
558 }
559 
560 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
561 /// solely with their pointer.
562 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
563   ID.AddPointer(VTList.VTs);
564 }
565 
566 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
567 static void AddNodeIDOperands(FoldingSetNodeID &ID,
568                               ArrayRef<SDValue> Ops) {
569   for (auto& Op : Ops) {
570     ID.AddPointer(Op.getNode());
571     ID.AddInteger(Op.getResNo());
572   }
573 }
574 
575 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
576 static void AddNodeIDOperands(FoldingSetNodeID &ID,
577                               ArrayRef<SDUse> Ops) {
578   for (auto& Op : Ops) {
579     ID.AddPointer(Op.getNode());
580     ID.AddInteger(Op.getResNo());
581   }
582 }
583 
584 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
585                           SDVTList VTList, ArrayRef<SDValue> OpList) {
586   AddNodeIDOpcode(ID, OpC);
587   AddNodeIDValueTypes(ID, VTList);
588   AddNodeIDOperands(ID, OpList);
589 }
590 
591 /// If this is an SDNode with special info, add this info to the NodeID data.
592 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
593   switch (N->getOpcode()) {
594   case ISD::TargetExternalSymbol:
595   case ISD::ExternalSymbol:
596   case ISD::MCSymbol:
597     llvm_unreachable("Should only be used on nodes with operands");
598   default: break;  // Normal nodes don't need extra info.
599   case ISD::TargetConstant:
600   case ISD::Constant: {
601     const ConstantSDNode *C = cast<ConstantSDNode>(N);
602     ID.AddPointer(C->getConstantIntValue());
603     ID.AddBoolean(C->isOpaque());
604     break;
605   }
606   case ISD::TargetConstantFP:
607   case ISD::ConstantFP:
608     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
609     break;
610   case ISD::TargetGlobalAddress:
611   case ISD::GlobalAddress:
612   case ISD::TargetGlobalTLSAddress:
613   case ISD::GlobalTLSAddress: {
614     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
615     ID.AddPointer(GA->getGlobal());
616     ID.AddInteger(GA->getOffset());
617     ID.AddInteger(GA->getTargetFlags());
618     break;
619   }
620   case ISD::BasicBlock:
621     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
622     break;
623   case ISD::Register:
624     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
625     break;
626   case ISD::RegisterMask:
627     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
628     break;
629   case ISD::SRCVALUE:
630     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
631     break;
632   case ISD::FrameIndex:
633   case ISD::TargetFrameIndex:
634     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
635     break;
636   case ISD::LIFETIME_START:
637   case ISD::LIFETIME_END:
638     if (cast<LifetimeSDNode>(N)->hasOffset()) {
639       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
640       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
641     }
642     break;
643   case ISD::PSEUDO_PROBE:
644     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
645     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
646     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
647     break;
648   case ISD::JumpTable:
649   case ISD::TargetJumpTable:
650     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
651     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
652     break;
653   case ISD::ConstantPool:
654   case ISD::TargetConstantPool: {
655     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
656     ID.AddInteger(CP->getAlign().value());
657     ID.AddInteger(CP->getOffset());
658     if (CP->isMachineConstantPoolEntry())
659       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
660     else
661       ID.AddPointer(CP->getConstVal());
662     ID.AddInteger(CP->getTargetFlags());
663     break;
664   }
665   case ISD::TargetIndex: {
666     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
667     ID.AddInteger(TI->getIndex());
668     ID.AddInteger(TI->getOffset());
669     ID.AddInteger(TI->getTargetFlags());
670     break;
671   }
672   case ISD::LOAD: {
673     const LoadSDNode *LD = cast<LoadSDNode>(N);
674     ID.AddInteger(LD->getMemoryVT().getRawBits());
675     ID.AddInteger(LD->getRawSubclassData());
676     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
677     break;
678   }
679   case ISD::STORE: {
680     const StoreSDNode *ST = cast<StoreSDNode>(N);
681     ID.AddInteger(ST->getMemoryVT().getRawBits());
682     ID.AddInteger(ST->getRawSubclassData());
683     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
684     break;
685   }
686   case ISD::VP_LOAD: {
687     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
688     ID.AddInteger(ELD->getMemoryVT().getRawBits());
689     ID.AddInteger(ELD->getRawSubclassData());
690     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
691     break;
692   }
693   case ISD::VP_STORE: {
694     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
695     ID.AddInteger(EST->getMemoryVT().getRawBits());
696     ID.AddInteger(EST->getRawSubclassData());
697     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
698     break;
699   }
700   case ISD::VP_GATHER: {
701     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
702     ID.AddInteger(EG->getMemoryVT().getRawBits());
703     ID.AddInteger(EG->getRawSubclassData());
704     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
705     break;
706   }
707   case ISD::VP_SCATTER: {
708     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
709     ID.AddInteger(ES->getMemoryVT().getRawBits());
710     ID.AddInteger(ES->getRawSubclassData());
711     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
712     break;
713   }
714   case ISD::MLOAD: {
715     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
716     ID.AddInteger(MLD->getMemoryVT().getRawBits());
717     ID.AddInteger(MLD->getRawSubclassData());
718     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
719     break;
720   }
721   case ISD::MSTORE: {
722     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
723     ID.AddInteger(MST->getMemoryVT().getRawBits());
724     ID.AddInteger(MST->getRawSubclassData());
725     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
726     break;
727   }
728   case ISD::MGATHER: {
729     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
730     ID.AddInteger(MG->getMemoryVT().getRawBits());
731     ID.AddInteger(MG->getRawSubclassData());
732     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
733     break;
734   }
735   case ISD::MSCATTER: {
736     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
737     ID.AddInteger(MS->getMemoryVT().getRawBits());
738     ID.AddInteger(MS->getRawSubclassData());
739     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
740     break;
741   }
742   case ISD::ATOMIC_CMP_SWAP:
743   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
744   case ISD::ATOMIC_SWAP:
745   case ISD::ATOMIC_LOAD_ADD:
746   case ISD::ATOMIC_LOAD_SUB:
747   case ISD::ATOMIC_LOAD_AND:
748   case ISD::ATOMIC_LOAD_CLR:
749   case ISD::ATOMIC_LOAD_OR:
750   case ISD::ATOMIC_LOAD_XOR:
751   case ISD::ATOMIC_LOAD_NAND:
752   case ISD::ATOMIC_LOAD_MIN:
753   case ISD::ATOMIC_LOAD_MAX:
754   case ISD::ATOMIC_LOAD_UMIN:
755   case ISD::ATOMIC_LOAD_UMAX:
756   case ISD::ATOMIC_LOAD:
757   case ISD::ATOMIC_STORE: {
758     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
759     ID.AddInteger(AT->getMemoryVT().getRawBits());
760     ID.AddInteger(AT->getRawSubclassData());
761     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
762     break;
763   }
764   case ISD::PREFETCH: {
765     const MemSDNode *PF = cast<MemSDNode>(N);
766     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
767     break;
768   }
769   case ISD::VECTOR_SHUFFLE: {
770     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
771     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
772          i != e; ++i)
773       ID.AddInteger(SVN->getMaskElt(i));
774     break;
775   }
776   case ISD::TargetBlockAddress:
777   case ISD::BlockAddress: {
778     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
779     ID.AddPointer(BA->getBlockAddress());
780     ID.AddInteger(BA->getOffset());
781     ID.AddInteger(BA->getTargetFlags());
782     break;
783   }
784   } // end switch (N->getOpcode())
785 
786   // Target specific memory nodes could also have address spaces to check.
787   if (N->isTargetMemoryOpcode())
788     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
789 }
790 
791 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
792 /// data.
793 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
794   AddNodeIDOpcode(ID, N->getOpcode());
795   // Add the return value info.
796   AddNodeIDValueTypes(ID, N->getVTList());
797   // Add the operand info.
798   AddNodeIDOperands(ID, N->ops());
799 
800   // Handle SDNode leafs with special info.
801   AddNodeIDCustom(ID, N);
802 }
803 
804 //===----------------------------------------------------------------------===//
805 //                              SelectionDAG Class
806 //===----------------------------------------------------------------------===//
807 
808 /// doNotCSE - Return true if CSE should not be performed for this node.
809 static bool doNotCSE(SDNode *N) {
810   if (N->getValueType(0) == MVT::Glue)
811     return true; // Never CSE anything that produces a flag.
812 
813   switch (N->getOpcode()) {
814   default: break;
815   case ISD::HANDLENODE:
816   case ISD::EH_LABEL:
817     return true;   // Never CSE these nodes.
818   }
819 
820   // Check that remaining values produced are not flags.
821   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
822     if (N->getValueType(i) == MVT::Glue)
823       return true; // Never CSE anything that produces a flag.
824 
825   return false;
826 }
827 
828 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
829 /// SelectionDAG.
830 void SelectionDAG::RemoveDeadNodes() {
831   // Create a dummy node (which is not added to allnodes), that adds a reference
832   // to the root node, preventing it from being deleted.
833   HandleSDNode Dummy(getRoot());
834 
835   SmallVector<SDNode*, 128> DeadNodes;
836 
837   // Add all obviously-dead nodes to the DeadNodes worklist.
838   for (SDNode &Node : allnodes())
839     if (Node.use_empty())
840       DeadNodes.push_back(&Node);
841 
842   RemoveDeadNodes(DeadNodes);
843 
844   // If the root changed (e.g. it was a dead load, update the root).
845   setRoot(Dummy.getValue());
846 }
847 
848 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
849 /// given list, and any nodes that become unreachable as a result.
850 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
851 
852   // Process the worklist, deleting the nodes and adding their uses to the
853   // worklist.
854   while (!DeadNodes.empty()) {
855     SDNode *N = DeadNodes.pop_back_val();
856     // Skip to next node if we've already managed to delete the node. This could
857     // happen if replacing a node causes a node previously added to the node to
858     // be deleted.
859     if (N->getOpcode() == ISD::DELETED_NODE)
860       continue;
861 
862     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
863       DUL->NodeDeleted(N, nullptr);
864 
865     // Take the node out of the appropriate CSE map.
866     RemoveNodeFromCSEMaps(N);
867 
868     // Next, brutally remove the operand list.  This is safe to do, as there are
869     // no cycles in the graph.
870     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
871       SDUse &Use = *I++;
872       SDNode *Operand = Use.getNode();
873       Use.set(SDValue());
874 
875       // Now that we removed this operand, see if there are no uses of it left.
876       if (Operand->use_empty())
877         DeadNodes.push_back(Operand);
878     }
879 
880     DeallocateNode(N);
881   }
882 }
883 
884 void SelectionDAG::RemoveDeadNode(SDNode *N){
885   SmallVector<SDNode*, 16> DeadNodes(1, N);
886 
887   // Create a dummy node that adds a reference to the root node, preventing
888   // it from being deleted.  (This matters if the root is an operand of the
889   // dead node.)
890   HandleSDNode Dummy(getRoot());
891 
892   RemoveDeadNodes(DeadNodes);
893 }
894 
895 void SelectionDAG::DeleteNode(SDNode *N) {
896   // First take this out of the appropriate CSE map.
897   RemoveNodeFromCSEMaps(N);
898 
899   // Finally, remove uses due to operands of this node, remove from the
900   // AllNodes list, and delete the node.
901   DeleteNodeNotInCSEMaps(N);
902 }
903 
904 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
905   assert(N->getIterator() != AllNodes.begin() &&
906          "Cannot delete the entry node!");
907   assert(N->use_empty() && "Cannot delete a node that is not dead!");
908 
909   // Drop all of the operands and decrement used node's use counts.
910   N->DropOperands();
911 
912   DeallocateNode(N);
913 }
914 
915 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
916   assert(!(V->isVariadic() && isParameter));
917   if (isParameter)
918     ByvalParmDbgValues.push_back(V);
919   else
920     DbgValues.push_back(V);
921   for (const SDNode *Node : V->getSDNodes())
922     if (Node)
923       DbgValMap[Node].push_back(V);
924 }
925 
926 void SDDbgInfo::erase(const SDNode *Node) {
927   DbgValMapType::iterator I = DbgValMap.find(Node);
928   if (I == DbgValMap.end())
929     return;
930   for (auto &Val: I->second)
931     Val->setIsInvalidated();
932   DbgValMap.erase(I);
933 }
934 
935 void SelectionDAG::DeallocateNode(SDNode *N) {
936   // If we have operands, deallocate them.
937   removeOperands(N);
938 
939   NodeAllocator.Deallocate(AllNodes.remove(N));
940 
941   // Set the opcode to DELETED_NODE to help catch bugs when node
942   // memory is reallocated.
943   // FIXME: There are places in SDag that have grown a dependency on the opcode
944   // value in the released node.
945   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
946   N->NodeType = ISD::DELETED_NODE;
947 
948   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
949   // them and forget about that node.
950   DbgInfo->erase(N);
951 }
952 
953 #ifndef NDEBUG
954 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
955 static void VerifySDNode(SDNode *N) {
956   switch (N->getOpcode()) {
957   default:
958     break;
959   case ISD::BUILD_PAIR: {
960     EVT VT = N->getValueType(0);
961     assert(N->getNumValues() == 1 && "Too many results!");
962     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
963            "Wrong return type!");
964     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
965     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
966            "Mismatched operand types!");
967     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
968            "Wrong operand type!");
969     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
970            "Wrong return type size");
971     break;
972   }
973   case ISD::BUILD_VECTOR: {
974     assert(N->getNumValues() == 1 && "Too many results!");
975     assert(N->getValueType(0).isVector() && "Wrong return type!");
976     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
977            "Wrong number of operands!");
978     EVT EltVT = N->getValueType(0).getVectorElementType();
979     for (const SDUse &Op : N->ops()) {
980       assert((Op.getValueType() == EltVT ||
981               (EltVT.isInteger() && Op.getValueType().isInteger() &&
982                EltVT.bitsLE(Op.getValueType()))) &&
983              "Wrong operand type!");
984       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
985              "Operands must all have the same type");
986     }
987     break;
988   }
989   }
990 }
991 #endif // NDEBUG
992 
993 /// Insert a newly allocated node into the DAG.
994 ///
995 /// Handles insertion into the all nodes list and CSE map, as well as
996 /// verification and other common operations when a new node is allocated.
997 void SelectionDAG::InsertNode(SDNode *N) {
998   AllNodes.push_back(N);
999 #ifndef NDEBUG
1000   N->PersistentId = NextPersistentId++;
1001   VerifySDNode(N);
1002 #endif
1003   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1004     DUL->NodeInserted(N);
1005 }
1006 
1007 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1008 /// correspond to it.  This is useful when we're about to delete or repurpose
1009 /// the node.  We don't want future request for structurally identical nodes
1010 /// to return N anymore.
1011 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1012   bool Erased = false;
1013   switch (N->getOpcode()) {
1014   case ISD::HANDLENODE: return false;  // noop.
1015   case ISD::CONDCODE:
1016     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1017            "Cond code doesn't exist!");
1018     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1019     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1020     break;
1021   case ISD::ExternalSymbol:
1022     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1023     break;
1024   case ISD::TargetExternalSymbol: {
1025     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1026     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1027         ESN->getSymbol(), ESN->getTargetFlags()));
1028     break;
1029   }
1030   case ISD::MCSymbol: {
1031     auto *MCSN = cast<MCSymbolSDNode>(N);
1032     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1033     break;
1034   }
1035   case ISD::VALUETYPE: {
1036     EVT VT = cast<VTSDNode>(N)->getVT();
1037     if (VT.isExtended()) {
1038       Erased = ExtendedValueTypeNodes.erase(VT);
1039     } else {
1040       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1041       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1042     }
1043     break;
1044   }
1045   default:
1046     // Remove it from the CSE Map.
1047     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1048     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1049     Erased = CSEMap.RemoveNode(N);
1050     break;
1051   }
1052 #ifndef NDEBUG
1053   // Verify that the node was actually in one of the CSE maps, unless it has a
1054   // flag result (which cannot be CSE'd) or is one of the special cases that are
1055   // not subject to CSE.
1056   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1057       !N->isMachineOpcode() && !doNotCSE(N)) {
1058     N->dump(this);
1059     dbgs() << "\n";
1060     llvm_unreachable("Node is not in map!");
1061   }
1062 #endif
1063   return Erased;
1064 }
1065 
1066 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1067 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1068 /// node already exists, in which case transfer all its users to the existing
1069 /// node. This transfer can potentially trigger recursive merging.
1070 void
1071 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1072   // For node types that aren't CSE'd, just act as if no identical node
1073   // already exists.
1074   if (!doNotCSE(N)) {
1075     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1076     if (Existing != N) {
1077       // If there was already an existing matching node, use ReplaceAllUsesWith
1078       // to replace the dead one with the existing one.  This can cause
1079       // recursive merging of other unrelated nodes down the line.
1080       ReplaceAllUsesWith(N, Existing);
1081 
1082       // N is now dead. Inform the listeners and delete it.
1083       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1084         DUL->NodeDeleted(N, Existing);
1085       DeleteNodeNotInCSEMaps(N);
1086       return;
1087     }
1088   }
1089 
1090   // If the node doesn't already exist, we updated it.  Inform listeners.
1091   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1092     DUL->NodeUpdated(N);
1093 }
1094 
1095 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1096 /// were replaced with those specified.  If this node is never memoized,
1097 /// return null, otherwise return a pointer to the slot it would take.  If a
1098 /// node already exists with these operands, the slot will be non-null.
1099 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1100                                            void *&InsertPos) {
1101   if (doNotCSE(N))
1102     return nullptr;
1103 
1104   SDValue Ops[] = { Op };
1105   FoldingSetNodeID ID;
1106   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1107   AddNodeIDCustom(ID, N);
1108   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1109   if (Node)
1110     Node->intersectFlagsWith(N->getFlags());
1111   return Node;
1112 }
1113 
1114 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1115 /// were replaced with those specified.  If this node is never memoized,
1116 /// return null, otherwise return a pointer to the slot it would take.  If a
1117 /// node already exists with these operands, the slot will be non-null.
1118 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1119                                            SDValue Op1, SDValue Op2,
1120                                            void *&InsertPos) {
1121   if (doNotCSE(N))
1122     return nullptr;
1123 
1124   SDValue Ops[] = { Op1, Op2 };
1125   FoldingSetNodeID ID;
1126   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1127   AddNodeIDCustom(ID, N);
1128   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1129   if (Node)
1130     Node->intersectFlagsWith(N->getFlags());
1131   return Node;
1132 }
1133 
1134 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1135 /// were replaced with those specified.  If this node is never memoized,
1136 /// return null, otherwise return a pointer to the slot it would take.  If a
1137 /// node already exists with these operands, the slot will be non-null.
1138 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1139                                            void *&InsertPos) {
1140   if (doNotCSE(N))
1141     return nullptr;
1142 
1143   FoldingSetNodeID ID;
1144   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1145   AddNodeIDCustom(ID, N);
1146   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1147   if (Node)
1148     Node->intersectFlagsWith(N->getFlags());
1149   return Node;
1150 }
1151 
1152 Align SelectionDAG::getEVTAlign(EVT VT) const {
1153   Type *Ty = VT == MVT::iPTR ?
1154                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1155                    VT.getTypeForEVT(*getContext());
1156 
1157   return getDataLayout().getABITypeAlign(Ty);
1158 }
1159 
1160 // EntryNode could meaningfully have debug info if we can find it...
1161 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1162     : TM(tm), OptLevel(OL),
1163       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1164       Root(getEntryNode()) {
1165   InsertNode(&EntryNode);
1166   DbgInfo = new SDDbgInfo();
1167 }
1168 
1169 void SelectionDAG::init(MachineFunction &NewMF,
1170                         OptimizationRemarkEmitter &NewORE,
1171                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1172                         LegacyDivergenceAnalysis * Divergence,
1173                         ProfileSummaryInfo *PSIin,
1174                         BlockFrequencyInfo *BFIin) {
1175   MF = &NewMF;
1176   SDAGISelPass = PassPtr;
1177   ORE = &NewORE;
1178   TLI = getSubtarget().getTargetLowering();
1179   TSI = getSubtarget().getSelectionDAGInfo();
1180   LibInfo = LibraryInfo;
1181   Context = &MF->getFunction().getContext();
1182   DA = Divergence;
1183   PSI = PSIin;
1184   BFI = BFIin;
1185 }
1186 
1187 SelectionDAG::~SelectionDAG() {
1188   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1189   allnodes_clear();
1190   OperandRecycler.clear(OperandAllocator);
1191   delete DbgInfo;
1192 }
1193 
1194 bool SelectionDAG::shouldOptForSize() const {
1195   return MF->getFunction().hasOptSize() ||
1196       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1197 }
1198 
1199 void SelectionDAG::allnodes_clear() {
1200   assert(&*AllNodes.begin() == &EntryNode);
1201   AllNodes.remove(AllNodes.begin());
1202   while (!AllNodes.empty())
1203     DeallocateNode(&AllNodes.front());
1204 #ifndef NDEBUG
1205   NextPersistentId = 0;
1206 #endif
1207 }
1208 
1209 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1210                                           void *&InsertPos) {
1211   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1212   if (N) {
1213     switch (N->getOpcode()) {
1214     default: break;
1215     case ISD::Constant:
1216     case ISD::ConstantFP:
1217       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1218                        "debug location.  Use another overload.");
1219     }
1220   }
1221   return N;
1222 }
1223 
1224 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1225                                           const SDLoc &DL, void *&InsertPos) {
1226   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1227   if (N) {
1228     switch (N->getOpcode()) {
1229     case ISD::Constant:
1230     case ISD::ConstantFP:
1231       // Erase debug location from the node if the node is used at several
1232       // different places. Do not propagate one location to all uses as it
1233       // will cause a worse single stepping debugging experience.
1234       if (N->getDebugLoc() != DL.getDebugLoc())
1235         N->setDebugLoc(DebugLoc());
1236       break;
1237     default:
1238       // When the node's point of use is located earlier in the instruction
1239       // sequence than its prior point of use, update its debug info to the
1240       // earlier location.
1241       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1242         N->setDebugLoc(DL.getDebugLoc());
1243       break;
1244     }
1245   }
1246   return N;
1247 }
1248 
1249 void SelectionDAG::clear() {
1250   allnodes_clear();
1251   OperandRecycler.clear(OperandAllocator);
1252   OperandAllocator.Reset();
1253   CSEMap.clear();
1254 
1255   ExtendedValueTypeNodes.clear();
1256   ExternalSymbols.clear();
1257   TargetExternalSymbols.clear();
1258   MCSymbols.clear();
1259   SDCallSiteDbgInfo.clear();
1260   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1261             static_cast<CondCodeSDNode*>(nullptr));
1262   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1263             static_cast<SDNode*>(nullptr));
1264 
1265   EntryNode.UseList = nullptr;
1266   InsertNode(&EntryNode);
1267   Root = getEntryNode();
1268   DbgInfo->clear();
1269 }
1270 
1271 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1272   return VT.bitsGT(Op.getValueType())
1273              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1274              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1275 }
1276 
1277 std::pair<SDValue, SDValue>
1278 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1279                                        const SDLoc &DL, EVT VT) {
1280   assert(!VT.bitsEq(Op.getValueType()) &&
1281          "Strict no-op FP extend/round not allowed.");
1282   SDValue Res =
1283       VT.bitsGT(Op.getValueType())
1284           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1285           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1286                     {Chain, Op, getIntPtrConstant(0, DL)});
1287 
1288   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1289 }
1290 
1291 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1292   return VT.bitsGT(Op.getValueType()) ?
1293     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1294     getNode(ISD::TRUNCATE, DL, VT, Op);
1295 }
1296 
1297 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1298   return VT.bitsGT(Op.getValueType()) ?
1299     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1300     getNode(ISD::TRUNCATE, DL, VT, Op);
1301 }
1302 
1303 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1304   return VT.bitsGT(Op.getValueType()) ?
1305     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1306     getNode(ISD::TRUNCATE, DL, VT, Op);
1307 }
1308 
1309 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1310                                         EVT OpVT) {
1311   if (VT.bitsLE(Op.getValueType()))
1312     return getNode(ISD::TRUNCATE, SL, VT, Op);
1313 
1314   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1315   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1316 }
1317 
1318 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1319   EVT OpVT = Op.getValueType();
1320   assert(VT.isInteger() && OpVT.isInteger() &&
1321          "Cannot getZeroExtendInReg FP types");
1322   assert(VT.isVector() == OpVT.isVector() &&
1323          "getZeroExtendInReg type should be vector iff the operand "
1324          "type is vector!");
1325   assert((!VT.isVector() ||
1326           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1327          "Vector element counts must match in getZeroExtendInReg");
1328   assert(VT.bitsLE(OpVT) && "Not extending!");
1329   if (OpVT == VT)
1330     return Op;
1331   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1332                                    VT.getScalarSizeInBits());
1333   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1334 }
1335 
1336 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1337   // Only unsigned pointer semantics are supported right now. In the future this
1338   // might delegate to TLI to check pointer signedness.
1339   return getZExtOrTrunc(Op, DL, VT);
1340 }
1341 
1342 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1343   // Only unsigned pointer semantics are supported right now. In the future this
1344   // might delegate to TLI to check pointer signedness.
1345   return getZeroExtendInReg(Op, DL, VT);
1346 }
1347 
1348 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1349 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1350   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1351 }
1352 
1353 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1354   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1355   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1356 }
1357 
1358 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1359                                       EVT OpVT) {
1360   if (!V)
1361     return getConstant(0, DL, VT);
1362 
1363   switch (TLI->getBooleanContents(OpVT)) {
1364   case TargetLowering::ZeroOrOneBooleanContent:
1365   case TargetLowering::UndefinedBooleanContent:
1366     return getConstant(1, DL, VT);
1367   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1368     return getAllOnesConstant(DL, VT);
1369   }
1370   llvm_unreachable("Unexpected boolean content enum!");
1371 }
1372 
1373 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1374                                   bool isT, bool isO) {
1375   EVT EltVT = VT.getScalarType();
1376   assert((EltVT.getSizeInBits() >= 64 ||
1377           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1378          "getConstant with a uint64_t value that doesn't fit in the type!");
1379   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1380 }
1381 
1382 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1383                                   bool isT, bool isO) {
1384   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1385 }
1386 
1387 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1388                                   EVT VT, bool isT, bool isO) {
1389   assert(VT.isInteger() && "Cannot create FP integer constant!");
1390 
1391   EVT EltVT = VT.getScalarType();
1392   const ConstantInt *Elt = &Val;
1393 
1394   // In some cases the vector type is legal but the element type is illegal and
1395   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1396   // inserted value (the type does not need to match the vector element type).
1397   // Any extra bits introduced will be truncated away.
1398   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1399                            TargetLowering::TypePromoteInteger) {
1400     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1401     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1402     Elt = ConstantInt::get(*getContext(), NewVal);
1403   }
1404   // In other cases the element type is illegal and needs to be expanded, for
1405   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1406   // the value into n parts and use a vector type with n-times the elements.
1407   // Then bitcast to the type requested.
1408   // Legalizing constants too early makes the DAGCombiner's job harder so we
1409   // only legalize if the DAG tells us we must produce legal types.
1410   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1411            TLI->getTypeAction(*getContext(), EltVT) ==
1412                TargetLowering::TypeExpandInteger) {
1413     const APInt &NewVal = Elt->getValue();
1414     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1415     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1416 
1417     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1418     if (VT.isScalableVector()) {
1419       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1420              "Can only handle an even split!");
1421       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1422 
1423       SmallVector<SDValue, 2> ScalarParts;
1424       for (unsigned i = 0; i != Parts; ++i)
1425         ScalarParts.push_back(getConstant(
1426             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1427             ViaEltVT, isT, isO));
1428 
1429       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1430     }
1431 
1432     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1433     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1434 
1435     // Check the temporary vector is the correct size. If this fails then
1436     // getTypeToTransformTo() probably returned a type whose size (in bits)
1437     // isn't a power-of-2 factor of the requested type size.
1438     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1439 
1440     SmallVector<SDValue, 2> EltParts;
1441     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1442       EltParts.push_back(getConstant(
1443           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1444           ViaEltVT, isT, isO));
1445 
1446     // EltParts is currently in little endian order. If we actually want
1447     // big-endian order then reverse it now.
1448     if (getDataLayout().isBigEndian())
1449       std::reverse(EltParts.begin(), EltParts.end());
1450 
1451     // The elements must be reversed when the element order is different
1452     // to the endianness of the elements (because the BITCAST is itself a
1453     // vector shuffle in this situation). However, we do not need any code to
1454     // perform this reversal because getConstant() is producing a vector
1455     // splat.
1456     // This situation occurs in MIPS MSA.
1457 
1458     SmallVector<SDValue, 8> Ops;
1459     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1460       llvm::append_range(Ops, EltParts);
1461 
1462     SDValue V =
1463         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1464     return V;
1465   }
1466 
1467   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1468          "APInt size does not match type size!");
1469   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1470   FoldingSetNodeID ID;
1471   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1472   ID.AddPointer(Elt);
1473   ID.AddBoolean(isO);
1474   void *IP = nullptr;
1475   SDNode *N = nullptr;
1476   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1477     if (!VT.isVector())
1478       return SDValue(N, 0);
1479 
1480   if (!N) {
1481     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1482     CSEMap.InsertNode(N, IP);
1483     InsertNode(N);
1484     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1485   }
1486 
1487   SDValue Result(N, 0);
1488   if (VT.isScalableVector())
1489     Result = getSplatVector(VT, DL, Result);
1490   else if (VT.isVector())
1491     Result = getSplatBuildVector(VT, DL, Result);
1492 
1493   return Result;
1494 }
1495 
1496 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1497                                         bool isTarget) {
1498   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1499 }
1500 
1501 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1502                                              const SDLoc &DL, bool LegalTypes) {
1503   assert(VT.isInteger() && "Shift amount is not an integer type!");
1504   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1505   return getConstant(Val, DL, ShiftVT);
1506 }
1507 
1508 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1509                                            bool isTarget) {
1510   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1511 }
1512 
1513 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1514                                     bool isTarget) {
1515   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1516 }
1517 
1518 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1519                                     EVT VT, bool isTarget) {
1520   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1521 
1522   EVT EltVT = VT.getScalarType();
1523 
1524   // Do the map lookup using the actual bit pattern for the floating point
1525   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1526   // we don't have issues with SNANs.
1527   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1528   FoldingSetNodeID ID;
1529   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1530   ID.AddPointer(&V);
1531   void *IP = nullptr;
1532   SDNode *N = nullptr;
1533   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1534     if (!VT.isVector())
1535       return SDValue(N, 0);
1536 
1537   if (!N) {
1538     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1539     CSEMap.InsertNode(N, IP);
1540     InsertNode(N);
1541   }
1542 
1543   SDValue Result(N, 0);
1544   if (VT.isScalableVector())
1545     Result = getSplatVector(VT, DL, Result);
1546   else if (VT.isVector())
1547     Result = getSplatBuildVector(VT, DL, Result);
1548   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1549   return Result;
1550 }
1551 
1552 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1553                                     bool isTarget) {
1554   EVT EltVT = VT.getScalarType();
1555   if (EltVT == MVT::f32)
1556     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1557   if (EltVT == MVT::f64)
1558     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1559   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1560       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1561     bool Ignored;
1562     APFloat APF = APFloat(Val);
1563     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1564                 &Ignored);
1565     return getConstantFP(APF, DL, VT, isTarget);
1566   }
1567   llvm_unreachable("Unsupported type in getConstantFP");
1568 }
1569 
1570 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1571                                        EVT VT, int64_t Offset, bool isTargetGA,
1572                                        unsigned TargetFlags) {
1573   assert((TargetFlags == 0 || isTargetGA) &&
1574          "Cannot set target flags on target-independent globals");
1575 
1576   // Truncate (with sign-extension) the offset value to the pointer size.
1577   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1578   if (BitWidth < 64)
1579     Offset = SignExtend64(Offset, BitWidth);
1580 
1581   unsigned Opc;
1582   if (GV->isThreadLocal())
1583     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1584   else
1585     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1586 
1587   FoldingSetNodeID ID;
1588   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1589   ID.AddPointer(GV);
1590   ID.AddInteger(Offset);
1591   ID.AddInteger(TargetFlags);
1592   void *IP = nullptr;
1593   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1594     return SDValue(E, 0);
1595 
1596   auto *N = newSDNode<GlobalAddressSDNode>(
1597       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1598   CSEMap.InsertNode(N, IP);
1599     InsertNode(N);
1600   return SDValue(N, 0);
1601 }
1602 
1603 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1604   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1605   FoldingSetNodeID ID;
1606   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1607   ID.AddInteger(FI);
1608   void *IP = nullptr;
1609   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1610     return SDValue(E, 0);
1611 
1612   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1613   CSEMap.InsertNode(N, IP);
1614   InsertNode(N);
1615   return SDValue(N, 0);
1616 }
1617 
1618 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1619                                    unsigned TargetFlags) {
1620   assert((TargetFlags == 0 || isTarget) &&
1621          "Cannot set target flags on target-independent jump tables");
1622   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1623   FoldingSetNodeID ID;
1624   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1625   ID.AddInteger(JTI);
1626   ID.AddInteger(TargetFlags);
1627   void *IP = nullptr;
1628   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1629     return SDValue(E, 0);
1630 
1631   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1632   CSEMap.InsertNode(N, IP);
1633   InsertNode(N);
1634   return SDValue(N, 0);
1635 }
1636 
1637 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1638                                       MaybeAlign Alignment, int Offset,
1639                                       bool isTarget, unsigned TargetFlags) {
1640   assert((TargetFlags == 0 || isTarget) &&
1641          "Cannot set target flags on target-independent globals");
1642   if (!Alignment)
1643     Alignment = shouldOptForSize()
1644                     ? getDataLayout().getABITypeAlign(C->getType())
1645                     : getDataLayout().getPrefTypeAlign(C->getType());
1646   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1647   FoldingSetNodeID ID;
1648   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1649   ID.AddInteger(Alignment->value());
1650   ID.AddInteger(Offset);
1651   ID.AddPointer(C);
1652   ID.AddInteger(TargetFlags);
1653   void *IP = nullptr;
1654   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1655     return SDValue(E, 0);
1656 
1657   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1658                                           TargetFlags);
1659   CSEMap.InsertNode(N, IP);
1660   InsertNode(N);
1661   SDValue V = SDValue(N, 0);
1662   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1663   return V;
1664 }
1665 
1666 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1667                                       MaybeAlign Alignment, int Offset,
1668                                       bool isTarget, unsigned TargetFlags) {
1669   assert((TargetFlags == 0 || isTarget) &&
1670          "Cannot set target flags on target-independent globals");
1671   if (!Alignment)
1672     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1673   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1674   FoldingSetNodeID ID;
1675   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1676   ID.AddInteger(Alignment->value());
1677   ID.AddInteger(Offset);
1678   C->addSelectionDAGCSEId(ID);
1679   ID.AddInteger(TargetFlags);
1680   void *IP = nullptr;
1681   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1682     return SDValue(E, 0);
1683 
1684   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1685                                           TargetFlags);
1686   CSEMap.InsertNode(N, IP);
1687   InsertNode(N);
1688   return SDValue(N, 0);
1689 }
1690 
1691 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1692                                      unsigned TargetFlags) {
1693   FoldingSetNodeID ID;
1694   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1695   ID.AddInteger(Index);
1696   ID.AddInteger(Offset);
1697   ID.AddInteger(TargetFlags);
1698   void *IP = nullptr;
1699   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1700     return SDValue(E, 0);
1701 
1702   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1703   CSEMap.InsertNode(N, IP);
1704   InsertNode(N);
1705   return SDValue(N, 0);
1706 }
1707 
1708 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1709   FoldingSetNodeID ID;
1710   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1711   ID.AddPointer(MBB);
1712   void *IP = nullptr;
1713   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1714     return SDValue(E, 0);
1715 
1716   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1717   CSEMap.InsertNode(N, IP);
1718   InsertNode(N);
1719   return SDValue(N, 0);
1720 }
1721 
1722 SDValue SelectionDAG::getValueType(EVT VT) {
1723   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1724       ValueTypeNodes.size())
1725     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1726 
1727   SDNode *&N = VT.isExtended() ?
1728     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1729 
1730   if (N) return SDValue(N, 0);
1731   N = newSDNode<VTSDNode>(VT);
1732   InsertNode(N);
1733   return SDValue(N, 0);
1734 }
1735 
1736 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1737   SDNode *&N = ExternalSymbols[Sym];
1738   if (N) return SDValue(N, 0);
1739   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1740   InsertNode(N);
1741   return SDValue(N, 0);
1742 }
1743 
1744 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1745   SDNode *&N = MCSymbols[Sym];
1746   if (N)
1747     return SDValue(N, 0);
1748   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1749   InsertNode(N);
1750   return SDValue(N, 0);
1751 }
1752 
1753 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1754                                               unsigned TargetFlags) {
1755   SDNode *&N =
1756       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1757   if (N) return SDValue(N, 0);
1758   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1759   InsertNode(N);
1760   return SDValue(N, 0);
1761 }
1762 
1763 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1764   if ((unsigned)Cond >= CondCodeNodes.size())
1765     CondCodeNodes.resize(Cond+1);
1766 
1767   if (!CondCodeNodes[Cond]) {
1768     auto *N = newSDNode<CondCodeSDNode>(Cond);
1769     CondCodeNodes[Cond] = N;
1770     InsertNode(N);
1771   }
1772 
1773   return SDValue(CondCodeNodes[Cond], 0);
1774 }
1775 
1776 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1777   APInt One(ResVT.getScalarSizeInBits(), 1);
1778   return getStepVector(DL, ResVT, One);
1779 }
1780 
1781 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1782   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1783   if (ResVT.isScalableVector())
1784     return getNode(
1785         ISD::STEP_VECTOR, DL, ResVT,
1786         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1787 
1788   SmallVector<SDValue, 16> OpsStepConstants;
1789   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1790     OpsStepConstants.push_back(
1791         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1792   return getBuildVector(ResVT, DL, OpsStepConstants);
1793 }
1794 
1795 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1796 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1797 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1798   std::swap(N1, N2);
1799   ShuffleVectorSDNode::commuteMask(M);
1800 }
1801 
1802 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1803                                        SDValue N2, ArrayRef<int> Mask) {
1804   assert(VT.getVectorNumElements() == Mask.size() &&
1805          "Must have the same number of vector elements as mask elements!");
1806   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1807          "Invalid VECTOR_SHUFFLE");
1808 
1809   // Canonicalize shuffle undef, undef -> undef
1810   if (N1.isUndef() && N2.isUndef())
1811     return getUNDEF(VT);
1812 
1813   // Validate that all indices in Mask are within the range of the elements
1814   // input to the shuffle.
1815   int NElts = Mask.size();
1816   assert(llvm::all_of(Mask,
1817                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1818          "Index out of range");
1819 
1820   // Copy the mask so we can do any needed cleanup.
1821   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1822 
1823   // Canonicalize shuffle v, v -> v, undef
1824   if (N1 == N2) {
1825     N2 = getUNDEF(VT);
1826     for (int i = 0; i != NElts; ++i)
1827       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1828   }
1829 
1830   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1831   if (N1.isUndef())
1832     commuteShuffle(N1, N2, MaskVec);
1833 
1834   if (TLI->hasVectorBlend()) {
1835     // If shuffling a splat, try to blend the splat instead. We do this here so
1836     // that even when this arises during lowering we don't have to re-handle it.
1837     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1838       BitVector UndefElements;
1839       SDValue Splat = BV->getSplatValue(&UndefElements);
1840       if (!Splat)
1841         return;
1842 
1843       for (int i = 0; i < NElts; ++i) {
1844         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1845           continue;
1846 
1847         // If this input comes from undef, mark it as such.
1848         if (UndefElements[MaskVec[i] - Offset]) {
1849           MaskVec[i] = -1;
1850           continue;
1851         }
1852 
1853         // If we can blend a non-undef lane, use that instead.
1854         if (!UndefElements[i])
1855           MaskVec[i] = i + Offset;
1856       }
1857     };
1858     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1859       BlendSplat(N1BV, 0);
1860     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1861       BlendSplat(N2BV, NElts);
1862   }
1863 
1864   // Canonicalize all index into lhs, -> shuffle lhs, undef
1865   // Canonicalize all index into rhs, -> shuffle rhs, undef
1866   bool AllLHS = true, AllRHS = true;
1867   bool N2Undef = N2.isUndef();
1868   for (int i = 0; i != NElts; ++i) {
1869     if (MaskVec[i] >= NElts) {
1870       if (N2Undef)
1871         MaskVec[i] = -1;
1872       else
1873         AllLHS = false;
1874     } else if (MaskVec[i] >= 0) {
1875       AllRHS = false;
1876     }
1877   }
1878   if (AllLHS && AllRHS)
1879     return getUNDEF(VT);
1880   if (AllLHS && !N2Undef)
1881     N2 = getUNDEF(VT);
1882   if (AllRHS) {
1883     N1 = getUNDEF(VT);
1884     commuteShuffle(N1, N2, MaskVec);
1885   }
1886   // Reset our undef status after accounting for the mask.
1887   N2Undef = N2.isUndef();
1888   // Re-check whether both sides ended up undef.
1889   if (N1.isUndef() && N2Undef)
1890     return getUNDEF(VT);
1891 
1892   // If Identity shuffle return that node.
1893   bool Identity = true, AllSame = true;
1894   for (int i = 0; i != NElts; ++i) {
1895     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1896     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1897   }
1898   if (Identity && NElts)
1899     return N1;
1900 
1901   // Shuffling a constant splat doesn't change the result.
1902   if (N2Undef) {
1903     SDValue V = N1;
1904 
1905     // Look through any bitcasts. We check that these don't change the number
1906     // (and size) of elements and just changes their types.
1907     while (V.getOpcode() == ISD::BITCAST)
1908       V = V->getOperand(0);
1909 
1910     // A splat should always show up as a build vector node.
1911     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1912       BitVector UndefElements;
1913       SDValue Splat = BV->getSplatValue(&UndefElements);
1914       // If this is a splat of an undef, shuffling it is also undef.
1915       if (Splat && Splat.isUndef())
1916         return getUNDEF(VT);
1917 
1918       bool SameNumElts =
1919           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1920 
1921       // We only have a splat which can skip shuffles if there is a splatted
1922       // value and no undef lanes rearranged by the shuffle.
1923       if (Splat && UndefElements.none()) {
1924         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1925         // number of elements match or the value splatted is a zero constant.
1926         if (SameNumElts)
1927           return N1;
1928         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1929           if (C->isZero())
1930             return N1;
1931       }
1932 
1933       // If the shuffle itself creates a splat, build the vector directly.
1934       if (AllSame && SameNumElts) {
1935         EVT BuildVT = BV->getValueType(0);
1936         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1937         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1938 
1939         // We may have jumped through bitcasts, so the type of the
1940         // BUILD_VECTOR may not match the type of the shuffle.
1941         if (BuildVT != VT)
1942           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1943         return NewBV;
1944       }
1945     }
1946   }
1947 
1948   FoldingSetNodeID ID;
1949   SDValue Ops[2] = { N1, N2 };
1950   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1951   for (int i = 0; i != NElts; ++i)
1952     ID.AddInteger(MaskVec[i]);
1953 
1954   void* IP = nullptr;
1955   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1956     return SDValue(E, 0);
1957 
1958   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1959   // SDNode doesn't have access to it.  This memory will be "leaked" when
1960   // the node is deallocated, but recovered when the NodeAllocator is released.
1961   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1962   llvm::copy(MaskVec, MaskAlloc);
1963 
1964   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1965                                            dl.getDebugLoc(), MaskAlloc);
1966   createOperands(N, Ops);
1967 
1968   CSEMap.InsertNode(N, IP);
1969   InsertNode(N);
1970   SDValue V = SDValue(N, 0);
1971   NewSDValueDbgMsg(V, "Creating new node: ", this);
1972   return V;
1973 }
1974 
1975 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1976   EVT VT = SV.getValueType(0);
1977   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1978   ShuffleVectorSDNode::commuteMask(MaskVec);
1979 
1980   SDValue Op0 = SV.getOperand(0);
1981   SDValue Op1 = SV.getOperand(1);
1982   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1983 }
1984 
1985 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1986   FoldingSetNodeID ID;
1987   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1988   ID.AddInteger(RegNo);
1989   void *IP = nullptr;
1990   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1991     return SDValue(E, 0);
1992 
1993   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1994   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1995   CSEMap.InsertNode(N, IP);
1996   InsertNode(N);
1997   return SDValue(N, 0);
1998 }
1999 
2000 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2001   FoldingSetNodeID ID;
2002   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2003   ID.AddPointer(RegMask);
2004   void *IP = nullptr;
2005   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2006     return SDValue(E, 0);
2007 
2008   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2009   CSEMap.InsertNode(N, IP);
2010   InsertNode(N);
2011   return SDValue(N, 0);
2012 }
2013 
2014 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2015                                  MCSymbol *Label) {
2016   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2017 }
2018 
2019 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2020                                    SDValue Root, MCSymbol *Label) {
2021   FoldingSetNodeID ID;
2022   SDValue Ops[] = { Root };
2023   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2024   ID.AddPointer(Label);
2025   void *IP = nullptr;
2026   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2027     return SDValue(E, 0);
2028 
2029   auto *N =
2030       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2031   createOperands(N, Ops);
2032 
2033   CSEMap.InsertNode(N, IP);
2034   InsertNode(N);
2035   return SDValue(N, 0);
2036 }
2037 
2038 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2039                                       int64_t Offset, bool isTarget,
2040                                       unsigned TargetFlags) {
2041   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2042 
2043   FoldingSetNodeID ID;
2044   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2045   ID.AddPointer(BA);
2046   ID.AddInteger(Offset);
2047   ID.AddInteger(TargetFlags);
2048   void *IP = nullptr;
2049   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2050     return SDValue(E, 0);
2051 
2052   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2053   CSEMap.InsertNode(N, IP);
2054   InsertNode(N);
2055   return SDValue(N, 0);
2056 }
2057 
2058 SDValue SelectionDAG::getSrcValue(const Value *V) {
2059   FoldingSetNodeID ID;
2060   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2061   ID.AddPointer(V);
2062 
2063   void *IP = nullptr;
2064   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2065     return SDValue(E, 0);
2066 
2067   auto *N = newSDNode<SrcValueSDNode>(V);
2068   CSEMap.InsertNode(N, IP);
2069   InsertNode(N);
2070   return SDValue(N, 0);
2071 }
2072 
2073 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2074   FoldingSetNodeID ID;
2075   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2076   ID.AddPointer(MD);
2077 
2078   void *IP = nullptr;
2079   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2080     return SDValue(E, 0);
2081 
2082   auto *N = newSDNode<MDNodeSDNode>(MD);
2083   CSEMap.InsertNode(N, IP);
2084   InsertNode(N);
2085   return SDValue(N, 0);
2086 }
2087 
2088 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2089   if (VT == V.getValueType())
2090     return V;
2091 
2092   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2093 }
2094 
2095 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2096                                        unsigned SrcAS, unsigned DestAS) {
2097   SDValue Ops[] = {Ptr};
2098   FoldingSetNodeID ID;
2099   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2100   ID.AddInteger(SrcAS);
2101   ID.AddInteger(DestAS);
2102 
2103   void *IP = nullptr;
2104   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2105     return SDValue(E, 0);
2106 
2107   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2108                                            VT, SrcAS, DestAS);
2109   createOperands(N, Ops);
2110 
2111   CSEMap.InsertNode(N, IP);
2112   InsertNode(N);
2113   return SDValue(N, 0);
2114 }
2115 
2116 SDValue SelectionDAG::getFreeze(SDValue V) {
2117   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2118 }
2119 
2120 /// getShiftAmountOperand - Return the specified value casted to
2121 /// the target's desired shift amount type.
2122 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2123   EVT OpTy = Op.getValueType();
2124   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2125   if (OpTy == ShTy || OpTy.isVector()) return Op;
2126 
2127   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2128 }
2129 
2130 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2131   SDLoc dl(Node);
2132   const TargetLowering &TLI = getTargetLoweringInfo();
2133   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2134   EVT VT = Node->getValueType(0);
2135   SDValue Tmp1 = Node->getOperand(0);
2136   SDValue Tmp2 = Node->getOperand(1);
2137   const MaybeAlign MA(Node->getConstantOperandVal(3));
2138 
2139   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2140                                Tmp2, MachinePointerInfo(V));
2141   SDValue VAList = VAListLoad;
2142 
2143   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2144     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2145                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2146 
2147     VAList =
2148         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2149                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2150   }
2151 
2152   // Increment the pointer, VAList, to the next vaarg
2153   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2154                  getConstant(getDataLayout().getTypeAllocSize(
2155                                                VT.getTypeForEVT(*getContext())),
2156                              dl, VAList.getValueType()));
2157   // Store the incremented VAList to the legalized pointer
2158   Tmp1 =
2159       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2160   // Load the actual argument out of the pointer VAList
2161   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2162 }
2163 
2164 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2165   SDLoc dl(Node);
2166   const TargetLowering &TLI = getTargetLoweringInfo();
2167   // This defaults to loading a pointer from the input and storing it to the
2168   // output, returning the chain.
2169   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2170   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2171   SDValue Tmp1 =
2172       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2173               Node->getOperand(2), MachinePointerInfo(VS));
2174   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2175                   MachinePointerInfo(VD));
2176 }
2177 
2178 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2179   const DataLayout &DL = getDataLayout();
2180   Type *Ty = VT.getTypeForEVT(*getContext());
2181   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2182 
2183   if (TLI->isTypeLegal(VT) || !VT.isVector())
2184     return RedAlign;
2185 
2186   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2187   const Align StackAlign = TFI->getStackAlign();
2188 
2189   // See if we can choose a smaller ABI alignment in cases where it's an
2190   // illegal vector type that will get broken down.
2191   if (RedAlign > StackAlign) {
2192     EVT IntermediateVT;
2193     MVT RegisterVT;
2194     unsigned NumIntermediates;
2195     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2196                                 NumIntermediates, RegisterVT);
2197     Ty = IntermediateVT.getTypeForEVT(*getContext());
2198     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2199     if (RedAlign2 < RedAlign)
2200       RedAlign = RedAlign2;
2201   }
2202 
2203   return RedAlign;
2204 }
2205 
2206 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2207   MachineFrameInfo &MFI = MF->getFrameInfo();
2208   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2209   int StackID = 0;
2210   if (Bytes.isScalable())
2211     StackID = TFI->getStackIDForScalableVectors();
2212   // The stack id gives an indication of whether the object is scalable or
2213   // not, so it's safe to pass in the minimum size here.
2214   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2215                                        false, nullptr, StackID);
2216   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2217 }
2218 
2219 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2220   Type *Ty = VT.getTypeForEVT(*getContext());
2221   Align StackAlign =
2222       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2223   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2224 }
2225 
2226 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2227   TypeSize VT1Size = VT1.getStoreSize();
2228   TypeSize VT2Size = VT2.getStoreSize();
2229   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2230          "Don't know how to choose the maximum size when creating a stack "
2231          "temporary");
2232   TypeSize Bytes =
2233       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2234 
2235   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2236   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2237   const DataLayout &DL = getDataLayout();
2238   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2239   return CreateStackTemporary(Bytes, Align);
2240 }
2241 
2242 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2243                                 ISD::CondCode Cond, const SDLoc &dl) {
2244   EVT OpVT = N1.getValueType();
2245 
2246   // These setcc operations always fold.
2247   switch (Cond) {
2248   default: break;
2249   case ISD::SETFALSE:
2250   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2251   case ISD::SETTRUE:
2252   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2253 
2254   case ISD::SETOEQ:
2255   case ISD::SETOGT:
2256   case ISD::SETOGE:
2257   case ISD::SETOLT:
2258   case ISD::SETOLE:
2259   case ISD::SETONE:
2260   case ISD::SETO:
2261   case ISD::SETUO:
2262   case ISD::SETUEQ:
2263   case ISD::SETUNE:
2264     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2265     break;
2266   }
2267 
2268   if (OpVT.isInteger()) {
2269     // For EQ and NE, we can always pick a value for the undef to make the
2270     // predicate pass or fail, so we can return undef.
2271     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2272     // icmp eq/ne X, undef -> undef.
2273     if ((N1.isUndef() || N2.isUndef()) &&
2274         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2275       return getUNDEF(VT);
2276 
2277     // If both operands are undef, we can return undef for int comparison.
2278     // icmp undef, undef -> undef.
2279     if (N1.isUndef() && N2.isUndef())
2280       return getUNDEF(VT);
2281 
2282     // icmp X, X -> true/false
2283     // icmp X, undef -> true/false because undef could be X.
2284     if (N1 == N2)
2285       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2286   }
2287 
2288   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2289     const APInt &C2 = N2C->getAPIntValue();
2290     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2291       const APInt &C1 = N1C->getAPIntValue();
2292 
2293       switch (Cond) {
2294       default: llvm_unreachable("Unknown integer setcc!");
2295       case ISD::SETEQ:  return getBoolConstant(C1 == C2, dl, VT, OpVT);
2296       case ISD::SETNE:  return getBoolConstant(C1 != C2, dl, VT, OpVT);
2297       case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2298       case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2299       case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2300       case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2301       case ISD::SETLT:  return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2302       case ISD::SETGT:  return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2303       case ISD::SETLE:  return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2304       case ISD::SETGE:  return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2305       }
2306     }
2307   }
2308 
2309   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2310   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2311 
2312   if (N1CFP && N2CFP) {
2313     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2314     switch (Cond) {
2315     default: break;
2316     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2317                         return getUNDEF(VT);
2318                       LLVM_FALLTHROUGH;
2319     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2320                                              OpVT);
2321     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2322                         return getUNDEF(VT);
2323                       LLVM_FALLTHROUGH;
2324     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2325                                              R==APFloat::cmpLessThan, dl, VT,
2326                                              OpVT);
2327     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2328                         return getUNDEF(VT);
2329                       LLVM_FALLTHROUGH;
2330     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2331                                              OpVT);
2332     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2333                         return getUNDEF(VT);
2334                       LLVM_FALLTHROUGH;
2335     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2336                                              VT, OpVT);
2337     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2338                         return getUNDEF(VT);
2339                       LLVM_FALLTHROUGH;
2340     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2341                                              R==APFloat::cmpEqual, dl, VT,
2342                                              OpVT);
2343     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2344                         return getUNDEF(VT);
2345                       LLVM_FALLTHROUGH;
2346     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2347                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2348     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2349                                              OpVT);
2350     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2351                                              OpVT);
2352     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2353                                              R==APFloat::cmpEqual, dl, VT,
2354                                              OpVT);
2355     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2356                                              OpVT);
2357     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2358                                              R==APFloat::cmpLessThan, dl, VT,
2359                                              OpVT);
2360     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2361                                              R==APFloat::cmpUnordered, dl, VT,
2362                                              OpVT);
2363     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2364                                              VT, OpVT);
2365     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2366                                              OpVT);
2367     }
2368   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2369     // Ensure that the constant occurs on the RHS.
2370     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2371     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2372       return SDValue();
2373     return getSetCC(dl, VT, N2, N1, SwappedCond);
2374   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2375              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2376     // If an operand is known to be a nan (or undef that could be a nan), we can
2377     // fold it.
2378     // Choosing NaN for the undef will always make unordered comparison succeed
2379     // and ordered comparison fails.
2380     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2381     switch (ISD::getUnorderedFlavor(Cond)) {
2382     default:
2383       llvm_unreachable("Unknown flavor!");
2384     case 0: // Known false.
2385       return getBoolConstant(false, dl, VT, OpVT);
2386     case 1: // Known true.
2387       return getBoolConstant(true, dl, VT, OpVT);
2388     case 2: // Undefined.
2389       return getUNDEF(VT);
2390     }
2391   }
2392 
2393   // Could not fold it.
2394   return SDValue();
2395 }
2396 
2397 /// See if the specified operand can be simplified with the knowledge that only
2398 /// the bits specified by DemandedBits are used.
2399 /// TODO: really we should be making this into the DAG equivalent of
2400 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2401 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2402   EVT VT = V.getValueType();
2403 
2404   if (VT.isScalableVector())
2405     return SDValue();
2406 
2407   APInt DemandedElts = VT.isVector()
2408                            ? APInt::getAllOnes(VT.getVectorNumElements())
2409                            : APInt(1, 1);
2410   return GetDemandedBits(V, DemandedBits, DemandedElts);
2411 }
2412 
2413 /// See if the specified operand can be simplified with the knowledge that only
2414 /// the bits specified by DemandedBits are used in the elements specified by
2415 /// DemandedElts.
2416 /// TODO: really we should be making this into the DAG equivalent of
2417 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2418 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2419                                       const APInt &DemandedElts) {
2420   switch (V.getOpcode()) {
2421   default:
2422     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2423                                                 *this, 0);
2424   case ISD::Constant: {
2425     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2426     APInt NewVal = CVal & DemandedBits;
2427     if (NewVal != CVal)
2428       return getConstant(NewVal, SDLoc(V), V.getValueType());
2429     break;
2430   }
2431   case ISD::SRL:
2432     // Only look at single-use SRLs.
2433     if (!V.getNode()->hasOneUse())
2434       break;
2435     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2436       // See if we can recursively simplify the LHS.
2437       unsigned Amt = RHSC->getZExtValue();
2438 
2439       // Watch out for shift count overflow though.
2440       if (Amt >= DemandedBits.getBitWidth())
2441         break;
2442       APInt SrcDemandedBits = DemandedBits << Amt;
2443       if (SDValue SimplifyLHS =
2444               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2445         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2446                        V.getOperand(1));
2447     }
2448     break;
2449   }
2450   return SDValue();
2451 }
2452 
2453 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2454 /// use this predicate to simplify operations downstream.
2455 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2456   unsigned BitWidth = Op.getScalarValueSizeInBits();
2457   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2458 }
2459 
2460 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2461 /// this predicate to simplify operations downstream.  Mask is known to be zero
2462 /// for bits that V cannot have.
2463 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2464                                      unsigned Depth) const {
2465   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2466 }
2467 
2468 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2469 /// DemandedElts.  We use this predicate to simplify operations downstream.
2470 /// Mask is known to be zero for bits that V cannot have.
2471 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2472                                      const APInt &DemandedElts,
2473                                      unsigned Depth) const {
2474   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2475 }
2476 
2477 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2478 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2479                                         unsigned Depth) const {
2480   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2481 }
2482 
2483 /// isSplatValue - Return true if the vector V has the same value
2484 /// across all DemandedElts. For scalable vectors it does not make
2485 /// sense to specify which elements are demanded or undefined, therefore
2486 /// they are simply ignored.
2487 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2488                                 APInt &UndefElts, unsigned Depth) {
2489   EVT VT = V.getValueType();
2490   assert(VT.isVector() && "Vector type expected");
2491 
2492   if (!VT.isScalableVector() && !DemandedElts)
2493     return false; // No demanded elts, better to assume we don't know anything.
2494 
2495   if (Depth >= MaxRecursionDepth)
2496     return false; // Limit search depth.
2497 
2498   // Deal with some common cases here that work for both fixed and scalable
2499   // vector types.
2500   switch (V.getOpcode()) {
2501   case ISD::SPLAT_VECTOR:
2502     UndefElts = V.getOperand(0).isUndef()
2503                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2504                     : APInt(DemandedElts.getBitWidth(), 0);
2505     return true;
2506   case ISD::ADD:
2507   case ISD::SUB:
2508   case ISD::AND:
2509   case ISD::XOR:
2510   case ISD::OR: {
2511     APInt UndefLHS, UndefRHS;
2512     SDValue LHS = V.getOperand(0);
2513     SDValue RHS = V.getOperand(1);
2514     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2515         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2516       UndefElts = UndefLHS | UndefRHS;
2517       return true;
2518     }
2519     return false;
2520   }
2521   case ISD::ABS:
2522   case ISD::TRUNCATE:
2523   case ISD::SIGN_EXTEND:
2524   case ISD::ZERO_EXTEND:
2525     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2526   }
2527 
2528   // We don't support other cases than those above for scalable vectors at
2529   // the moment.
2530   if (VT.isScalableVector())
2531     return false;
2532 
2533   unsigned NumElts = VT.getVectorNumElements();
2534   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2535   UndefElts = APInt::getZero(NumElts);
2536 
2537   switch (V.getOpcode()) {
2538   case ISD::BUILD_VECTOR: {
2539     SDValue Scl;
2540     for (unsigned i = 0; i != NumElts; ++i) {
2541       SDValue Op = V.getOperand(i);
2542       if (Op.isUndef()) {
2543         UndefElts.setBit(i);
2544         continue;
2545       }
2546       if (!DemandedElts[i])
2547         continue;
2548       if (Scl && Scl != Op)
2549         return false;
2550       Scl = Op;
2551     }
2552     return true;
2553   }
2554   case ISD::VECTOR_SHUFFLE: {
2555     // Check if this is a shuffle node doing a splat.
2556     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2557     int SplatIndex = -1;
2558     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2559     for (int i = 0; i != (int)NumElts; ++i) {
2560       int M = Mask[i];
2561       if (M < 0) {
2562         UndefElts.setBit(i);
2563         continue;
2564       }
2565       if (!DemandedElts[i])
2566         continue;
2567       if (0 <= SplatIndex && SplatIndex != M)
2568         return false;
2569       SplatIndex = M;
2570     }
2571     return true;
2572   }
2573   case ISD::EXTRACT_SUBVECTOR: {
2574     // Offset the demanded elts by the subvector index.
2575     SDValue Src = V.getOperand(0);
2576     // We don't support scalable vectors at the moment.
2577     if (Src.getValueType().isScalableVector())
2578       return false;
2579     uint64_t Idx = V.getConstantOperandVal(1);
2580     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2581     APInt UndefSrcElts;
2582     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2583     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2584       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2585       return true;
2586     }
2587     break;
2588   }
2589   }
2590 
2591   return false;
2592 }
2593 
2594 /// Helper wrapper to main isSplatValue function.
2595 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2596   EVT VT = V.getValueType();
2597   assert(VT.isVector() && "Vector type expected");
2598 
2599   APInt UndefElts;
2600   APInt DemandedElts;
2601 
2602   // For now we don't support this with scalable vectors.
2603   if (!VT.isScalableVector())
2604     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2605   return isSplatValue(V, DemandedElts, UndefElts) &&
2606          (AllowUndefs || !UndefElts);
2607 }
2608 
2609 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2610   V = peekThroughExtractSubvectors(V);
2611 
2612   EVT VT = V.getValueType();
2613   unsigned Opcode = V.getOpcode();
2614   switch (Opcode) {
2615   default: {
2616     APInt UndefElts;
2617     APInt DemandedElts;
2618 
2619     if (!VT.isScalableVector())
2620       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2621 
2622     if (isSplatValue(V, DemandedElts, UndefElts)) {
2623       if (VT.isScalableVector()) {
2624         // DemandedElts and UndefElts are ignored for scalable vectors, since
2625         // the only supported cases are SPLAT_VECTOR nodes.
2626         SplatIdx = 0;
2627       } else {
2628         // Handle case where all demanded elements are UNDEF.
2629         if (DemandedElts.isSubsetOf(UndefElts)) {
2630           SplatIdx = 0;
2631           return getUNDEF(VT);
2632         }
2633         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2634       }
2635       return V;
2636     }
2637     break;
2638   }
2639   case ISD::SPLAT_VECTOR:
2640     SplatIdx = 0;
2641     return V;
2642   case ISD::VECTOR_SHUFFLE: {
2643     if (VT.isScalableVector())
2644       return SDValue();
2645 
2646     // Check if this is a shuffle node doing a splat.
2647     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2648     // getTargetVShiftNode currently struggles without the splat source.
2649     auto *SVN = cast<ShuffleVectorSDNode>(V);
2650     if (!SVN->isSplat())
2651       break;
2652     int Idx = SVN->getSplatIndex();
2653     int NumElts = V.getValueType().getVectorNumElements();
2654     SplatIdx = Idx % NumElts;
2655     return V.getOperand(Idx / NumElts);
2656   }
2657   }
2658 
2659   return SDValue();
2660 }
2661 
2662 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2663   int SplatIdx;
2664   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2665     EVT SVT = SrcVector.getValueType().getScalarType();
2666     EVT LegalSVT = SVT;
2667     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2668       if (!SVT.isInteger())
2669         return SDValue();
2670       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2671       if (LegalSVT.bitsLT(SVT))
2672         return SDValue();
2673     }
2674     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2675                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2676   }
2677   return SDValue();
2678 }
2679 
2680 const APInt *
2681 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2682                                           const APInt &DemandedElts) const {
2683   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2684           V.getOpcode() == ISD::SRA) &&
2685          "Unknown shift node");
2686   unsigned BitWidth = V.getScalarValueSizeInBits();
2687   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2688     // Shifting more than the bitwidth is not valid.
2689     const APInt &ShAmt = SA->getAPIntValue();
2690     if (ShAmt.ult(BitWidth))
2691       return &ShAmt;
2692   }
2693   return nullptr;
2694 }
2695 
2696 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2697     SDValue V, const APInt &DemandedElts) const {
2698   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2699           V.getOpcode() == ISD::SRA) &&
2700          "Unknown shift node");
2701   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2702     return ValidAmt;
2703   unsigned BitWidth = V.getScalarValueSizeInBits();
2704   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2705   if (!BV)
2706     return nullptr;
2707   const APInt *MinShAmt = nullptr;
2708   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2709     if (!DemandedElts[i])
2710       continue;
2711     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2712     if (!SA)
2713       return nullptr;
2714     // Shifting more than the bitwidth is not valid.
2715     const APInt &ShAmt = SA->getAPIntValue();
2716     if (ShAmt.uge(BitWidth))
2717       return nullptr;
2718     if (MinShAmt && MinShAmt->ule(ShAmt))
2719       continue;
2720     MinShAmt = &ShAmt;
2721   }
2722   return MinShAmt;
2723 }
2724 
2725 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2726     SDValue V, const APInt &DemandedElts) const {
2727   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2728           V.getOpcode() == ISD::SRA) &&
2729          "Unknown shift node");
2730   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2731     return ValidAmt;
2732   unsigned BitWidth = V.getScalarValueSizeInBits();
2733   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2734   if (!BV)
2735     return nullptr;
2736   const APInt *MaxShAmt = nullptr;
2737   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2738     if (!DemandedElts[i])
2739       continue;
2740     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2741     if (!SA)
2742       return nullptr;
2743     // Shifting more than the bitwidth is not valid.
2744     const APInt &ShAmt = SA->getAPIntValue();
2745     if (ShAmt.uge(BitWidth))
2746       return nullptr;
2747     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2748       continue;
2749     MaxShAmt = &ShAmt;
2750   }
2751   return MaxShAmt;
2752 }
2753 
2754 /// Determine which bits of Op are known to be either zero or one and return
2755 /// them in Known. For vectors, the known bits are those that are shared by
2756 /// every vector element.
2757 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2758   EVT VT = Op.getValueType();
2759 
2760   // TOOD: Until we have a plan for how to represent demanded elements for
2761   // scalable vectors, we can just bail out for now.
2762   if (Op.getValueType().isScalableVector()) {
2763     unsigned BitWidth = Op.getScalarValueSizeInBits();
2764     return KnownBits(BitWidth);
2765   }
2766 
2767   APInt DemandedElts = VT.isVector()
2768                            ? APInt::getAllOnes(VT.getVectorNumElements())
2769                            : APInt(1, 1);
2770   return computeKnownBits(Op, DemandedElts, Depth);
2771 }
2772 
2773 /// Determine which bits of Op are known to be either zero or one and return
2774 /// them in Known. The DemandedElts argument allows us to only collect the known
2775 /// bits that are shared by the requested vector elements.
2776 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2777                                          unsigned Depth) const {
2778   unsigned BitWidth = Op.getScalarValueSizeInBits();
2779 
2780   KnownBits Known(BitWidth);   // Don't know anything.
2781 
2782   // TOOD: Until we have a plan for how to represent demanded elements for
2783   // scalable vectors, we can just bail out for now.
2784   if (Op.getValueType().isScalableVector())
2785     return Known;
2786 
2787   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2788     // We know all of the bits for a constant!
2789     return KnownBits::makeConstant(C->getAPIntValue());
2790   }
2791   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2792     // We know all of the bits for a constant fp!
2793     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2794   }
2795 
2796   if (Depth >= MaxRecursionDepth)
2797     return Known;  // Limit search depth.
2798 
2799   KnownBits Known2;
2800   unsigned NumElts = DemandedElts.getBitWidth();
2801   assert((!Op.getValueType().isVector() ||
2802           NumElts == Op.getValueType().getVectorNumElements()) &&
2803          "Unexpected vector size");
2804 
2805   if (!DemandedElts)
2806     return Known;  // No demanded elts, better to assume we don't know anything.
2807 
2808   unsigned Opcode = Op.getOpcode();
2809   switch (Opcode) {
2810   case ISD::BUILD_VECTOR:
2811     // Collect the known bits that are shared by every demanded vector element.
2812     Known.Zero.setAllBits(); Known.One.setAllBits();
2813     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2814       if (!DemandedElts[i])
2815         continue;
2816 
2817       SDValue SrcOp = Op.getOperand(i);
2818       Known2 = computeKnownBits(SrcOp, Depth + 1);
2819 
2820       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2821       if (SrcOp.getValueSizeInBits() != BitWidth) {
2822         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2823                "Expected BUILD_VECTOR implicit truncation");
2824         Known2 = Known2.trunc(BitWidth);
2825       }
2826 
2827       // Known bits are the values that are shared by every demanded element.
2828       Known = KnownBits::commonBits(Known, Known2);
2829 
2830       // If we don't know any bits, early out.
2831       if (Known.isUnknown())
2832         break;
2833     }
2834     break;
2835   case ISD::VECTOR_SHUFFLE: {
2836     // Collect the known bits that are shared by every vector element referenced
2837     // by the shuffle.
2838     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2839     Known.Zero.setAllBits(); Known.One.setAllBits();
2840     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2841     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2842     for (unsigned i = 0; i != NumElts; ++i) {
2843       if (!DemandedElts[i])
2844         continue;
2845 
2846       int M = SVN->getMaskElt(i);
2847       if (M < 0) {
2848         // For UNDEF elements, we don't know anything about the common state of
2849         // the shuffle result.
2850         Known.resetAll();
2851         DemandedLHS.clearAllBits();
2852         DemandedRHS.clearAllBits();
2853         break;
2854       }
2855 
2856       if ((unsigned)M < NumElts)
2857         DemandedLHS.setBit((unsigned)M % NumElts);
2858       else
2859         DemandedRHS.setBit((unsigned)M % NumElts);
2860     }
2861     // Known bits are the values that are shared by every demanded element.
2862     if (!!DemandedLHS) {
2863       SDValue LHS = Op.getOperand(0);
2864       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2865       Known = KnownBits::commonBits(Known, Known2);
2866     }
2867     // If we don't know any bits, early out.
2868     if (Known.isUnknown())
2869       break;
2870     if (!!DemandedRHS) {
2871       SDValue RHS = Op.getOperand(1);
2872       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2873       Known = KnownBits::commonBits(Known, Known2);
2874     }
2875     break;
2876   }
2877   case ISD::CONCAT_VECTORS: {
2878     // Split DemandedElts and test each of the demanded subvectors.
2879     Known.Zero.setAllBits(); Known.One.setAllBits();
2880     EVT SubVectorVT = Op.getOperand(0).getValueType();
2881     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2882     unsigned NumSubVectors = Op.getNumOperands();
2883     for (unsigned i = 0; i != NumSubVectors; ++i) {
2884       APInt DemandedSub =
2885           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2886       if (!!DemandedSub) {
2887         SDValue Sub = Op.getOperand(i);
2888         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2889         Known = KnownBits::commonBits(Known, Known2);
2890       }
2891       // If we don't know any bits, early out.
2892       if (Known.isUnknown())
2893         break;
2894     }
2895     break;
2896   }
2897   case ISD::INSERT_SUBVECTOR: {
2898     // Demand any elements from the subvector and the remainder from the src its
2899     // inserted into.
2900     SDValue Src = Op.getOperand(0);
2901     SDValue Sub = Op.getOperand(1);
2902     uint64_t Idx = Op.getConstantOperandVal(2);
2903     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2904     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2905     APInt DemandedSrcElts = DemandedElts;
2906     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2907 
2908     Known.One.setAllBits();
2909     Known.Zero.setAllBits();
2910     if (!!DemandedSubElts) {
2911       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2912       if (Known.isUnknown())
2913         break; // early-out.
2914     }
2915     if (!!DemandedSrcElts) {
2916       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2917       Known = KnownBits::commonBits(Known, Known2);
2918     }
2919     break;
2920   }
2921   case ISD::EXTRACT_SUBVECTOR: {
2922     // Offset the demanded elts by the subvector index.
2923     SDValue Src = Op.getOperand(0);
2924     // Bail until we can represent demanded elements for scalable vectors.
2925     if (Src.getValueType().isScalableVector())
2926       break;
2927     uint64_t Idx = Op.getConstantOperandVal(1);
2928     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2929     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2930     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2931     break;
2932   }
2933   case ISD::SCALAR_TO_VECTOR: {
2934     // We know about scalar_to_vector as much as we know about it source,
2935     // which becomes the first element of otherwise unknown vector.
2936     if (DemandedElts != 1)
2937       break;
2938 
2939     SDValue N0 = Op.getOperand(0);
2940     Known = computeKnownBits(N0, Depth + 1);
2941     if (N0.getValueSizeInBits() != BitWidth)
2942       Known = Known.trunc(BitWidth);
2943 
2944     break;
2945   }
2946   case ISD::BITCAST: {
2947     SDValue N0 = Op.getOperand(0);
2948     EVT SubVT = N0.getValueType();
2949     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2950 
2951     // Ignore bitcasts from unsupported types.
2952     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2953       break;
2954 
2955     // Fast handling of 'identity' bitcasts.
2956     if (BitWidth == SubBitWidth) {
2957       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2958       break;
2959     }
2960 
2961     bool IsLE = getDataLayout().isLittleEndian();
2962 
2963     // Bitcast 'small element' vector to 'large element' scalar/vector.
2964     if ((BitWidth % SubBitWidth) == 0) {
2965       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2966 
2967       // Collect known bits for the (larger) output by collecting the known
2968       // bits from each set of sub elements and shift these into place.
2969       // We need to separately call computeKnownBits for each set of
2970       // sub elements as the knownbits for each is likely to be different.
2971       unsigned SubScale = BitWidth / SubBitWidth;
2972       APInt SubDemandedElts(NumElts * SubScale, 0);
2973       for (unsigned i = 0; i != NumElts; ++i)
2974         if (DemandedElts[i])
2975           SubDemandedElts.setBit(i * SubScale);
2976 
2977       for (unsigned i = 0; i != SubScale; ++i) {
2978         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2979                          Depth + 1);
2980         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2981         Known.insertBits(Known2, SubBitWidth * Shifts);
2982       }
2983     }
2984 
2985     // Bitcast 'large element' scalar/vector to 'small element' vector.
2986     if ((SubBitWidth % BitWidth) == 0) {
2987       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2988 
2989       // Collect known bits for the (smaller) output by collecting the known
2990       // bits from the overlapping larger input elements and extracting the
2991       // sub sections we actually care about.
2992       unsigned SubScale = SubBitWidth / BitWidth;
2993       APInt SubDemandedElts(NumElts / SubScale, 0);
2994       for (unsigned i = 0; i != NumElts; ++i)
2995         if (DemandedElts[i])
2996           SubDemandedElts.setBit(i / SubScale);
2997 
2998       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2999 
3000       Known.Zero.setAllBits(); Known.One.setAllBits();
3001       for (unsigned i = 0; i != NumElts; ++i)
3002         if (DemandedElts[i]) {
3003           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3004           unsigned Offset = (Shifts % SubScale) * BitWidth;
3005           Known = KnownBits::commonBits(Known,
3006                                         Known2.extractBits(BitWidth, Offset));
3007           // If we don't know any bits, early out.
3008           if (Known.isUnknown())
3009             break;
3010         }
3011     }
3012     break;
3013   }
3014   case ISD::AND:
3015     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3016     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3017 
3018     Known &= Known2;
3019     break;
3020   case ISD::OR:
3021     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3022     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3023 
3024     Known |= Known2;
3025     break;
3026   case ISD::XOR:
3027     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3028     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3029 
3030     Known ^= Known2;
3031     break;
3032   case ISD::MUL: {
3033     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3034     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3035     Known = KnownBits::mul(Known, Known2);
3036     break;
3037   }
3038   case ISD::MULHU: {
3039     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3040     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3041     Known = KnownBits::mulhu(Known, Known2);
3042     break;
3043   }
3044   case ISD::MULHS: {
3045     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3046     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3047     Known = KnownBits::mulhs(Known, Known2);
3048     break;
3049   }
3050   case ISD::UMUL_LOHI: {
3051     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3052     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3053     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3054     if (Op.getResNo() == 0)
3055       Known = KnownBits::mul(Known, Known2);
3056     else
3057       Known = KnownBits::mulhu(Known, Known2);
3058     break;
3059   }
3060   case ISD::SMUL_LOHI: {
3061     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3062     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3063     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3064     if (Op.getResNo() == 0)
3065       Known = KnownBits::mul(Known, Known2);
3066     else
3067       Known = KnownBits::mulhs(Known, Known2);
3068     break;
3069   }
3070   case ISD::UDIV: {
3071     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3072     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3073     Known = KnownBits::udiv(Known, Known2);
3074     break;
3075   }
3076   case ISD::SELECT:
3077   case ISD::VSELECT:
3078     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3079     // If we don't know any bits, early out.
3080     if (Known.isUnknown())
3081       break;
3082     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3083 
3084     // Only known if known in both the LHS and RHS.
3085     Known = KnownBits::commonBits(Known, Known2);
3086     break;
3087   case ISD::SELECT_CC:
3088     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3089     // If we don't know any bits, early out.
3090     if (Known.isUnknown())
3091       break;
3092     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3093 
3094     // Only known if known in both the LHS and RHS.
3095     Known = KnownBits::commonBits(Known, Known2);
3096     break;
3097   case ISD::SMULO:
3098   case ISD::UMULO:
3099     if (Op.getResNo() != 1)
3100       break;
3101     // The boolean result conforms to getBooleanContents.
3102     // If we know the result of a setcc has the top bits zero, use this info.
3103     // We know that we have an integer-based boolean since these operations
3104     // are only available for integer.
3105     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3106             TargetLowering::ZeroOrOneBooleanContent &&
3107         BitWidth > 1)
3108       Known.Zero.setBitsFrom(1);
3109     break;
3110   case ISD::SETCC:
3111   case ISD::STRICT_FSETCC:
3112   case ISD::STRICT_FSETCCS: {
3113     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3114     // If we know the result of a setcc has the top bits zero, use this info.
3115     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3116             TargetLowering::ZeroOrOneBooleanContent &&
3117         BitWidth > 1)
3118       Known.Zero.setBitsFrom(1);
3119     break;
3120   }
3121   case ISD::SHL:
3122     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3123     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3124     Known = KnownBits::shl(Known, Known2);
3125 
3126     // Minimum shift low bits are known zero.
3127     if (const APInt *ShMinAmt =
3128             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3129       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3130     break;
3131   case ISD::SRL:
3132     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3133     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3134     Known = KnownBits::lshr(Known, Known2);
3135 
3136     // Minimum shift high bits are known zero.
3137     if (const APInt *ShMinAmt =
3138             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3139       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3140     break;
3141   case ISD::SRA:
3142     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3143     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3144     Known = KnownBits::ashr(Known, Known2);
3145     // TODO: Add minimum shift high known sign bits.
3146     break;
3147   case ISD::FSHL:
3148   case ISD::FSHR:
3149     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3150       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3151 
3152       // For fshl, 0-shift returns the 1st arg.
3153       // For fshr, 0-shift returns the 2nd arg.
3154       if (Amt == 0) {
3155         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3156                                  DemandedElts, Depth + 1);
3157         break;
3158       }
3159 
3160       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3161       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3162       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3163       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3164       if (Opcode == ISD::FSHL) {
3165         Known.One <<= Amt;
3166         Known.Zero <<= Amt;
3167         Known2.One.lshrInPlace(BitWidth - Amt);
3168         Known2.Zero.lshrInPlace(BitWidth - Amt);
3169       } else {
3170         Known.One <<= BitWidth - Amt;
3171         Known.Zero <<= BitWidth - Amt;
3172         Known2.One.lshrInPlace(Amt);
3173         Known2.Zero.lshrInPlace(Amt);
3174       }
3175       Known.One |= Known2.One;
3176       Known.Zero |= Known2.Zero;
3177     }
3178     break;
3179   case ISD::SIGN_EXTEND_INREG: {
3180     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3181     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3182     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3183     break;
3184   }
3185   case ISD::CTTZ:
3186   case ISD::CTTZ_ZERO_UNDEF: {
3187     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3188     // If we have a known 1, its position is our upper bound.
3189     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3190     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3191     Known.Zero.setBitsFrom(LowBits);
3192     break;
3193   }
3194   case ISD::CTLZ:
3195   case ISD::CTLZ_ZERO_UNDEF: {
3196     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3197     // If we have a known 1, its position is our upper bound.
3198     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3199     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3200     Known.Zero.setBitsFrom(LowBits);
3201     break;
3202   }
3203   case ISD::CTPOP: {
3204     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3205     // If we know some of the bits are zero, they can't be one.
3206     unsigned PossibleOnes = Known2.countMaxPopulation();
3207     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3208     break;
3209   }
3210   case ISD::PARITY: {
3211     // Parity returns 0 everywhere but the LSB.
3212     Known.Zero.setBitsFrom(1);
3213     break;
3214   }
3215   case ISD::LOAD: {
3216     LoadSDNode *LD = cast<LoadSDNode>(Op);
3217     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3218     if (ISD::isNON_EXTLoad(LD) && Cst) {
3219       // Determine any common known bits from the loaded constant pool value.
3220       Type *CstTy = Cst->getType();
3221       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3222         // If its a vector splat, then we can (quickly) reuse the scalar path.
3223         // NOTE: We assume all elements match and none are UNDEF.
3224         if (CstTy->isVectorTy()) {
3225           if (const Constant *Splat = Cst->getSplatValue()) {
3226             Cst = Splat;
3227             CstTy = Cst->getType();
3228           }
3229         }
3230         // TODO - do we need to handle different bitwidths?
3231         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3232           // Iterate across all vector elements finding common known bits.
3233           Known.One.setAllBits();
3234           Known.Zero.setAllBits();
3235           for (unsigned i = 0; i != NumElts; ++i) {
3236             if (!DemandedElts[i])
3237               continue;
3238             if (Constant *Elt = Cst->getAggregateElement(i)) {
3239               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3240                 const APInt &Value = CInt->getValue();
3241                 Known.One &= Value;
3242                 Known.Zero &= ~Value;
3243                 continue;
3244               }
3245               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3246                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3247                 Known.One &= Value;
3248                 Known.Zero &= ~Value;
3249                 continue;
3250               }
3251             }
3252             Known.One.clearAllBits();
3253             Known.Zero.clearAllBits();
3254             break;
3255           }
3256         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3257           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3258             Known = KnownBits::makeConstant(CInt->getValue());
3259           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3260             Known =
3261                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3262           }
3263         }
3264       }
3265     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3266       // If this is a ZEXTLoad and we are looking at the loaded value.
3267       EVT VT = LD->getMemoryVT();
3268       unsigned MemBits = VT.getScalarSizeInBits();
3269       Known.Zero.setBitsFrom(MemBits);
3270     } else if (const MDNode *Ranges = LD->getRanges()) {
3271       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3272         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3273     }
3274     break;
3275   }
3276   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3277     EVT InVT = Op.getOperand(0).getValueType();
3278     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3279     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3280     Known = Known.zext(BitWidth);
3281     break;
3282   }
3283   case ISD::ZERO_EXTEND: {
3284     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3285     Known = Known.zext(BitWidth);
3286     break;
3287   }
3288   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3289     EVT InVT = Op.getOperand(0).getValueType();
3290     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3291     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3292     // If the sign bit is known to be zero or one, then sext will extend
3293     // it to the top bits, else it will just zext.
3294     Known = Known.sext(BitWidth);
3295     break;
3296   }
3297   case ISD::SIGN_EXTEND: {
3298     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3299     // If the sign bit is known to be zero or one, then sext will extend
3300     // it to the top bits, else it will just zext.
3301     Known = Known.sext(BitWidth);
3302     break;
3303   }
3304   case ISD::ANY_EXTEND_VECTOR_INREG: {
3305     EVT InVT = Op.getOperand(0).getValueType();
3306     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3307     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3308     Known = Known.anyext(BitWidth);
3309     break;
3310   }
3311   case ISD::ANY_EXTEND: {
3312     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3313     Known = Known.anyext(BitWidth);
3314     break;
3315   }
3316   case ISD::TRUNCATE: {
3317     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3318     Known = Known.trunc(BitWidth);
3319     break;
3320   }
3321   case ISD::AssertZext: {
3322     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3323     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3324     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3325     Known.Zero |= (~InMask);
3326     Known.One  &= (~Known.Zero);
3327     break;
3328   }
3329   case ISD::AssertAlign: {
3330     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3331     assert(LogOfAlign != 0);
3332     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3333     // well as clearing one bits.
3334     Known.Zero.setLowBits(LogOfAlign);
3335     Known.One.clearLowBits(LogOfAlign);
3336     break;
3337   }
3338   case ISD::FGETSIGN:
3339     // All bits are zero except the low bit.
3340     Known.Zero.setBitsFrom(1);
3341     break;
3342   case ISD::USUBO:
3343   case ISD::SSUBO:
3344     if (Op.getResNo() == 1) {
3345       // If we know the result of a setcc has the top bits zero, use this info.
3346       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3347               TargetLowering::ZeroOrOneBooleanContent &&
3348           BitWidth > 1)
3349         Known.Zero.setBitsFrom(1);
3350       break;
3351     }
3352     LLVM_FALLTHROUGH;
3353   case ISD::SUB:
3354   case ISD::SUBC: {
3355     assert(Op.getResNo() == 0 &&
3356            "We only compute knownbits for the difference here.");
3357 
3358     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3359     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3360     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3361                                         Known, Known2);
3362     break;
3363   }
3364   case ISD::UADDO:
3365   case ISD::SADDO:
3366   case ISD::ADDCARRY:
3367     if (Op.getResNo() == 1) {
3368       // If we know the result of a setcc has the top bits zero, use this info.
3369       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3370               TargetLowering::ZeroOrOneBooleanContent &&
3371           BitWidth > 1)
3372         Known.Zero.setBitsFrom(1);
3373       break;
3374     }
3375     LLVM_FALLTHROUGH;
3376   case ISD::ADD:
3377   case ISD::ADDC:
3378   case ISD::ADDE: {
3379     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3380 
3381     // With ADDE and ADDCARRY, a carry bit may be added in.
3382     KnownBits Carry(1);
3383     if (Opcode == ISD::ADDE)
3384       // Can't track carry from glue, set carry to unknown.
3385       Carry.resetAll();
3386     else if (Opcode == ISD::ADDCARRY)
3387       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3388       // the trouble (how often will we find a known carry bit). And I haven't
3389       // tested this very much yet, but something like this might work:
3390       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3391       //   Carry = Carry.zextOrTrunc(1, false);
3392       Carry.resetAll();
3393     else
3394       Carry.setAllZero();
3395 
3396     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3397     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3398     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3399     break;
3400   }
3401   case ISD::SREM: {
3402     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3403     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3404     Known = KnownBits::srem(Known, Known2);
3405     break;
3406   }
3407   case ISD::UREM: {
3408     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3409     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3410     Known = KnownBits::urem(Known, Known2);
3411     break;
3412   }
3413   case ISD::EXTRACT_ELEMENT: {
3414     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3415     const unsigned Index = Op.getConstantOperandVal(1);
3416     const unsigned EltBitWidth = Op.getValueSizeInBits();
3417 
3418     // Remove low part of known bits mask
3419     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3420     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3421 
3422     // Remove high part of known bit mask
3423     Known = Known.trunc(EltBitWidth);
3424     break;
3425   }
3426   case ISD::EXTRACT_VECTOR_ELT: {
3427     SDValue InVec = Op.getOperand(0);
3428     SDValue EltNo = Op.getOperand(1);
3429     EVT VecVT = InVec.getValueType();
3430     // computeKnownBits not yet implemented for scalable vectors.
3431     if (VecVT.isScalableVector())
3432       break;
3433     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3434     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3435 
3436     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3437     // anything about the extended bits.
3438     if (BitWidth > EltBitWidth)
3439       Known = Known.trunc(EltBitWidth);
3440 
3441     // If we know the element index, just demand that vector element, else for
3442     // an unknown element index, ignore DemandedElts and demand them all.
3443     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3444     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3445     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3446       DemandedSrcElts =
3447           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3448 
3449     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3450     if (BitWidth > EltBitWidth)
3451       Known = Known.anyext(BitWidth);
3452     break;
3453   }
3454   case ISD::INSERT_VECTOR_ELT: {
3455     // If we know the element index, split the demand between the
3456     // source vector and the inserted element, otherwise assume we need
3457     // the original demanded vector elements and the value.
3458     SDValue InVec = Op.getOperand(0);
3459     SDValue InVal = Op.getOperand(1);
3460     SDValue EltNo = Op.getOperand(2);
3461     bool DemandedVal = true;
3462     APInt DemandedVecElts = DemandedElts;
3463     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3464     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3465       unsigned EltIdx = CEltNo->getZExtValue();
3466       DemandedVal = !!DemandedElts[EltIdx];
3467       DemandedVecElts.clearBit(EltIdx);
3468     }
3469     Known.One.setAllBits();
3470     Known.Zero.setAllBits();
3471     if (DemandedVal) {
3472       Known2 = computeKnownBits(InVal, Depth + 1);
3473       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3474     }
3475     if (!!DemandedVecElts) {
3476       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3477       Known = KnownBits::commonBits(Known, Known2);
3478     }
3479     break;
3480   }
3481   case ISD::BITREVERSE: {
3482     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3483     Known = Known2.reverseBits();
3484     break;
3485   }
3486   case ISD::BSWAP: {
3487     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3488     Known = Known2.byteSwap();
3489     break;
3490   }
3491   case ISD::ABS: {
3492     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3493     Known = Known2.abs();
3494     break;
3495   }
3496   case ISD::USUBSAT: {
3497     // The result of usubsat will never be larger than the LHS.
3498     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3499     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3500     break;
3501   }
3502   case ISD::UMIN: {
3503     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3504     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3505     Known = KnownBits::umin(Known, Known2);
3506     break;
3507   }
3508   case ISD::UMAX: {
3509     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3510     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3511     Known = KnownBits::umax(Known, Known2);
3512     break;
3513   }
3514   case ISD::SMIN:
3515   case ISD::SMAX: {
3516     // If we have a clamp pattern, we know that the number of sign bits will be
3517     // the minimum of the clamp min/max range.
3518     bool IsMax = (Opcode == ISD::SMAX);
3519     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3520     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3521       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3522         CstHigh =
3523             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3524     if (CstLow && CstHigh) {
3525       if (!IsMax)
3526         std::swap(CstLow, CstHigh);
3527 
3528       const APInt &ValueLow = CstLow->getAPIntValue();
3529       const APInt &ValueHigh = CstHigh->getAPIntValue();
3530       if (ValueLow.sle(ValueHigh)) {
3531         unsigned LowSignBits = ValueLow.getNumSignBits();
3532         unsigned HighSignBits = ValueHigh.getNumSignBits();
3533         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3534         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3535           Known.One.setHighBits(MinSignBits);
3536           break;
3537         }
3538         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3539           Known.Zero.setHighBits(MinSignBits);
3540           break;
3541         }
3542       }
3543     }
3544 
3545     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3546     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3547     if (IsMax)
3548       Known = KnownBits::smax(Known, Known2);
3549     else
3550       Known = KnownBits::smin(Known, Known2);
3551     break;
3552   }
3553   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3554     if (Op.getResNo() == 1) {
3555       // The boolean result conforms to getBooleanContents.
3556       // If we know the result of a setcc has the top bits zero, use this info.
3557       // We know that we have an integer-based boolean since these operations
3558       // are only available for integer.
3559       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3560               TargetLowering::ZeroOrOneBooleanContent &&
3561           BitWidth > 1)
3562         Known.Zero.setBitsFrom(1);
3563       break;
3564     }
3565     LLVM_FALLTHROUGH;
3566   case ISD::ATOMIC_CMP_SWAP:
3567   case ISD::ATOMIC_SWAP:
3568   case ISD::ATOMIC_LOAD_ADD:
3569   case ISD::ATOMIC_LOAD_SUB:
3570   case ISD::ATOMIC_LOAD_AND:
3571   case ISD::ATOMIC_LOAD_CLR:
3572   case ISD::ATOMIC_LOAD_OR:
3573   case ISD::ATOMIC_LOAD_XOR:
3574   case ISD::ATOMIC_LOAD_NAND:
3575   case ISD::ATOMIC_LOAD_MIN:
3576   case ISD::ATOMIC_LOAD_MAX:
3577   case ISD::ATOMIC_LOAD_UMIN:
3578   case ISD::ATOMIC_LOAD_UMAX:
3579   case ISD::ATOMIC_LOAD: {
3580     unsigned MemBits =
3581         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3582     // If we are looking at the loaded value.
3583     if (Op.getResNo() == 0) {
3584       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3585         Known.Zero.setBitsFrom(MemBits);
3586     }
3587     break;
3588   }
3589   case ISD::FrameIndex:
3590   case ISD::TargetFrameIndex:
3591     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3592                                        Known, getMachineFunction());
3593     break;
3594 
3595   default:
3596     if (Opcode < ISD::BUILTIN_OP_END)
3597       break;
3598     LLVM_FALLTHROUGH;
3599   case ISD::INTRINSIC_WO_CHAIN:
3600   case ISD::INTRINSIC_W_CHAIN:
3601   case ISD::INTRINSIC_VOID:
3602     // Allow the target to implement this method for its nodes.
3603     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3604     break;
3605   }
3606 
3607   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3608   return Known;
3609 }
3610 
3611 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3612                                                              SDValue N1) const {
3613   // X + 0 never overflow
3614   if (isNullConstant(N1))
3615     return OFK_Never;
3616 
3617   KnownBits N1Known = computeKnownBits(N1);
3618   if (N1Known.Zero.getBoolValue()) {
3619     KnownBits N0Known = computeKnownBits(N0);
3620 
3621     bool overflow;
3622     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3623     if (!overflow)
3624       return OFK_Never;
3625   }
3626 
3627   // mulhi + 1 never overflow
3628   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3629       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3630     return OFK_Never;
3631 
3632   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3633     KnownBits N0Known = computeKnownBits(N0);
3634 
3635     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3636       return OFK_Never;
3637   }
3638 
3639   return OFK_Sometime;
3640 }
3641 
3642 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3643   EVT OpVT = Val.getValueType();
3644   unsigned BitWidth = OpVT.getScalarSizeInBits();
3645 
3646   // Is the constant a known power of 2?
3647   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3648     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3649 
3650   // A left-shift of a constant one will have exactly one bit set because
3651   // shifting the bit off the end is undefined.
3652   if (Val.getOpcode() == ISD::SHL) {
3653     auto *C = isConstOrConstSplat(Val.getOperand(0));
3654     if (C && C->getAPIntValue() == 1)
3655       return true;
3656   }
3657 
3658   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3659   // one bit set.
3660   if (Val.getOpcode() == ISD::SRL) {
3661     auto *C = isConstOrConstSplat(Val.getOperand(0));
3662     if (C && C->getAPIntValue().isSignMask())
3663       return true;
3664   }
3665 
3666   // Are all operands of a build vector constant powers of two?
3667   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3668     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3669           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3670             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3671           return false;
3672         }))
3673       return true;
3674 
3675   // Is the operand of a splat vector a constant power of two?
3676   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3677     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3678       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3679         return true;
3680 
3681   // More could be done here, though the above checks are enough
3682   // to handle some common cases.
3683 
3684   // Fall back to computeKnownBits to catch other known cases.
3685   KnownBits Known = computeKnownBits(Val);
3686   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3687 }
3688 
3689 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3690   EVT VT = Op.getValueType();
3691 
3692   // TODO: Assume we don't know anything for now.
3693   if (VT.isScalableVector())
3694     return 1;
3695 
3696   APInt DemandedElts = VT.isVector()
3697                            ? APInt::getAllOnes(VT.getVectorNumElements())
3698                            : APInt(1, 1);
3699   return ComputeNumSignBits(Op, DemandedElts, Depth);
3700 }
3701 
3702 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3703                                           unsigned Depth) const {
3704   EVT VT = Op.getValueType();
3705   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3706   unsigned VTBits = VT.getScalarSizeInBits();
3707   unsigned NumElts = DemandedElts.getBitWidth();
3708   unsigned Tmp, Tmp2;
3709   unsigned FirstAnswer = 1;
3710 
3711   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3712     const APInt &Val = C->getAPIntValue();
3713     return Val.getNumSignBits();
3714   }
3715 
3716   if (Depth >= MaxRecursionDepth)
3717     return 1;  // Limit search depth.
3718 
3719   if (!DemandedElts || VT.isScalableVector())
3720     return 1;  // No demanded elts, better to assume we don't know anything.
3721 
3722   unsigned Opcode = Op.getOpcode();
3723   switch (Opcode) {
3724   default: break;
3725   case ISD::AssertSext:
3726     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3727     return VTBits-Tmp+1;
3728   case ISD::AssertZext:
3729     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3730     return VTBits-Tmp;
3731 
3732   case ISD::BUILD_VECTOR:
3733     Tmp = VTBits;
3734     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3735       if (!DemandedElts[i])
3736         continue;
3737 
3738       SDValue SrcOp = Op.getOperand(i);
3739       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3740 
3741       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3742       if (SrcOp.getValueSizeInBits() != VTBits) {
3743         assert(SrcOp.getValueSizeInBits() > VTBits &&
3744                "Expected BUILD_VECTOR implicit truncation");
3745         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3746         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3747       }
3748       Tmp = std::min(Tmp, Tmp2);
3749     }
3750     return Tmp;
3751 
3752   case ISD::VECTOR_SHUFFLE: {
3753     // Collect the minimum number of sign bits that are shared by every vector
3754     // element referenced by the shuffle.
3755     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3756     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3757     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3758     for (unsigned i = 0; i != NumElts; ++i) {
3759       int M = SVN->getMaskElt(i);
3760       if (!DemandedElts[i])
3761         continue;
3762       // For UNDEF elements, we don't know anything about the common state of
3763       // the shuffle result.
3764       if (M < 0)
3765         return 1;
3766       if ((unsigned)M < NumElts)
3767         DemandedLHS.setBit((unsigned)M % NumElts);
3768       else
3769         DemandedRHS.setBit((unsigned)M % NumElts);
3770     }
3771     Tmp = std::numeric_limits<unsigned>::max();
3772     if (!!DemandedLHS)
3773       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3774     if (!!DemandedRHS) {
3775       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3776       Tmp = std::min(Tmp, Tmp2);
3777     }
3778     // If we don't know anything, early out and try computeKnownBits fall-back.
3779     if (Tmp == 1)
3780       break;
3781     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3782     return Tmp;
3783   }
3784 
3785   case ISD::BITCAST: {
3786     SDValue N0 = Op.getOperand(0);
3787     EVT SrcVT = N0.getValueType();
3788     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3789 
3790     // Ignore bitcasts from unsupported types..
3791     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3792       break;
3793 
3794     // Fast handling of 'identity' bitcasts.
3795     if (VTBits == SrcBits)
3796       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3797 
3798     bool IsLE = getDataLayout().isLittleEndian();
3799 
3800     // Bitcast 'large element' scalar/vector to 'small element' vector.
3801     if ((SrcBits % VTBits) == 0) {
3802       assert(VT.isVector() && "Expected bitcast to vector");
3803 
3804       unsigned Scale = SrcBits / VTBits;
3805       APInt SrcDemandedElts(NumElts / Scale, 0);
3806       for (unsigned i = 0; i != NumElts; ++i)
3807         if (DemandedElts[i])
3808           SrcDemandedElts.setBit(i / Scale);
3809 
3810       // Fast case - sign splat can be simply split across the small elements.
3811       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3812       if (Tmp == SrcBits)
3813         return VTBits;
3814 
3815       // Slow case - determine how far the sign extends into each sub-element.
3816       Tmp2 = VTBits;
3817       for (unsigned i = 0; i != NumElts; ++i)
3818         if (DemandedElts[i]) {
3819           unsigned SubOffset = i % Scale;
3820           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3821           SubOffset = SubOffset * VTBits;
3822           if (Tmp <= SubOffset)
3823             return 1;
3824           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3825         }
3826       return Tmp2;
3827     }
3828     break;
3829   }
3830 
3831   case ISD::SIGN_EXTEND:
3832     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3833     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3834   case ISD::SIGN_EXTEND_INREG:
3835     // Max of the input and what this extends.
3836     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3837     Tmp = VTBits-Tmp+1;
3838     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3839     return std::max(Tmp, Tmp2);
3840   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3841     SDValue Src = Op.getOperand(0);
3842     EVT SrcVT = Src.getValueType();
3843     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3844     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3845     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3846   }
3847   case ISD::SRA:
3848     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3849     // SRA X, C -> adds C sign bits.
3850     if (const APInt *ShAmt =
3851             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3852       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3853     return Tmp;
3854   case ISD::SHL:
3855     if (const APInt *ShAmt =
3856             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3857       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3858       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3859       if (ShAmt->ult(Tmp))
3860         return Tmp - ShAmt->getZExtValue();
3861     }
3862     break;
3863   case ISD::AND:
3864   case ISD::OR:
3865   case ISD::XOR:    // NOT is handled here.
3866     // Logical binary ops preserve the number of sign bits at the worst.
3867     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3868     if (Tmp != 1) {
3869       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3870       FirstAnswer = std::min(Tmp, Tmp2);
3871       // We computed what we know about the sign bits as our first
3872       // answer. Now proceed to the generic code that uses
3873       // computeKnownBits, and pick whichever answer is better.
3874     }
3875     break;
3876 
3877   case ISD::SELECT:
3878   case ISD::VSELECT:
3879     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3880     if (Tmp == 1) return 1;  // Early out.
3881     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3882     return std::min(Tmp, Tmp2);
3883   case ISD::SELECT_CC:
3884     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3885     if (Tmp == 1) return 1;  // Early out.
3886     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3887     return std::min(Tmp, Tmp2);
3888 
3889   case ISD::SMIN:
3890   case ISD::SMAX: {
3891     // If we have a clamp pattern, we know that the number of sign bits will be
3892     // the minimum of the clamp min/max range.
3893     bool IsMax = (Opcode == ISD::SMAX);
3894     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3895     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3896       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3897         CstHigh =
3898             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3899     if (CstLow && CstHigh) {
3900       if (!IsMax)
3901         std::swap(CstLow, CstHigh);
3902       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3903         Tmp = CstLow->getAPIntValue().getNumSignBits();
3904         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3905         return std::min(Tmp, Tmp2);
3906       }
3907     }
3908 
3909     // Fallback - just get the minimum number of sign bits of the operands.
3910     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3911     if (Tmp == 1)
3912       return 1;  // Early out.
3913     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3914     return std::min(Tmp, Tmp2);
3915   }
3916   case ISD::UMIN:
3917   case ISD::UMAX:
3918     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3919     if (Tmp == 1)
3920       return 1;  // Early out.
3921     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3922     return std::min(Tmp, Tmp2);
3923   case ISD::SADDO:
3924   case ISD::UADDO:
3925   case ISD::SSUBO:
3926   case ISD::USUBO:
3927   case ISD::SMULO:
3928   case ISD::UMULO:
3929     if (Op.getResNo() != 1)
3930       break;
3931     // The boolean result conforms to getBooleanContents.  Fall through.
3932     // If setcc returns 0/-1, all bits are sign bits.
3933     // We know that we have an integer-based boolean since these operations
3934     // are only available for integer.
3935     if (TLI->getBooleanContents(VT.isVector(), false) ==
3936         TargetLowering::ZeroOrNegativeOneBooleanContent)
3937       return VTBits;
3938     break;
3939   case ISD::SETCC:
3940   case ISD::STRICT_FSETCC:
3941   case ISD::STRICT_FSETCCS: {
3942     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3943     // If setcc returns 0/-1, all bits are sign bits.
3944     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3945         TargetLowering::ZeroOrNegativeOneBooleanContent)
3946       return VTBits;
3947     break;
3948   }
3949   case ISD::ROTL:
3950   case ISD::ROTR:
3951     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3952 
3953     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3954     if (Tmp == VTBits)
3955       return VTBits;
3956 
3957     if (ConstantSDNode *C =
3958             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3959       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3960 
3961       // Handle rotate right by N like a rotate left by 32-N.
3962       if (Opcode == ISD::ROTR)
3963         RotAmt = (VTBits - RotAmt) % VTBits;
3964 
3965       // If we aren't rotating out all of the known-in sign bits, return the
3966       // number that are left.  This handles rotl(sext(x), 1) for example.
3967       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3968     }
3969     break;
3970   case ISD::ADD:
3971   case ISD::ADDC:
3972     // Add can have at most one carry bit.  Thus we know that the output
3973     // is, at worst, one more bit than the inputs.
3974     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3975     if (Tmp == 1) return 1; // Early out.
3976 
3977     // Special case decrementing a value (ADD X, -1):
3978     if (ConstantSDNode *CRHS =
3979             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3980       if (CRHS->isAllOnes()) {
3981         KnownBits Known =
3982             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3983 
3984         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3985         // sign bits set.
3986         if ((Known.Zero | 1).isAllOnes())
3987           return VTBits;
3988 
3989         // If we are subtracting one from a positive number, there is no carry
3990         // out of the result.
3991         if (Known.isNonNegative())
3992           return Tmp;
3993       }
3994 
3995     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3996     if (Tmp2 == 1) return 1; // Early out.
3997     return std::min(Tmp, Tmp2) - 1;
3998   case ISD::SUB:
3999     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4000     if (Tmp2 == 1) return 1; // Early out.
4001 
4002     // Handle NEG.
4003     if (ConstantSDNode *CLHS =
4004             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4005       if (CLHS->isZero()) {
4006         KnownBits Known =
4007             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4008         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4009         // sign bits set.
4010         if ((Known.Zero | 1).isAllOnes())
4011           return VTBits;
4012 
4013         // If the input is known to be positive (the sign bit is known clear),
4014         // the output of the NEG has the same number of sign bits as the input.
4015         if (Known.isNonNegative())
4016           return Tmp2;
4017 
4018         // Otherwise, we treat this like a SUB.
4019       }
4020 
4021     // Sub can have at most one carry bit.  Thus we know that the output
4022     // is, at worst, one more bit than the inputs.
4023     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4024     if (Tmp == 1) return 1; // Early out.
4025     return std::min(Tmp, Tmp2) - 1;
4026   case ISD::MUL: {
4027     // The output of the Mul can be at most twice the valid bits in the inputs.
4028     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4029     if (SignBitsOp0 == 1)
4030       break;
4031     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4032     if (SignBitsOp1 == 1)
4033       break;
4034     unsigned OutValidBits =
4035         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4036     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4037   }
4038   case ISD::SREM:
4039     // The sign bit is the LHS's sign bit, except when the result of the
4040     // remainder is zero. The magnitude of the result should be less than or
4041     // equal to the magnitude of the LHS. Therefore, the result should have
4042     // at least as many sign bits as the left hand side.
4043     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4044   case ISD::TRUNCATE: {
4045     // Check if the sign bits of source go down as far as the truncated value.
4046     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4047     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4048     if (NumSrcSignBits > (NumSrcBits - VTBits))
4049       return NumSrcSignBits - (NumSrcBits - VTBits);
4050     break;
4051   }
4052   case ISD::EXTRACT_ELEMENT: {
4053     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4054     const int BitWidth = Op.getValueSizeInBits();
4055     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4056 
4057     // Get reverse index (starting from 1), Op1 value indexes elements from
4058     // little end. Sign starts at big end.
4059     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4060 
4061     // If the sign portion ends in our element the subtraction gives correct
4062     // result. Otherwise it gives either negative or > bitwidth result
4063     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4064   }
4065   case ISD::INSERT_VECTOR_ELT: {
4066     // If we know the element index, split the demand between the
4067     // source vector and the inserted element, otherwise assume we need
4068     // the original demanded vector elements and the value.
4069     SDValue InVec = Op.getOperand(0);
4070     SDValue InVal = Op.getOperand(1);
4071     SDValue EltNo = Op.getOperand(2);
4072     bool DemandedVal = true;
4073     APInt DemandedVecElts = DemandedElts;
4074     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4075     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4076       unsigned EltIdx = CEltNo->getZExtValue();
4077       DemandedVal = !!DemandedElts[EltIdx];
4078       DemandedVecElts.clearBit(EltIdx);
4079     }
4080     Tmp = std::numeric_limits<unsigned>::max();
4081     if (DemandedVal) {
4082       // TODO - handle implicit truncation of inserted elements.
4083       if (InVal.getScalarValueSizeInBits() != VTBits)
4084         break;
4085       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4086       Tmp = std::min(Tmp, Tmp2);
4087     }
4088     if (!!DemandedVecElts) {
4089       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4090       Tmp = std::min(Tmp, Tmp2);
4091     }
4092     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4093     return Tmp;
4094   }
4095   case ISD::EXTRACT_VECTOR_ELT: {
4096     SDValue InVec = Op.getOperand(0);
4097     SDValue EltNo = Op.getOperand(1);
4098     EVT VecVT = InVec.getValueType();
4099     // ComputeNumSignBits not yet implemented for scalable vectors.
4100     if (VecVT.isScalableVector())
4101       break;
4102     const unsigned BitWidth = Op.getValueSizeInBits();
4103     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4104     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4105 
4106     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4107     // anything about sign bits. But if the sizes match we can derive knowledge
4108     // about sign bits from the vector operand.
4109     if (BitWidth != EltBitWidth)
4110       break;
4111 
4112     // If we know the element index, just demand that vector element, else for
4113     // an unknown element index, ignore DemandedElts and demand them all.
4114     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4115     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4116     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4117       DemandedSrcElts =
4118           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4119 
4120     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4121   }
4122   case ISD::EXTRACT_SUBVECTOR: {
4123     // Offset the demanded elts by the subvector index.
4124     SDValue Src = Op.getOperand(0);
4125     // Bail until we can represent demanded elements for scalable vectors.
4126     if (Src.getValueType().isScalableVector())
4127       break;
4128     uint64_t Idx = Op.getConstantOperandVal(1);
4129     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4130     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4131     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4132   }
4133   case ISD::CONCAT_VECTORS: {
4134     // Determine the minimum number of sign bits across all demanded
4135     // elts of the input vectors. Early out if the result is already 1.
4136     Tmp = std::numeric_limits<unsigned>::max();
4137     EVT SubVectorVT = Op.getOperand(0).getValueType();
4138     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4139     unsigned NumSubVectors = Op.getNumOperands();
4140     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4141       APInt DemandedSub =
4142           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4143       if (!DemandedSub)
4144         continue;
4145       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4146       Tmp = std::min(Tmp, Tmp2);
4147     }
4148     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4149     return Tmp;
4150   }
4151   case ISD::INSERT_SUBVECTOR: {
4152     // Demand any elements from the subvector and the remainder from the src its
4153     // inserted into.
4154     SDValue Src = Op.getOperand(0);
4155     SDValue Sub = Op.getOperand(1);
4156     uint64_t Idx = Op.getConstantOperandVal(2);
4157     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4158     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4159     APInt DemandedSrcElts = DemandedElts;
4160     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4161 
4162     Tmp = std::numeric_limits<unsigned>::max();
4163     if (!!DemandedSubElts) {
4164       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4165       if (Tmp == 1)
4166         return 1; // early-out
4167     }
4168     if (!!DemandedSrcElts) {
4169       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4170       Tmp = std::min(Tmp, Tmp2);
4171     }
4172     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4173     return Tmp;
4174   }
4175   case ISD::ATOMIC_CMP_SWAP:
4176   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4177   case ISD::ATOMIC_SWAP:
4178   case ISD::ATOMIC_LOAD_ADD:
4179   case ISD::ATOMIC_LOAD_SUB:
4180   case ISD::ATOMIC_LOAD_AND:
4181   case ISD::ATOMIC_LOAD_CLR:
4182   case ISD::ATOMIC_LOAD_OR:
4183   case ISD::ATOMIC_LOAD_XOR:
4184   case ISD::ATOMIC_LOAD_NAND:
4185   case ISD::ATOMIC_LOAD_MIN:
4186   case ISD::ATOMIC_LOAD_MAX:
4187   case ISD::ATOMIC_LOAD_UMIN:
4188   case ISD::ATOMIC_LOAD_UMAX:
4189   case ISD::ATOMIC_LOAD: {
4190     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4191     // If we are looking at the loaded value.
4192     if (Op.getResNo() == 0) {
4193       if (Tmp == VTBits)
4194         return 1; // early-out
4195       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4196         return VTBits - Tmp + 1;
4197       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4198         return VTBits - Tmp;
4199     }
4200     break;
4201   }
4202   }
4203 
4204   // If we are looking at the loaded value of the SDNode.
4205   if (Op.getResNo() == 0) {
4206     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4207     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4208       unsigned ExtType = LD->getExtensionType();
4209       switch (ExtType) {
4210       default: break;
4211       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4212         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4213         return VTBits - Tmp + 1;
4214       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4215         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4216         return VTBits - Tmp;
4217       case ISD::NON_EXTLOAD:
4218         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4219           // We only need to handle vectors - computeKnownBits should handle
4220           // scalar cases.
4221           Type *CstTy = Cst->getType();
4222           if (CstTy->isVectorTy() &&
4223               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4224             Tmp = VTBits;
4225             for (unsigned i = 0; i != NumElts; ++i) {
4226               if (!DemandedElts[i])
4227                 continue;
4228               if (Constant *Elt = Cst->getAggregateElement(i)) {
4229                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4230                   const APInt &Value = CInt->getValue();
4231                   Tmp = std::min(Tmp, Value.getNumSignBits());
4232                   continue;
4233                 }
4234                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4235                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4236                   Tmp = std::min(Tmp, Value.getNumSignBits());
4237                   continue;
4238                 }
4239               }
4240               // Unknown type. Conservatively assume no bits match sign bit.
4241               return 1;
4242             }
4243             return Tmp;
4244           }
4245         }
4246         break;
4247       }
4248     }
4249   }
4250 
4251   // Allow the target to implement this method for its nodes.
4252   if (Opcode >= ISD::BUILTIN_OP_END ||
4253       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4254       Opcode == ISD::INTRINSIC_W_CHAIN ||
4255       Opcode == ISD::INTRINSIC_VOID) {
4256     unsigned NumBits =
4257         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4258     if (NumBits > 1)
4259       FirstAnswer = std::max(FirstAnswer, NumBits);
4260   }
4261 
4262   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4263   // use this information.
4264   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4265 
4266   APInt Mask;
4267   if (Known.isNonNegative()) {        // sign bit is 0
4268     Mask = Known.Zero;
4269   } else if (Known.isNegative()) {  // sign bit is 1;
4270     Mask = Known.One;
4271   } else {
4272     // Nothing known.
4273     return FirstAnswer;
4274   }
4275 
4276   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4277   // the number of identical bits in the top of the input value.
4278   Mask <<= Mask.getBitWidth()-VTBits;
4279   return std::max(FirstAnswer, Mask.countLeadingOnes());
4280 }
4281 
4282 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4283                                                     unsigned Depth) const {
4284   // Early out for FREEZE.
4285   if (Op.getOpcode() == ISD::FREEZE)
4286     return true;
4287 
4288   // TODO: Assume we don't know anything for now.
4289   EVT VT = Op.getValueType();
4290   if (VT.isScalableVector())
4291     return false;
4292 
4293   APInt DemandedElts = VT.isVector()
4294                            ? APInt::getAllOnes(VT.getVectorNumElements())
4295                            : APInt(1, 1);
4296   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4297 }
4298 
4299 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4300                                                     const APInt &DemandedElts,
4301                                                     bool PoisonOnly,
4302                                                     unsigned Depth) const {
4303   unsigned Opcode = Op.getOpcode();
4304 
4305   // Early out for FREEZE.
4306   if (Opcode == ISD::FREEZE)
4307     return true;
4308 
4309   if (Depth >= MaxRecursionDepth)
4310     return false; // Limit search depth.
4311 
4312   if (isIntOrFPConstant(Op))
4313     return true;
4314 
4315   switch (Opcode) {
4316   case ISD::UNDEF:
4317     return PoisonOnly;
4318 
4319   case ISD::BUILD_VECTOR:
4320     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4321     // this shouldn't affect the result.
4322     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4323       if (!DemandedElts[i])
4324         continue;
4325       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4326                                             Depth + 1))
4327         return false;
4328     }
4329     return true;
4330 
4331   // TODO: Search for noundef attributes from library functions.
4332 
4333   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4334 
4335   default:
4336     // Allow the target to implement this method for its nodes.
4337     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4338         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4339       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4340           Op, DemandedElts, *this, PoisonOnly, Depth);
4341     break;
4342   }
4343 
4344   return false;
4345 }
4346 
4347 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4348   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4349       !isa<ConstantSDNode>(Op.getOperand(1)))
4350     return false;
4351 
4352   if (Op.getOpcode() == ISD::OR &&
4353       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4354     return false;
4355 
4356   return true;
4357 }
4358 
4359 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4360   // If we're told that NaNs won't happen, assume they won't.
4361   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4362     return true;
4363 
4364   if (Depth >= MaxRecursionDepth)
4365     return false; // Limit search depth.
4366 
4367   // TODO: Handle vectors.
4368   // If the value is a constant, we can obviously see if it is a NaN or not.
4369   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4370     return !C->getValueAPF().isNaN() ||
4371            (SNaN && !C->getValueAPF().isSignaling());
4372   }
4373 
4374   unsigned Opcode = Op.getOpcode();
4375   switch (Opcode) {
4376   case ISD::FADD:
4377   case ISD::FSUB:
4378   case ISD::FMUL:
4379   case ISD::FDIV:
4380   case ISD::FREM:
4381   case ISD::FSIN:
4382   case ISD::FCOS: {
4383     if (SNaN)
4384       return true;
4385     // TODO: Need isKnownNeverInfinity
4386     return false;
4387   }
4388   case ISD::FCANONICALIZE:
4389   case ISD::FEXP:
4390   case ISD::FEXP2:
4391   case ISD::FTRUNC:
4392   case ISD::FFLOOR:
4393   case ISD::FCEIL:
4394   case ISD::FROUND:
4395   case ISD::FROUNDEVEN:
4396   case ISD::FRINT:
4397   case ISD::FNEARBYINT: {
4398     if (SNaN)
4399       return true;
4400     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4401   }
4402   case ISD::FABS:
4403   case ISD::FNEG:
4404   case ISD::FCOPYSIGN: {
4405     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4406   }
4407   case ISD::SELECT:
4408     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4409            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4410   case ISD::FP_EXTEND:
4411   case ISD::FP_ROUND: {
4412     if (SNaN)
4413       return true;
4414     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4415   }
4416   case ISD::SINT_TO_FP:
4417   case ISD::UINT_TO_FP:
4418     return true;
4419   case ISD::FMA:
4420   case ISD::FMAD: {
4421     if (SNaN)
4422       return true;
4423     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4424            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4425            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4426   }
4427   case ISD::FSQRT: // Need is known positive
4428   case ISD::FLOG:
4429   case ISD::FLOG2:
4430   case ISD::FLOG10:
4431   case ISD::FPOWI:
4432   case ISD::FPOW: {
4433     if (SNaN)
4434       return true;
4435     // TODO: Refine on operand
4436     return false;
4437   }
4438   case ISD::FMINNUM:
4439   case ISD::FMAXNUM: {
4440     // Only one needs to be known not-nan, since it will be returned if the
4441     // other ends up being one.
4442     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4443            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4444   }
4445   case ISD::FMINNUM_IEEE:
4446   case ISD::FMAXNUM_IEEE: {
4447     if (SNaN)
4448       return true;
4449     // This can return a NaN if either operand is an sNaN, or if both operands
4450     // are NaN.
4451     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4452             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4453            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4454             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4455   }
4456   case ISD::FMINIMUM:
4457   case ISD::FMAXIMUM: {
4458     // TODO: Does this quiet or return the origina NaN as-is?
4459     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4460            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4461   }
4462   case ISD::EXTRACT_VECTOR_ELT: {
4463     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4464   }
4465   default:
4466     if (Opcode >= ISD::BUILTIN_OP_END ||
4467         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4468         Opcode == ISD::INTRINSIC_W_CHAIN ||
4469         Opcode == ISD::INTRINSIC_VOID) {
4470       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4471     }
4472 
4473     return false;
4474   }
4475 }
4476 
4477 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4478   assert(Op.getValueType().isFloatingPoint() &&
4479          "Floating point type expected");
4480 
4481   // If the value is a constant, we can obviously see if it is a zero or not.
4482   // TODO: Add BuildVector support.
4483   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4484     return !C->isZero();
4485   return false;
4486 }
4487 
4488 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4489   assert(!Op.getValueType().isFloatingPoint() &&
4490          "Floating point types unsupported - use isKnownNeverZeroFloat");
4491 
4492   // If the value is a constant, we can obviously see if it is a zero or not.
4493   if (ISD::matchUnaryPredicate(Op,
4494                                [](ConstantSDNode *C) { return !C->isZero(); }))
4495     return true;
4496 
4497   // TODO: Recognize more cases here.
4498   switch (Op.getOpcode()) {
4499   default: break;
4500   case ISD::OR:
4501     if (isKnownNeverZero(Op.getOperand(1)) ||
4502         isKnownNeverZero(Op.getOperand(0)))
4503       return true;
4504     break;
4505   }
4506 
4507   return false;
4508 }
4509 
4510 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4511   // Check the obvious case.
4512   if (A == B) return true;
4513 
4514   // For for negative and positive zero.
4515   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4516     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4517       if (CA->isZero() && CB->isZero()) return true;
4518 
4519   // Otherwise they may not be equal.
4520   return false;
4521 }
4522 
4523 // FIXME: unify with llvm::haveNoCommonBitsSet.
4524 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4525 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4526   assert(A.getValueType() == B.getValueType() &&
4527          "Values must have the same type");
4528   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4529                                         computeKnownBits(B));
4530 }
4531 
4532 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4533                                SelectionDAG &DAG) {
4534   if (cast<ConstantSDNode>(Step)->isZero())
4535     return DAG.getConstant(0, DL, VT);
4536 
4537   return SDValue();
4538 }
4539 
4540 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4541                                 ArrayRef<SDValue> Ops,
4542                                 SelectionDAG &DAG) {
4543   int NumOps = Ops.size();
4544   assert(NumOps != 0 && "Can't build an empty vector!");
4545   assert(!VT.isScalableVector() &&
4546          "BUILD_VECTOR cannot be used with scalable types");
4547   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4548          "Incorrect element count in BUILD_VECTOR!");
4549 
4550   // BUILD_VECTOR of UNDEFs is UNDEF.
4551   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4552     return DAG.getUNDEF(VT);
4553 
4554   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4555   SDValue IdentitySrc;
4556   bool IsIdentity = true;
4557   for (int i = 0; i != NumOps; ++i) {
4558     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4559         Ops[i].getOperand(0).getValueType() != VT ||
4560         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4561         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4562         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4563       IsIdentity = false;
4564       break;
4565     }
4566     IdentitySrc = Ops[i].getOperand(0);
4567   }
4568   if (IsIdentity)
4569     return IdentitySrc;
4570 
4571   return SDValue();
4572 }
4573 
4574 /// Try to simplify vector concatenation to an input value, undef, or build
4575 /// vector.
4576 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4577                                   ArrayRef<SDValue> Ops,
4578                                   SelectionDAG &DAG) {
4579   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4580   assert(llvm::all_of(Ops,
4581                       [Ops](SDValue Op) {
4582                         return Ops[0].getValueType() == Op.getValueType();
4583                       }) &&
4584          "Concatenation of vectors with inconsistent value types!");
4585   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4586              VT.getVectorElementCount() &&
4587          "Incorrect element count in vector concatenation!");
4588 
4589   if (Ops.size() == 1)
4590     return Ops[0];
4591 
4592   // Concat of UNDEFs is UNDEF.
4593   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4594     return DAG.getUNDEF(VT);
4595 
4596   // Scan the operands and look for extract operations from a single source
4597   // that correspond to insertion at the same location via this concatenation:
4598   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4599   SDValue IdentitySrc;
4600   bool IsIdentity = true;
4601   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4602     SDValue Op = Ops[i];
4603     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4604     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4605         Op.getOperand(0).getValueType() != VT ||
4606         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4607         Op.getConstantOperandVal(1) != IdentityIndex) {
4608       IsIdentity = false;
4609       break;
4610     }
4611     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4612            "Unexpected identity source vector for concat of extracts");
4613     IdentitySrc = Op.getOperand(0);
4614   }
4615   if (IsIdentity) {
4616     assert(IdentitySrc && "Failed to set source vector of extracts");
4617     return IdentitySrc;
4618   }
4619 
4620   // The code below this point is only designed to work for fixed width
4621   // vectors, so we bail out for now.
4622   if (VT.isScalableVector())
4623     return SDValue();
4624 
4625   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4626   // simplified to one big BUILD_VECTOR.
4627   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4628   EVT SVT = VT.getScalarType();
4629   SmallVector<SDValue, 16> Elts;
4630   for (SDValue Op : Ops) {
4631     EVT OpVT = Op.getValueType();
4632     if (Op.isUndef())
4633       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4634     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4635       Elts.append(Op->op_begin(), Op->op_end());
4636     else
4637       return SDValue();
4638   }
4639 
4640   // BUILD_VECTOR requires all inputs to be of the same type, find the
4641   // maximum type and extend them all.
4642   for (SDValue Op : Elts)
4643     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4644 
4645   if (SVT.bitsGT(VT.getScalarType())) {
4646     for (SDValue &Op : Elts) {
4647       if (Op.isUndef())
4648         Op = DAG.getUNDEF(SVT);
4649       else
4650         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4651                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4652                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4653     }
4654   }
4655 
4656   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4657   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4658   return V;
4659 }
4660 
4661 /// Gets or creates the specified node.
4662 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4663   FoldingSetNodeID ID;
4664   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4665   void *IP = nullptr;
4666   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4667     return SDValue(E, 0);
4668 
4669   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4670                               getVTList(VT));
4671   CSEMap.InsertNode(N, IP);
4672 
4673   InsertNode(N);
4674   SDValue V = SDValue(N, 0);
4675   NewSDValueDbgMsg(V, "Creating new node: ", this);
4676   return V;
4677 }
4678 
4679 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4680                               SDValue Operand) {
4681   SDNodeFlags Flags;
4682   if (Inserter)
4683     Flags = Inserter->getFlags();
4684   return getNode(Opcode, DL, VT, Operand, Flags);
4685 }
4686 
4687 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4688                               SDValue Operand, const SDNodeFlags Flags) {
4689   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4690          "Operand is DELETED_NODE!");
4691   // Constant fold unary operations with an integer constant operand. Even
4692   // opaque constant will be folded, because the folding of unary operations
4693   // doesn't create new constants with different values. Nevertheless, the
4694   // opaque flag is preserved during folding to prevent future folding with
4695   // other constants.
4696   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4697     const APInt &Val = C->getAPIntValue();
4698     switch (Opcode) {
4699     default: break;
4700     case ISD::SIGN_EXTEND:
4701       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4702                          C->isTargetOpcode(), C->isOpaque());
4703     case ISD::TRUNCATE:
4704       if (C->isOpaque())
4705         break;
4706       LLVM_FALLTHROUGH;
4707     case ISD::ZERO_EXTEND:
4708       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4709                          C->isTargetOpcode(), C->isOpaque());
4710     case ISD::ANY_EXTEND:
4711       // Some targets like RISCV prefer to sign extend some types.
4712       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4713         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4714                            C->isTargetOpcode(), C->isOpaque());
4715       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4716                          C->isTargetOpcode(), C->isOpaque());
4717     case ISD::UINT_TO_FP:
4718     case ISD::SINT_TO_FP: {
4719       APFloat apf(EVTToAPFloatSemantics(VT),
4720                   APInt::getZero(VT.getSizeInBits()));
4721       (void)apf.convertFromAPInt(Val,
4722                                  Opcode==ISD::SINT_TO_FP,
4723                                  APFloat::rmNearestTiesToEven);
4724       return getConstantFP(apf, DL, VT);
4725     }
4726     case ISD::BITCAST:
4727       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4728         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4729       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4730         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4731       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4732         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4733       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4734         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4735       break;
4736     case ISD::ABS:
4737       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4738                          C->isOpaque());
4739     case ISD::BITREVERSE:
4740       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4741                          C->isOpaque());
4742     case ISD::BSWAP:
4743       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4744                          C->isOpaque());
4745     case ISD::CTPOP:
4746       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4747                          C->isOpaque());
4748     case ISD::CTLZ:
4749     case ISD::CTLZ_ZERO_UNDEF:
4750       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4751                          C->isOpaque());
4752     case ISD::CTTZ:
4753     case ISD::CTTZ_ZERO_UNDEF:
4754       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4755                          C->isOpaque());
4756     case ISD::FP16_TO_FP: {
4757       bool Ignored;
4758       APFloat FPV(APFloat::IEEEhalf(),
4759                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4760 
4761       // This can return overflow, underflow, or inexact; we don't care.
4762       // FIXME need to be more flexible about rounding mode.
4763       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4764                         APFloat::rmNearestTiesToEven, &Ignored);
4765       return getConstantFP(FPV, DL, VT);
4766     }
4767     case ISD::STEP_VECTOR: {
4768       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4769         return V;
4770       break;
4771     }
4772     }
4773   }
4774 
4775   // Constant fold unary operations with a floating point constant operand.
4776   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4777     APFloat V = C->getValueAPF();    // make copy
4778     switch (Opcode) {
4779     case ISD::FNEG:
4780       V.changeSign();
4781       return getConstantFP(V, DL, VT);
4782     case ISD::FABS:
4783       V.clearSign();
4784       return getConstantFP(V, DL, VT);
4785     case ISD::FCEIL: {
4786       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4787       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4788         return getConstantFP(V, DL, VT);
4789       break;
4790     }
4791     case ISD::FTRUNC: {
4792       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4793       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4794         return getConstantFP(V, DL, VT);
4795       break;
4796     }
4797     case ISD::FFLOOR: {
4798       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4799       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4800         return getConstantFP(V, DL, VT);
4801       break;
4802     }
4803     case ISD::FP_EXTEND: {
4804       bool ignored;
4805       // This can return overflow, underflow, or inexact; we don't care.
4806       // FIXME need to be more flexible about rounding mode.
4807       (void)V.convert(EVTToAPFloatSemantics(VT),
4808                       APFloat::rmNearestTiesToEven, &ignored);
4809       return getConstantFP(V, DL, VT);
4810     }
4811     case ISD::FP_TO_SINT:
4812     case ISD::FP_TO_UINT: {
4813       bool ignored;
4814       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4815       // FIXME need to be more flexible about rounding mode.
4816       APFloat::opStatus s =
4817           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4818       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4819         break;
4820       return getConstant(IntVal, DL, VT);
4821     }
4822     case ISD::BITCAST:
4823       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4824         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4825       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4826         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4827       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4828         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4829       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4830         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4831       break;
4832     case ISD::FP_TO_FP16: {
4833       bool Ignored;
4834       // This can return overflow, underflow, or inexact; we don't care.
4835       // FIXME need to be more flexible about rounding mode.
4836       (void)V.convert(APFloat::IEEEhalf(),
4837                       APFloat::rmNearestTiesToEven, &Ignored);
4838       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4839     }
4840     }
4841   }
4842 
4843   // Constant fold unary operations with a vector integer or float operand.
4844   switch (Opcode) {
4845   default:
4846     // FIXME: Entirely reasonable to perform folding of other unary
4847     // operations here as the need arises.
4848     break;
4849   case ISD::FNEG:
4850   case ISD::FABS:
4851   case ISD::FCEIL:
4852   case ISD::FTRUNC:
4853   case ISD::FFLOOR:
4854   case ISD::FP_EXTEND:
4855   case ISD::FP_TO_SINT:
4856   case ISD::FP_TO_UINT:
4857   case ISD::TRUNCATE:
4858   case ISD::ANY_EXTEND:
4859   case ISD::ZERO_EXTEND:
4860   case ISD::SIGN_EXTEND:
4861   case ISD::UINT_TO_FP:
4862   case ISD::SINT_TO_FP:
4863   case ISD::ABS:
4864   case ISD::BITREVERSE:
4865   case ISD::BSWAP:
4866   case ISD::CTLZ:
4867   case ISD::CTLZ_ZERO_UNDEF:
4868   case ISD::CTTZ:
4869   case ISD::CTTZ_ZERO_UNDEF:
4870   case ISD::CTPOP: {
4871     SDValue Ops = {Operand};
4872     if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4873       return Fold;
4874   }
4875   }
4876 
4877   unsigned OpOpcode = Operand.getNode()->getOpcode();
4878   switch (Opcode) {
4879   case ISD::STEP_VECTOR:
4880     assert(VT.isScalableVector() &&
4881            "STEP_VECTOR can only be used with scalable types");
4882     assert(OpOpcode == ISD::TargetConstant &&
4883            VT.getVectorElementType() == Operand.getValueType() &&
4884            "Unexpected step operand");
4885     break;
4886   case ISD::FREEZE:
4887     assert(VT == Operand.getValueType() && "Unexpected VT!");
4888     break;
4889   case ISD::TokenFactor:
4890   case ISD::MERGE_VALUES:
4891   case ISD::CONCAT_VECTORS:
4892     return Operand;         // Factor, merge or concat of one node?  No need.
4893   case ISD::BUILD_VECTOR: {
4894     // Attempt to simplify BUILD_VECTOR.
4895     SDValue Ops[] = {Operand};
4896     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4897       return V;
4898     break;
4899   }
4900   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4901   case ISD::FP_EXTEND:
4902     assert(VT.isFloatingPoint() &&
4903            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4904     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4905     assert((!VT.isVector() ||
4906             VT.getVectorElementCount() ==
4907             Operand.getValueType().getVectorElementCount()) &&
4908            "Vector element count mismatch!");
4909     assert(Operand.getValueType().bitsLT(VT) &&
4910            "Invalid fpext node, dst < src!");
4911     if (Operand.isUndef())
4912       return getUNDEF(VT);
4913     break;
4914   case ISD::FP_TO_SINT:
4915   case ISD::FP_TO_UINT:
4916     if (Operand.isUndef())
4917       return getUNDEF(VT);
4918     break;
4919   case ISD::SINT_TO_FP:
4920   case ISD::UINT_TO_FP:
4921     // [us]itofp(undef) = 0, because the result value is bounded.
4922     if (Operand.isUndef())
4923       return getConstantFP(0.0, DL, VT);
4924     break;
4925   case ISD::SIGN_EXTEND:
4926     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4927            "Invalid SIGN_EXTEND!");
4928     assert(VT.isVector() == Operand.getValueType().isVector() &&
4929            "SIGN_EXTEND result type type should be vector iff the operand "
4930            "type is vector!");
4931     if (Operand.getValueType() == VT) return Operand;   // noop extension
4932     assert((!VT.isVector() ||
4933             VT.getVectorElementCount() ==
4934                 Operand.getValueType().getVectorElementCount()) &&
4935            "Vector element count mismatch!");
4936     assert(Operand.getValueType().bitsLT(VT) &&
4937            "Invalid sext node, dst < src!");
4938     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4939       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4940     if (OpOpcode == ISD::UNDEF)
4941       // sext(undef) = 0, because the top bits will all be the same.
4942       return getConstant(0, DL, VT);
4943     break;
4944   case ISD::ZERO_EXTEND:
4945     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4946            "Invalid ZERO_EXTEND!");
4947     assert(VT.isVector() == Operand.getValueType().isVector() &&
4948            "ZERO_EXTEND result type type should be vector iff the operand "
4949            "type is vector!");
4950     if (Operand.getValueType() == VT) return Operand;   // noop extension
4951     assert((!VT.isVector() ||
4952             VT.getVectorElementCount() ==
4953                 Operand.getValueType().getVectorElementCount()) &&
4954            "Vector element count mismatch!");
4955     assert(Operand.getValueType().bitsLT(VT) &&
4956            "Invalid zext node, dst < src!");
4957     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4958       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4959     if (OpOpcode == ISD::UNDEF)
4960       // zext(undef) = 0, because the top bits will be zero.
4961       return getConstant(0, DL, VT);
4962     break;
4963   case ISD::ANY_EXTEND:
4964     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4965            "Invalid ANY_EXTEND!");
4966     assert(VT.isVector() == Operand.getValueType().isVector() &&
4967            "ANY_EXTEND result type type should be vector iff the operand "
4968            "type is vector!");
4969     if (Operand.getValueType() == VT) return Operand;   // noop extension
4970     assert((!VT.isVector() ||
4971             VT.getVectorElementCount() ==
4972                 Operand.getValueType().getVectorElementCount()) &&
4973            "Vector element count mismatch!");
4974     assert(Operand.getValueType().bitsLT(VT) &&
4975            "Invalid anyext node, dst < src!");
4976 
4977     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4978         OpOpcode == ISD::ANY_EXTEND)
4979       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4980       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4981     if (OpOpcode == ISD::UNDEF)
4982       return getUNDEF(VT);
4983 
4984     // (ext (trunc x)) -> x
4985     if (OpOpcode == ISD::TRUNCATE) {
4986       SDValue OpOp = Operand.getOperand(0);
4987       if (OpOp.getValueType() == VT) {
4988         transferDbgValues(Operand, OpOp);
4989         return OpOp;
4990       }
4991     }
4992     break;
4993   case ISD::TRUNCATE:
4994     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4995            "Invalid TRUNCATE!");
4996     assert(VT.isVector() == Operand.getValueType().isVector() &&
4997            "TRUNCATE result type type should be vector iff the operand "
4998            "type is vector!");
4999     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5000     assert((!VT.isVector() ||
5001             VT.getVectorElementCount() ==
5002                 Operand.getValueType().getVectorElementCount()) &&
5003            "Vector element count mismatch!");
5004     assert(Operand.getValueType().bitsGT(VT) &&
5005            "Invalid truncate node, src < dst!");
5006     if (OpOpcode == ISD::TRUNCATE)
5007       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5008     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5009         OpOpcode == ISD::ANY_EXTEND) {
5010       // If the source is smaller than the dest, we still need an extend.
5011       if (Operand.getOperand(0).getValueType().getScalarType()
5012             .bitsLT(VT.getScalarType()))
5013         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5014       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5015         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5016       return Operand.getOperand(0);
5017     }
5018     if (OpOpcode == ISD::UNDEF)
5019       return getUNDEF(VT);
5020     break;
5021   case ISD::ANY_EXTEND_VECTOR_INREG:
5022   case ISD::ZERO_EXTEND_VECTOR_INREG:
5023   case ISD::SIGN_EXTEND_VECTOR_INREG:
5024     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5025     assert(Operand.getValueType().bitsLE(VT) &&
5026            "The input must be the same size or smaller than the result.");
5027     assert(VT.getVectorMinNumElements() <
5028                Operand.getValueType().getVectorMinNumElements() &&
5029            "The destination vector type must have fewer lanes than the input.");
5030     break;
5031   case ISD::ABS:
5032     assert(VT.isInteger() && VT == Operand.getValueType() &&
5033            "Invalid ABS!");
5034     if (OpOpcode == ISD::UNDEF)
5035       return getUNDEF(VT);
5036     break;
5037   case ISD::BSWAP:
5038     assert(VT.isInteger() && VT == Operand.getValueType() &&
5039            "Invalid BSWAP!");
5040     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5041            "BSWAP types must be a multiple of 16 bits!");
5042     if (OpOpcode == ISD::UNDEF)
5043       return getUNDEF(VT);
5044     break;
5045   case ISD::BITREVERSE:
5046     assert(VT.isInteger() && VT == Operand.getValueType() &&
5047            "Invalid BITREVERSE!");
5048     if (OpOpcode == ISD::UNDEF)
5049       return getUNDEF(VT);
5050     break;
5051   case ISD::BITCAST:
5052     // Basic sanity checking.
5053     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5054            "Cannot BITCAST between types of different sizes!");
5055     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5056     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5057       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5058     if (OpOpcode == ISD::UNDEF)
5059       return getUNDEF(VT);
5060     break;
5061   case ISD::SCALAR_TO_VECTOR:
5062     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5063            (VT.getVectorElementType() == Operand.getValueType() ||
5064             (VT.getVectorElementType().isInteger() &&
5065              Operand.getValueType().isInteger() &&
5066              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5067            "Illegal SCALAR_TO_VECTOR node!");
5068     if (OpOpcode == ISD::UNDEF)
5069       return getUNDEF(VT);
5070     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5071     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5072         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5073         Operand.getConstantOperandVal(1) == 0 &&
5074         Operand.getOperand(0).getValueType() == VT)
5075       return Operand.getOperand(0);
5076     break;
5077   case ISD::FNEG:
5078     // Negation of an unknown bag of bits is still completely undefined.
5079     if (OpOpcode == ISD::UNDEF)
5080       return getUNDEF(VT);
5081 
5082     if (OpOpcode == ISD::FNEG)  // --X -> X
5083       return Operand.getOperand(0);
5084     break;
5085   case ISD::FABS:
5086     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5087       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5088     break;
5089   case ISD::VSCALE:
5090     assert(VT == Operand.getValueType() && "Unexpected VT!");
5091     break;
5092   case ISD::CTPOP:
5093     if (Operand.getValueType().getScalarType() == MVT::i1)
5094       return Operand;
5095     break;
5096   case ISD::CTLZ:
5097   case ISD::CTTZ:
5098     if (Operand.getValueType().getScalarType() == MVT::i1)
5099       return getNOT(DL, Operand, Operand.getValueType());
5100     break;
5101   case ISD::VECREDUCE_SMIN:
5102   case ISD::VECREDUCE_UMAX:
5103     if (Operand.getValueType().getScalarType() == MVT::i1)
5104       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5105     break;
5106   case ISD::VECREDUCE_SMAX:
5107   case ISD::VECREDUCE_UMIN:
5108     if (Operand.getValueType().getScalarType() == MVT::i1)
5109       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5110     break;
5111   }
5112 
5113   SDNode *N;
5114   SDVTList VTs = getVTList(VT);
5115   SDValue Ops[] = {Operand};
5116   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5117     FoldingSetNodeID ID;
5118     AddNodeIDNode(ID, Opcode, VTs, Ops);
5119     void *IP = nullptr;
5120     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5121       E->intersectFlagsWith(Flags);
5122       return SDValue(E, 0);
5123     }
5124 
5125     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5126     N->setFlags(Flags);
5127     createOperands(N, Ops);
5128     CSEMap.InsertNode(N, IP);
5129   } else {
5130     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5131     createOperands(N, Ops);
5132   }
5133 
5134   InsertNode(N);
5135   SDValue V = SDValue(N, 0);
5136   NewSDValueDbgMsg(V, "Creating new node: ", this);
5137   return V;
5138 }
5139 
5140 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5141                                        const APInt &C2) {
5142   switch (Opcode) {
5143   case ISD::ADD:  return C1 + C2;
5144   case ISD::SUB:  return C1 - C2;
5145   case ISD::MUL:  return C1 * C2;
5146   case ISD::AND:  return C1 & C2;
5147   case ISD::OR:   return C1 | C2;
5148   case ISD::XOR:  return C1 ^ C2;
5149   case ISD::SHL:  return C1 << C2;
5150   case ISD::SRL:  return C1.lshr(C2);
5151   case ISD::SRA:  return C1.ashr(C2);
5152   case ISD::ROTL: return C1.rotl(C2);
5153   case ISD::ROTR: return C1.rotr(C2);
5154   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5155   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5156   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5157   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5158   case ISD::SADDSAT: return C1.sadd_sat(C2);
5159   case ISD::UADDSAT: return C1.uadd_sat(C2);
5160   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5161   case ISD::USUBSAT: return C1.usub_sat(C2);
5162   case ISD::UDIV:
5163     if (!C2.getBoolValue())
5164       break;
5165     return C1.udiv(C2);
5166   case ISD::UREM:
5167     if (!C2.getBoolValue())
5168       break;
5169     return C1.urem(C2);
5170   case ISD::SDIV:
5171     if (!C2.getBoolValue())
5172       break;
5173     return C1.sdiv(C2);
5174   case ISD::SREM:
5175     if (!C2.getBoolValue())
5176       break;
5177     return C1.srem(C2);
5178   case ISD::MULHS: {
5179     unsigned FullWidth = C1.getBitWidth() * 2;
5180     APInt C1Ext = C1.sext(FullWidth);
5181     APInt C2Ext = C2.sext(FullWidth);
5182     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5183   }
5184   case ISD::MULHU: {
5185     unsigned FullWidth = C1.getBitWidth() * 2;
5186     APInt C1Ext = C1.zext(FullWidth);
5187     APInt C2Ext = C2.zext(FullWidth);
5188     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5189   }
5190   }
5191   return llvm::None;
5192 }
5193 
5194 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5195                                        const GlobalAddressSDNode *GA,
5196                                        const SDNode *N2) {
5197   if (GA->getOpcode() != ISD::GlobalAddress)
5198     return SDValue();
5199   if (!TLI->isOffsetFoldingLegal(GA))
5200     return SDValue();
5201   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5202   if (!C2)
5203     return SDValue();
5204   int64_t Offset = C2->getSExtValue();
5205   switch (Opcode) {
5206   case ISD::ADD: break;
5207   case ISD::SUB: Offset = -uint64_t(Offset); break;
5208   default: return SDValue();
5209   }
5210   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5211                           GA->getOffset() + uint64_t(Offset));
5212 }
5213 
5214 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5215   switch (Opcode) {
5216   case ISD::SDIV:
5217   case ISD::UDIV:
5218   case ISD::SREM:
5219   case ISD::UREM: {
5220     // If a divisor is zero/undef or any element of a divisor vector is
5221     // zero/undef, the whole op is undef.
5222     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5223     SDValue Divisor = Ops[1];
5224     if (Divisor.isUndef() || isNullConstant(Divisor))
5225       return true;
5226 
5227     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5228            llvm::any_of(Divisor->op_values(),
5229                         [](SDValue V) { return V.isUndef() ||
5230                                         isNullConstant(V); });
5231     // TODO: Handle signed overflow.
5232   }
5233   // TODO: Handle oversized shifts.
5234   default:
5235     return false;
5236   }
5237 }
5238 
5239 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5240                                              EVT VT, ArrayRef<SDValue> Ops) {
5241   // If the opcode is a target-specific ISD node, there's nothing we can
5242   // do here and the operand rules may not line up with the below, so
5243   // bail early.
5244   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5245   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5246   // foldCONCAT_VECTORS in getNode before this is called.
5247   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5248     return SDValue();
5249 
5250   // For now, the array Ops should only contain two values.
5251   // This enforcement will be removed once this function is merged with
5252   // FoldConstantVectorArithmetic
5253   if (Ops.size() != 2)
5254     return SDValue();
5255 
5256   if (isUndef(Opcode, Ops))
5257     return getUNDEF(VT);
5258 
5259   SDNode *N1 = Ops[0].getNode();
5260   SDNode *N2 = Ops[1].getNode();
5261 
5262   // Handle the case of two scalars.
5263   if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
5264     if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
5265       if (C1->isOpaque() || C2->isOpaque())
5266         return SDValue();
5267 
5268       Optional<APInt> FoldAttempt =
5269           FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5270       if (!FoldAttempt)
5271         return SDValue();
5272 
5273       SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5274       assert((!Folded || !VT.isVector()) &&
5275              "Can't fold vectors ops with scalar operands");
5276       return Folded;
5277     }
5278   }
5279 
5280   // fold (add Sym, c) -> Sym+c
5281   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
5282     return FoldSymbolOffset(Opcode, VT, GA, N2);
5283   if (TLI->isCommutativeBinOp(Opcode))
5284     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
5285       return FoldSymbolOffset(Opcode, VT, GA, N1);
5286 
5287   // For fixed width vectors, extract each constant element and fold them
5288   // individually. Either input may be an undef value.
5289   bool IsBVOrSV1 = N1->getOpcode() == ISD::BUILD_VECTOR ||
5290                    N1->getOpcode() == ISD::SPLAT_VECTOR;
5291   if (!IsBVOrSV1 && !N1->isUndef())
5292     return SDValue();
5293   bool IsBVOrSV2 = N2->getOpcode() == ISD::BUILD_VECTOR ||
5294                    N2->getOpcode() == ISD::SPLAT_VECTOR;
5295   if (!IsBVOrSV2 && !N2->isUndef())
5296     return SDValue();
5297   // If both operands are undef, that's handled the same way as scalars.
5298   if (!IsBVOrSV1 && !IsBVOrSV2)
5299     return SDValue();
5300 
5301   EVT SVT = VT.getScalarType();
5302   EVT LegalSVT = SVT;
5303   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5304     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5305     if (LegalSVT.bitsLT(SVT))
5306       return SDValue();
5307   }
5308 
5309   SmallVector<SDValue, 4> Outputs;
5310   unsigned NumOps = 0;
5311   if (IsBVOrSV1)
5312     NumOps = std::max(NumOps, N1->getNumOperands());
5313   if (IsBVOrSV2)
5314     NumOps = std::max(NumOps, N2->getNumOperands());
5315   assert(NumOps != 0 && "Expected non-zero operands");
5316   // Scalable vectors should only be SPLAT_VECTOR or UNDEF here. We only need
5317   // one iteration for that.
5318   assert((!VT.isScalableVector() || NumOps == 1) &&
5319          "Scalable vector should only have one scalar");
5320 
5321   for (unsigned I = 0; I != NumOps; ++I) {
5322     // We can have a fixed length SPLAT_VECTOR and a BUILD_VECTOR so we need
5323     // to use operand 0 of the SPLAT_VECTOR for each fixed element.
5324     SDValue V1;
5325     if (N1->getOpcode() == ISD::BUILD_VECTOR)
5326       V1 = N1->getOperand(I);
5327     else if (N1->getOpcode() == ISD::SPLAT_VECTOR)
5328       V1 = N1->getOperand(0);
5329     else
5330       V1 = getUNDEF(SVT);
5331 
5332     SDValue V2;
5333     if (N2->getOpcode() == ISD::BUILD_VECTOR)
5334       V2 = N2->getOperand(I);
5335     else if (N2->getOpcode() == ISD::SPLAT_VECTOR)
5336       V2 = N2->getOperand(0);
5337     else
5338       V2 = getUNDEF(SVT);
5339 
5340     if (SVT.isInteger()) {
5341       if (V1.getValueType().bitsGT(SVT))
5342         V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
5343       if (V2.getValueType().bitsGT(SVT))
5344         V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
5345     }
5346 
5347     if (V1.getValueType() != SVT || V2.getValueType() != SVT)
5348       return SDValue();
5349 
5350     // Fold one vector element.
5351     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
5352     if (LegalSVT != SVT)
5353       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5354 
5355     // Scalar folding only succeeded if the result is a constant or UNDEF.
5356     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5357         ScalarResult.getOpcode() != ISD::ConstantFP)
5358       return SDValue();
5359     Outputs.push_back(ScalarResult);
5360   }
5361 
5362   if (N1->getOpcode() == ISD::BUILD_VECTOR ||
5363       N2->getOpcode() == ISD::BUILD_VECTOR) {
5364     assert(VT.getVectorNumElements() == Outputs.size() &&
5365            "Vector size mismatch!");
5366 
5367     // Build a big vector out of the scalar elements we generated.
5368     return getBuildVector(VT, SDLoc(), Outputs);
5369   }
5370 
5371   assert((N1->getOpcode() == ISD::SPLAT_VECTOR ||
5372           N2->getOpcode() == ISD::SPLAT_VECTOR) &&
5373          "One operand should be a splat vector");
5374 
5375   assert(Outputs.size() == 1 && "Vector size mismatch!");
5376   return getSplatVector(VT, SDLoc(), Outputs[0]);
5377 }
5378 
5379 // TODO: Merge with FoldConstantArithmetic
5380 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
5381                                                    const SDLoc &DL, EVT VT,
5382                                                    ArrayRef<SDValue> Ops,
5383                                                    const SDNodeFlags Flags) {
5384   // If the opcode is a target-specific ISD node, there's nothing we can
5385   // do here and the operand rules may not line up with the below, so
5386   // bail early.
5387   if (Opcode >= ISD::BUILTIN_OP_END)
5388     return SDValue();
5389 
5390   if (isUndef(Opcode, Ops))
5391     return getUNDEF(VT);
5392 
5393   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
5394   if (!VT.isVector())
5395     return SDValue();
5396 
5397   ElementCount NumElts = VT.getVectorElementCount();
5398 
5399   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5400     return !Op.getValueType().isVector() ||
5401            Op.getValueType().getVectorElementCount() == NumElts;
5402   };
5403 
5404   auto IsConstantBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5405     APInt SplatVal;
5406     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
5407     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5408            (BV && BV->isConstant()) ||
5409            (Op.getOpcode() == ISD::SPLAT_VECTOR &&
5410             ISD::isConstantSplatVector(Op.getNode(), SplatVal));
5411   };
5412 
5413   // All operands must be vector types with the same number of elements as
5414   // the result type and must be either UNDEF or a build vector of constant
5415   // or UNDEF scalars.
5416   if (!llvm::all_of(Ops, IsConstantBuildVectorSplatVectorOrUndef) ||
5417       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5418     return SDValue();
5419 
5420   // If we are comparing vectors, then the result needs to be a i1 boolean
5421   // that is then sign-extended back to the legal result type.
5422   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5423 
5424   // Find legal integer scalar type for constant promotion and
5425   // ensure that its scalar size is at least as large as source.
5426   EVT LegalSVT = VT.getScalarType();
5427   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5428     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5429     if (LegalSVT.bitsLT(VT.getScalarType()))
5430       return SDValue();
5431   }
5432 
5433   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5434   // only have one operand to check. For fixed-length vector types we may have
5435   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5436   unsigned NumOperands = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5437 
5438   // Constant fold each scalar lane separately.
5439   SmallVector<SDValue, 4> ScalarResults;
5440   for (unsigned I = 0; I != NumOperands; I++) {
5441     SmallVector<SDValue, 4> ScalarOps;
5442     for (SDValue Op : Ops) {
5443       EVT InSVT = Op.getValueType().getScalarType();
5444       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5445           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5446         // We've checked that this is UNDEF or a constant of some kind.
5447         if (Op.isUndef())
5448           ScalarOps.push_back(getUNDEF(InSVT));
5449         else
5450           ScalarOps.push_back(Op);
5451         continue;
5452       }
5453 
5454       SDValue ScalarOp =
5455           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5456       EVT ScalarVT = ScalarOp.getValueType();
5457 
5458       // Build vector (integer) scalar operands may need implicit
5459       // truncation - do this before constant folding.
5460       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5461         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5462 
5463       ScalarOps.push_back(ScalarOp);
5464     }
5465 
5466     // Constant fold the scalar operands.
5467     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
5468 
5469     // Legalize the (integer) scalar constant if necessary.
5470     if (LegalSVT != SVT)
5471       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5472 
5473     // Scalar folding only succeeded if the result is a constant or UNDEF.
5474     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5475         ScalarResult.getOpcode() != ISD::ConstantFP)
5476       return SDValue();
5477     ScalarResults.push_back(ScalarResult);
5478   }
5479 
5480   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5481                                    : getBuildVector(VT, DL, ScalarResults);
5482   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5483   return V;
5484 }
5485 
5486 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5487                                          EVT VT, SDValue N1, SDValue N2) {
5488   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5489   //       should. That will require dealing with a potentially non-default
5490   //       rounding mode, checking the "opStatus" return value from the APFloat
5491   //       math calculations, and possibly other variations.
5492   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5493   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5494   if (N1CFP && N2CFP) {
5495     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5496     switch (Opcode) {
5497     case ISD::FADD:
5498       C1.add(C2, APFloat::rmNearestTiesToEven);
5499       return getConstantFP(C1, DL, VT);
5500     case ISD::FSUB:
5501       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5502       return getConstantFP(C1, DL, VT);
5503     case ISD::FMUL:
5504       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5505       return getConstantFP(C1, DL, VT);
5506     case ISD::FDIV:
5507       C1.divide(C2, APFloat::rmNearestTiesToEven);
5508       return getConstantFP(C1, DL, VT);
5509     case ISD::FREM:
5510       C1.mod(C2);
5511       return getConstantFP(C1, DL, VT);
5512     case ISD::FCOPYSIGN:
5513       C1.copySign(C2);
5514       return getConstantFP(C1, DL, VT);
5515     default: break;
5516     }
5517   }
5518   if (N1CFP && Opcode == ISD::FP_ROUND) {
5519     APFloat C1 = N1CFP->getValueAPF();    // make copy
5520     bool Unused;
5521     // This can return overflow, underflow, or inexact; we don't care.
5522     // FIXME need to be more flexible about rounding mode.
5523     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5524                       &Unused);
5525     return getConstantFP(C1, DL, VT);
5526   }
5527 
5528   switch (Opcode) {
5529   case ISD::FSUB:
5530     // -0.0 - undef --> undef (consistent with "fneg undef")
5531     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5532       return getUNDEF(VT);
5533     LLVM_FALLTHROUGH;
5534 
5535   case ISD::FADD:
5536   case ISD::FMUL:
5537   case ISD::FDIV:
5538   case ISD::FREM:
5539     // If both operands are undef, the result is undef. If 1 operand is undef,
5540     // the result is NaN. This should match the behavior of the IR optimizer.
5541     if (N1.isUndef() && N2.isUndef())
5542       return getUNDEF(VT);
5543     if (N1.isUndef() || N2.isUndef())
5544       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5545   }
5546   return SDValue();
5547 }
5548 
5549 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5550   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5551 
5552   // There's no need to assert on a byte-aligned pointer. All pointers are at
5553   // least byte aligned.
5554   if (A == Align(1))
5555     return Val;
5556 
5557   FoldingSetNodeID ID;
5558   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5559   ID.AddInteger(A.value());
5560 
5561   void *IP = nullptr;
5562   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5563     return SDValue(E, 0);
5564 
5565   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5566                                          Val.getValueType(), A);
5567   createOperands(N, {Val});
5568 
5569   CSEMap.InsertNode(N, IP);
5570   InsertNode(N);
5571 
5572   SDValue V(N, 0);
5573   NewSDValueDbgMsg(V, "Creating new node: ", this);
5574   return V;
5575 }
5576 
5577 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5578                               SDValue N1, SDValue N2) {
5579   SDNodeFlags Flags;
5580   if (Inserter)
5581     Flags = Inserter->getFlags();
5582   return getNode(Opcode, DL, VT, N1, N2, Flags);
5583 }
5584 
5585 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5586                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5587   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5588          N2.getOpcode() != ISD::DELETED_NODE &&
5589          "Operand is DELETED_NODE!");
5590   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5591   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5592   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5593   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5594 
5595   // Canonicalize constant to RHS if commutative.
5596   if (TLI->isCommutativeBinOp(Opcode)) {
5597     if (N1C && !N2C) {
5598       std::swap(N1C, N2C);
5599       std::swap(N1, N2);
5600     } else if (N1CFP && !N2CFP) {
5601       std::swap(N1CFP, N2CFP);
5602       std::swap(N1, N2);
5603     }
5604   }
5605 
5606   switch (Opcode) {
5607   default: break;
5608   case ISD::TokenFactor:
5609     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5610            N2.getValueType() == MVT::Other && "Invalid token factor!");
5611     // Fold trivial token factors.
5612     if (N1.getOpcode() == ISD::EntryToken) return N2;
5613     if (N2.getOpcode() == ISD::EntryToken) return N1;
5614     if (N1 == N2) return N1;
5615     break;
5616   case ISD::BUILD_VECTOR: {
5617     // Attempt to simplify BUILD_VECTOR.
5618     SDValue Ops[] = {N1, N2};
5619     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5620       return V;
5621     break;
5622   }
5623   case ISD::CONCAT_VECTORS: {
5624     SDValue Ops[] = {N1, N2};
5625     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5626       return V;
5627     break;
5628   }
5629   case ISD::AND:
5630     assert(VT.isInteger() && "This operator does not apply to FP types!");
5631     assert(N1.getValueType() == N2.getValueType() &&
5632            N1.getValueType() == VT && "Binary operator types must match!");
5633     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5634     // worth handling here.
5635     if (N2C && N2C->isZero())
5636       return N2;
5637     if (N2C && N2C->isAllOnes()) // X & -1 -> X
5638       return N1;
5639     break;
5640   case ISD::OR:
5641   case ISD::XOR:
5642   case ISD::ADD:
5643   case ISD::SUB:
5644     assert(VT.isInteger() && "This operator does not apply to FP types!");
5645     assert(N1.getValueType() == N2.getValueType() &&
5646            N1.getValueType() == VT && "Binary operator types must match!");
5647     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5648     // it's worth handling here.
5649     if (N2C && N2C->isZero())
5650       return N1;
5651     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5652         VT.getVectorElementType() == MVT::i1)
5653       return getNode(ISD::XOR, DL, VT, N1, N2);
5654     break;
5655   case ISD::MUL:
5656     assert(VT.isInteger() && "This operator does not apply to FP types!");
5657     assert(N1.getValueType() == N2.getValueType() &&
5658            N1.getValueType() == VT && "Binary operator types must match!");
5659     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5660       return getNode(ISD::AND, DL, VT, N1, N2);
5661     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5662       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5663       const APInt &N2CImm = N2C->getAPIntValue();
5664       return getVScale(DL, VT, MulImm * N2CImm);
5665     }
5666     break;
5667   case ISD::UDIV:
5668   case ISD::UREM:
5669   case ISD::MULHU:
5670   case ISD::MULHS:
5671   case ISD::SDIV:
5672   case ISD::SREM:
5673   case ISD::SADDSAT:
5674   case ISD::SSUBSAT:
5675   case ISD::UADDSAT:
5676   case ISD::USUBSAT:
5677     assert(VT.isInteger() && "This operator does not apply to FP types!");
5678     assert(N1.getValueType() == N2.getValueType() &&
5679            N1.getValueType() == VT && "Binary operator types must match!");
5680     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5681       // fold (add_sat x, y) -> (or x, y) for bool types.
5682       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5683         return getNode(ISD::OR, DL, VT, N1, N2);
5684       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5685       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5686         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5687     }
5688     break;
5689   case ISD::SMIN:
5690   case ISD::UMAX:
5691     assert(VT.isInteger() && "This operator does not apply to FP types!");
5692     assert(N1.getValueType() == N2.getValueType() &&
5693            N1.getValueType() == VT && "Binary operator types must match!");
5694     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5695       return getNode(ISD::OR, DL, VT, N1, N2);
5696     break;
5697   case ISD::SMAX:
5698   case ISD::UMIN:
5699     assert(VT.isInteger() && "This operator does not apply to FP types!");
5700     assert(N1.getValueType() == N2.getValueType() &&
5701            N1.getValueType() == VT && "Binary operator types must match!");
5702     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5703       return getNode(ISD::AND, DL, VT, N1, N2);
5704     break;
5705   case ISD::FADD:
5706   case ISD::FSUB:
5707   case ISD::FMUL:
5708   case ISD::FDIV:
5709   case ISD::FREM:
5710     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5711     assert(N1.getValueType() == N2.getValueType() &&
5712            N1.getValueType() == VT && "Binary operator types must match!");
5713     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5714       return V;
5715     break;
5716   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5717     assert(N1.getValueType() == VT &&
5718            N1.getValueType().isFloatingPoint() &&
5719            N2.getValueType().isFloatingPoint() &&
5720            "Invalid FCOPYSIGN!");
5721     break;
5722   case ISD::SHL:
5723     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5724       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5725       const APInt &ShiftImm = N2C->getAPIntValue();
5726       return getVScale(DL, VT, MulImm << ShiftImm);
5727     }
5728     LLVM_FALLTHROUGH;
5729   case ISD::SRA:
5730   case ISD::SRL:
5731     if (SDValue V = simplifyShift(N1, N2))
5732       return V;
5733     LLVM_FALLTHROUGH;
5734   case ISD::ROTL:
5735   case ISD::ROTR:
5736     assert(VT == N1.getValueType() &&
5737            "Shift operators return type must be the same as their first arg");
5738     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5739            "Shifts only work on integers");
5740     assert((!VT.isVector() || VT == N2.getValueType()) &&
5741            "Vector shift amounts must be in the same as their first arg");
5742     // Verify that the shift amount VT is big enough to hold valid shift
5743     // amounts.  This catches things like trying to shift an i1024 value by an
5744     // i8, which is easy to fall into in generic code that uses
5745     // TLI.getShiftAmount().
5746     assert(N2.getValueType().getScalarSizeInBits() >=
5747                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5748            "Invalid use of small shift amount with oversized value!");
5749 
5750     // Always fold shifts of i1 values so the code generator doesn't need to
5751     // handle them.  Since we know the size of the shift has to be less than the
5752     // size of the value, the shift/rotate count is guaranteed to be zero.
5753     if (VT == MVT::i1)
5754       return N1;
5755     if (N2C && N2C->isZero())
5756       return N1;
5757     break;
5758   case ISD::FP_ROUND:
5759     assert(VT.isFloatingPoint() &&
5760            N1.getValueType().isFloatingPoint() &&
5761            VT.bitsLE(N1.getValueType()) &&
5762            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5763            "Invalid FP_ROUND!");
5764     if (N1.getValueType() == VT) return N1;  // noop conversion.
5765     break;
5766   case ISD::AssertSext:
5767   case ISD::AssertZext: {
5768     EVT EVT = cast<VTSDNode>(N2)->getVT();
5769     assert(VT == N1.getValueType() && "Not an inreg extend!");
5770     assert(VT.isInteger() && EVT.isInteger() &&
5771            "Cannot *_EXTEND_INREG FP types");
5772     assert(!EVT.isVector() &&
5773            "AssertSExt/AssertZExt type should be the vector element type "
5774            "rather than the vector type!");
5775     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5776     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5777     break;
5778   }
5779   case ISD::SIGN_EXTEND_INREG: {
5780     EVT EVT = cast<VTSDNode>(N2)->getVT();
5781     assert(VT == N1.getValueType() && "Not an inreg extend!");
5782     assert(VT.isInteger() && EVT.isInteger() &&
5783            "Cannot *_EXTEND_INREG FP types");
5784     assert(EVT.isVector() == VT.isVector() &&
5785            "SIGN_EXTEND_INREG type should be vector iff the operand "
5786            "type is vector!");
5787     assert((!EVT.isVector() ||
5788             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5789            "Vector element counts must match in SIGN_EXTEND_INREG");
5790     assert(EVT.bitsLE(VT) && "Not extending!");
5791     if (EVT == VT) return N1;  // Not actually extending
5792 
5793     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5794       unsigned FromBits = EVT.getScalarSizeInBits();
5795       Val <<= Val.getBitWidth() - FromBits;
5796       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5797       return getConstant(Val, DL, ConstantVT);
5798     };
5799 
5800     if (N1C) {
5801       const APInt &Val = N1C->getAPIntValue();
5802       return SignExtendInReg(Val, VT);
5803     }
5804 
5805     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5806       SmallVector<SDValue, 8> Ops;
5807       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5808       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5809         SDValue Op = N1.getOperand(i);
5810         if (Op.isUndef()) {
5811           Ops.push_back(getUNDEF(OpVT));
5812           continue;
5813         }
5814         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5815         APInt Val = C->getAPIntValue();
5816         Ops.push_back(SignExtendInReg(Val, OpVT));
5817       }
5818       return getBuildVector(VT, DL, Ops);
5819     }
5820     break;
5821   }
5822   case ISD::FP_TO_SINT_SAT:
5823   case ISD::FP_TO_UINT_SAT: {
5824     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5825            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5826     assert(N1.getValueType().isVector() == VT.isVector() &&
5827            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5828            "vector!");
5829     assert((!VT.isVector() || VT.getVectorNumElements() ==
5830                                   N1.getValueType().getVectorNumElements()) &&
5831            "Vector element counts must match in FP_TO_*INT_SAT");
5832     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5833            "Type to saturate to must be a scalar.");
5834     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5835            "Not extending!");
5836     break;
5837   }
5838   case ISD::EXTRACT_VECTOR_ELT:
5839     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5840            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5841              element type of the vector.");
5842 
5843     // Extract from an undefined value or using an undefined index is undefined.
5844     if (N1.isUndef() || N2.isUndef())
5845       return getUNDEF(VT);
5846 
5847     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5848     // vectors. For scalable vectors we will provide appropriate support for
5849     // dealing with arbitrary indices.
5850     if (N2C && N1.getValueType().isFixedLengthVector() &&
5851         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5852       return getUNDEF(VT);
5853 
5854     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5855     // expanding copies of large vectors from registers. This only works for
5856     // fixed length vectors, since we need to know the exact number of
5857     // elements.
5858     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5859         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5860       unsigned Factor =
5861         N1.getOperand(0).getValueType().getVectorNumElements();
5862       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5863                      N1.getOperand(N2C->getZExtValue() / Factor),
5864                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5865     }
5866 
5867     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5868     // lowering is expanding large vector constants.
5869     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5870                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5871       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5872               N1.getValueType().isFixedLengthVector()) &&
5873              "BUILD_VECTOR used for scalable vectors");
5874       unsigned Index =
5875           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5876       SDValue Elt = N1.getOperand(Index);
5877 
5878       if (VT != Elt.getValueType())
5879         // If the vector element type is not legal, the BUILD_VECTOR operands
5880         // are promoted and implicitly truncated, and the result implicitly
5881         // extended. Make that explicit here.
5882         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5883 
5884       return Elt;
5885     }
5886 
5887     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5888     // operations are lowered to scalars.
5889     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5890       // If the indices are the same, return the inserted element else
5891       // if the indices are known different, extract the element from
5892       // the original vector.
5893       SDValue N1Op2 = N1.getOperand(2);
5894       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5895 
5896       if (N1Op2C && N2C) {
5897         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5898           if (VT == N1.getOperand(1).getValueType())
5899             return N1.getOperand(1);
5900           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5901         }
5902         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5903       }
5904     }
5905 
5906     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5907     // when vector types are scalarized and v1iX is legal.
5908     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5909     // Here we are completely ignoring the extract element index (N2),
5910     // which is fine for fixed width vectors, since any index other than 0
5911     // is undefined anyway. However, this cannot be ignored for scalable
5912     // vectors - in theory we could support this, but we don't want to do this
5913     // without a profitability check.
5914     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5915         N1.getValueType().isFixedLengthVector() &&
5916         N1.getValueType().getVectorNumElements() == 1) {
5917       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5918                      N1.getOperand(1));
5919     }
5920     break;
5921   case ISD::EXTRACT_ELEMENT:
5922     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5923     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5924            (N1.getValueType().isInteger() == VT.isInteger()) &&
5925            N1.getValueType() != VT &&
5926            "Wrong types for EXTRACT_ELEMENT!");
5927 
5928     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5929     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5930     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5931     if (N1.getOpcode() == ISD::BUILD_PAIR)
5932       return N1.getOperand(N2C->getZExtValue());
5933 
5934     // EXTRACT_ELEMENT of a constant int is also very common.
5935     if (N1C) {
5936       unsigned ElementSize = VT.getSizeInBits();
5937       unsigned Shift = ElementSize * N2C->getZExtValue();
5938       const APInt &Val = N1C->getAPIntValue();
5939       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5940     }
5941     break;
5942   case ISD::EXTRACT_SUBVECTOR: {
5943     EVT N1VT = N1.getValueType();
5944     assert(VT.isVector() && N1VT.isVector() &&
5945            "Extract subvector VTs must be vectors!");
5946     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5947            "Extract subvector VTs must have the same element type!");
5948     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5949            "Cannot extract a scalable vector from a fixed length vector!");
5950     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5951             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5952            "Extract subvector must be from larger vector to smaller vector!");
5953     assert(N2C && "Extract subvector index must be a constant");
5954     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5955             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5956                 N1VT.getVectorMinNumElements()) &&
5957            "Extract subvector overflow!");
5958     assert(N2C->getAPIntValue().getBitWidth() ==
5959                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5960            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5961 
5962     // Trivial extraction.
5963     if (VT == N1VT)
5964       return N1;
5965 
5966     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5967     if (N1.isUndef())
5968       return getUNDEF(VT);
5969 
5970     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5971     // the concat have the same type as the extract.
5972     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5973         VT == N1.getOperand(0).getValueType()) {
5974       unsigned Factor = VT.getVectorMinNumElements();
5975       return N1.getOperand(N2C->getZExtValue() / Factor);
5976     }
5977 
5978     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5979     // during shuffle legalization.
5980     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5981         VT == N1.getOperand(1).getValueType())
5982       return N1.getOperand(1);
5983     break;
5984   }
5985   }
5986 
5987   // Perform trivial constant folding.
5988   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5989     return SV;
5990 
5991   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5992     return V;
5993 
5994   // Canonicalize an UNDEF to the RHS, even over a constant.
5995   if (N1.isUndef()) {
5996     if (TLI->isCommutativeBinOp(Opcode)) {
5997       std::swap(N1, N2);
5998     } else {
5999       switch (Opcode) {
6000       case ISD::SIGN_EXTEND_INREG:
6001       case ISD::SUB:
6002         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6003       case ISD::UDIV:
6004       case ISD::SDIV:
6005       case ISD::UREM:
6006       case ISD::SREM:
6007       case ISD::SSUBSAT:
6008       case ISD::USUBSAT:
6009         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6010       }
6011     }
6012   }
6013 
6014   // Fold a bunch of operators when the RHS is undef.
6015   if (N2.isUndef()) {
6016     switch (Opcode) {
6017     case ISD::XOR:
6018       if (N1.isUndef())
6019         // Handle undef ^ undef -> 0 special case. This is a common
6020         // idiom (misuse).
6021         return getConstant(0, DL, VT);
6022       LLVM_FALLTHROUGH;
6023     case ISD::ADD:
6024     case ISD::SUB:
6025     case ISD::UDIV:
6026     case ISD::SDIV:
6027     case ISD::UREM:
6028     case ISD::SREM:
6029       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6030     case ISD::MUL:
6031     case ISD::AND:
6032     case ISD::SSUBSAT:
6033     case ISD::USUBSAT:
6034       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6035     case ISD::OR:
6036     case ISD::SADDSAT:
6037     case ISD::UADDSAT:
6038       return getAllOnesConstant(DL, VT);
6039     }
6040   }
6041 
6042   // Memoize this node if possible.
6043   SDNode *N;
6044   SDVTList VTs = getVTList(VT);
6045   SDValue Ops[] = {N1, N2};
6046   if (VT != MVT::Glue) {
6047     FoldingSetNodeID ID;
6048     AddNodeIDNode(ID, Opcode, VTs, Ops);
6049     void *IP = nullptr;
6050     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6051       E->intersectFlagsWith(Flags);
6052       return SDValue(E, 0);
6053     }
6054 
6055     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6056     N->setFlags(Flags);
6057     createOperands(N, Ops);
6058     CSEMap.InsertNode(N, IP);
6059   } else {
6060     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6061     createOperands(N, Ops);
6062   }
6063 
6064   InsertNode(N);
6065   SDValue V = SDValue(N, 0);
6066   NewSDValueDbgMsg(V, "Creating new node: ", this);
6067   return V;
6068 }
6069 
6070 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6071                               SDValue N1, SDValue N2, SDValue N3) {
6072   SDNodeFlags Flags;
6073   if (Inserter)
6074     Flags = Inserter->getFlags();
6075   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6076 }
6077 
6078 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6079                               SDValue N1, SDValue N2, SDValue N3,
6080                               const SDNodeFlags Flags) {
6081   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6082          N2.getOpcode() != ISD::DELETED_NODE &&
6083          N3.getOpcode() != ISD::DELETED_NODE &&
6084          "Operand is DELETED_NODE!");
6085   // Perform various simplifications.
6086   switch (Opcode) {
6087   case ISD::FMA: {
6088     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6089     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6090            N3.getValueType() == VT && "FMA types must match!");
6091     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6092     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6093     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6094     if (N1CFP && N2CFP && N3CFP) {
6095       APFloat  V1 = N1CFP->getValueAPF();
6096       const APFloat &V2 = N2CFP->getValueAPF();
6097       const APFloat &V3 = N3CFP->getValueAPF();
6098       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6099       return getConstantFP(V1, DL, VT);
6100     }
6101     break;
6102   }
6103   case ISD::BUILD_VECTOR: {
6104     // Attempt to simplify BUILD_VECTOR.
6105     SDValue Ops[] = {N1, N2, N3};
6106     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6107       return V;
6108     break;
6109   }
6110   case ISD::CONCAT_VECTORS: {
6111     SDValue Ops[] = {N1, N2, N3};
6112     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6113       return V;
6114     break;
6115   }
6116   case ISD::SETCC: {
6117     assert(VT.isInteger() && "SETCC result type must be an integer!");
6118     assert(N1.getValueType() == N2.getValueType() &&
6119            "SETCC operands must have the same type!");
6120     assert(VT.isVector() == N1.getValueType().isVector() &&
6121            "SETCC type should be vector iff the operand type is vector!");
6122     assert((!VT.isVector() || VT.getVectorElementCount() ==
6123                                   N1.getValueType().getVectorElementCount()) &&
6124            "SETCC vector element counts must match!");
6125     // Use FoldSetCC to simplify SETCC's.
6126     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6127       return V;
6128     // Vector constant folding.
6129     SDValue Ops[] = {N1, N2, N3};
6130     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
6131       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6132       return V;
6133     }
6134     break;
6135   }
6136   case ISD::SELECT:
6137   case ISD::VSELECT:
6138     if (SDValue V = simplifySelect(N1, N2, N3))
6139       return V;
6140     break;
6141   case ISD::VECTOR_SHUFFLE:
6142     llvm_unreachable("should use getVectorShuffle constructor!");
6143   case ISD::INSERT_VECTOR_ELT: {
6144     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6145     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6146     // for scalable vectors where we will generate appropriate code to
6147     // deal with out-of-bounds cases correctly.
6148     if (N3C && N1.getValueType().isFixedLengthVector() &&
6149         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6150       return getUNDEF(VT);
6151 
6152     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6153     if (N3.isUndef())
6154       return getUNDEF(VT);
6155 
6156     // If the inserted element is an UNDEF, just use the input vector.
6157     if (N2.isUndef())
6158       return N1;
6159 
6160     break;
6161   }
6162   case ISD::INSERT_SUBVECTOR: {
6163     // Inserting undef into undef is still undef.
6164     if (N1.isUndef() && N2.isUndef())
6165       return getUNDEF(VT);
6166 
6167     EVT N2VT = N2.getValueType();
6168     assert(VT == N1.getValueType() &&
6169            "Dest and insert subvector source types must match!");
6170     assert(VT.isVector() && N2VT.isVector() &&
6171            "Insert subvector VTs must be vectors!");
6172     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6173            "Cannot insert a scalable vector into a fixed length vector!");
6174     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6175             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6176            "Insert subvector must be from smaller vector to larger vector!");
6177     assert(isa<ConstantSDNode>(N3) &&
6178            "Insert subvector index must be constant");
6179     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6180             (N2VT.getVectorMinNumElements() +
6181              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6182                 VT.getVectorMinNumElements()) &&
6183            "Insert subvector overflow!");
6184     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6185                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6186            "Constant index for INSERT_SUBVECTOR has an invalid size");
6187 
6188     // Trivial insertion.
6189     if (VT == N2VT)
6190       return N2;
6191 
6192     // If this is an insert of an extracted vector into an undef vector, we
6193     // can just use the input to the extract.
6194     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6195         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6196       return N2.getOperand(0);
6197     break;
6198   }
6199   case ISD::BITCAST:
6200     // Fold bit_convert nodes from a type to themselves.
6201     if (N1.getValueType() == VT)
6202       return N1;
6203     break;
6204   }
6205 
6206   // Memoize node if it doesn't produce a flag.
6207   SDNode *N;
6208   SDVTList VTs = getVTList(VT);
6209   SDValue Ops[] = {N1, N2, N3};
6210   if (VT != MVT::Glue) {
6211     FoldingSetNodeID ID;
6212     AddNodeIDNode(ID, Opcode, VTs, Ops);
6213     void *IP = nullptr;
6214     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6215       E->intersectFlagsWith(Flags);
6216       return SDValue(E, 0);
6217     }
6218 
6219     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6220     N->setFlags(Flags);
6221     createOperands(N, Ops);
6222     CSEMap.InsertNode(N, IP);
6223   } else {
6224     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6225     createOperands(N, Ops);
6226   }
6227 
6228   InsertNode(N);
6229   SDValue V = SDValue(N, 0);
6230   NewSDValueDbgMsg(V, "Creating new node: ", this);
6231   return V;
6232 }
6233 
6234 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6235                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6236   SDValue Ops[] = { N1, N2, N3, N4 };
6237   return getNode(Opcode, DL, VT, Ops);
6238 }
6239 
6240 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6241                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6242                               SDValue N5) {
6243   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6244   return getNode(Opcode, DL, VT, Ops);
6245 }
6246 
6247 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6248 /// the incoming stack arguments to be loaded from the stack.
6249 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6250   SmallVector<SDValue, 8> ArgChains;
6251 
6252   // Include the original chain at the beginning of the list. When this is
6253   // used by target LowerCall hooks, this helps legalize find the
6254   // CALLSEQ_BEGIN node.
6255   ArgChains.push_back(Chain);
6256 
6257   // Add a chain value for each stack argument.
6258   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
6259        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
6260     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
6261       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6262         if (FI->getIndex() < 0)
6263           ArgChains.push_back(SDValue(L, 1));
6264 
6265   // Build a tokenfactor for all the chains.
6266   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6267 }
6268 
6269 /// getMemsetValue - Vectorized representation of the memset value
6270 /// operand.
6271 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6272                               const SDLoc &dl) {
6273   assert(!Value.isUndef());
6274 
6275   unsigned NumBits = VT.getScalarSizeInBits();
6276   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6277     assert(C->getAPIntValue().getBitWidth() == 8);
6278     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6279     if (VT.isInteger()) {
6280       bool IsOpaque = VT.getSizeInBits() > 64 ||
6281           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6282       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6283     }
6284     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6285                              VT);
6286   }
6287 
6288   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6289   EVT IntVT = VT.getScalarType();
6290   if (!IntVT.isInteger())
6291     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6292 
6293   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6294   if (NumBits > 8) {
6295     // Use a multiplication with 0x010101... to extend the input to the
6296     // required length.
6297     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6298     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6299                         DAG.getConstant(Magic, dl, IntVT));
6300   }
6301 
6302   if (VT != Value.getValueType() && !VT.isInteger())
6303     Value = DAG.getBitcast(VT.getScalarType(), Value);
6304   if (VT != Value.getValueType())
6305     Value = DAG.getSplatBuildVector(VT, dl, Value);
6306 
6307   return Value;
6308 }
6309 
6310 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6311 /// used when a memcpy is turned into a memset when the source is a constant
6312 /// string ptr.
6313 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6314                                   const TargetLowering &TLI,
6315                                   const ConstantDataArraySlice &Slice) {
6316   // Handle vector with all elements zero.
6317   if (Slice.Array == nullptr) {
6318     if (VT.isInteger())
6319       return DAG.getConstant(0, dl, VT);
6320     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6321       return DAG.getConstantFP(0.0, dl, VT);
6322     if (VT.isVector()) {
6323       unsigned NumElts = VT.getVectorNumElements();
6324       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6325       return DAG.getNode(ISD::BITCAST, dl, VT,
6326                          DAG.getConstant(0, dl,
6327                                          EVT::getVectorVT(*DAG.getContext(),
6328                                                           EltVT, NumElts)));
6329     }
6330     llvm_unreachable("Expected type!");
6331   }
6332 
6333   assert(!VT.isVector() && "Can't handle vector type here!");
6334   unsigned NumVTBits = VT.getSizeInBits();
6335   unsigned NumVTBytes = NumVTBits / 8;
6336   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6337 
6338   APInt Val(NumVTBits, 0);
6339   if (DAG.getDataLayout().isLittleEndian()) {
6340     for (unsigned i = 0; i != NumBytes; ++i)
6341       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6342   } else {
6343     for (unsigned i = 0; i != NumBytes; ++i)
6344       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6345   }
6346 
6347   // If the "cost" of materializing the integer immediate is less than the cost
6348   // of a load, then it is cost effective to turn the load into the immediate.
6349   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6350   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6351     return DAG.getConstant(Val, dl, VT);
6352   return SDValue(nullptr, 0);
6353 }
6354 
6355 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6356                                            const SDLoc &DL,
6357                                            const SDNodeFlags Flags) {
6358   EVT VT = Base.getValueType();
6359   SDValue Index;
6360 
6361   if (Offset.isScalable())
6362     Index = getVScale(DL, Base.getValueType(),
6363                       APInt(Base.getValueSizeInBits().getFixedSize(),
6364                             Offset.getKnownMinSize()));
6365   else
6366     Index = getConstant(Offset.getFixedSize(), DL, VT);
6367 
6368   return getMemBasePlusOffset(Base, Index, DL, Flags);
6369 }
6370 
6371 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6372                                            const SDLoc &DL,
6373                                            const SDNodeFlags Flags) {
6374   assert(Offset.getValueType().isInteger());
6375   EVT BasePtrVT = Ptr.getValueType();
6376   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6377 }
6378 
6379 /// Returns true if memcpy source is constant data.
6380 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6381   uint64_t SrcDelta = 0;
6382   GlobalAddressSDNode *G = nullptr;
6383   if (Src.getOpcode() == ISD::GlobalAddress)
6384     G = cast<GlobalAddressSDNode>(Src);
6385   else if (Src.getOpcode() == ISD::ADD &&
6386            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6387            Src.getOperand(1).getOpcode() == ISD::Constant) {
6388     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6389     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6390   }
6391   if (!G)
6392     return false;
6393 
6394   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6395                                   SrcDelta + G->getOffset());
6396 }
6397 
6398 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6399                                       SelectionDAG &DAG) {
6400   // On Darwin, -Os means optimize for size without hurting performance, so
6401   // only really optimize for size when -Oz (MinSize) is used.
6402   if (MF.getTarget().getTargetTriple().isOSDarwin())
6403     return MF.getFunction().hasMinSize();
6404   return DAG.shouldOptForSize();
6405 }
6406 
6407 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6408                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6409                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6410                           SmallVector<SDValue, 16> &OutStoreChains) {
6411   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6412   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6413   SmallVector<SDValue, 16> GluedLoadChains;
6414   for (unsigned i = From; i < To; ++i) {
6415     OutChains.push_back(OutLoadChains[i]);
6416     GluedLoadChains.push_back(OutLoadChains[i]);
6417   }
6418 
6419   // Chain for all loads.
6420   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6421                                   GluedLoadChains);
6422 
6423   for (unsigned i = From; i < To; ++i) {
6424     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6425     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6426                                   ST->getBasePtr(), ST->getMemoryVT(),
6427                                   ST->getMemOperand());
6428     OutChains.push_back(NewStore);
6429   }
6430 }
6431 
6432 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6433                                        SDValue Chain, SDValue Dst, SDValue Src,
6434                                        uint64_t Size, Align Alignment,
6435                                        bool isVol, bool AlwaysInline,
6436                                        MachinePointerInfo DstPtrInfo,
6437                                        MachinePointerInfo SrcPtrInfo,
6438                                        const AAMDNodes &AAInfo) {
6439   // Turn a memcpy of undef to nop.
6440   // FIXME: We need to honor volatile even is Src is undef.
6441   if (Src.isUndef())
6442     return Chain;
6443 
6444   // Expand memcpy to a series of load and store ops if the size operand falls
6445   // below a certain threshold.
6446   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6447   // rather than maybe a humongous number of loads and stores.
6448   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6449   const DataLayout &DL = DAG.getDataLayout();
6450   LLVMContext &C = *DAG.getContext();
6451   std::vector<EVT> MemOps;
6452   bool DstAlignCanChange = false;
6453   MachineFunction &MF = DAG.getMachineFunction();
6454   MachineFrameInfo &MFI = MF.getFrameInfo();
6455   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6456   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6457   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6458     DstAlignCanChange = true;
6459   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6460   if (!SrcAlign || Alignment > *SrcAlign)
6461     SrcAlign = Alignment;
6462   assert(SrcAlign && "SrcAlign must be set");
6463   ConstantDataArraySlice Slice;
6464   // If marked as volatile, perform a copy even when marked as constant.
6465   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6466   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6467   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6468   const MemOp Op = isZeroConstant
6469                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6470                                     /*IsZeroMemset*/ true, isVol)
6471                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6472                                      *SrcAlign, isVol, CopyFromConstant);
6473   if (!TLI.findOptimalMemOpLowering(
6474           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6475           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6476     return SDValue();
6477 
6478   if (DstAlignCanChange) {
6479     Type *Ty = MemOps[0].getTypeForEVT(C);
6480     Align NewAlign = DL.getABITypeAlign(Ty);
6481 
6482     // Don't promote to an alignment that would require dynamic stack
6483     // realignment.
6484     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6485     if (!TRI->hasStackRealignment(MF))
6486       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6487         NewAlign = NewAlign / 2;
6488 
6489     if (NewAlign > Alignment) {
6490       // Give the stack frame object a larger alignment if needed.
6491       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6492         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6493       Alignment = NewAlign;
6494     }
6495   }
6496 
6497   // Prepare AAInfo for loads/stores after lowering this memcpy.
6498   AAMDNodes NewAAInfo = AAInfo;
6499   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6500 
6501   MachineMemOperand::Flags MMOFlags =
6502       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6503   SmallVector<SDValue, 16> OutLoadChains;
6504   SmallVector<SDValue, 16> OutStoreChains;
6505   SmallVector<SDValue, 32> OutChains;
6506   unsigned NumMemOps = MemOps.size();
6507   uint64_t SrcOff = 0, DstOff = 0;
6508   for (unsigned i = 0; i != NumMemOps; ++i) {
6509     EVT VT = MemOps[i];
6510     unsigned VTSize = VT.getSizeInBits() / 8;
6511     SDValue Value, Store;
6512 
6513     if (VTSize > Size) {
6514       // Issuing an unaligned load / store pair  that overlaps with the previous
6515       // pair. Adjust the offset accordingly.
6516       assert(i == NumMemOps-1 && i != 0);
6517       SrcOff -= VTSize - Size;
6518       DstOff -= VTSize - Size;
6519     }
6520 
6521     if (CopyFromConstant &&
6522         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6523       // It's unlikely a store of a vector immediate can be done in a single
6524       // instruction. It would require a load from a constantpool first.
6525       // We only handle zero vectors here.
6526       // FIXME: Handle other cases where store of vector immediate is done in
6527       // a single instruction.
6528       ConstantDataArraySlice SubSlice;
6529       if (SrcOff < Slice.Length) {
6530         SubSlice = Slice;
6531         SubSlice.move(SrcOff);
6532       } else {
6533         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6534         SubSlice.Array = nullptr;
6535         SubSlice.Offset = 0;
6536         SubSlice.Length = VTSize;
6537       }
6538       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6539       if (Value.getNode()) {
6540         Store = DAG.getStore(
6541             Chain, dl, Value,
6542             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6543             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6544         OutChains.push_back(Store);
6545       }
6546     }
6547 
6548     if (!Store.getNode()) {
6549       // The type might not be legal for the target.  This should only happen
6550       // if the type is smaller than a legal type, as on PPC, so the right
6551       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6552       // to Load/Store if NVT==VT.
6553       // FIXME does the case above also need this?
6554       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6555       assert(NVT.bitsGE(VT));
6556 
6557       bool isDereferenceable =
6558         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6559       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6560       if (isDereferenceable)
6561         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6562 
6563       Value = DAG.getExtLoad(
6564           ISD::EXTLOAD, dl, NVT, Chain,
6565           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6566           SrcPtrInfo.getWithOffset(SrcOff), VT,
6567           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6568       OutLoadChains.push_back(Value.getValue(1));
6569 
6570       Store = DAG.getTruncStore(
6571           Chain, dl, Value,
6572           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6573           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6574       OutStoreChains.push_back(Store);
6575     }
6576     SrcOff += VTSize;
6577     DstOff += VTSize;
6578     Size -= VTSize;
6579   }
6580 
6581   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6582                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6583   unsigned NumLdStInMemcpy = OutStoreChains.size();
6584 
6585   if (NumLdStInMemcpy) {
6586     // It may be that memcpy might be converted to memset if it's memcpy
6587     // of constants. In such a case, we won't have loads and stores, but
6588     // just stores. In the absence of loads, there is nothing to gang up.
6589     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6590       // If target does not care, just leave as it.
6591       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6592         OutChains.push_back(OutLoadChains[i]);
6593         OutChains.push_back(OutStoreChains[i]);
6594       }
6595     } else {
6596       // Ld/St less than/equal limit set by target.
6597       if (NumLdStInMemcpy <= GluedLdStLimit) {
6598           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6599                                         NumLdStInMemcpy, OutLoadChains,
6600                                         OutStoreChains);
6601       } else {
6602         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6603         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6604         unsigned GlueIter = 0;
6605 
6606         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6607           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6608           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6609 
6610           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6611                                        OutLoadChains, OutStoreChains);
6612           GlueIter += GluedLdStLimit;
6613         }
6614 
6615         // Residual ld/st.
6616         if (RemainingLdStInMemcpy) {
6617           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6618                                         RemainingLdStInMemcpy, OutLoadChains,
6619                                         OutStoreChains);
6620         }
6621       }
6622     }
6623   }
6624   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6625 }
6626 
6627 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6628                                         SDValue Chain, SDValue Dst, SDValue Src,
6629                                         uint64_t Size, Align Alignment,
6630                                         bool isVol, bool AlwaysInline,
6631                                         MachinePointerInfo DstPtrInfo,
6632                                         MachinePointerInfo SrcPtrInfo,
6633                                         const AAMDNodes &AAInfo) {
6634   // Turn a memmove of undef to nop.
6635   // FIXME: We need to honor volatile even is Src is undef.
6636   if (Src.isUndef())
6637     return Chain;
6638 
6639   // Expand memmove to a series of load and store ops if the size operand falls
6640   // below a certain threshold.
6641   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6642   const DataLayout &DL = DAG.getDataLayout();
6643   LLVMContext &C = *DAG.getContext();
6644   std::vector<EVT> MemOps;
6645   bool DstAlignCanChange = false;
6646   MachineFunction &MF = DAG.getMachineFunction();
6647   MachineFrameInfo &MFI = MF.getFrameInfo();
6648   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6649   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6650   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6651     DstAlignCanChange = true;
6652   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6653   if (!SrcAlign || Alignment > *SrcAlign)
6654     SrcAlign = Alignment;
6655   assert(SrcAlign && "SrcAlign must be set");
6656   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6657   if (!TLI.findOptimalMemOpLowering(
6658           MemOps, Limit,
6659           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6660                       /*IsVolatile*/ true),
6661           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6662           MF.getFunction().getAttributes()))
6663     return SDValue();
6664 
6665   if (DstAlignCanChange) {
6666     Type *Ty = MemOps[0].getTypeForEVT(C);
6667     Align NewAlign = DL.getABITypeAlign(Ty);
6668     if (NewAlign > Alignment) {
6669       // Give the stack frame object a larger alignment if needed.
6670       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6671         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6672       Alignment = NewAlign;
6673     }
6674   }
6675 
6676   // Prepare AAInfo for loads/stores after lowering this memmove.
6677   AAMDNodes NewAAInfo = AAInfo;
6678   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6679 
6680   MachineMemOperand::Flags MMOFlags =
6681       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6682   uint64_t SrcOff = 0, DstOff = 0;
6683   SmallVector<SDValue, 8> LoadValues;
6684   SmallVector<SDValue, 8> LoadChains;
6685   SmallVector<SDValue, 8> OutChains;
6686   unsigned NumMemOps = MemOps.size();
6687   for (unsigned i = 0; i < NumMemOps; i++) {
6688     EVT VT = MemOps[i];
6689     unsigned VTSize = VT.getSizeInBits() / 8;
6690     SDValue Value;
6691 
6692     bool isDereferenceable =
6693       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6694     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6695     if (isDereferenceable)
6696       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6697 
6698     Value = DAG.getLoad(
6699         VT, dl, Chain,
6700         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6701         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6702     LoadValues.push_back(Value);
6703     LoadChains.push_back(Value.getValue(1));
6704     SrcOff += VTSize;
6705   }
6706   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6707   OutChains.clear();
6708   for (unsigned i = 0; i < NumMemOps; i++) {
6709     EVT VT = MemOps[i];
6710     unsigned VTSize = VT.getSizeInBits() / 8;
6711     SDValue Store;
6712 
6713     Store = DAG.getStore(
6714         Chain, dl, LoadValues[i],
6715         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6716         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6717     OutChains.push_back(Store);
6718     DstOff += VTSize;
6719   }
6720 
6721   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6722 }
6723 
6724 /// Lower the call to 'memset' intrinsic function into a series of store
6725 /// operations.
6726 ///
6727 /// \param DAG Selection DAG where lowered code is placed.
6728 /// \param dl Link to corresponding IR location.
6729 /// \param Chain Control flow dependency.
6730 /// \param Dst Pointer to destination memory location.
6731 /// \param Src Value of byte to write into the memory.
6732 /// \param Size Number of bytes to write.
6733 /// \param Alignment Alignment of the destination in bytes.
6734 /// \param isVol True if destination is volatile.
6735 /// \param DstPtrInfo IR information on the memory pointer.
6736 /// \returns New head in the control flow, if lowering was successful, empty
6737 /// SDValue otherwise.
6738 ///
6739 /// The function tries to replace 'llvm.memset' intrinsic with several store
6740 /// operations and value calculation code. This is usually profitable for small
6741 /// memory size.
6742 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6743                                SDValue Chain, SDValue Dst, SDValue Src,
6744                                uint64_t Size, Align Alignment, bool isVol,
6745                                MachinePointerInfo DstPtrInfo,
6746                                const AAMDNodes &AAInfo) {
6747   // Turn a memset of undef to nop.
6748   // FIXME: We need to honor volatile even is Src is undef.
6749   if (Src.isUndef())
6750     return Chain;
6751 
6752   // Expand memset to a series of load/store ops if the size operand
6753   // falls below a certain threshold.
6754   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6755   std::vector<EVT> MemOps;
6756   bool DstAlignCanChange = false;
6757   MachineFunction &MF = DAG.getMachineFunction();
6758   MachineFrameInfo &MFI = MF.getFrameInfo();
6759   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6760   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6761   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6762     DstAlignCanChange = true;
6763   bool IsZeroVal =
6764       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6765   if (!TLI.findOptimalMemOpLowering(
6766           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6767           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6768           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6769     return SDValue();
6770 
6771   if (DstAlignCanChange) {
6772     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6773     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6774     if (NewAlign > Alignment) {
6775       // Give the stack frame object a larger alignment if needed.
6776       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6777         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6778       Alignment = NewAlign;
6779     }
6780   }
6781 
6782   SmallVector<SDValue, 8> OutChains;
6783   uint64_t DstOff = 0;
6784   unsigned NumMemOps = MemOps.size();
6785 
6786   // Find the largest store and generate the bit pattern for it.
6787   EVT LargestVT = MemOps[0];
6788   for (unsigned i = 1; i < NumMemOps; i++)
6789     if (MemOps[i].bitsGT(LargestVT))
6790       LargestVT = MemOps[i];
6791   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6792 
6793   // Prepare AAInfo for loads/stores after lowering this memset.
6794   AAMDNodes NewAAInfo = AAInfo;
6795   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6796 
6797   for (unsigned i = 0; i < NumMemOps; i++) {
6798     EVT VT = MemOps[i];
6799     unsigned VTSize = VT.getSizeInBits() / 8;
6800     if (VTSize > Size) {
6801       // Issuing an unaligned load / store pair  that overlaps with the previous
6802       // pair. Adjust the offset accordingly.
6803       assert(i == NumMemOps-1 && i != 0);
6804       DstOff -= VTSize - Size;
6805     }
6806 
6807     // If this store is smaller than the largest store see whether we can get
6808     // the smaller value for free with a truncate.
6809     SDValue Value = MemSetValue;
6810     if (VT.bitsLT(LargestVT)) {
6811       if (!LargestVT.isVector() && !VT.isVector() &&
6812           TLI.isTruncateFree(LargestVT, VT))
6813         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6814       else
6815         Value = getMemsetValue(Src, VT, DAG, dl);
6816     }
6817     assert(Value.getValueType() == VT && "Value with wrong type.");
6818     SDValue Store = DAG.getStore(
6819         Chain, dl, Value,
6820         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6821         DstPtrInfo.getWithOffset(DstOff), Alignment,
6822         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6823         NewAAInfo);
6824     OutChains.push_back(Store);
6825     DstOff += VT.getSizeInBits() / 8;
6826     Size -= VTSize;
6827   }
6828 
6829   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6830 }
6831 
6832 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6833                                             unsigned AS) {
6834   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6835   // pointer operands can be losslessly bitcasted to pointers of address space 0
6836   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6837     report_fatal_error("cannot lower memory intrinsic in address space " +
6838                        Twine(AS));
6839   }
6840 }
6841 
6842 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6843                                 SDValue Src, SDValue Size, Align Alignment,
6844                                 bool isVol, bool AlwaysInline, bool isTailCall,
6845                                 MachinePointerInfo DstPtrInfo,
6846                                 MachinePointerInfo SrcPtrInfo,
6847                                 const AAMDNodes &AAInfo) {
6848   // Check to see if we should lower the memcpy to loads and stores first.
6849   // For cases within the target-specified limits, this is the best choice.
6850   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6851   if (ConstantSize) {
6852     // Memcpy with size zero? Just return the original chain.
6853     if (ConstantSize->isZero())
6854       return Chain;
6855 
6856     SDValue Result = getMemcpyLoadsAndStores(
6857         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6858         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6859     if (Result.getNode())
6860       return Result;
6861   }
6862 
6863   // Then check to see if we should lower the memcpy with target-specific
6864   // code. If the target chooses to do this, this is the next best.
6865   if (TSI) {
6866     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6867         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6868         DstPtrInfo, SrcPtrInfo);
6869     if (Result.getNode())
6870       return Result;
6871   }
6872 
6873   // If we really need inline code and the target declined to provide it,
6874   // use a (potentially long) sequence of loads and stores.
6875   if (AlwaysInline) {
6876     assert(ConstantSize && "AlwaysInline requires a constant size!");
6877     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6878                                    ConstantSize->getZExtValue(), Alignment,
6879                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6880   }
6881 
6882   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6883   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6884 
6885   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6886   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6887   // respect volatile, so they may do things like read or write memory
6888   // beyond the given memory regions. But fixing this isn't easy, and most
6889   // people don't care.
6890 
6891   // Emit a library call.
6892   TargetLowering::ArgListTy Args;
6893   TargetLowering::ArgListEntry Entry;
6894   Entry.Ty = Type::getInt8PtrTy(*getContext());
6895   Entry.Node = Dst; Args.push_back(Entry);
6896   Entry.Node = Src; Args.push_back(Entry);
6897 
6898   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6899   Entry.Node = Size; Args.push_back(Entry);
6900   // FIXME: pass in SDLoc
6901   TargetLowering::CallLoweringInfo CLI(*this);
6902   CLI.setDebugLoc(dl)
6903       .setChain(Chain)
6904       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6905                     Dst.getValueType().getTypeForEVT(*getContext()),
6906                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6907                                       TLI->getPointerTy(getDataLayout())),
6908                     std::move(Args))
6909       .setDiscardResult()
6910       .setTailCall(isTailCall);
6911 
6912   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6913   return CallResult.second;
6914 }
6915 
6916 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6917                                       SDValue Dst, unsigned DstAlign,
6918                                       SDValue Src, unsigned SrcAlign,
6919                                       SDValue Size, Type *SizeTy,
6920                                       unsigned ElemSz, bool isTailCall,
6921                                       MachinePointerInfo DstPtrInfo,
6922                                       MachinePointerInfo SrcPtrInfo) {
6923   // Emit a library call.
6924   TargetLowering::ArgListTy Args;
6925   TargetLowering::ArgListEntry Entry;
6926   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6927   Entry.Node = Dst;
6928   Args.push_back(Entry);
6929 
6930   Entry.Node = Src;
6931   Args.push_back(Entry);
6932 
6933   Entry.Ty = SizeTy;
6934   Entry.Node = Size;
6935   Args.push_back(Entry);
6936 
6937   RTLIB::Libcall LibraryCall =
6938       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6939   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6940     report_fatal_error("Unsupported element size");
6941 
6942   TargetLowering::CallLoweringInfo CLI(*this);
6943   CLI.setDebugLoc(dl)
6944       .setChain(Chain)
6945       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6946                     Type::getVoidTy(*getContext()),
6947                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6948                                       TLI->getPointerTy(getDataLayout())),
6949                     std::move(Args))
6950       .setDiscardResult()
6951       .setTailCall(isTailCall);
6952 
6953   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6954   return CallResult.second;
6955 }
6956 
6957 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6958                                  SDValue Src, SDValue Size, Align Alignment,
6959                                  bool isVol, bool isTailCall,
6960                                  MachinePointerInfo DstPtrInfo,
6961                                  MachinePointerInfo SrcPtrInfo,
6962                                  const AAMDNodes &AAInfo) {
6963   // Check to see if we should lower the memmove to loads and stores first.
6964   // For cases within the target-specified limits, this is the best choice.
6965   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6966   if (ConstantSize) {
6967     // Memmove with size zero? Just return the original chain.
6968     if (ConstantSize->isZero())
6969       return Chain;
6970 
6971     SDValue Result = getMemmoveLoadsAndStores(
6972         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6973         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6974     if (Result.getNode())
6975       return Result;
6976   }
6977 
6978   // Then check to see if we should lower the memmove with target-specific
6979   // code. If the target chooses to do this, this is the next best.
6980   if (TSI) {
6981     SDValue Result =
6982         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6983                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6984     if (Result.getNode())
6985       return Result;
6986   }
6987 
6988   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6989   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6990 
6991   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6992   // not be safe.  See memcpy above for more details.
6993 
6994   // Emit a library call.
6995   TargetLowering::ArgListTy Args;
6996   TargetLowering::ArgListEntry Entry;
6997   Entry.Ty = Type::getInt8PtrTy(*getContext());
6998   Entry.Node = Dst; Args.push_back(Entry);
6999   Entry.Node = Src; Args.push_back(Entry);
7000 
7001   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7002   Entry.Node = Size; Args.push_back(Entry);
7003   // FIXME:  pass in SDLoc
7004   TargetLowering::CallLoweringInfo CLI(*this);
7005   CLI.setDebugLoc(dl)
7006       .setChain(Chain)
7007       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7008                     Dst.getValueType().getTypeForEVT(*getContext()),
7009                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7010                                       TLI->getPointerTy(getDataLayout())),
7011                     std::move(Args))
7012       .setDiscardResult()
7013       .setTailCall(isTailCall);
7014 
7015   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7016   return CallResult.second;
7017 }
7018 
7019 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7020                                        SDValue Dst, unsigned DstAlign,
7021                                        SDValue Src, unsigned SrcAlign,
7022                                        SDValue Size, Type *SizeTy,
7023                                        unsigned ElemSz, bool isTailCall,
7024                                        MachinePointerInfo DstPtrInfo,
7025                                        MachinePointerInfo SrcPtrInfo) {
7026   // Emit a library call.
7027   TargetLowering::ArgListTy Args;
7028   TargetLowering::ArgListEntry Entry;
7029   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7030   Entry.Node = Dst;
7031   Args.push_back(Entry);
7032 
7033   Entry.Node = Src;
7034   Args.push_back(Entry);
7035 
7036   Entry.Ty = SizeTy;
7037   Entry.Node = Size;
7038   Args.push_back(Entry);
7039 
7040   RTLIB::Libcall LibraryCall =
7041       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7042   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7043     report_fatal_error("Unsupported element size");
7044 
7045   TargetLowering::CallLoweringInfo CLI(*this);
7046   CLI.setDebugLoc(dl)
7047       .setChain(Chain)
7048       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7049                     Type::getVoidTy(*getContext()),
7050                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7051                                       TLI->getPointerTy(getDataLayout())),
7052                     std::move(Args))
7053       .setDiscardResult()
7054       .setTailCall(isTailCall);
7055 
7056   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7057   return CallResult.second;
7058 }
7059 
7060 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7061                                 SDValue Src, SDValue Size, Align Alignment,
7062                                 bool isVol, bool isTailCall,
7063                                 MachinePointerInfo DstPtrInfo,
7064                                 const AAMDNodes &AAInfo) {
7065   // Check to see if we should lower the memset to stores first.
7066   // For cases within the target-specified limits, this is the best choice.
7067   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7068   if (ConstantSize) {
7069     // Memset with size zero? Just return the original chain.
7070     if (ConstantSize->isZero())
7071       return Chain;
7072 
7073     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7074                                      ConstantSize->getZExtValue(), Alignment,
7075                                      isVol, DstPtrInfo, AAInfo);
7076 
7077     if (Result.getNode())
7078       return Result;
7079   }
7080 
7081   // Then check to see if we should lower the memset with target-specific
7082   // code. If the target chooses to do this, this is the next best.
7083   if (TSI) {
7084     SDValue Result = TSI->EmitTargetCodeForMemset(
7085         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7086     if (Result.getNode())
7087       return Result;
7088   }
7089 
7090   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7091 
7092   // Emit a library call.
7093   TargetLowering::ArgListTy Args;
7094   TargetLowering::ArgListEntry Entry;
7095   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7096   Args.push_back(Entry);
7097   Entry.Node = Src;
7098   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7099   Args.push_back(Entry);
7100   Entry.Node = Size;
7101   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7102   Args.push_back(Entry);
7103 
7104   // FIXME: pass in SDLoc
7105   TargetLowering::CallLoweringInfo CLI(*this);
7106   CLI.setDebugLoc(dl)
7107       .setChain(Chain)
7108       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7109                     Dst.getValueType().getTypeForEVT(*getContext()),
7110                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7111                                       TLI->getPointerTy(getDataLayout())),
7112                     std::move(Args))
7113       .setDiscardResult()
7114       .setTailCall(isTailCall);
7115 
7116   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7117   return CallResult.second;
7118 }
7119 
7120 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7121                                       SDValue Dst, unsigned DstAlign,
7122                                       SDValue Value, SDValue Size, Type *SizeTy,
7123                                       unsigned ElemSz, bool isTailCall,
7124                                       MachinePointerInfo DstPtrInfo) {
7125   // Emit a library call.
7126   TargetLowering::ArgListTy Args;
7127   TargetLowering::ArgListEntry Entry;
7128   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7129   Entry.Node = Dst;
7130   Args.push_back(Entry);
7131 
7132   Entry.Ty = Type::getInt8Ty(*getContext());
7133   Entry.Node = Value;
7134   Args.push_back(Entry);
7135 
7136   Entry.Ty = SizeTy;
7137   Entry.Node = Size;
7138   Args.push_back(Entry);
7139 
7140   RTLIB::Libcall LibraryCall =
7141       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7142   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7143     report_fatal_error("Unsupported element size");
7144 
7145   TargetLowering::CallLoweringInfo CLI(*this);
7146   CLI.setDebugLoc(dl)
7147       .setChain(Chain)
7148       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7149                     Type::getVoidTy(*getContext()),
7150                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7151                                       TLI->getPointerTy(getDataLayout())),
7152                     std::move(Args))
7153       .setDiscardResult()
7154       .setTailCall(isTailCall);
7155 
7156   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7157   return CallResult.second;
7158 }
7159 
7160 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7161                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7162                                 MachineMemOperand *MMO) {
7163   FoldingSetNodeID ID;
7164   ID.AddInteger(MemVT.getRawBits());
7165   AddNodeIDNode(ID, Opcode, VTList, Ops);
7166   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7167   void* IP = nullptr;
7168   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7169     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7170     return SDValue(E, 0);
7171   }
7172 
7173   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7174                                     VTList, MemVT, MMO);
7175   createOperands(N, Ops);
7176 
7177   CSEMap.InsertNode(N, IP);
7178   InsertNode(N);
7179   return SDValue(N, 0);
7180 }
7181 
7182 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7183                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7184                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7185                                        MachineMemOperand *MMO) {
7186   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7187          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7188   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7189 
7190   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7191   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7192 }
7193 
7194 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7195                                 SDValue Chain, SDValue Ptr, SDValue Val,
7196                                 MachineMemOperand *MMO) {
7197   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7198           Opcode == ISD::ATOMIC_LOAD_SUB ||
7199           Opcode == ISD::ATOMIC_LOAD_AND ||
7200           Opcode == ISD::ATOMIC_LOAD_CLR ||
7201           Opcode == ISD::ATOMIC_LOAD_OR ||
7202           Opcode == ISD::ATOMIC_LOAD_XOR ||
7203           Opcode == ISD::ATOMIC_LOAD_NAND ||
7204           Opcode == ISD::ATOMIC_LOAD_MIN ||
7205           Opcode == ISD::ATOMIC_LOAD_MAX ||
7206           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7207           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7208           Opcode == ISD::ATOMIC_LOAD_FADD ||
7209           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7210           Opcode == ISD::ATOMIC_SWAP ||
7211           Opcode == ISD::ATOMIC_STORE) &&
7212          "Invalid Atomic Op");
7213 
7214   EVT VT = Val.getValueType();
7215 
7216   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7217                                                getVTList(VT, MVT::Other);
7218   SDValue Ops[] = {Chain, Ptr, Val};
7219   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7220 }
7221 
7222 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7223                                 EVT VT, SDValue Chain, SDValue Ptr,
7224                                 MachineMemOperand *MMO) {
7225   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7226 
7227   SDVTList VTs = getVTList(VT, MVT::Other);
7228   SDValue Ops[] = {Chain, Ptr};
7229   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7230 }
7231 
7232 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7233 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7234   if (Ops.size() == 1)
7235     return Ops[0];
7236 
7237   SmallVector<EVT, 4> VTs;
7238   VTs.reserve(Ops.size());
7239   for (const SDValue &Op : Ops)
7240     VTs.push_back(Op.getValueType());
7241   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7242 }
7243 
7244 SDValue SelectionDAG::getMemIntrinsicNode(
7245     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7246     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7247     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7248   if (!Size && MemVT.isScalableVector())
7249     Size = MemoryLocation::UnknownSize;
7250   else if (!Size)
7251     Size = MemVT.getStoreSize();
7252 
7253   MachineFunction &MF = getMachineFunction();
7254   MachineMemOperand *MMO =
7255       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7256 
7257   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7258 }
7259 
7260 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7261                                           SDVTList VTList,
7262                                           ArrayRef<SDValue> Ops, EVT MemVT,
7263                                           MachineMemOperand *MMO) {
7264   assert((Opcode == ISD::INTRINSIC_VOID ||
7265           Opcode == ISD::INTRINSIC_W_CHAIN ||
7266           Opcode == ISD::PREFETCH ||
7267           ((int)Opcode <= std::numeric_limits<int>::max() &&
7268            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7269          "Opcode is not a memory-accessing opcode!");
7270 
7271   // Memoize the node unless it returns a flag.
7272   MemIntrinsicSDNode *N;
7273   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7274     FoldingSetNodeID ID;
7275     AddNodeIDNode(ID, Opcode, VTList, Ops);
7276     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7277         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7278     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7279     void *IP = nullptr;
7280     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7281       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7282       return SDValue(E, 0);
7283     }
7284 
7285     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7286                                       VTList, MemVT, MMO);
7287     createOperands(N, Ops);
7288 
7289   CSEMap.InsertNode(N, IP);
7290   } else {
7291     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7292                                       VTList, MemVT, MMO);
7293     createOperands(N, Ops);
7294   }
7295   InsertNode(N);
7296   SDValue V(N, 0);
7297   NewSDValueDbgMsg(V, "Creating new node: ", this);
7298   return V;
7299 }
7300 
7301 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7302                                       SDValue Chain, int FrameIndex,
7303                                       int64_t Size, int64_t Offset) {
7304   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7305   const auto VTs = getVTList(MVT::Other);
7306   SDValue Ops[2] = {
7307       Chain,
7308       getFrameIndex(FrameIndex,
7309                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7310                     true)};
7311 
7312   FoldingSetNodeID ID;
7313   AddNodeIDNode(ID, Opcode, VTs, Ops);
7314   ID.AddInteger(FrameIndex);
7315   ID.AddInteger(Size);
7316   ID.AddInteger(Offset);
7317   void *IP = nullptr;
7318   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7319     return SDValue(E, 0);
7320 
7321   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7322       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7323   createOperands(N, Ops);
7324   CSEMap.InsertNode(N, IP);
7325   InsertNode(N);
7326   SDValue V(N, 0);
7327   NewSDValueDbgMsg(V, "Creating new node: ", this);
7328   return V;
7329 }
7330 
7331 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7332                                          uint64_t Guid, uint64_t Index,
7333                                          uint32_t Attr) {
7334   const unsigned Opcode = ISD::PSEUDO_PROBE;
7335   const auto VTs = getVTList(MVT::Other);
7336   SDValue Ops[] = {Chain};
7337   FoldingSetNodeID ID;
7338   AddNodeIDNode(ID, Opcode, VTs, Ops);
7339   ID.AddInteger(Guid);
7340   ID.AddInteger(Index);
7341   void *IP = nullptr;
7342   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7343     return SDValue(E, 0);
7344 
7345   auto *N = newSDNode<PseudoProbeSDNode>(
7346       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7347   createOperands(N, Ops);
7348   CSEMap.InsertNode(N, IP);
7349   InsertNode(N);
7350   SDValue V(N, 0);
7351   NewSDValueDbgMsg(V, "Creating new node: ", this);
7352   return V;
7353 }
7354 
7355 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7356 /// MachinePointerInfo record from it.  This is particularly useful because the
7357 /// code generator has many cases where it doesn't bother passing in a
7358 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7359 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7360                                            SelectionDAG &DAG, SDValue Ptr,
7361                                            int64_t Offset = 0) {
7362   // If this is FI+Offset, we can model it.
7363   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7364     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7365                                              FI->getIndex(), Offset);
7366 
7367   // If this is (FI+Offset1)+Offset2, we can model it.
7368   if (Ptr.getOpcode() != ISD::ADD ||
7369       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7370       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7371     return Info;
7372 
7373   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7374   return MachinePointerInfo::getFixedStack(
7375       DAG.getMachineFunction(), FI,
7376       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7377 }
7378 
7379 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7380 /// MachinePointerInfo record from it.  This is particularly useful because the
7381 /// code generator has many cases where it doesn't bother passing in a
7382 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7383 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7384                                            SelectionDAG &DAG, SDValue Ptr,
7385                                            SDValue OffsetOp) {
7386   // If the 'Offset' value isn't a constant, we can't handle this.
7387   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7388     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7389   if (OffsetOp.isUndef())
7390     return InferPointerInfo(Info, DAG, Ptr);
7391   return Info;
7392 }
7393 
7394 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7395                               EVT VT, const SDLoc &dl, SDValue Chain,
7396                               SDValue Ptr, SDValue Offset,
7397                               MachinePointerInfo PtrInfo, EVT MemVT,
7398                               Align Alignment,
7399                               MachineMemOperand::Flags MMOFlags,
7400                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7401   assert(Chain.getValueType() == MVT::Other &&
7402         "Invalid chain type");
7403 
7404   MMOFlags |= MachineMemOperand::MOLoad;
7405   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7406   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7407   // clients.
7408   if (PtrInfo.V.isNull())
7409     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7410 
7411   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7412   MachineFunction &MF = getMachineFunction();
7413   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7414                                                    Alignment, AAInfo, Ranges);
7415   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7416 }
7417 
7418 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7419                               EVT VT, const SDLoc &dl, SDValue Chain,
7420                               SDValue Ptr, SDValue Offset, EVT MemVT,
7421                               MachineMemOperand *MMO) {
7422   if (VT == MemVT) {
7423     ExtType = ISD::NON_EXTLOAD;
7424   } else if (ExtType == ISD::NON_EXTLOAD) {
7425     assert(VT == MemVT && "Non-extending load from different memory type!");
7426   } else {
7427     // Extending load.
7428     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7429            "Should only be an extending load, not truncating!");
7430     assert(VT.isInteger() == MemVT.isInteger() &&
7431            "Cannot convert from FP to Int or Int -> FP!");
7432     assert(VT.isVector() == MemVT.isVector() &&
7433            "Cannot use an ext load to convert to or from a vector!");
7434     assert((!VT.isVector() ||
7435             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7436            "Cannot use an ext load to change the number of vector elements!");
7437   }
7438 
7439   bool Indexed = AM != ISD::UNINDEXED;
7440   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7441 
7442   SDVTList VTs = Indexed ?
7443     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7444   SDValue Ops[] = { Chain, Ptr, Offset };
7445   FoldingSetNodeID ID;
7446   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7447   ID.AddInteger(MemVT.getRawBits());
7448   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7449       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7450   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7451   void *IP = nullptr;
7452   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7453     cast<LoadSDNode>(E)->refineAlignment(MMO);
7454     return SDValue(E, 0);
7455   }
7456   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7457                                   ExtType, MemVT, MMO);
7458   createOperands(N, Ops);
7459 
7460   CSEMap.InsertNode(N, IP);
7461   InsertNode(N);
7462   SDValue V(N, 0);
7463   NewSDValueDbgMsg(V, "Creating new node: ", this);
7464   return V;
7465 }
7466 
7467 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7468                               SDValue Ptr, MachinePointerInfo PtrInfo,
7469                               MaybeAlign Alignment,
7470                               MachineMemOperand::Flags MMOFlags,
7471                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7472   SDValue Undef = getUNDEF(Ptr.getValueType());
7473   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7474                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7475 }
7476 
7477 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7478                               SDValue Ptr, MachineMemOperand *MMO) {
7479   SDValue Undef = getUNDEF(Ptr.getValueType());
7480   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7481                  VT, MMO);
7482 }
7483 
7484 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7485                                  EVT VT, SDValue Chain, SDValue Ptr,
7486                                  MachinePointerInfo PtrInfo, EVT MemVT,
7487                                  MaybeAlign Alignment,
7488                                  MachineMemOperand::Flags MMOFlags,
7489                                  const AAMDNodes &AAInfo) {
7490   SDValue Undef = getUNDEF(Ptr.getValueType());
7491   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7492                  MemVT, Alignment, MMOFlags, AAInfo);
7493 }
7494 
7495 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7496                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7497                                  MachineMemOperand *MMO) {
7498   SDValue Undef = getUNDEF(Ptr.getValueType());
7499   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7500                  MemVT, MMO);
7501 }
7502 
7503 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7504                                      SDValue Base, SDValue Offset,
7505                                      ISD::MemIndexedMode AM) {
7506   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7507   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7508   // Don't propagate the invariant or dereferenceable flags.
7509   auto MMOFlags =
7510       LD->getMemOperand()->getFlags() &
7511       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7512   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7513                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7514                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7515 }
7516 
7517 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7518                                SDValue Ptr, MachinePointerInfo PtrInfo,
7519                                Align Alignment,
7520                                MachineMemOperand::Flags MMOFlags,
7521                                const AAMDNodes &AAInfo) {
7522   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7523 
7524   MMOFlags |= MachineMemOperand::MOStore;
7525   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7526 
7527   if (PtrInfo.V.isNull())
7528     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7529 
7530   MachineFunction &MF = getMachineFunction();
7531   uint64_t Size =
7532       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7533   MachineMemOperand *MMO =
7534       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7535   return getStore(Chain, dl, Val, Ptr, MMO);
7536 }
7537 
7538 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7539                                SDValue Ptr, MachineMemOperand *MMO) {
7540   assert(Chain.getValueType() == MVT::Other &&
7541         "Invalid chain type");
7542   EVT VT = Val.getValueType();
7543   SDVTList VTs = getVTList(MVT::Other);
7544   SDValue Undef = getUNDEF(Ptr.getValueType());
7545   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7546   FoldingSetNodeID ID;
7547   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7548   ID.AddInteger(VT.getRawBits());
7549   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7550       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7551   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7552   void *IP = nullptr;
7553   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7554     cast<StoreSDNode>(E)->refineAlignment(MMO);
7555     return SDValue(E, 0);
7556   }
7557   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7558                                    ISD::UNINDEXED, false, VT, MMO);
7559   createOperands(N, Ops);
7560 
7561   CSEMap.InsertNode(N, IP);
7562   InsertNode(N);
7563   SDValue V(N, 0);
7564   NewSDValueDbgMsg(V, "Creating new node: ", this);
7565   return V;
7566 }
7567 
7568 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7569                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7570                                     EVT SVT, Align Alignment,
7571                                     MachineMemOperand::Flags MMOFlags,
7572                                     const AAMDNodes &AAInfo) {
7573   assert(Chain.getValueType() == MVT::Other &&
7574         "Invalid chain type");
7575 
7576   MMOFlags |= MachineMemOperand::MOStore;
7577   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7578 
7579   if (PtrInfo.V.isNull())
7580     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7581 
7582   MachineFunction &MF = getMachineFunction();
7583   MachineMemOperand *MMO = MF.getMachineMemOperand(
7584       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7585       Alignment, AAInfo);
7586   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7587 }
7588 
7589 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7590                                     SDValue Ptr, EVT SVT,
7591                                     MachineMemOperand *MMO) {
7592   EVT VT = Val.getValueType();
7593 
7594   assert(Chain.getValueType() == MVT::Other &&
7595         "Invalid chain type");
7596   if (VT == SVT)
7597     return getStore(Chain, dl, Val, Ptr, MMO);
7598 
7599   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7600          "Should only be a truncating store, not extending!");
7601   assert(VT.isInteger() == SVT.isInteger() &&
7602          "Can't do FP-INT conversion!");
7603   assert(VT.isVector() == SVT.isVector() &&
7604          "Cannot use trunc store to convert to or from a vector!");
7605   assert((!VT.isVector() ||
7606           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7607          "Cannot use trunc store to change the number of vector elements!");
7608 
7609   SDVTList VTs = getVTList(MVT::Other);
7610   SDValue Undef = getUNDEF(Ptr.getValueType());
7611   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7612   FoldingSetNodeID ID;
7613   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7614   ID.AddInteger(SVT.getRawBits());
7615   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7616       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7617   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7618   void *IP = nullptr;
7619   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7620     cast<StoreSDNode>(E)->refineAlignment(MMO);
7621     return SDValue(E, 0);
7622   }
7623   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7624                                    ISD::UNINDEXED, true, SVT, MMO);
7625   createOperands(N, Ops);
7626 
7627   CSEMap.InsertNode(N, IP);
7628   InsertNode(N);
7629   SDValue V(N, 0);
7630   NewSDValueDbgMsg(V, "Creating new node: ", this);
7631   return V;
7632 }
7633 
7634 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7635                                       SDValue Base, SDValue Offset,
7636                                       ISD::MemIndexedMode AM) {
7637   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7638   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7639   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7640   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7641   FoldingSetNodeID ID;
7642   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7643   ID.AddInteger(ST->getMemoryVT().getRawBits());
7644   ID.AddInteger(ST->getRawSubclassData());
7645   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7646   void *IP = nullptr;
7647   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7648     return SDValue(E, 0);
7649 
7650   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7651                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7652                                    ST->getMemOperand());
7653   createOperands(N, Ops);
7654 
7655   CSEMap.InsertNode(N, IP);
7656   InsertNode(N);
7657   SDValue V(N, 0);
7658   NewSDValueDbgMsg(V, "Creating new node: ", this);
7659   return V;
7660 }
7661 
7662 SDValue SelectionDAG::getLoadVP(
7663     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7664     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7665     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7666     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7667     const MDNode *Ranges, bool IsExpanding) {
7668   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7669 
7670   MMOFlags |= MachineMemOperand::MOLoad;
7671   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7672   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7673   // clients.
7674   if (PtrInfo.V.isNull())
7675     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7676 
7677   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7678   MachineFunction &MF = getMachineFunction();
7679   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7680                                                    Alignment, AAInfo, Ranges);
7681   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7682                    MMO, IsExpanding);
7683 }
7684 
7685 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7686                                 ISD::LoadExtType ExtType, EVT VT,
7687                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7688                                 SDValue Offset, SDValue Mask, SDValue EVL,
7689                                 EVT MemVT, MachineMemOperand *MMO,
7690                                 bool IsExpanding) {
7691   if (VT == MemVT) {
7692     ExtType = ISD::NON_EXTLOAD;
7693   } else if (ExtType == ISD::NON_EXTLOAD) {
7694     assert(VT == MemVT && "Non-extending load from different memory type!");
7695   } else {
7696     // Extending load.
7697     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7698            "Should only be an extending load, not truncating!");
7699     assert(VT.isInteger() == MemVT.isInteger() &&
7700            "Cannot convert from FP to Int or Int -> FP!");
7701     assert(VT.isVector() == MemVT.isVector() &&
7702            "Cannot use an ext load to convert to or from a vector!");
7703     assert((!VT.isVector() ||
7704             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7705            "Cannot use an ext load to change the number of vector elements!");
7706   }
7707 
7708   bool Indexed = AM != ISD::UNINDEXED;
7709   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7710 
7711   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7712                          : getVTList(VT, MVT::Other);
7713   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7714   FoldingSetNodeID ID;
7715   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7716   ID.AddInteger(VT.getRawBits());
7717   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7718       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7719   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7720   void *IP = nullptr;
7721   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7722     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7723     return SDValue(E, 0);
7724   }
7725   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7726                                     ExtType, IsExpanding, MemVT, MMO);
7727   createOperands(N, Ops);
7728 
7729   CSEMap.InsertNode(N, IP);
7730   InsertNode(N);
7731   SDValue V(N, 0);
7732   NewSDValueDbgMsg(V, "Creating new node: ", this);
7733   return V;
7734 }
7735 
7736 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7737                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7738                                 MachinePointerInfo PtrInfo,
7739                                 MaybeAlign Alignment,
7740                                 MachineMemOperand::Flags MMOFlags,
7741                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7742                                 bool IsExpanding) {
7743   SDValue Undef = getUNDEF(Ptr.getValueType());
7744   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7745                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7746                    IsExpanding);
7747 }
7748 
7749 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7750                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7751                                 MachineMemOperand *MMO, bool IsExpanding) {
7752   SDValue Undef = getUNDEF(Ptr.getValueType());
7753   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7754                    Mask, EVL, VT, MMO, IsExpanding);
7755 }
7756 
7757 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7758                                    EVT VT, SDValue Chain, SDValue Ptr,
7759                                    SDValue Mask, SDValue EVL,
7760                                    MachinePointerInfo PtrInfo, EVT MemVT,
7761                                    MaybeAlign Alignment,
7762                                    MachineMemOperand::Flags MMOFlags,
7763                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7764   SDValue Undef = getUNDEF(Ptr.getValueType());
7765   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7766                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7767                    IsExpanding);
7768 }
7769 
7770 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7771                                    EVT VT, SDValue Chain, SDValue Ptr,
7772                                    SDValue Mask, SDValue EVL, EVT MemVT,
7773                                    MachineMemOperand *MMO, bool IsExpanding) {
7774   SDValue Undef = getUNDEF(Ptr.getValueType());
7775   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7776                    EVL, MemVT, MMO, IsExpanding);
7777 }
7778 
7779 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7780                                        SDValue Base, SDValue Offset,
7781                                        ISD::MemIndexedMode AM) {
7782   auto *LD = cast<VPLoadSDNode>(OrigLoad);
7783   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7784   // Don't propagate the invariant or dereferenceable flags.
7785   auto MMOFlags =
7786       LD->getMemOperand()->getFlags() &
7787       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7788   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7789                    LD->getChain(), Base, Offset, LD->getMask(),
7790                    LD->getVectorLength(), LD->getPointerInfo(),
7791                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7792                    nullptr, LD->isExpandingLoad());
7793 }
7794 
7795 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7796                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7797                                  MachinePointerInfo PtrInfo, Align Alignment,
7798                                  MachineMemOperand::Flags MMOFlags,
7799                                  const AAMDNodes &AAInfo, bool IsCompressing) {
7800   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7801 
7802   MMOFlags |= MachineMemOperand::MOStore;
7803   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7804 
7805   if (PtrInfo.V.isNull())
7806     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7807 
7808   MachineFunction &MF = getMachineFunction();
7809   uint64_t Size =
7810       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7811   MachineMemOperand *MMO =
7812       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7813   return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7814 }
7815 
7816 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7817                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7818                                  MachineMemOperand *MMO, bool IsCompressing) {
7819   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7820   EVT VT = Val.getValueType();
7821   SDVTList VTs = getVTList(MVT::Other);
7822   SDValue Undef = getUNDEF(Ptr.getValueType());
7823   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7824   FoldingSetNodeID ID;
7825   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7826   ID.AddInteger(VT.getRawBits());
7827   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7828       dl.getIROrder(), VTs, ISD::UNINDEXED, false, IsCompressing, VT, MMO));
7829   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7830   void *IP = nullptr;
7831   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7832     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7833     return SDValue(E, 0);
7834   }
7835   auto *N =
7836       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7837                                ISD::UNINDEXED, false, IsCompressing, VT, MMO);
7838   createOperands(N, Ops);
7839 
7840   CSEMap.InsertNode(N, IP);
7841   InsertNode(N);
7842   SDValue V(N, 0);
7843   NewSDValueDbgMsg(V, "Creating new node: ", this);
7844   return V;
7845 }
7846 
7847 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7848                                       SDValue Val, SDValue Ptr, SDValue Mask,
7849                                       SDValue EVL, MachinePointerInfo PtrInfo,
7850                                       EVT SVT, Align Alignment,
7851                                       MachineMemOperand::Flags MMOFlags,
7852                                       const AAMDNodes &AAInfo,
7853                                       bool IsCompressing) {
7854   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7855 
7856   MMOFlags |= MachineMemOperand::MOStore;
7857   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7858 
7859   if (PtrInfo.V.isNull())
7860     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7861 
7862   MachineFunction &MF = getMachineFunction();
7863   MachineMemOperand *MMO = MF.getMachineMemOperand(
7864       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7865       Alignment, AAInfo);
7866   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7867                          IsCompressing);
7868 }
7869 
7870 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7871                                       SDValue Val, SDValue Ptr, SDValue Mask,
7872                                       SDValue EVL, EVT SVT,
7873                                       MachineMemOperand *MMO,
7874                                       bool IsCompressing) {
7875   EVT VT = Val.getValueType();
7876 
7877   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7878   if (VT == SVT)
7879     return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7880 
7881   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7882          "Should only be a truncating store, not extending!");
7883   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
7884   assert(VT.isVector() == SVT.isVector() &&
7885          "Cannot use trunc store to convert to or from a vector!");
7886   assert((!VT.isVector() ||
7887           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7888          "Cannot use trunc store to change the number of vector elements!");
7889 
7890   SDVTList VTs = getVTList(MVT::Other);
7891   SDValue Undef = getUNDEF(Ptr.getValueType());
7892   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7893   FoldingSetNodeID ID;
7894   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7895   ID.AddInteger(SVT.getRawBits());
7896   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7897       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
7898   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7899   void *IP = nullptr;
7900   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7901     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7902     return SDValue(E, 0);
7903   }
7904   auto *N =
7905       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7906                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
7907   createOperands(N, Ops);
7908 
7909   CSEMap.InsertNode(N, IP);
7910   InsertNode(N);
7911   SDValue V(N, 0);
7912   NewSDValueDbgMsg(V, "Creating new node: ", this);
7913   return V;
7914 }
7915 
7916 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
7917                                         SDValue Base, SDValue Offset,
7918                                         ISD::MemIndexedMode AM) {
7919   auto *ST = cast<VPStoreSDNode>(OrigStore);
7920   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
7921   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7922   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
7923                    Offset,         ST->getMask(),  ST->getVectorLength()};
7924   FoldingSetNodeID ID;
7925   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7926   ID.AddInteger(ST->getMemoryVT().getRawBits());
7927   ID.AddInteger(ST->getRawSubclassData());
7928   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7929   void *IP = nullptr;
7930   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7931     return SDValue(E, 0);
7932 
7933   auto *N = newSDNode<VPStoreSDNode>(
7934       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
7935       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
7936   createOperands(N, Ops);
7937 
7938   CSEMap.InsertNode(N, IP);
7939   InsertNode(N);
7940   SDValue V(N, 0);
7941   NewSDValueDbgMsg(V, "Creating new node: ", this);
7942   return V;
7943 }
7944 
7945 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7946                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
7947                                   ISD::MemIndexType IndexType) {
7948   assert(Ops.size() == 6 && "Incompatible number of operands");
7949 
7950   FoldingSetNodeID ID;
7951   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
7952   ID.AddInteger(VT.getRawBits());
7953   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
7954       dl.getIROrder(), VTs, VT, MMO, IndexType));
7955   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7956   void *IP = nullptr;
7957   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7958     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
7959     return SDValue(E, 0);
7960   }
7961 
7962   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7963                                       VT, MMO, IndexType);
7964   createOperands(N, Ops);
7965 
7966   assert(N->getMask().getValueType().getVectorElementCount() ==
7967              N->getValueType(0).getVectorElementCount() &&
7968          "Vector width mismatch between mask and data");
7969   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7970              N->getValueType(0).getVectorElementCount().isScalable() &&
7971          "Scalable flags of index and data do not match");
7972   assert(ElementCount::isKnownGE(
7973              N->getIndex().getValueType().getVectorElementCount(),
7974              N->getValueType(0).getVectorElementCount()) &&
7975          "Vector width mismatch between index and data");
7976   assert(isa<ConstantSDNode>(N->getScale()) &&
7977          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7978          "Scale should be a constant power of 2");
7979 
7980   CSEMap.InsertNode(N, IP);
7981   InsertNode(N);
7982   SDValue V(N, 0);
7983   NewSDValueDbgMsg(V, "Creating new node: ", this);
7984   return V;
7985 }
7986 
7987 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7988                                    ArrayRef<SDValue> Ops,
7989                                    MachineMemOperand *MMO,
7990                                    ISD::MemIndexType IndexType) {
7991   assert(Ops.size() == 7 && "Incompatible number of operands");
7992 
7993   FoldingSetNodeID ID;
7994   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
7995   ID.AddInteger(VT.getRawBits());
7996   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
7997       dl.getIROrder(), VTs, VT, MMO, IndexType));
7998   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7999   void *IP = nullptr;
8000   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8001     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8002     return SDValue(E, 0);
8003   }
8004   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8005                                        VT, MMO, IndexType);
8006   createOperands(N, Ops);
8007 
8008   assert(N->getMask().getValueType().getVectorElementCount() ==
8009              N->getValue().getValueType().getVectorElementCount() &&
8010          "Vector width mismatch between mask and data");
8011   assert(
8012       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8013           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8014       "Scalable flags of index and data do not match");
8015   assert(ElementCount::isKnownGE(
8016              N->getIndex().getValueType().getVectorElementCount(),
8017              N->getValue().getValueType().getVectorElementCount()) &&
8018          "Vector width mismatch between index and data");
8019   assert(isa<ConstantSDNode>(N->getScale()) &&
8020          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8021          "Scale should be a constant power of 2");
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::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8031                                     SDValue Base, SDValue Offset, SDValue Mask,
8032                                     SDValue PassThru, EVT MemVT,
8033                                     MachineMemOperand *MMO,
8034                                     ISD::MemIndexedMode AM,
8035                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8036   bool Indexed = AM != ISD::UNINDEXED;
8037   assert((Indexed || Offset.isUndef()) &&
8038          "Unindexed masked load with an offset!");
8039   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8040                          : getVTList(VT, MVT::Other);
8041   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8042   FoldingSetNodeID ID;
8043   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8044   ID.AddInteger(MemVT.getRawBits());
8045   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8046       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8047   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8048   void *IP = nullptr;
8049   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8050     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8051     return SDValue(E, 0);
8052   }
8053   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8054                                         AM, ExtTy, isExpanding, MemVT, MMO);
8055   createOperands(N, Ops);
8056 
8057   CSEMap.InsertNode(N, IP);
8058   InsertNode(N);
8059   SDValue V(N, 0);
8060   NewSDValueDbgMsg(V, "Creating new node: ", this);
8061   return V;
8062 }
8063 
8064 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8065                                            SDValue Base, SDValue Offset,
8066                                            ISD::MemIndexedMode AM) {
8067   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8068   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8069   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8070                        Offset, LD->getMask(), LD->getPassThru(),
8071                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8072                        LD->getExtensionType(), LD->isExpandingLoad());
8073 }
8074 
8075 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8076                                      SDValue Val, SDValue Base, SDValue Offset,
8077                                      SDValue Mask, EVT MemVT,
8078                                      MachineMemOperand *MMO,
8079                                      ISD::MemIndexedMode AM, bool IsTruncating,
8080                                      bool IsCompressing) {
8081   assert(Chain.getValueType() == MVT::Other &&
8082         "Invalid chain type");
8083   bool Indexed = AM != ISD::UNINDEXED;
8084   assert((Indexed || Offset.isUndef()) &&
8085          "Unindexed masked store with an offset!");
8086   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8087                          : getVTList(MVT::Other);
8088   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8089   FoldingSetNodeID ID;
8090   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8091   ID.AddInteger(MemVT.getRawBits());
8092   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8093       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8094   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8095   void *IP = nullptr;
8096   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8097     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8098     return SDValue(E, 0);
8099   }
8100   auto *N =
8101       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8102                                    IsTruncating, IsCompressing, MemVT, MMO);
8103   createOperands(N, Ops);
8104 
8105   CSEMap.InsertNode(N, IP);
8106   InsertNode(N);
8107   SDValue V(N, 0);
8108   NewSDValueDbgMsg(V, "Creating new node: ", this);
8109   return V;
8110 }
8111 
8112 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8113                                             SDValue Base, SDValue Offset,
8114                                             ISD::MemIndexedMode AM) {
8115   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8116   assert(ST->getOffset().isUndef() &&
8117          "Masked store is already a indexed store!");
8118   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8119                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8120                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8121 }
8122 
8123 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8124                                       ArrayRef<SDValue> Ops,
8125                                       MachineMemOperand *MMO,
8126                                       ISD::MemIndexType IndexType,
8127                                       ISD::LoadExtType ExtTy) {
8128   assert(Ops.size() == 6 && "Incompatible number of operands");
8129 
8130   FoldingSetNodeID ID;
8131   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8132   ID.AddInteger(MemVT.getRawBits());
8133   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8134       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8135   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8136   void *IP = nullptr;
8137   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8138     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8139     return SDValue(E, 0);
8140   }
8141 
8142   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8143   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8144                                           VTs, MemVT, MMO, IndexType, ExtTy);
8145   createOperands(N, Ops);
8146 
8147   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8148          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8149   assert(N->getMask().getValueType().getVectorElementCount() ==
8150              N->getValueType(0).getVectorElementCount() &&
8151          "Vector width mismatch between mask and data");
8152   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8153              N->getValueType(0).getVectorElementCount().isScalable() &&
8154          "Scalable flags of index and data do not match");
8155   assert(ElementCount::isKnownGE(
8156              N->getIndex().getValueType().getVectorElementCount(),
8157              N->getValueType(0).getVectorElementCount()) &&
8158          "Vector width mismatch between index and data");
8159   assert(isa<ConstantSDNode>(N->getScale()) &&
8160          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8161          "Scale should be a constant power of 2");
8162 
8163   CSEMap.InsertNode(N, IP);
8164   InsertNode(N);
8165   SDValue V(N, 0);
8166   NewSDValueDbgMsg(V, "Creating new node: ", this);
8167   return V;
8168 }
8169 
8170 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8171                                        ArrayRef<SDValue> Ops,
8172                                        MachineMemOperand *MMO,
8173                                        ISD::MemIndexType IndexType,
8174                                        bool IsTrunc) {
8175   assert(Ops.size() == 6 && "Incompatible number of operands");
8176 
8177   FoldingSetNodeID ID;
8178   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8179   ID.AddInteger(MemVT.getRawBits());
8180   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8181       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8182   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8183   void *IP = nullptr;
8184   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8185     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8186     return SDValue(E, 0);
8187   }
8188 
8189   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8190   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8191                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8192   createOperands(N, Ops);
8193 
8194   assert(N->getMask().getValueType().getVectorElementCount() ==
8195              N->getValue().getValueType().getVectorElementCount() &&
8196          "Vector width mismatch between mask and data");
8197   assert(
8198       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8199           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8200       "Scalable flags of index and data do not match");
8201   assert(ElementCount::isKnownGE(
8202              N->getIndex().getValueType().getVectorElementCount(),
8203              N->getValue().getValueType().getVectorElementCount()) &&
8204          "Vector width mismatch between index and data");
8205   assert(isa<ConstantSDNode>(N->getScale()) &&
8206          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8207          "Scale should be a constant power of 2");
8208 
8209   CSEMap.InsertNode(N, IP);
8210   InsertNode(N);
8211   SDValue V(N, 0);
8212   NewSDValueDbgMsg(V, "Creating new node: ", this);
8213   return V;
8214 }
8215 
8216 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8217   // select undef, T, F --> T (if T is a constant), otherwise F
8218   // select, ?, undef, F --> F
8219   // select, ?, T, undef --> T
8220   if (Cond.isUndef())
8221     return isConstantValueOfAnyType(T) ? T : F;
8222   if (T.isUndef())
8223     return F;
8224   if (F.isUndef())
8225     return T;
8226 
8227   // select true, T, F --> T
8228   // select false, T, F --> F
8229   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8230     return CondC->isZero() ? F : T;
8231 
8232   // TODO: This should simplify VSELECT with constant condition using something
8233   // like this (but check boolean contents to be complete?):
8234   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8235   //    return T;
8236   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8237   //    return F;
8238 
8239   // select ?, T, T --> T
8240   if (T == F)
8241     return T;
8242 
8243   return SDValue();
8244 }
8245 
8246 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8247   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8248   if (X.isUndef())
8249     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8250   // shift X, undef --> undef (because it may shift by the bitwidth)
8251   if (Y.isUndef())
8252     return getUNDEF(X.getValueType());
8253 
8254   // shift 0, Y --> 0
8255   // shift X, 0 --> X
8256   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8257     return X;
8258 
8259   // shift X, C >= bitwidth(X) --> undef
8260   // All vector elements must be too big (or undef) to avoid partial undefs.
8261   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8262     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8263   };
8264   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8265     return getUNDEF(X.getValueType());
8266 
8267   return SDValue();
8268 }
8269 
8270 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8271                                       SDNodeFlags Flags) {
8272   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8273   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8274   // operation is poison. That result can be relaxed to undef.
8275   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8276   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8277   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8278                 (YC && YC->getValueAPF().isNaN());
8279   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8280                 (YC && YC->getValueAPF().isInfinity());
8281 
8282   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8283     return getUNDEF(X.getValueType());
8284 
8285   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8286     return getUNDEF(X.getValueType());
8287 
8288   if (!YC)
8289     return SDValue();
8290 
8291   // X + -0.0 --> X
8292   if (Opcode == ISD::FADD)
8293     if (YC->getValueAPF().isNegZero())
8294       return X;
8295 
8296   // X - +0.0 --> X
8297   if (Opcode == ISD::FSUB)
8298     if (YC->getValueAPF().isPosZero())
8299       return X;
8300 
8301   // X * 1.0 --> X
8302   // X / 1.0 --> X
8303   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8304     if (YC->getValueAPF().isExactlyValue(1.0))
8305       return X;
8306 
8307   // X * 0.0 --> 0.0
8308   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8309     if (YC->getValueAPF().isZero())
8310       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8311 
8312   return SDValue();
8313 }
8314 
8315 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8316                                SDValue Ptr, SDValue SV, unsigned Align) {
8317   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8318   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8319 }
8320 
8321 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8322                               ArrayRef<SDUse> Ops) {
8323   switch (Ops.size()) {
8324   case 0: return getNode(Opcode, DL, VT);
8325   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8326   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8327   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8328   default: break;
8329   }
8330 
8331   // Copy from an SDUse array into an SDValue array for use with
8332   // the regular getNode logic.
8333   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8334   return getNode(Opcode, DL, VT, NewOps);
8335 }
8336 
8337 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8338                               ArrayRef<SDValue> Ops) {
8339   SDNodeFlags Flags;
8340   if (Inserter)
8341     Flags = Inserter->getFlags();
8342   return getNode(Opcode, DL, VT, Ops, Flags);
8343 }
8344 
8345 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8346                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8347   unsigned NumOps = Ops.size();
8348   switch (NumOps) {
8349   case 0: return getNode(Opcode, DL, VT);
8350   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8351   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8352   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8353   default: break;
8354   }
8355 
8356 #ifndef NDEBUG
8357   for (auto &Op : Ops)
8358     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8359            "Operand is DELETED_NODE!");
8360 #endif
8361 
8362   switch (Opcode) {
8363   default: break;
8364   case ISD::BUILD_VECTOR:
8365     // Attempt to simplify BUILD_VECTOR.
8366     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8367       return V;
8368     break;
8369   case ISD::CONCAT_VECTORS:
8370     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8371       return V;
8372     break;
8373   case ISD::SELECT_CC:
8374     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8375     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8376            "LHS and RHS of condition must have same type!");
8377     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8378            "True and False arms of SelectCC must have same type!");
8379     assert(Ops[2].getValueType() == VT &&
8380            "select_cc node must be of same type as true and false value!");
8381     break;
8382   case ISD::BR_CC:
8383     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8384     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8385            "LHS/RHS of comparison should match types!");
8386     break;
8387   }
8388 
8389   // Memoize nodes.
8390   SDNode *N;
8391   SDVTList VTs = getVTList(VT);
8392 
8393   if (VT != MVT::Glue) {
8394     FoldingSetNodeID ID;
8395     AddNodeIDNode(ID, Opcode, VTs, Ops);
8396     void *IP = nullptr;
8397 
8398     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8399       return SDValue(E, 0);
8400 
8401     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8402     createOperands(N, Ops);
8403 
8404     CSEMap.InsertNode(N, IP);
8405   } else {
8406     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8407     createOperands(N, Ops);
8408   }
8409 
8410   N->setFlags(Flags);
8411   InsertNode(N);
8412   SDValue V(N, 0);
8413   NewSDValueDbgMsg(V, "Creating new node: ", this);
8414   return V;
8415 }
8416 
8417 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8418                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8419   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8420 }
8421 
8422 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8423                               ArrayRef<SDValue> Ops) {
8424   SDNodeFlags Flags;
8425   if (Inserter)
8426     Flags = Inserter->getFlags();
8427   return getNode(Opcode, DL, VTList, Ops, Flags);
8428 }
8429 
8430 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8431                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8432   if (VTList.NumVTs == 1)
8433     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8434 
8435 #ifndef NDEBUG
8436   for (auto &Op : Ops)
8437     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8438            "Operand is DELETED_NODE!");
8439 #endif
8440 
8441   switch (Opcode) {
8442   case ISD::STRICT_FP_EXTEND:
8443     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8444            "Invalid STRICT_FP_EXTEND!");
8445     assert(VTList.VTs[0].isFloatingPoint() &&
8446            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8447     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8448            "STRICT_FP_EXTEND result type should be vector iff the operand "
8449            "type is vector!");
8450     assert((!VTList.VTs[0].isVector() ||
8451             VTList.VTs[0].getVectorNumElements() ==
8452             Ops[1].getValueType().getVectorNumElements()) &&
8453            "Vector element count mismatch!");
8454     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8455            "Invalid fpext node, dst <= src!");
8456     break;
8457   case ISD::STRICT_FP_ROUND:
8458     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8459     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8460            "STRICT_FP_ROUND result type should be vector iff the operand "
8461            "type is vector!");
8462     assert((!VTList.VTs[0].isVector() ||
8463             VTList.VTs[0].getVectorNumElements() ==
8464             Ops[1].getValueType().getVectorNumElements()) &&
8465            "Vector element count mismatch!");
8466     assert(VTList.VTs[0].isFloatingPoint() &&
8467            Ops[1].getValueType().isFloatingPoint() &&
8468            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8469            isa<ConstantSDNode>(Ops[2]) &&
8470            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8471             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8472            "Invalid STRICT_FP_ROUND!");
8473     break;
8474 #if 0
8475   // FIXME: figure out how to safely handle things like
8476   // int foo(int x) { return 1 << (x & 255); }
8477   // int bar() { return foo(256); }
8478   case ISD::SRA_PARTS:
8479   case ISD::SRL_PARTS:
8480   case ISD::SHL_PARTS:
8481     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8482         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8483       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8484     else if (N3.getOpcode() == ISD::AND)
8485       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8486         // If the and is only masking out bits that cannot effect the shift,
8487         // eliminate the and.
8488         unsigned NumBits = VT.getScalarSizeInBits()*2;
8489         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8490           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8491       }
8492     break;
8493 #endif
8494   }
8495 
8496   // Memoize the node unless it returns a flag.
8497   SDNode *N;
8498   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8499     FoldingSetNodeID ID;
8500     AddNodeIDNode(ID, Opcode, VTList, Ops);
8501     void *IP = nullptr;
8502     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8503       return SDValue(E, 0);
8504 
8505     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8506     createOperands(N, Ops);
8507     CSEMap.InsertNode(N, IP);
8508   } else {
8509     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8510     createOperands(N, Ops);
8511   }
8512 
8513   N->setFlags(Flags);
8514   InsertNode(N);
8515   SDValue V(N, 0);
8516   NewSDValueDbgMsg(V, "Creating new node: ", this);
8517   return V;
8518 }
8519 
8520 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8521                               SDVTList VTList) {
8522   return getNode(Opcode, DL, VTList, None);
8523 }
8524 
8525 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8526                               SDValue N1) {
8527   SDValue Ops[] = { N1 };
8528   return getNode(Opcode, DL, VTList, Ops);
8529 }
8530 
8531 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8532                               SDValue N1, SDValue N2) {
8533   SDValue Ops[] = { N1, N2 };
8534   return getNode(Opcode, DL, VTList, Ops);
8535 }
8536 
8537 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8538                               SDValue N1, SDValue N2, SDValue N3) {
8539   SDValue Ops[] = { N1, N2, N3 };
8540   return getNode(Opcode, DL, VTList, Ops);
8541 }
8542 
8543 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8544                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8545   SDValue Ops[] = { N1, N2, N3, N4 };
8546   return getNode(Opcode, DL, VTList, Ops);
8547 }
8548 
8549 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8550                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8551                               SDValue N5) {
8552   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8553   return getNode(Opcode, DL, VTList, Ops);
8554 }
8555 
8556 SDVTList SelectionDAG::getVTList(EVT VT) {
8557   return makeVTList(SDNode::getValueTypeList(VT), 1);
8558 }
8559 
8560 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8561   FoldingSetNodeID ID;
8562   ID.AddInteger(2U);
8563   ID.AddInteger(VT1.getRawBits());
8564   ID.AddInteger(VT2.getRawBits());
8565 
8566   void *IP = nullptr;
8567   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8568   if (!Result) {
8569     EVT *Array = Allocator.Allocate<EVT>(2);
8570     Array[0] = VT1;
8571     Array[1] = VT2;
8572     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8573     VTListMap.InsertNode(Result, IP);
8574   }
8575   return Result->getSDVTList();
8576 }
8577 
8578 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8579   FoldingSetNodeID ID;
8580   ID.AddInteger(3U);
8581   ID.AddInteger(VT1.getRawBits());
8582   ID.AddInteger(VT2.getRawBits());
8583   ID.AddInteger(VT3.getRawBits());
8584 
8585   void *IP = nullptr;
8586   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8587   if (!Result) {
8588     EVT *Array = Allocator.Allocate<EVT>(3);
8589     Array[0] = VT1;
8590     Array[1] = VT2;
8591     Array[2] = VT3;
8592     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8593     VTListMap.InsertNode(Result, IP);
8594   }
8595   return Result->getSDVTList();
8596 }
8597 
8598 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8599   FoldingSetNodeID ID;
8600   ID.AddInteger(4U);
8601   ID.AddInteger(VT1.getRawBits());
8602   ID.AddInteger(VT2.getRawBits());
8603   ID.AddInteger(VT3.getRawBits());
8604   ID.AddInteger(VT4.getRawBits());
8605 
8606   void *IP = nullptr;
8607   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8608   if (!Result) {
8609     EVT *Array = Allocator.Allocate<EVT>(4);
8610     Array[0] = VT1;
8611     Array[1] = VT2;
8612     Array[2] = VT3;
8613     Array[3] = VT4;
8614     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8615     VTListMap.InsertNode(Result, IP);
8616   }
8617   return Result->getSDVTList();
8618 }
8619 
8620 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8621   unsigned NumVTs = VTs.size();
8622   FoldingSetNodeID ID;
8623   ID.AddInteger(NumVTs);
8624   for (unsigned index = 0; index < NumVTs; index++) {
8625     ID.AddInteger(VTs[index].getRawBits());
8626   }
8627 
8628   void *IP = nullptr;
8629   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8630   if (!Result) {
8631     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8632     llvm::copy(VTs, Array);
8633     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8634     VTListMap.InsertNode(Result, IP);
8635   }
8636   return Result->getSDVTList();
8637 }
8638 
8639 
8640 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8641 /// specified operands.  If the resultant node already exists in the DAG,
8642 /// this does not modify the specified node, instead it returns the node that
8643 /// already exists.  If the resultant node does not exist in the DAG, the
8644 /// input node is returned.  As a degenerate case, if you specify the same
8645 /// input operands as the node already has, the input node is returned.
8646 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8647   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8648 
8649   // Check to see if there is no change.
8650   if (Op == N->getOperand(0)) return N;
8651 
8652   // See if the modified node already exists.
8653   void *InsertPos = nullptr;
8654   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8655     return Existing;
8656 
8657   // Nope it doesn't.  Remove the node from its current place in the maps.
8658   if (InsertPos)
8659     if (!RemoveNodeFromCSEMaps(N))
8660       InsertPos = nullptr;
8661 
8662   // Now we update the operands.
8663   N->OperandList[0].set(Op);
8664 
8665   updateDivergence(N);
8666   // If this gets put into a CSE map, add it.
8667   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8668   return N;
8669 }
8670 
8671 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8672   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8673 
8674   // Check to see if there is no change.
8675   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8676     return N;   // No operands changed, just return the input node.
8677 
8678   // See if the modified node already exists.
8679   void *InsertPos = nullptr;
8680   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8681     return Existing;
8682 
8683   // Nope it doesn't.  Remove the node from its current place in the maps.
8684   if (InsertPos)
8685     if (!RemoveNodeFromCSEMaps(N))
8686       InsertPos = nullptr;
8687 
8688   // Now we update the operands.
8689   if (N->OperandList[0] != Op1)
8690     N->OperandList[0].set(Op1);
8691   if (N->OperandList[1] != Op2)
8692     N->OperandList[1].set(Op2);
8693 
8694   updateDivergence(N);
8695   // If this gets put into a CSE map, add it.
8696   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8697   return N;
8698 }
8699 
8700 SDNode *SelectionDAG::
8701 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8702   SDValue Ops[] = { Op1, Op2, Op3 };
8703   return UpdateNodeOperands(N, Ops);
8704 }
8705 
8706 SDNode *SelectionDAG::
8707 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8708                    SDValue Op3, SDValue Op4) {
8709   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8710   return UpdateNodeOperands(N, Ops);
8711 }
8712 
8713 SDNode *SelectionDAG::
8714 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8715                    SDValue Op3, SDValue Op4, SDValue Op5) {
8716   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8717   return UpdateNodeOperands(N, Ops);
8718 }
8719 
8720 SDNode *SelectionDAG::
8721 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8722   unsigned NumOps = Ops.size();
8723   assert(N->getNumOperands() == NumOps &&
8724          "Update with wrong number of operands");
8725 
8726   // If no operands changed just return the input node.
8727   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8728     return N;
8729 
8730   // See if the modified node already exists.
8731   void *InsertPos = nullptr;
8732   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8733     return Existing;
8734 
8735   // Nope it doesn't.  Remove the node from its current place in the maps.
8736   if (InsertPos)
8737     if (!RemoveNodeFromCSEMaps(N))
8738       InsertPos = nullptr;
8739 
8740   // Now we update the operands.
8741   for (unsigned i = 0; i != NumOps; ++i)
8742     if (N->OperandList[i] != Ops[i])
8743       N->OperandList[i].set(Ops[i]);
8744 
8745   updateDivergence(N);
8746   // If this gets put into a CSE map, add it.
8747   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8748   return N;
8749 }
8750 
8751 /// DropOperands - Release the operands and set this node to have
8752 /// zero operands.
8753 void SDNode::DropOperands() {
8754   // Unlike the code in MorphNodeTo that does this, we don't need to
8755   // watch for dead nodes here.
8756   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8757     SDUse &Use = *I++;
8758     Use.set(SDValue());
8759   }
8760 }
8761 
8762 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8763                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8764   if (NewMemRefs.empty()) {
8765     N->clearMemRefs();
8766     return;
8767   }
8768 
8769   // Check if we can avoid allocating by storing a single reference directly.
8770   if (NewMemRefs.size() == 1) {
8771     N->MemRefs = NewMemRefs[0];
8772     N->NumMemRefs = 1;
8773     return;
8774   }
8775 
8776   MachineMemOperand **MemRefsBuffer =
8777       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8778   llvm::copy(NewMemRefs, MemRefsBuffer);
8779   N->MemRefs = MemRefsBuffer;
8780   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8781 }
8782 
8783 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8784 /// machine opcode.
8785 ///
8786 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8787                                    EVT VT) {
8788   SDVTList VTs = getVTList(VT);
8789   return SelectNodeTo(N, MachineOpc, VTs, None);
8790 }
8791 
8792 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8793                                    EVT VT, SDValue Op1) {
8794   SDVTList VTs = getVTList(VT);
8795   SDValue Ops[] = { Op1 };
8796   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8797 }
8798 
8799 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8800                                    EVT VT, SDValue Op1,
8801                                    SDValue Op2) {
8802   SDVTList VTs = getVTList(VT);
8803   SDValue Ops[] = { Op1, Op2 };
8804   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8805 }
8806 
8807 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8808                                    EVT VT, SDValue Op1,
8809                                    SDValue Op2, SDValue Op3) {
8810   SDVTList VTs = getVTList(VT);
8811   SDValue Ops[] = { Op1, Op2, Op3 };
8812   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8813 }
8814 
8815 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8816                                    EVT VT, ArrayRef<SDValue> Ops) {
8817   SDVTList VTs = getVTList(VT);
8818   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8819 }
8820 
8821 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8822                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8823   SDVTList VTs = getVTList(VT1, VT2);
8824   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8825 }
8826 
8827 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8828                                    EVT VT1, EVT VT2) {
8829   SDVTList VTs = getVTList(VT1, VT2);
8830   return SelectNodeTo(N, MachineOpc, VTs, None);
8831 }
8832 
8833 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8834                                    EVT VT1, EVT VT2, EVT VT3,
8835                                    ArrayRef<SDValue> Ops) {
8836   SDVTList VTs = getVTList(VT1, VT2, VT3);
8837   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8838 }
8839 
8840 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8841                                    EVT VT1, EVT VT2,
8842                                    SDValue Op1, SDValue Op2) {
8843   SDVTList VTs = getVTList(VT1, VT2);
8844   SDValue Ops[] = { Op1, Op2 };
8845   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8846 }
8847 
8848 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8849                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8850   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8851   // Reset the NodeID to -1.
8852   New->setNodeId(-1);
8853   if (New != N) {
8854     ReplaceAllUsesWith(N, New);
8855     RemoveDeadNode(N);
8856   }
8857   return New;
8858 }
8859 
8860 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8861 /// the line number information on the merged node since it is not possible to
8862 /// preserve the information that operation is associated with multiple lines.
8863 /// This will make the debugger working better at -O0, were there is a higher
8864 /// probability having other instructions associated with that line.
8865 ///
8866 /// For IROrder, we keep the smaller of the two
8867 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8868   DebugLoc NLoc = N->getDebugLoc();
8869   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8870     N->setDebugLoc(DebugLoc());
8871   }
8872   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8873   N->setIROrder(Order);
8874   return N;
8875 }
8876 
8877 /// MorphNodeTo - This *mutates* the specified node to have the specified
8878 /// return type, opcode, and operands.
8879 ///
8880 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8881 /// node of the specified opcode and operands, it returns that node instead of
8882 /// the current one.  Note that the SDLoc need not be the same.
8883 ///
8884 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8885 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8886 /// node, and because it doesn't require CSE recalculation for any of
8887 /// the node's users.
8888 ///
8889 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8890 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8891 /// the legalizer which maintain worklists that would need to be updated when
8892 /// deleting things.
8893 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8894                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8895   // If an identical node already exists, use it.
8896   void *IP = nullptr;
8897   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8898     FoldingSetNodeID ID;
8899     AddNodeIDNode(ID, Opc, VTs, Ops);
8900     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8901       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8902   }
8903 
8904   if (!RemoveNodeFromCSEMaps(N))
8905     IP = nullptr;
8906 
8907   // Start the morphing.
8908   N->NodeType = Opc;
8909   N->ValueList = VTs.VTs;
8910   N->NumValues = VTs.NumVTs;
8911 
8912   // Clear the operands list, updating used nodes to remove this from their
8913   // use list.  Keep track of any operands that become dead as a result.
8914   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8915   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8916     SDUse &Use = *I++;
8917     SDNode *Used = Use.getNode();
8918     Use.set(SDValue());
8919     if (Used->use_empty())
8920       DeadNodeSet.insert(Used);
8921   }
8922 
8923   // For MachineNode, initialize the memory references information.
8924   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8925     MN->clearMemRefs();
8926 
8927   // Swap for an appropriately sized array from the recycler.
8928   removeOperands(N);
8929   createOperands(N, Ops);
8930 
8931   // Delete any nodes that are still dead after adding the uses for the
8932   // new operands.
8933   if (!DeadNodeSet.empty()) {
8934     SmallVector<SDNode *, 16> DeadNodes;
8935     for (SDNode *N : DeadNodeSet)
8936       if (N->use_empty())
8937         DeadNodes.push_back(N);
8938     RemoveDeadNodes(DeadNodes);
8939   }
8940 
8941   if (IP)
8942     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8943   return N;
8944 }
8945 
8946 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8947   unsigned OrigOpc = Node->getOpcode();
8948   unsigned NewOpc;
8949   switch (OrigOpc) {
8950   default:
8951     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8952 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8953   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8954 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8955   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8956 #include "llvm/IR/ConstrainedOps.def"
8957   }
8958 
8959   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8960 
8961   // We're taking this node out of the chain, so we need to re-link things.
8962   SDValue InputChain = Node->getOperand(0);
8963   SDValue OutputChain = SDValue(Node, 1);
8964   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8965 
8966   SmallVector<SDValue, 3> Ops;
8967   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8968     Ops.push_back(Node->getOperand(i));
8969 
8970   SDVTList VTs = getVTList(Node->getValueType(0));
8971   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8972 
8973   // MorphNodeTo can operate in two ways: if an existing node with the
8974   // specified operands exists, it can just return it.  Otherwise, it
8975   // updates the node in place to have the requested operands.
8976   if (Res == Node) {
8977     // If we updated the node in place, reset the node ID.  To the isel,
8978     // this should be just like a newly allocated machine node.
8979     Res->setNodeId(-1);
8980   } else {
8981     ReplaceAllUsesWith(Node, Res);
8982     RemoveDeadNode(Node);
8983   }
8984 
8985   return Res;
8986 }
8987 
8988 /// getMachineNode - These are used for target selectors to create a new node
8989 /// with specified return type(s), MachineInstr opcode, and operands.
8990 ///
8991 /// Note that getMachineNode returns the resultant node.  If there is already a
8992 /// node of the specified opcode and operands, it returns that node instead of
8993 /// the current one.
8994 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8995                                             EVT VT) {
8996   SDVTList VTs = getVTList(VT);
8997   return getMachineNode(Opcode, dl, VTs, None);
8998 }
8999 
9000 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9001                                             EVT VT, SDValue Op1) {
9002   SDVTList VTs = getVTList(VT);
9003   SDValue Ops[] = { Op1 };
9004   return getMachineNode(Opcode, dl, VTs, Ops);
9005 }
9006 
9007 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9008                                             EVT VT, SDValue Op1, SDValue Op2) {
9009   SDVTList VTs = getVTList(VT);
9010   SDValue Ops[] = { Op1, Op2 };
9011   return getMachineNode(Opcode, dl, VTs, Ops);
9012 }
9013 
9014 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9015                                             EVT VT, SDValue Op1, SDValue Op2,
9016                                             SDValue Op3) {
9017   SDVTList VTs = getVTList(VT);
9018   SDValue Ops[] = { Op1, Op2, Op3 };
9019   return getMachineNode(Opcode, dl, VTs, Ops);
9020 }
9021 
9022 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9023                                             EVT VT, ArrayRef<SDValue> Ops) {
9024   SDVTList VTs = getVTList(VT);
9025   return getMachineNode(Opcode, dl, VTs, Ops);
9026 }
9027 
9028 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9029                                             EVT VT1, EVT VT2, SDValue Op1,
9030                                             SDValue Op2) {
9031   SDVTList VTs = getVTList(VT1, VT2);
9032   SDValue Ops[] = { Op1, Op2 };
9033   return getMachineNode(Opcode, dl, VTs, Ops);
9034 }
9035 
9036 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9037                                             EVT VT1, EVT VT2, SDValue Op1,
9038                                             SDValue Op2, SDValue Op3) {
9039   SDVTList VTs = getVTList(VT1, VT2);
9040   SDValue Ops[] = { Op1, Op2, Op3 };
9041   return getMachineNode(Opcode, dl, VTs, Ops);
9042 }
9043 
9044 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9045                                             EVT VT1, EVT VT2,
9046                                             ArrayRef<SDValue> Ops) {
9047   SDVTList VTs = getVTList(VT1, VT2);
9048   return getMachineNode(Opcode, dl, VTs, Ops);
9049 }
9050 
9051 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9052                                             EVT VT1, EVT VT2, EVT VT3,
9053                                             SDValue Op1, SDValue Op2) {
9054   SDVTList VTs = getVTList(VT1, VT2, VT3);
9055   SDValue Ops[] = { Op1, Op2 };
9056   return getMachineNode(Opcode, dl, VTs, Ops);
9057 }
9058 
9059 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9060                                             EVT VT1, EVT VT2, EVT VT3,
9061                                             SDValue Op1, SDValue Op2,
9062                                             SDValue Op3) {
9063   SDVTList VTs = getVTList(VT1, VT2, VT3);
9064   SDValue Ops[] = { Op1, Op2, Op3 };
9065   return getMachineNode(Opcode, dl, VTs, Ops);
9066 }
9067 
9068 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9069                                             EVT VT1, EVT VT2, EVT VT3,
9070                                             ArrayRef<SDValue> Ops) {
9071   SDVTList VTs = getVTList(VT1, VT2, VT3);
9072   return getMachineNode(Opcode, dl, VTs, Ops);
9073 }
9074 
9075 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9076                                             ArrayRef<EVT> ResultTys,
9077                                             ArrayRef<SDValue> Ops) {
9078   SDVTList VTs = getVTList(ResultTys);
9079   return getMachineNode(Opcode, dl, VTs, Ops);
9080 }
9081 
9082 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9083                                             SDVTList VTs,
9084                                             ArrayRef<SDValue> Ops) {
9085   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9086   MachineSDNode *N;
9087   void *IP = nullptr;
9088 
9089   if (DoCSE) {
9090     FoldingSetNodeID ID;
9091     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9092     IP = nullptr;
9093     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9094       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9095     }
9096   }
9097 
9098   // Allocate a new MachineSDNode.
9099   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9100   createOperands(N, Ops);
9101 
9102   if (DoCSE)
9103     CSEMap.InsertNode(N, IP);
9104 
9105   InsertNode(N);
9106   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9107   return N;
9108 }
9109 
9110 /// getTargetExtractSubreg - A convenience function for creating
9111 /// TargetOpcode::EXTRACT_SUBREG nodes.
9112 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9113                                              SDValue Operand) {
9114   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9115   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9116                                   VT, Operand, SRIdxVal);
9117   return SDValue(Subreg, 0);
9118 }
9119 
9120 /// getTargetInsertSubreg - A convenience function for creating
9121 /// TargetOpcode::INSERT_SUBREG nodes.
9122 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9123                                             SDValue Operand, SDValue Subreg) {
9124   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9125   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9126                                   VT, Operand, Subreg, SRIdxVal);
9127   return SDValue(Result, 0);
9128 }
9129 
9130 /// getNodeIfExists - Get the specified node if it's already available, or
9131 /// else return NULL.
9132 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9133                                       ArrayRef<SDValue> Ops) {
9134   SDNodeFlags Flags;
9135   if (Inserter)
9136     Flags = Inserter->getFlags();
9137   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9138 }
9139 
9140 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9141                                       ArrayRef<SDValue> Ops,
9142                                       const SDNodeFlags Flags) {
9143   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9144     FoldingSetNodeID ID;
9145     AddNodeIDNode(ID, Opcode, VTList, Ops);
9146     void *IP = nullptr;
9147     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9148       E->intersectFlagsWith(Flags);
9149       return E;
9150     }
9151   }
9152   return nullptr;
9153 }
9154 
9155 /// doesNodeExist - Check if a node exists without modifying its flags.
9156 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9157                                  ArrayRef<SDValue> Ops) {
9158   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9159     FoldingSetNodeID ID;
9160     AddNodeIDNode(ID, Opcode, VTList, Ops);
9161     void *IP = nullptr;
9162     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9163       return true;
9164   }
9165   return false;
9166 }
9167 
9168 /// getDbgValue - Creates a SDDbgValue node.
9169 ///
9170 /// SDNode
9171 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9172                                       SDNode *N, unsigned R, bool IsIndirect,
9173                                       const DebugLoc &DL, unsigned O) {
9174   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9175          "Expected inlined-at fields to agree");
9176   return new (DbgInfo->getAlloc())
9177       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9178                  {}, IsIndirect, DL, O,
9179                  /*IsVariadic=*/false);
9180 }
9181 
9182 /// Constant
9183 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9184                                               DIExpression *Expr,
9185                                               const Value *C,
9186                                               const DebugLoc &DL, unsigned O) {
9187   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9188          "Expected inlined-at fields to agree");
9189   return new (DbgInfo->getAlloc())
9190       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9191                  /*IsIndirect=*/false, DL, O,
9192                  /*IsVariadic=*/false);
9193 }
9194 
9195 /// FrameIndex
9196 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9197                                                 DIExpression *Expr, unsigned FI,
9198                                                 bool IsIndirect,
9199                                                 const DebugLoc &DL,
9200                                                 unsigned O) {
9201   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9202          "Expected inlined-at fields to agree");
9203   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9204 }
9205 
9206 /// FrameIndex with dependencies
9207 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9208                                                 DIExpression *Expr, unsigned FI,
9209                                                 ArrayRef<SDNode *> Dependencies,
9210                                                 bool IsIndirect,
9211                                                 const DebugLoc &DL,
9212                                                 unsigned O) {
9213   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9214          "Expected inlined-at fields to agree");
9215   return new (DbgInfo->getAlloc())
9216       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9217                  Dependencies, IsIndirect, DL, O,
9218                  /*IsVariadic=*/false);
9219 }
9220 
9221 /// VReg
9222 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9223                                           unsigned VReg, bool IsIndirect,
9224                                           const DebugLoc &DL, unsigned O) {
9225   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9226          "Expected inlined-at fields to agree");
9227   return new (DbgInfo->getAlloc())
9228       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9229                  {}, IsIndirect, DL, O,
9230                  /*IsVariadic=*/false);
9231 }
9232 
9233 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9234                                           ArrayRef<SDDbgOperand> Locs,
9235                                           ArrayRef<SDNode *> Dependencies,
9236                                           bool IsIndirect, const DebugLoc &DL,
9237                                           unsigned O, bool IsVariadic) {
9238   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9239          "Expected inlined-at fields to agree");
9240   return new (DbgInfo->getAlloc())
9241       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9242                  DL, O, IsVariadic);
9243 }
9244 
9245 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9246                                      unsigned OffsetInBits, unsigned SizeInBits,
9247                                      bool InvalidateDbg) {
9248   SDNode *FromNode = From.getNode();
9249   SDNode *ToNode = To.getNode();
9250   assert(FromNode && ToNode && "Can't modify dbg values");
9251 
9252   // PR35338
9253   // TODO: assert(From != To && "Redundant dbg value transfer");
9254   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9255   if (From == To || FromNode == ToNode)
9256     return;
9257 
9258   if (!FromNode->getHasDebugValue())
9259     return;
9260 
9261   SDDbgOperand FromLocOp =
9262       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9263   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9264 
9265   SmallVector<SDDbgValue *, 2> ClonedDVs;
9266   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9267     if (Dbg->isInvalidated())
9268       continue;
9269 
9270     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9271 
9272     // Create a new location ops vector that is equal to the old vector, but
9273     // with each instance of FromLocOp replaced with ToLocOp.
9274     bool Changed = false;
9275     auto NewLocOps = Dbg->copyLocationOps();
9276     std::replace_if(
9277         NewLocOps.begin(), NewLocOps.end(),
9278         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9279           bool Match = Op == FromLocOp;
9280           Changed |= Match;
9281           return Match;
9282         },
9283         ToLocOp);
9284     // Ignore this SDDbgValue if we didn't find a matching location.
9285     if (!Changed)
9286       continue;
9287 
9288     DIVariable *Var = Dbg->getVariable();
9289     auto *Expr = Dbg->getExpression();
9290     // If a fragment is requested, update the expression.
9291     if (SizeInBits) {
9292       // When splitting a larger (e.g., sign-extended) value whose
9293       // lower bits are described with an SDDbgValue, do not attempt
9294       // to transfer the SDDbgValue to the upper bits.
9295       if (auto FI = Expr->getFragmentInfo())
9296         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9297           continue;
9298       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9299                                                              SizeInBits);
9300       if (!Fragment)
9301         continue;
9302       Expr = *Fragment;
9303     }
9304 
9305     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9306     // Clone the SDDbgValue and move it to To.
9307     SDDbgValue *Clone = getDbgValueList(
9308         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9309         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9310         Dbg->isVariadic());
9311     ClonedDVs.push_back(Clone);
9312 
9313     if (InvalidateDbg) {
9314       // Invalidate value and indicate the SDDbgValue should not be emitted.
9315       Dbg->setIsInvalidated();
9316       Dbg->setIsEmitted();
9317     }
9318   }
9319 
9320   for (SDDbgValue *Dbg : ClonedDVs) {
9321     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9322            "Transferred DbgValues should depend on the new SDNode");
9323     AddDbgValue(Dbg, false);
9324   }
9325 }
9326 
9327 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9328   if (!N.getHasDebugValue())
9329     return;
9330 
9331   SmallVector<SDDbgValue *, 2> ClonedDVs;
9332   for (auto DV : GetDbgValues(&N)) {
9333     if (DV->isInvalidated())
9334       continue;
9335     switch (N.getOpcode()) {
9336     default:
9337       break;
9338     case ISD::ADD:
9339       SDValue N0 = N.getOperand(0);
9340       SDValue N1 = N.getOperand(1);
9341       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9342           isConstantIntBuildVectorOrConstantInt(N1)) {
9343         uint64_t Offset = N.getConstantOperandVal(1);
9344 
9345         // Rewrite an ADD constant node into a DIExpression. Since we are
9346         // performing arithmetic to compute the variable's *value* in the
9347         // DIExpression, we need to mark the expression with a
9348         // DW_OP_stack_value.
9349         auto *DIExpr = DV->getExpression();
9350         auto NewLocOps = DV->copyLocationOps();
9351         bool Changed = false;
9352         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9353           // We're not given a ResNo to compare against because the whole
9354           // node is going away. We know that any ISD::ADD only has one
9355           // result, so we can assume any node match is using the result.
9356           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9357               NewLocOps[i].getSDNode() != &N)
9358             continue;
9359           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9360           SmallVector<uint64_t, 3> ExprOps;
9361           DIExpression::appendOffset(ExprOps, Offset);
9362           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9363           Changed = true;
9364         }
9365         (void)Changed;
9366         assert(Changed && "Salvage target doesn't use N");
9367 
9368         auto AdditionalDependencies = DV->getAdditionalDependencies();
9369         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9370                                             NewLocOps, AdditionalDependencies,
9371                                             DV->isIndirect(), DV->getDebugLoc(),
9372                                             DV->getOrder(), DV->isVariadic());
9373         ClonedDVs.push_back(Clone);
9374         DV->setIsInvalidated();
9375         DV->setIsEmitted();
9376         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9377                    N0.getNode()->dumprFull(this);
9378                    dbgs() << " into " << *DIExpr << '\n');
9379       }
9380     }
9381   }
9382 
9383   for (SDDbgValue *Dbg : ClonedDVs) {
9384     assert(!Dbg->getSDNodes().empty() &&
9385            "Salvaged DbgValue should depend on a new SDNode");
9386     AddDbgValue(Dbg, false);
9387   }
9388 }
9389 
9390 /// Creates a SDDbgLabel node.
9391 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9392                                       const DebugLoc &DL, unsigned O) {
9393   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9394          "Expected inlined-at fields to agree");
9395   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9396 }
9397 
9398 namespace {
9399 
9400 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9401 /// pointed to by a use iterator is deleted, increment the use iterator
9402 /// so that it doesn't dangle.
9403 ///
9404 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9405   SDNode::use_iterator &UI;
9406   SDNode::use_iterator &UE;
9407 
9408   void NodeDeleted(SDNode *N, SDNode *E) override {
9409     // Increment the iterator as needed.
9410     while (UI != UE && N == *UI)
9411       ++UI;
9412   }
9413 
9414 public:
9415   RAUWUpdateListener(SelectionDAG &d,
9416                      SDNode::use_iterator &ui,
9417                      SDNode::use_iterator &ue)
9418     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9419 };
9420 
9421 } // end anonymous namespace
9422 
9423 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9424 /// This can cause recursive merging of nodes in the DAG.
9425 ///
9426 /// This version assumes From has a single result value.
9427 ///
9428 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9429   SDNode *From = FromN.getNode();
9430   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9431          "Cannot replace with this method!");
9432   assert(From != To.getNode() && "Cannot replace uses of with self");
9433 
9434   // Preserve Debug Values
9435   transferDbgValues(FromN, To);
9436 
9437   // Iterate over all the existing uses of From. New uses will be added
9438   // to the beginning of the use list, which we avoid visiting.
9439   // This specifically avoids visiting uses of From that arise while the
9440   // replacement is happening, because any such uses would be the result
9441   // of CSE: If an existing node looks like From after one of its operands
9442   // is replaced by To, we don't want to replace of all its users with To
9443   // too. See PR3018 for more info.
9444   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9445   RAUWUpdateListener Listener(*this, UI, UE);
9446   while (UI != UE) {
9447     SDNode *User = *UI;
9448 
9449     // This node is about to morph, remove its old self from the CSE maps.
9450     RemoveNodeFromCSEMaps(User);
9451 
9452     // A user can appear in a use list multiple times, and when this
9453     // happens the uses are usually next to each other in the list.
9454     // To help reduce the number of CSE recomputations, process all
9455     // the uses of this user that we can find this way.
9456     do {
9457       SDUse &Use = UI.getUse();
9458       ++UI;
9459       Use.set(To);
9460       if (To->isDivergent() != From->isDivergent())
9461         updateDivergence(User);
9462     } while (UI != UE && *UI == User);
9463     // Now that we have modified User, add it back to the CSE maps.  If it
9464     // already exists there, recursively merge the results together.
9465     AddModifiedNodeToCSEMaps(User);
9466   }
9467 
9468   // If we just RAUW'd the root, take note.
9469   if (FromN == getRoot())
9470     setRoot(To);
9471 }
9472 
9473 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9474 /// This can cause recursive merging of nodes in the DAG.
9475 ///
9476 /// This version assumes that for each value of From, there is a
9477 /// corresponding value in To in the same position with the same type.
9478 ///
9479 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9480 #ifndef NDEBUG
9481   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9482     assert((!From->hasAnyUseOfValue(i) ||
9483             From->getValueType(i) == To->getValueType(i)) &&
9484            "Cannot use this version of ReplaceAllUsesWith!");
9485 #endif
9486 
9487   // Handle the trivial case.
9488   if (From == To)
9489     return;
9490 
9491   // Preserve Debug Info. Only do this if there's a use.
9492   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9493     if (From->hasAnyUseOfValue(i)) {
9494       assert((i < To->getNumValues()) && "Invalid To location");
9495       transferDbgValues(SDValue(From, i), SDValue(To, i));
9496     }
9497 
9498   // Iterate over just the existing users of From. See the comments in
9499   // the ReplaceAllUsesWith above.
9500   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9501   RAUWUpdateListener Listener(*this, UI, UE);
9502   while (UI != UE) {
9503     SDNode *User = *UI;
9504 
9505     // This node is about to morph, remove its old self from the CSE maps.
9506     RemoveNodeFromCSEMaps(User);
9507 
9508     // A user can appear in a use list multiple times, and when this
9509     // happens the uses are usually next to each other in the list.
9510     // To help reduce the number of CSE recomputations, process all
9511     // the uses of this user that we can find this way.
9512     do {
9513       SDUse &Use = UI.getUse();
9514       ++UI;
9515       Use.setNode(To);
9516       if (To->isDivergent() != From->isDivergent())
9517         updateDivergence(User);
9518     } while (UI != UE && *UI == User);
9519 
9520     // Now that we have modified User, add it back to the CSE maps.  If it
9521     // already exists there, recursively merge the results together.
9522     AddModifiedNodeToCSEMaps(User);
9523   }
9524 
9525   // If we just RAUW'd the root, take note.
9526   if (From == getRoot().getNode())
9527     setRoot(SDValue(To, getRoot().getResNo()));
9528 }
9529 
9530 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9531 /// This can cause recursive merging of nodes in the DAG.
9532 ///
9533 /// This version can replace From with any result values.  To must match the
9534 /// number and types of values returned by From.
9535 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9536   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9537     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9538 
9539   // Preserve Debug Info.
9540   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9541     transferDbgValues(SDValue(From, i), To[i]);
9542 
9543   // Iterate over just the existing users of From. See the comments in
9544   // the ReplaceAllUsesWith above.
9545   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9546   RAUWUpdateListener Listener(*this, UI, UE);
9547   while (UI != UE) {
9548     SDNode *User = *UI;
9549 
9550     // This node is about to morph, remove its old self from the CSE maps.
9551     RemoveNodeFromCSEMaps(User);
9552 
9553     // A user can appear in a use list multiple times, and when this happens the
9554     // uses are usually next to each other in the list.  To help reduce the
9555     // number of CSE and divergence recomputations, process all the uses of this
9556     // user that we can find this way.
9557     bool To_IsDivergent = false;
9558     do {
9559       SDUse &Use = UI.getUse();
9560       const SDValue &ToOp = To[Use.getResNo()];
9561       ++UI;
9562       Use.set(ToOp);
9563       To_IsDivergent |= ToOp->isDivergent();
9564     } while (UI != UE && *UI == User);
9565 
9566     if (To_IsDivergent != From->isDivergent())
9567       updateDivergence(User);
9568 
9569     // Now that we have modified User, add it back to the CSE maps.  If it
9570     // already exists there, recursively merge the results together.
9571     AddModifiedNodeToCSEMaps(User);
9572   }
9573 
9574   // If we just RAUW'd the root, take note.
9575   if (From == getRoot().getNode())
9576     setRoot(SDValue(To[getRoot().getResNo()]));
9577 }
9578 
9579 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9580 /// uses of other values produced by From.getNode() alone.  The Deleted
9581 /// vector is handled the same way as for ReplaceAllUsesWith.
9582 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9583   // Handle the really simple, really trivial case efficiently.
9584   if (From == To) return;
9585 
9586   // Handle the simple, trivial, case efficiently.
9587   if (From.getNode()->getNumValues() == 1) {
9588     ReplaceAllUsesWith(From, To);
9589     return;
9590   }
9591 
9592   // Preserve Debug Info.
9593   transferDbgValues(From, To);
9594 
9595   // Iterate over just the existing users of From. See the comments in
9596   // the ReplaceAllUsesWith above.
9597   SDNode::use_iterator UI = From.getNode()->use_begin(),
9598                        UE = From.getNode()->use_end();
9599   RAUWUpdateListener Listener(*this, UI, UE);
9600   while (UI != UE) {
9601     SDNode *User = *UI;
9602     bool UserRemovedFromCSEMaps = false;
9603 
9604     // A user can appear in a use list multiple times, and when this
9605     // happens the uses are usually next to each other in the list.
9606     // To help reduce the number of CSE recomputations, process all
9607     // the uses of this user that we can find this way.
9608     do {
9609       SDUse &Use = UI.getUse();
9610 
9611       // Skip uses of different values from the same node.
9612       if (Use.getResNo() != From.getResNo()) {
9613         ++UI;
9614         continue;
9615       }
9616 
9617       // If this node hasn't been modified yet, it's still in the CSE maps,
9618       // so remove its old self from the CSE maps.
9619       if (!UserRemovedFromCSEMaps) {
9620         RemoveNodeFromCSEMaps(User);
9621         UserRemovedFromCSEMaps = true;
9622       }
9623 
9624       ++UI;
9625       Use.set(To);
9626       if (To->isDivergent() != From->isDivergent())
9627         updateDivergence(User);
9628     } while (UI != UE && *UI == User);
9629     // We are iterating over all uses of the From node, so if a use
9630     // doesn't use the specific value, no changes are made.
9631     if (!UserRemovedFromCSEMaps)
9632       continue;
9633 
9634     // Now that we have modified User, add it back to the CSE maps.  If it
9635     // already exists there, recursively merge the results together.
9636     AddModifiedNodeToCSEMaps(User);
9637   }
9638 
9639   // If we just RAUW'd the root, take note.
9640   if (From == getRoot())
9641     setRoot(To);
9642 }
9643 
9644 namespace {
9645 
9646   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9647   /// to record information about a use.
9648   struct UseMemo {
9649     SDNode *User;
9650     unsigned Index;
9651     SDUse *Use;
9652   };
9653 
9654   /// operator< - Sort Memos by User.
9655   bool operator<(const UseMemo &L, const UseMemo &R) {
9656     return (intptr_t)L.User < (intptr_t)R.User;
9657   }
9658 
9659 } // end anonymous namespace
9660 
9661 bool SelectionDAG::calculateDivergence(SDNode *N) {
9662   if (TLI->isSDNodeAlwaysUniform(N)) {
9663     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9664            "Conflicting divergence information!");
9665     return false;
9666   }
9667   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9668     return true;
9669   for (auto &Op : N->ops()) {
9670     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9671       return true;
9672   }
9673   return false;
9674 }
9675 
9676 void SelectionDAG::updateDivergence(SDNode *N) {
9677   SmallVector<SDNode *, 16> Worklist(1, N);
9678   do {
9679     N = Worklist.pop_back_val();
9680     bool IsDivergent = calculateDivergence(N);
9681     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9682       N->SDNodeBits.IsDivergent = IsDivergent;
9683       llvm::append_range(Worklist, N->uses());
9684     }
9685   } while (!Worklist.empty());
9686 }
9687 
9688 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9689   DenseMap<SDNode *, unsigned> Degree;
9690   Order.reserve(AllNodes.size());
9691   for (auto &N : allnodes()) {
9692     unsigned NOps = N.getNumOperands();
9693     Degree[&N] = NOps;
9694     if (0 == NOps)
9695       Order.push_back(&N);
9696   }
9697   for (size_t I = 0; I != Order.size(); ++I) {
9698     SDNode *N = Order[I];
9699     for (auto U : N->uses()) {
9700       unsigned &UnsortedOps = Degree[U];
9701       if (0 == --UnsortedOps)
9702         Order.push_back(U);
9703     }
9704   }
9705 }
9706 
9707 #ifndef NDEBUG
9708 void SelectionDAG::VerifyDAGDiverence() {
9709   std::vector<SDNode *> TopoOrder;
9710   CreateTopologicalOrder(TopoOrder);
9711   for (auto *N : TopoOrder) {
9712     assert(calculateDivergence(N) == N->isDivergent() &&
9713            "Divergence bit inconsistency detected");
9714   }
9715 }
9716 #endif
9717 
9718 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9719 /// uses of other values produced by From.getNode() alone.  The same value
9720 /// may appear in both the From and To list.  The Deleted vector is
9721 /// handled the same way as for ReplaceAllUsesWith.
9722 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9723                                               const SDValue *To,
9724                                               unsigned Num){
9725   // Handle the simple, trivial case efficiently.
9726   if (Num == 1)
9727     return ReplaceAllUsesOfValueWith(*From, *To);
9728 
9729   transferDbgValues(*From, *To);
9730 
9731   // Read up all the uses and make records of them. This helps
9732   // processing new uses that are introduced during the
9733   // replacement process.
9734   SmallVector<UseMemo, 4> Uses;
9735   for (unsigned i = 0; i != Num; ++i) {
9736     unsigned FromResNo = From[i].getResNo();
9737     SDNode *FromNode = From[i].getNode();
9738     for (SDNode::use_iterator UI = FromNode->use_begin(),
9739          E = FromNode->use_end(); UI != E; ++UI) {
9740       SDUse &Use = UI.getUse();
9741       if (Use.getResNo() == FromResNo) {
9742         UseMemo Memo = { *UI, i, &Use };
9743         Uses.push_back(Memo);
9744       }
9745     }
9746   }
9747 
9748   // Sort the uses, so that all the uses from a given User are together.
9749   llvm::sort(Uses);
9750 
9751   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9752        UseIndex != UseIndexEnd; ) {
9753     // We know that this user uses some value of From.  If it is the right
9754     // value, update it.
9755     SDNode *User = Uses[UseIndex].User;
9756 
9757     // This node is about to morph, remove its old self from the CSE maps.
9758     RemoveNodeFromCSEMaps(User);
9759 
9760     // The Uses array is sorted, so all the uses for a given User
9761     // are next to each other in the list.
9762     // To help reduce the number of CSE recomputations, process all
9763     // the uses of this user that we can find this way.
9764     do {
9765       unsigned i = Uses[UseIndex].Index;
9766       SDUse &Use = *Uses[UseIndex].Use;
9767       ++UseIndex;
9768 
9769       Use.set(To[i]);
9770     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9771 
9772     // Now that we have modified User, add it back to the CSE maps.  If it
9773     // already exists there, recursively merge the results together.
9774     AddModifiedNodeToCSEMaps(User);
9775   }
9776 }
9777 
9778 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9779 /// based on their topological order. It returns the maximum id and a vector
9780 /// of the SDNodes* in assigned order by reference.
9781 unsigned SelectionDAG::AssignTopologicalOrder() {
9782   unsigned DAGSize = 0;
9783 
9784   // SortedPos tracks the progress of the algorithm. Nodes before it are
9785   // sorted, nodes after it are unsorted. When the algorithm completes
9786   // it is at the end of the list.
9787   allnodes_iterator SortedPos = allnodes_begin();
9788 
9789   // Visit all the nodes. Move nodes with no operands to the front of
9790   // the list immediately. Annotate nodes that do have operands with their
9791   // operand count. Before we do this, the Node Id fields of the nodes
9792   // may contain arbitrary values. After, the Node Id fields for nodes
9793   // before SortedPos will contain the topological sort index, and the
9794   // Node Id fields for nodes At SortedPos and after will contain the
9795   // count of outstanding operands.
9796   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
9797     SDNode *N = &*I++;
9798     checkForCycles(N, this);
9799     unsigned Degree = N->getNumOperands();
9800     if (Degree == 0) {
9801       // A node with no uses, add it to the result array immediately.
9802       N->setNodeId(DAGSize++);
9803       allnodes_iterator Q(N);
9804       if (Q != SortedPos)
9805         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9806       assert(SortedPos != AllNodes.end() && "Overran node list");
9807       ++SortedPos;
9808     } else {
9809       // Temporarily use the Node Id as scratch space for the degree count.
9810       N->setNodeId(Degree);
9811     }
9812   }
9813 
9814   // Visit all the nodes. As we iterate, move nodes into sorted order,
9815   // such that by the time the end is reached all nodes will be sorted.
9816   for (SDNode &Node : allnodes()) {
9817     SDNode *N = &Node;
9818     checkForCycles(N, this);
9819     // N is in sorted position, so all its uses have one less operand
9820     // that needs to be sorted.
9821     for (SDNode *P : N->uses()) {
9822       unsigned Degree = P->getNodeId();
9823       assert(Degree != 0 && "Invalid node degree");
9824       --Degree;
9825       if (Degree == 0) {
9826         // All of P's operands are sorted, so P may sorted now.
9827         P->setNodeId(DAGSize++);
9828         if (P->getIterator() != SortedPos)
9829           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9830         assert(SortedPos != AllNodes.end() && "Overran node list");
9831         ++SortedPos;
9832       } else {
9833         // Update P's outstanding operand count.
9834         P->setNodeId(Degree);
9835       }
9836     }
9837     if (Node.getIterator() == SortedPos) {
9838 #ifndef NDEBUG
9839       allnodes_iterator I(N);
9840       SDNode *S = &*++I;
9841       dbgs() << "Overran sorted position:\n";
9842       S->dumprFull(this); dbgs() << "\n";
9843       dbgs() << "Checking if this is due to cycles\n";
9844       checkForCycles(this, true);
9845 #endif
9846       llvm_unreachable(nullptr);
9847     }
9848   }
9849 
9850   assert(SortedPos == AllNodes.end() &&
9851          "Topological sort incomplete!");
9852   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9853          "First node in topological sort is not the entry token!");
9854   assert(AllNodes.front().getNodeId() == 0 &&
9855          "First node in topological sort has non-zero id!");
9856   assert(AllNodes.front().getNumOperands() == 0 &&
9857          "First node in topological sort has operands!");
9858   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9859          "Last node in topologic sort has unexpected id!");
9860   assert(AllNodes.back().use_empty() &&
9861          "Last node in topologic sort has users!");
9862   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9863   return DAGSize;
9864 }
9865 
9866 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9867 /// value is produced by SD.
9868 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9869   for (SDNode *SD : DB->getSDNodes()) {
9870     if (!SD)
9871       continue;
9872     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9873     SD->setHasDebugValue(true);
9874   }
9875   DbgInfo->add(DB, isParameter);
9876 }
9877 
9878 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9879 
9880 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9881                                                    SDValue NewMemOpChain) {
9882   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9883   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9884   // The new memory operation must have the same position as the old load in
9885   // terms of memory dependency. Create a TokenFactor for the old load and new
9886   // memory operation and update uses of the old load's output chain to use that
9887   // TokenFactor.
9888   if (OldChain == NewMemOpChain || OldChain.use_empty())
9889     return NewMemOpChain;
9890 
9891   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9892                                 OldChain, NewMemOpChain);
9893   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9894   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9895   return TokenFactor;
9896 }
9897 
9898 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9899                                                    SDValue NewMemOp) {
9900   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9901   SDValue OldChain = SDValue(OldLoad, 1);
9902   SDValue NewMemOpChain = NewMemOp.getValue(1);
9903   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9904 }
9905 
9906 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9907                                                      Function **OutFunction) {
9908   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9909 
9910   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9911   auto *Module = MF->getFunction().getParent();
9912   auto *Function = Module->getFunction(Symbol);
9913 
9914   if (OutFunction != nullptr)
9915       *OutFunction = Function;
9916 
9917   if (Function != nullptr) {
9918     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9919     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9920   }
9921 
9922   std::string ErrorStr;
9923   raw_string_ostream ErrorFormatter(ErrorStr);
9924 
9925   ErrorFormatter << "Undefined external symbol ";
9926   ErrorFormatter << '"' << Symbol << '"';
9927   ErrorFormatter.flush();
9928 
9929   report_fatal_error(ErrorStr);
9930 }
9931 
9932 //===----------------------------------------------------------------------===//
9933 //                              SDNode Class
9934 //===----------------------------------------------------------------------===//
9935 
9936 bool llvm::isNullConstant(SDValue V) {
9937   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9938   return Const != nullptr && Const->isZero();
9939 }
9940 
9941 bool llvm::isNullFPConstant(SDValue V) {
9942   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9943   return Const != nullptr && Const->isZero() && !Const->isNegative();
9944 }
9945 
9946 bool llvm::isAllOnesConstant(SDValue V) {
9947   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9948   return Const != nullptr && Const->isAllOnes();
9949 }
9950 
9951 bool llvm::isOneConstant(SDValue V) {
9952   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9953   return Const != nullptr && Const->isOne();
9954 }
9955 
9956 SDValue llvm::peekThroughBitcasts(SDValue V) {
9957   while (V.getOpcode() == ISD::BITCAST)
9958     V = V.getOperand(0);
9959   return V;
9960 }
9961 
9962 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9963   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9964     V = V.getOperand(0);
9965   return V;
9966 }
9967 
9968 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9969   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9970     V = V.getOperand(0);
9971   return V;
9972 }
9973 
9974 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9975   if (V.getOpcode() != ISD::XOR)
9976     return false;
9977   V = peekThroughBitcasts(V.getOperand(1));
9978   unsigned NumBits = V.getScalarValueSizeInBits();
9979   ConstantSDNode *C =
9980       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9981   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9982 }
9983 
9984 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9985                                           bool AllowTruncation) {
9986   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9987     return CN;
9988 
9989   // SplatVectors can truncate their operands. Ignore that case here unless
9990   // AllowTruncation is set.
9991   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9992     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9993     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9994       EVT CVT = CN->getValueType(0);
9995       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9996       if (AllowTruncation || CVT == VecEltVT)
9997         return CN;
9998     }
9999   }
10000 
10001   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10002     BitVector UndefElements;
10003     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10004 
10005     // BuildVectors can truncate their operands. Ignore that case here unless
10006     // AllowTruncation is set.
10007     if (CN && (UndefElements.none() || AllowUndefs)) {
10008       EVT CVT = CN->getValueType(0);
10009       EVT NSVT = N.getValueType().getScalarType();
10010       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10011       if (AllowTruncation || (CVT == NSVT))
10012         return CN;
10013     }
10014   }
10015 
10016   return nullptr;
10017 }
10018 
10019 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10020                                           bool AllowUndefs,
10021                                           bool AllowTruncation) {
10022   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10023     return CN;
10024 
10025   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10026     BitVector UndefElements;
10027     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10028 
10029     // BuildVectors can truncate their operands. Ignore that case here unless
10030     // AllowTruncation is set.
10031     if (CN && (UndefElements.none() || AllowUndefs)) {
10032       EVT CVT = CN->getValueType(0);
10033       EVT NSVT = N.getValueType().getScalarType();
10034       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10035       if (AllowTruncation || (CVT == NSVT))
10036         return CN;
10037     }
10038   }
10039 
10040   return nullptr;
10041 }
10042 
10043 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10044   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10045     return CN;
10046 
10047   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10048     BitVector UndefElements;
10049     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10050     if (CN && (UndefElements.none() || AllowUndefs))
10051       return CN;
10052   }
10053 
10054   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10055     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10056       return CN;
10057 
10058   return nullptr;
10059 }
10060 
10061 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10062                                               const APInt &DemandedElts,
10063                                               bool AllowUndefs) {
10064   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10065     return CN;
10066 
10067   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10068     BitVector UndefElements;
10069     ConstantFPSDNode *CN =
10070         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10071     if (CN && (UndefElements.none() || AllowUndefs))
10072       return CN;
10073   }
10074 
10075   return nullptr;
10076 }
10077 
10078 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10079   // TODO: may want to use peekThroughBitcast() here.
10080   ConstantSDNode *C =
10081       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10082   return C && C->isZero();
10083 }
10084 
10085 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10086   // TODO: may want to use peekThroughBitcast() here.
10087   unsigned BitWidth = N.getScalarValueSizeInBits();
10088   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10089   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10090 }
10091 
10092 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10093   N = peekThroughBitcasts(N);
10094   unsigned BitWidth = N.getScalarValueSizeInBits();
10095   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10096   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10097 }
10098 
10099 HandleSDNode::~HandleSDNode() {
10100   DropOperands();
10101 }
10102 
10103 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10104                                          const DebugLoc &DL,
10105                                          const GlobalValue *GA, EVT VT,
10106                                          int64_t o, unsigned TF)
10107     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10108   TheGlobal = GA;
10109 }
10110 
10111 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10112                                          EVT VT, unsigned SrcAS,
10113                                          unsigned DestAS)
10114     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10115       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10116 
10117 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10118                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10119     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10120   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10121   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10122   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10123   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10124 
10125   // We check here that the size of the memory operand fits within the size of
10126   // the MMO. This is because the MMO might indicate only a possible address
10127   // range instead of specifying the affected memory addresses precisely.
10128   // TODO: Make MachineMemOperands aware of scalable vectors.
10129   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10130          "Size mismatch!");
10131 }
10132 
10133 /// Profile - Gather unique data for the node.
10134 ///
10135 void SDNode::Profile(FoldingSetNodeID &ID) const {
10136   AddNodeIDNode(ID, this);
10137 }
10138 
10139 namespace {
10140 
10141   struct EVTArray {
10142     std::vector<EVT> VTs;
10143 
10144     EVTArray() {
10145       VTs.reserve(MVT::VALUETYPE_SIZE);
10146       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10147         VTs.push_back(MVT((MVT::SimpleValueType)i));
10148     }
10149   };
10150 
10151 } // end anonymous namespace
10152 
10153 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10154 static ManagedStatic<EVTArray> SimpleVTArray;
10155 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10156 
10157 /// getValueTypeList - Return a pointer to the specified value type.
10158 ///
10159 const EVT *SDNode::getValueTypeList(EVT VT) {
10160   if (VT.isExtended()) {
10161     sys::SmartScopedLock<true> Lock(*VTMutex);
10162     return &(*EVTs->insert(VT).first);
10163   }
10164   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10165   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10166 }
10167 
10168 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10169 /// indicated value.  This method ignores uses of other values defined by this
10170 /// operation.
10171 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10172   assert(Value < getNumValues() && "Bad value!");
10173 
10174   // TODO: Only iterate over uses of a given value of the node
10175   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10176     if (UI.getUse().getResNo() == Value) {
10177       if (NUses == 0)
10178         return false;
10179       --NUses;
10180     }
10181   }
10182 
10183   // Found exactly the right number of uses?
10184   return NUses == 0;
10185 }
10186 
10187 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10188 /// value. This method ignores uses of other values defined by this operation.
10189 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10190   assert(Value < getNumValues() && "Bad value!");
10191 
10192   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10193     if (UI.getUse().getResNo() == Value)
10194       return true;
10195 
10196   return false;
10197 }
10198 
10199 /// isOnlyUserOf - Return true if this node is the only use of N.
10200 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10201   bool Seen = false;
10202   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
10203     SDNode *User = *I;
10204     if (User == this)
10205       Seen = true;
10206     else
10207       return false;
10208   }
10209 
10210   return Seen;
10211 }
10212 
10213 /// Return true if the only users of N are contained in Nodes.
10214 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10215   bool Seen = false;
10216   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
10217     SDNode *User = *I;
10218     if (llvm::is_contained(Nodes, User))
10219       Seen = true;
10220     else
10221       return false;
10222   }
10223 
10224   return Seen;
10225 }
10226 
10227 /// isOperand - Return true if this node is an operand of N.
10228 bool SDValue::isOperandOf(const SDNode *N) const {
10229   return is_contained(N->op_values(), *this);
10230 }
10231 
10232 bool SDNode::isOperandOf(const SDNode *N) const {
10233   return any_of(N->op_values(),
10234                 [this](SDValue Op) { return this == Op.getNode(); });
10235 }
10236 
10237 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10238 /// be a chain) reaches the specified operand without crossing any
10239 /// side-effecting instructions on any chain path.  In practice, this looks
10240 /// through token factors and non-volatile loads.  In order to remain efficient,
10241 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10242 ///
10243 /// Note that we only need to examine chains when we're searching for
10244 /// side-effects; SelectionDAG requires that all side-effects are represented
10245 /// by chains, even if another operand would force a specific ordering. This
10246 /// constraint is necessary to allow transformations like splitting loads.
10247 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10248                                              unsigned Depth) const {
10249   if (*this == Dest) return true;
10250 
10251   // Don't search too deeply, we just want to be able to see through
10252   // TokenFactor's etc.
10253   if (Depth == 0) return false;
10254 
10255   // If this is a token factor, all inputs to the TF happen in parallel.
10256   if (getOpcode() == ISD::TokenFactor) {
10257     // First, try a shallow search.
10258     if (is_contained((*this)->ops(), Dest)) {
10259       // We found the chain we want as an operand of this TokenFactor.
10260       // Essentially, we reach the chain without side-effects if we could
10261       // serialize the TokenFactor into a simple chain of operations with
10262       // Dest as the last operation. This is automatically true if the
10263       // chain has one use: there are no other ordering constraints.
10264       // If the chain has more than one use, we give up: some other
10265       // use of Dest might force a side-effect between Dest and the current
10266       // node.
10267       if (Dest.hasOneUse())
10268         return true;
10269     }
10270     // Next, try a deep search: check whether every operand of the TokenFactor
10271     // reaches Dest.
10272     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10273       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10274     });
10275   }
10276 
10277   // Loads don't have side effects, look through them.
10278   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10279     if (Ld->isUnordered())
10280       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10281   }
10282   return false;
10283 }
10284 
10285 bool SDNode::hasPredecessor(const SDNode *N) const {
10286   SmallPtrSet<const SDNode *, 32> Visited;
10287   SmallVector<const SDNode *, 16> Worklist;
10288   Worklist.push_back(this);
10289   return hasPredecessorHelper(N, Visited, Worklist);
10290 }
10291 
10292 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10293   this->Flags.intersectWith(Flags);
10294 }
10295 
10296 SDValue
10297 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10298                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10299                                   bool AllowPartials) {
10300   // The pattern must end in an extract from index 0.
10301   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10302       !isNullConstant(Extract->getOperand(1)))
10303     return SDValue();
10304 
10305   // Match against one of the candidate binary ops.
10306   SDValue Op = Extract->getOperand(0);
10307   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10308         return Op.getOpcode() == unsigned(BinOp);
10309       }))
10310     return SDValue();
10311 
10312   // Floating-point reductions may require relaxed constraints on the final step
10313   // of the reduction because they may reorder intermediate operations.
10314   unsigned CandidateBinOp = Op.getOpcode();
10315   if (Op.getValueType().isFloatingPoint()) {
10316     SDNodeFlags Flags = Op->getFlags();
10317     switch (CandidateBinOp) {
10318     case ISD::FADD:
10319       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10320         return SDValue();
10321       break;
10322     default:
10323       llvm_unreachable("Unhandled FP opcode for binop reduction");
10324     }
10325   }
10326 
10327   // Matching failed - attempt to see if we did enough stages that a partial
10328   // reduction from a subvector is possible.
10329   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10330     if (!AllowPartials || !Op)
10331       return SDValue();
10332     EVT OpVT = Op.getValueType();
10333     EVT OpSVT = OpVT.getScalarType();
10334     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10335     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10336       return SDValue();
10337     BinOp = (ISD::NodeType)CandidateBinOp;
10338     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10339                    getVectorIdxConstant(0, SDLoc(Op)));
10340   };
10341 
10342   // At each stage, we're looking for something that looks like:
10343   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10344   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10345   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10346   // %a = binop <8 x i32> %op, %s
10347   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10348   // we expect something like:
10349   // <4,5,6,7,u,u,u,u>
10350   // <2,3,u,u,u,u,u,u>
10351   // <1,u,u,u,u,u,u,u>
10352   // While a partial reduction match would be:
10353   // <2,3,u,u,u,u,u,u>
10354   // <1,u,u,u,u,u,u,u>
10355   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10356   SDValue PrevOp;
10357   for (unsigned i = 0; i < Stages; ++i) {
10358     unsigned MaskEnd = (1 << i);
10359 
10360     if (Op.getOpcode() != CandidateBinOp)
10361       return PartialReduction(PrevOp, MaskEnd);
10362 
10363     SDValue Op0 = Op.getOperand(0);
10364     SDValue Op1 = Op.getOperand(1);
10365 
10366     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10367     if (Shuffle) {
10368       Op = Op1;
10369     } else {
10370       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10371       Op = Op0;
10372     }
10373 
10374     // The first operand of the shuffle should be the same as the other operand
10375     // of the binop.
10376     if (!Shuffle || Shuffle->getOperand(0) != Op)
10377       return PartialReduction(PrevOp, MaskEnd);
10378 
10379     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10380     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10381       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10382         return PartialReduction(PrevOp, MaskEnd);
10383 
10384     PrevOp = Op;
10385   }
10386 
10387   // Handle subvector reductions, which tend to appear after the shuffle
10388   // reduction stages.
10389   while (Op.getOpcode() == CandidateBinOp) {
10390     unsigned NumElts = Op.getValueType().getVectorNumElements();
10391     SDValue Op0 = Op.getOperand(0);
10392     SDValue Op1 = Op.getOperand(1);
10393     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10394         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10395         Op0.getOperand(0) != Op1.getOperand(0))
10396       break;
10397     SDValue Src = Op0.getOperand(0);
10398     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10399     if (NumSrcElts != (2 * NumElts))
10400       break;
10401     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10402           Op1.getConstantOperandAPInt(1) == NumElts) &&
10403         !(Op1.getConstantOperandAPInt(1) == 0 &&
10404           Op0.getConstantOperandAPInt(1) == NumElts))
10405       break;
10406     Op = Src;
10407   }
10408 
10409   BinOp = (ISD::NodeType)CandidateBinOp;
10410   return Op;
10411 }
10412 
10413 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10414   assert(N->getNumValues() == 1 &&
10415          "Can't unroll a vector with multiple results!");
10416 
10417   EVT VT = N->getValueType(0);
10418   unsigned NE = VT.getVectorNumElements();
10419   EVT EltVT = VT.getVectorElementType();
10420   SDLoc dl(N);
10421 
10422   SmallVector<SDValue, 8> Scalars;
10423   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10424 
10425   // If ResNE is 0, fully unroll the vector op.
10426   if (ResNE == 0)
10427     ResNE = NE;
10428   else if (NE > ResNE)
10429     NE = ResNE;
10430 
10431   unsigned i;
10432   for (i= 0; i != NE; ++i) {
10433     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10434       SDValue Operand = N->getOperand(j);
10435       EVT OperandVT = Operand.getValueType();
10436       if (OperandVT.isVector()) {
10437         // A vector operand; extract a single element.
10438         EVT OperandEltVT = OperandVT.getVectorElementType();
10439         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10440                               Operand, getVectorIdxConstant(i, dl));
10441       } else {
10442         // A scalar operand; just use it as is.
10443         Operands[j] = Operand;
10444       }
10445     }
10446 
10447     switch (N->getOpcode()) {
10448     default: {
10449       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10450                                 N->getFlags()));
10451       break;
10452     }
10453     case ISD::VSELECT:
10454       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10455       break;
10456     case ISD::SHL:
10457     case ISD::SRA:
10458     case ISD::SRL:
10459     case ISD::ROTL:
10460     case ISD::ROTR:
10461       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10462                                getShiftAmountOperand(Operands[0].getValueType(),
10463                                                      Operands[1])));
10464       break;
10465     case ISD::SIGN_EXTEND_INREG: {
10466       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10467       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10468                                 Operands[0],
10469                                 getValueType(ExtVT)));
10470     }
10471     }
10472   }
10473 
10474   for (; i < ResNE; ++i)
10475     Scalars.push_back(getUNDEF(EltVT));
10476 
10477   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10478   return getBuildVector(VecVT, dl, Scalars);
10479 }
10480 
10481 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10482     SDNode *N, unsigned ResNE) {
10483   unsigned Opcode = N->getOpcode();
10484   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10485           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10486           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10487          "Expected an overflow opcode");
10488 
10489   EVT ResVT = N->getValueType(0);
10490   EVT OvVT = N->getValueType(1);
10491   EVT ResEltVT = ResVT.getVectorElementType();
10492   EVT OvEltVT = OvVT.getVectorElementType();
10493   SDLoc dl(N);
10494 
10495   // If ResNE is 0, fully unroll the vector op.
10496   unsigned NE = ResVT.getVectorNumElements();
10497   if (ResNE == 0)
10498     ResNE = NE;
10499   else if (NE > ResNE)
10500     NE = ResNE;
10501 
10502   SmallVector<SDValue, 8> LHSScalars;
10503   SmallVector<SDValue, 8> RHSScalars;
10504   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10505   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10506 
10507   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10508   SDVTList VTs = getVTList(ResEltVT, SVT);
10509   SmallVector<SDValue, 8> ResScalars;
10510   SmallVector<SDValue, 8> OvScalars;
10511   for (unsigned i = 0; i < NE; ++i) {
10512     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10513     SDValue Ov =
10514         getSelect(dl, OvEltVT, Res.getValue(1),
10515                   getBoolConstant(true, dl, OvEltVT, ResVT),
10516                   getConstant(0, dl, OvEltVT));
10517 
10518     ResScalars.push_back(Res);
10519     OvScalars.push_back(Ov);
10520   }
10521 
10522   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10523   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10524 
10525   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10526   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10527   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10528                         getBuildVector(NewOvVT, dl, OvScalars));
10529 }
10530 
10531 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10532                                                   LoadSDNode *Base,
10533                                                   unsigned Bytes,
10534                                                   int Dist) const {
10535   if (LD->isVolatile() || Base->isVolatile())
10536     return false;
10537   // TODO: probably too restrictive for atomics, revisit
10538   if (!LD->isSimple())
10539     return false;
10540   if (LD->isIndexed() || Base->isIndexed())
10541     return false;
10542   if (LD->getChain() != Base->getChain())
10543     return false;
10544   EVT VT = LD->getValueType(0);
10545   if (VT.getSizeInBits() / 8 != Bytes)
10546     return false;
10547 
10548   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10549   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10550 
10551   int64_t Offset = 0;
10552   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10553     return (Dist * Bytes == Offset);
10554   return false;
10555 }
10556 
10557 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10558 /// if it cannot be inferred.
10559 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10560   // If this is a GlobalAddress + cst, return the alignment.
10561   const GlobalValue *GV = nullptr;
10562   int64_t GVOffset = 0;
10563   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10564     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10565     KnownBits Known(PtrWidth);
10566     llvm::computeKnownBits(GV, Known, getDataLayout());
10567     unsigned AlignBits = Known.countMinTrailingZeros();
10568     if (AlignBits)
10569       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10570   }
10571 
10572   // If this is a direct reference to a stack slot, use information about the
10573   // stack slot's alignment.
10574   int FrameIdx = INT_MIN;
10575   int64_t FrameOffset = 0;
10576   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10577     FrameIdx = FI->getIndex();
10578   } else if (isBaseWithConstantOffset(Ptr) &&
10579              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10580     // Handle FI+Cst
10581     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10582     FrameOffset = Ptr.getConstantOperandVal(1);
10583   }
10584 
10585   if (FrameIdx != INT_MIN) {
10586     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10587     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10588   }
10589 
10590   return None;
10591 }
10592 
10593 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10594 /// which is split (or expanded) into two not necessarily identical pieces.
10595 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10596   // Currently all types are split in half.
10597   EVT LoVT, HiVT;
10598   if (!VT.isVector())
10599     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10600   else
10601     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10602 
10603   return std::make_pair(LoVT, HiVT);
10604 }
10605 
10606 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10607 /// type, dependent on an enveloping VT that has been split into two identical
10608 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10609 std::pair<EVT, EVT>
10610 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10611                                        bool *HiIsEmpty) const {
10612   EVT EltTp = VT.getVectorElementType();
10613   // Examples:
10614   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10615   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10616   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10617   //   etc.
10618   ElementCount VTNumElts = VT.getVectorElementCount();
10619   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10620   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10621          "Mixing fixed width and scalable vectors when enveloping a type");
10622   EVT LoVT, HiVT;
10623   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10624     LoVT = EnvVT;
10625     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10626     *HiIsEmpty = false;
10627   } else {
10628     // Flag that hi type has zero storage size, but return split envelop type
10629     // (this would be easier if vector types with zero elements were allowed).
10630     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10631     HiVT = EnvVT;
10632     *HiIsEmpty = true;
10633   }
10634   return std::make_pair(LoVT, HiVT);
10635 }
10636 
10637 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10638 /// low/high part.
10639 std::pair<SDValue, SDValue>
10640 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10641                           const EVT &HiVT) {
10642   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10643          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10644          "Splitting vector with an invalid mixture of fixed and scalable "
10645          "vector types");
10646   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10647              N.getValueType().getVectorMinNumElements() &&
10648          "More vector elements requested than available!");
10649   SDValue Lo, Hi;
10650   Lo =
10651       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10652   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10653   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10654   // IDX with the runtime scaling factor of the result vector type. For
10655   // fixed-width result vectors, that runtime scaling factor is 1.
10656   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10657                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10658   return std::make_pair(Lo, Hi);
10659 }
10660 
10661 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10662 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10663   EVT VT = N.getValueType();
10664   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10665                                 NextPowerOf2(VT.getVectorNumElements()));
10666   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10667                  getVectorIdxConstant(0, DL));
10668 }
10669 
10670 void SelectionDAG::ExtractVectorElements(SDValue Op,
10671                                          SmallVectorImpl<SDValue> &Args,
10672                                          unsigned Start, unsigned Count,
10673                                          EVT EltVT) {
10674   EVT VT = Op.getValueType();
10675   if (Count == 0)
10676     Count = VT.getVectorNumElements();
10677   if (EltVT == EVT())
10678     EltVT = VT.getVectorElementType();
10679   SDLoc SL(Op);
10680   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10681     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10682                            getVectorIdxConstant(i, SL)));
10683   }
10684 }
10685 
10686 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10687 unsigned GlobalAddressSDNode::getAddressSpace() const {
10688   return getGlobal()->getType()->getAddressSpace();
10689 }
10690 
10691 Type *ConstantPoolSDNode::getType() const {
10692   if (isMachineConstantPoolEntry())
10693     return Val.MachineCPVal->getType();
10694   return Val.ConstVal->getType();
10695 }
10696 
10697 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10698                                         unsigned &SplatBitSize,
10699                                         bool &HasAnyUndefs,
10700                                         unsigned MinSplatBits,
10701                                         bool IsBigEndian) const {
10702   EVT VT = getValueType(0);
10703   assert(VT.isVector() && "Expected a vector type");
10704   unsigned VecWidth = VT.getSizeInBits();
10705   if (MinSplatBits > VecWidth)
10706     return false;
10707 
10708   // FIXME: The widths are based on this node's type, but build vectors can
10709   // truncate their operands.
10710   SplatValue = APInt(VecWidth, 0);
10711   SplatUndef = APInt(VecWidth, 0);
10712 
10713   // Get the bits. Bits with undefined values (when the corresponding element
10714   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10715   // in SplatValue. If any of the values are not constant, give up and return
10716   // false.
10717   unsigned int NumOps = getNumOperands();
10718   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10719   unsigned EltWidth = VT.getScalarSizeInBits();
10720 
10721   for (unsigned j = 0; j < NumOps; ++j) {
10722     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10723     SDValue OpVal = getOperand(i);
10724     unsigned BitPos = j * EltWidth;
10725 
10726     if (OpVal.isUndef())
10727       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10728     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10729       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10730     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10731       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10732     else
10733       return false;
10734   }
10735 
10736   // The build_vector is all constants or undefs. Find the smallest element
10737   // size that splats the vector.
10738   HasAnyUndefs = (SplatUndef != 0);
10739 
10740   // FIXME: This does not work for vectors with elements less than 8 bits.
10741   while (VecWidth > 8) {
10742     unsigned HalfSize = VecWidth / 2;
10743     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10744     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10745     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10746     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10747 
10748     // If the two halves do not match (ignoring undef bits), stop here.
10749     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10750         MinSplatBits > HalfSize)
10751       break;
10752 
10753     SplatValue = HighValue | LowValue;
10754     SplatUndef = HighUndef & LowUndef;
10755 
10756     VecWidth = HalfSize;
10757   }
10758 
10759   SplatBitSize = VecWidth;
10760   return true;
10761 }
10762 
10763 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10764                                          BitVector *UndefElements) const {
10765   unsigned NumOps = getNumOperands();
10766   if (UndefElements) {
10767     UndefElements->clear();
10768     UndefElements->resize(NumOps);
10769   }
10770   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10771   if (!DemandedElts)
10772     return SDValue();
10773   SDValue Splatted;
10774   for (unsigned i = 0; i != NumOps; ++i) {
10775     if (!DemandedElts[i])
10776       continue;
10777     SDValue Op = getOperand(i);
10778     if (Op.isUndef()) {
10779       if (UndefElements)
10780         (*UndefElements)[i] = true;
10781     } else if (!Splatted) {
10782       Splatted = Op;
10783     } else if (Splatted != Op) {
10784       return SDValue();
10785     }
10786   }
10787 
10788   if (!Splatted) {
10789     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10790     assert(getOperand(FirstDemandedIdx).isUndef() &&
10791            "Can only have a splat without a constant for all undefs.");
10792     return getOperand(FirstDemandedIdx);
10793   }
10794 
10795   return Splatted;
10796 }
10797 
10798 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10799   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10800   return getSplatValue(DemandedElts, UndefElements);
10801 }
10802 
10803 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10804                                             SmallVectorImpl<SDValue> &Sequence,
10805                                             BitVector *UndefElements) const {
10806   unsigned NumOps = getNumOperands();
10807   Sequence.clear();
10808   if (UndefElements) {
10809     UndefElements->clear();
10810     UndefElements->resize(NumOps);
10811   }
10812   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10813   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10814     return false;
10815 
10816   // Set the undefs even if we don't find a sequence (like getSplatValue).
10817   if (UndefElements)
10818     for (unsigned I = 0; I != NumOps; ++I)
10819       if (DemandedElts[I] && getOperand(I).isUndef())
10820         (*UndefElements)[I] = true;
10821 
10822   // Iteratively widen the sequence length looking for repetitions.
10823   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10824     Sequence.append(SeqLen, SDValue());
10825     for (unsigned I = 0; I != NumOps; ++I) {
10826       if (!DemandedElts[I])
10827         continue;
10828       SDValue &SeqOp = Sequence[I % SeqLen];
10829       SDValue Op = getOperand(I);
10830       if (Op.isUndef()) {
10831         if (!SeqOp)
10832           SeqOp = Op;
10833         continue;
10834       }
10835       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10836         Sequence.clear();
10837         break;
10838       }
10839       SeqOp = Op;
10840     }
10841     if (!Sequence.empty())
10842       return true;
10843   }
10844 
10845   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10846   return false;
10847 }
10848 
10849 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10850                                             BitVector *UndefElements) const {
10851   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10852   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10853 }
10854 
10855 ConstantSDNode *
10856 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10857                                         BitVector *UndefElements) const {
10858   return dyn_cast_or_null<ConstantSDNode>(
10859       getSplatValue(DemandedElts, UndefElements));
10860 }
10861 
10862 ConstantSDNode *
10863 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10864   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10865 }
10866 
10867 ConstantFPSDNode *
10868 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10869                                           BitVector *UndefElements) const {
10870   return dyn_cast_or_null<ConstantFPSDNode>(
10871       getSplatValue(DemandedElts, UndefElements));
10872 }
10873 
10874 ConstantFPSDNode *
10875 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10876   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10877 }
10878 
10879 int32_t
10880 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10881                                                    uint32_t BitWidth) const {
10882   if (ConstantFPSDNode *CN =
10883           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10884     bool IsExact;
10885     APSInt IntVal(BitWidth);
10886     const APFloat &APF = CN->getValueAPF();
10887     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10888             APFloat::opOK ||
10889         !IsExact)
10890       return -1;
10891 
10892     return IntVal.exactLogBase2();
10893   }
10894   return -1;
10895 }
10896 
10897 bool BuildVectorSDNode::isConstant() const {
10898   for (const SDValue &Op : op_values()) {
10899     unsigned Opc = Op.getOpcode();
10900     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10901       return false;
10902   }
10903   return true;
10904 }
10905 
10906 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10907   // Find the first non-undef value in the shuffle mask.
10908   unsigned i, e;
10909   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10910     /* search */;
10911 
10912   // If all elements are undefined, this shuffle can be considered a splat
10913   // (although it should eventually get simplified away completely).
10914   if (i == e)
10915     return true;
10916 
10917   // Make sure all remaining elements are either undef or the same as the first
10918   // non-undef value.
10919   for (int Idx = Mask[i]; i != e; ++i)
10920     if (Mask[i] >= 0 && Mask[i] != Idx)
10921       return false;
10922   return true;
10923 }
10924 
10925 // Returns the SDNode if it is a constant integer BuildVector
10926 // or constant integer.
10927 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10928   if (isa<ConstantSDNode>(N))
10929     return N.getNode();
10930   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10931     return N.getNode();
10932   // Treat a GlobalAddress supporting constant offset folding as a
10933   // constant integer.
10934   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10935     if (GA->getOpcode() == ISD::GlobalAddress &&
10936         TLI->isOffsetFoldingLegal(GA))
10937       return GA;
10938   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10939       isa<ConstantSDNode>(N.getOperand(0)))
10940     return N.getNode();
10941   return nullptr;
10942 }
10943 
10944 // Returns the SDNode if it is a constant float BuildVector
10945 // or constant float.
10946 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10947   if (isa<ConstantFPSDNode>(N))
10948     return N.getNode();
10949 
10950   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10951     return N.getNode();
10952 
10953   return nullptr;
10954 }
10955 
10956 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10957   assert(!Node->OperandList && "Node already has operands");
10958   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
10959          "too many operands to fit into SDNode");
10960   SDUse *Ops = OperandRecycler.allocate(
10961       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10962 
10963   bool IsDivergent = false;
10964   for (unsigned I = 0; I != Vals.size(); ++I) {
10965     Ops[I].setUser(Node);
10966     Ops[I].setInitial(Vals[I]);
10967     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10968       IsDivergent |= Ops[I].getNode()->isDivergent();
10969   }
10970   Node->NumOperands = Vals.size();
10971   Node->OperandList = Ops;
10972   if (!TLI->isSDNodeAlwaysUniform(Node)) {
10973     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10974     Node->SDNodeBits.IsDivergent = IsDivergent;
10975   }
10976   checkForCycles(Node);
10977 }
10978 
10979 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10980                                      SmallVectorImpl<SDValue> &Vals) {
10981   size_t Limit = SDNode::getMaxNumOperands();
10982   while (Vals.size() > Limit) {
10983     unsigned SliceIdx = Vals.size() - Limit;
10984     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
10985     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
10986     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
10987     Vals.emplace_back(NewTF);
10988   }
10989   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
10990 }
10991 
10992 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
10993                                         EVT VT, SDNodeFlags Flags) {
10994   switch (Opcode) {
10995   default:
10996     return SDValue();
10997   case ISD::ADD:
10998   case ISD::OR:
10999   case ISD::XOR:
11000   case ISD::UMAX:
11001     return getConstant(0, DL, VT);
11002   case ISD::MUL:
11003     return getConstant(1, DL, VT);
11004   case ISD::AND:
11005   case ISD::UMIN:
11006     return getAllOnesConstant(DL, VT);
11007   case ISD::SMAX:
11008     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11009   case ISD::SMIN:
11010     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11011   case ISD::FADD:
11012     return getConstantFP(-0.0, DL, VT);
11013   case ISD::FMUL:
11014     return getConstantFP(1.0, DL, VT);
11015   case ISD::FMINNUM:
11016   case ISD::FMAXNUM: {
11017     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11018     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11019     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11020                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11021                         APFloat::getLargest(Semantics);
11022     if (Opcode == ISD::FMAXNUM)
11023       NeutralAF.changeSign();
11024 
11025     return getConstantFP(NeutralAF, DL, VT);
11026   }
11027   }
11028 }
11029 
11030 #ifndef NDEBUG
11031 static void checkForCyclesHelper(const SDNode *N,
11032                                  SmallPtrSetImpl<const SDNode*> &Visited,
11033                                  SmallPtrSetImpl<const SDNode*> &Checked,
11034                                  const llvm::SelectionDAG *DAG) {
11035   // If this node has already been checked, don't check it again.
11036   if (Checked.count(N))
11037     return;
11038 
11039   // If a node has already been visited on this depth-first walk, reject it as
11040   // a cycle.
11041   if (!Visited.insert(N).second) {
11042     errs() << "Detected cycle in SelectionDAG\n";
11043     dbgs() << "Offending node:\n";
11044     N->dumprFull(DAG); dbgs() << "\n";
11045     abort();
11046   }
11047 
11048   for (const SDValue &Op : N->op_values())
11049     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11050 
11051   Checked.insert(N);
11052   Visited.erase(N);
11053 }
11054 #endif
11055 
11056 void llvm::checkForCycles(const llvm::SDNode *N,
11057                           const llvm::SelectionDAG *DAG,
11058                           bool force) {
11059 #ifndef NDEBUG
11060   bool check = force;
11061 #ifdef EXPENSIVE_CHECKS
11062   check = true;
11063 #endif  // EXPENSIVE_CHECKS
11064   if (check) {
11065     assert(N && "Checking nonexistent SDNode");
11066     SmallPtrSet<const SDNode*, 32> visited;
11067     SmallPtrSet<const SDNode*, 32> checked;
11068     checkForCyclesHelper(N, visited, checked, DAG);
11069   }
11070 #endif  // !NDEBUG
11071 }
11072 
11073 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11074   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11075 }
11076