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 (ISD::BUILD_VECTOR != LHS.getOpcode() ||
346       ISD::BUILD_VECTOR != RHS.getOpcode())
347     return false;
348 
349   EVT SVT = LHS.getValueType().getScalarType();
350   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
351     SDValue LHSOp = LHS.getOperand(i);
352     SDValue RHSOp = RHS.getOperand(i);
353     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
354     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
355     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
356     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
357     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
358       return false;
359     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
360                                LHSOp.getValueType() != RHSOp.getValueType()))
361       return false;
362     if (!Match(LHSCst, RHSCst))
363       return false;
364   }
365   return true;
366 }
367 
368 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
369   switch (VecReduceOpcode) {
370   default:
371     llvm_unreachable("Expected VECREDUCE opcode");
372   case ISD::VECREDUCE_FADD:
373   case ISD::VECREDUCE_SEQ_FADD:
374     return ISD::FADD;
375   case ISD::VECREDUCE_FMUL:
376   case ISD::VECREDUCE_SEQ_FMUL:
377     return ISD::FMUL;
378   case ISD::VECREDUCE_ADD:
379     return ISD::ADD;
380   case ISD::VECREDUCE_MUL:
381     return ISD::MUL;
382   case ISD::VECREDUCE_AND:
383     return ISD::AND;
384   case ISD::VECREDUCE_OR:
385     return ISD::OR;
386   case ISD::VECREDUCE_XOR:
387     return ISD::XOR;
388   case ISD::VECREDUCE_SMAX:
389     return ISD::SMAX;
390   case ISD::VECREDUCE_SMIN:
391     return ISD::SMIN;
392   case ISD::VECREDUCE_UMAX:
393     return ISD::UMAX;
394   case ISD::VECREDUCE_UMIN:
395     return ISD::UMIN;
396   case ISD::VECREDUCE_FMAX:
397     return ISD::FMAXNUM;
398   case ISD::VECREDUCE_FMIN:
399     return ISD::FMINNUM;
400   }
401 }
402 
403 bool ISD::isVPOpcode(unsigned Opcode) {
404   switch (Opcode) {
405   default:
406     return false;
407 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
408   case ISD::SDOPC:                                                             \
409     return true;
410 #include "llvm/IR/VPIntrinsics.def"
411   }
412 }
413 
414 /// The operand position of the vector mask.
415 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
416   switch (Opcode) {
417   default:
418     return None;
419 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...)        \
420   case ISD::SDOPC:                                                             \
421     return MASKPOS;
422 #include "llvm/IR/VPIntrinsics.def"
423   }
424 }
425 
426 /// The operand position of the explicit vector length parameter.
427 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
428   switch (Opcode) {
429   default:
430     return None;
431 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS)     \
432   case ISD::SDOPC:                                                             \
433     return EVLPOS;
434 #include "llvm/IR/VPIntrinsics.def"
435   }
436 }
437 
438 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
439   switch (ExtType) {
440   case ISD::EXTLOAD:
441     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
442   case ISD::SEXTLOAD:
443     return ISD::SIGN_EXTEND;
444   case ISD::ZEXTLOAD:
445     return ISD::ZERO_EXTEND;
446   default:
447     break;
448   }
449 
450   llvm_unreachable("Invalid LoadExtType");
451 }
452 
453 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
454   // To perform this operation, we just need to swap the L and G bits of the
455   // operation.
456   unsigned OldL = (Operation >> 2) & 1;
457   unsigned OldG = (Operation >> 1) & 1;
458   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
459                        (OldL << 1) |       // New G bit
460                        (OldG << 2));       // New L bit.
461 }
462 
463 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
464   unsigned Operation = Op;
465   if (isIntegerLike)
466     Operation ^= 7;   // Flip L, G, E bits, but not U.
467   else
468     Operation ^= 15;  // Flip all of the condition bits.
469 
470   if (Operation > ISD::SETTRUE2)
471     Operation &= ~8;  // Don't let N and U bits get set.
472 
473   return ISD::CondCode(Operation);
474 }
475 
476 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
477   return getSetCCInverseImpl(Op, Type.isInteger());
478 }
479 
480 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
481                                                bool isIntegerLike) {
482   return getSetCCInverseImpl(Op, isIntegerLike);
483 }
484 
485 /// For an integer comparison, return 1 if the comparison is a signed operation
486 /// and 2 if the result is an unsigned comparison. Return zero if the operation
487 /// does not depend on the sign of the input (setne and seteq).
488 static int isSignedOp(ISD::CondCode Opcode) {
489   switch (Opcode) {
490   default: llvm_unreachable("Illegal integer setcc operation!");
491   case ISD::SETEQ:
492   case ISD::SETNE: return 0;
493   case ISD::SETLT:
494   case ISD::SETLE:
495   case ISD::SETGT:
496   case ISD::SETGE: return 1;
497   case ISD::SETULT:
498   case ISD::SETULE:
499   case ISD::SETUGT:
500   case ISD::SETUGE: return 2;
501   }
502 }
503 
504 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
505                                        EVT Type) {
506   bool IsInteger = Type.isInteger();
507   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
508     // Cannot fold a signed integer setcc with an unsigned integer setcc.
509     return ISD::SETCC_INVALID;
510 
511   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
512 
513   // If the N and U bits get set, then the resultant comparison DOES suddenly
514   // care about orderedness, and it is true when ordered.
515   if (Op > ISD::SETTRUE2)
516     Op &= ~16;     // Clear the U bit if the N bit is set.
517 
518   // Canonicalize illegal integer setcc's.
519   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
520     Op = ISD::SETNE;
521 
522   return ISD::CondCode(Op);
523 }
524 
525 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
526                                         EVT Type) {
527   bool IsInteger = Type.isInteger();
528   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
529     // Cannot fold a signed setcc with an unsigned setcc.
530     return ISD::SETCC_INVALID;
531 
532   // Combine all of the condition bits.
533   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
534 
535   // Canonicalize illegal integer setcc's.
536   if (IsInteger) {
537     switch (Result) {
538     default: break;
539     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
540     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
541     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
542     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
543     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
544     }
545   }
546 
547   return Result;
548 }
549 
550 //===----------------------------------------------------------------------===//
551 //                           SDNode Profile Support
552 //===----------------------------------------------------------------------===//
553 
554 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
555 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
556   ID.AddInteger(OpC);
557 }
558 
559 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
560 /// solely with their pointer.
561 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
562   ID.AddPointer(VTList.VTs);
563 }
564 
565 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
566 static void AddNodeIDOperands(FoldingSetNodeID &ID,
567                               ArrayRef<SDValue> Ops) {
568   for (auto& Op : Ops) {
569     ID.AddPointer(Op.getNode());
570     ID.AddInteger(Op.getResNo());
571   }
572 }
573 
574 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
575 static void AddNodeIDOperands(FoldingSetNodeID &ID,
576                               ArrayRef<SDUse> Ops) {
577   for (auto& Op : Ops) {
578     ID.AddPointer(Op.getNode());
579     ID.AddInteger(Op.getResNo());
580   }
581 }
582 
583 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
584                           SDVTList VTList, ArrayRef<SDValue> OpList) {
585   AddNodeIDOpcode(ID, OpC);
586   AddNodeIDValueTypes(ID, VTList);
587   AddNodeIDOperands(ID, OpList);
588 }
589 
590 /// If this is an SDNode with special info, add this info to the NodeID data.
591 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
592   switch (N->getOpcode()) {
593   case ISD::TargetExternalSymbol:
594   case ISD::ExternalSymbol:
595   case ISD::MCSymbol:
596     llvm_unreachable("Should only be used on nodes with operands");
597   default: break;  // Normal nodes don't need extra info.
598   case ISD::TargetConstant:
599   case ISD::Constant: {
600     const ConstantSDNode *C = cast<ConstantSDNode>(N);
601     ID.AddPointer(C->getConstantIntValue());
602     ID.AddBoolean(C->isOpaque());
603     break;
604   }
605   case ISD::TargetConstantFP:
606   case ISD::ConstantFP:
607     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
608     break;
609   case ISD::TargetGlobalAddress:
610   case ISD::GlobalAddress:
611   case ISD::TargetGlobalTLSAddress:
612   case ISD::GlobalTLSAddress: {
613     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
614     ID.AddPointer(GA->getGlobal());
615     ID.AddInteger(GA->getOffset());
616     ID.AddInteger(GA->getTargetFlags());
617     break;
618   }
619   case ISD::BasicBlock:
620     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
621     break;
622   case ISD::Register:
623     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
624     break;
625   case ISD::RegisterMask:
626     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
627     break;
628   case ISD::SRCVALUE:
629     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
630     break;
631   case ISD::FrameIndex:
632   case ISD::TargetFrameIndex:
633     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
634     break;
635   case ISD::LIFETIME_START:
636   case ISD::LIFETIME_END:
637     if (cast<LifetimeSDNode>(N)->hasOffset()) {
638       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
639       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
640     }
641     break;
642   case ISD::PSEUDO_PROBE:
643     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
644     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
645     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
646     break;
647   case ISD::JumpTable:
648   case ISD::TargetJumpTable:
649     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
650     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
651     break;
652   case ISD::ConstantPool:
653   case ISD::TargetConstantPool: {
654     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
655     ID.AddInteger(CP->getAlign().value());
656     ID.AddInteger(CP->getOffset());
657     if (CP->isMachineConstantPoolEntry())
658       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
659     else
660       ID.AddPointer(CP->getConstVal());
661     ID.AddInteger(CP->getTargetFlags());
662     break;
663   }
664   case ISD::TargetIndex: {
665     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
666     ID.AddInteger(TI->getIndex());
667     ID.AddInteger(TI->getOffset());
668     ID.AddInteger(TI->getTargetFlags());
669     break;
670   }
671   case ISD::LOAD: {
672     const LoadSDNode *LD = cast<LoadSDNode>(N);
673     ID.AddInteger(LD->getMemoryVT().getRawBits());
674     ID.AddInteger(LD->getRawSubclassData());
675     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
676     break;
677   }
678   case ISD::STORE: {
679     const StoreSDNode *ST = cast<StoreSDNode>(N);
680     ID.AddInteger(ST->getMemoryVT().getRawBits());
681     ID.AddInteger(ST->getRawSubclassData());
682     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
683     break;
684   }
685   case ISD::MLOAD: {
686     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
687     ID.AddInteger(MLD->getMemoryVT().getRawBits());
688     ID.AddInteger(MLD->getRawSubclassData());
689     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
690     break;
691   }
692   case ISD::MSTORE: {
693     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
694     ID.AddInteger(MST->getMemoryVT().getRawBits());
695     ID.AddInteger(MST->getRawSubclassData());
696     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
697     break;
698   }
699   case ISD::MGATHER: {
700     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
701     ID.AddInteger(MG->getMemoryVT().getRawBits());
702     ID.AddInteger(MG->getRawSubclassData());
703     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
704     break;
705   }
706   case ISD::MSCATTER: {
707     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
708     ID.AddInteger(MS->getMemoryVT().getRawBits());
709     ID.AddInteger(MS->getRawSubclassData());
710     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
711     break;
712   }
713   case ISD::ATOMIC_CMP_SWAP:
714   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
715   case ISD::ATOMIC_SWAP:
716   case ISD::ATOMIC_LOAD_ADD:
717   case ISD::ATOMIC_LOAD_SUB:
718   case ISD::ATOMIC_LOAD_AND:
719   case ISD::ATOMIC_LOAD_CLR:
720   case ISD::ATOMIC_LOAD_OR:
721   case ISD::ATOMIC_LOAD_XOR:
722   case ISD::ATOMIC_LOAD_NAND:
723   case ISD::ATOMIC_LOAD_MIN:
724   case ISD::ATOMIC_LOAD_MAX:
725   case ISD::ATOMIC_LOAD_UMIN:
726   case ISD::ATOMIC_LOAD_UMAX:
727   case ISD::ATOMIC_LOAD:
728   case ISD::ATOMIC_STORE: {
729     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
730     ID.AddInteger(AT->getMemoryVT().getRawBits());
731     ID.AddInteger(AT->getRawSubclassData());
732     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
733     break;
734   }
735   case ISD::PREFETCH: {
736     const MemSDNode *PF = cast<MemSDNode>(N);
737     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
738     break;
739   }
740   case ISD::VECTOR_SHUFFLE: {
741     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
742     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
743          i != e; ++i)
744       ID.AddInteger(SVN->getMaskElt(i));
745     break;
746   }
747   case ISD::TargetBlockAddress:
748   case ISD::BlockAddress: {
749     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
750     ID.AddPointer(BA->getBlockAddress());
751     ID.AddInteger(BA->getOffset());
752     ID.AddInteger(BA->getTargetFlags());
753     break;
754   }
755   } // end switch (N->getOpcode())
756 
757   // Target specific memory nodes could also have address spaces to check.
758   if (N->isTargetMemoryOpcode())
759     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
760 }
761 
762 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
763 /// data.
764 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
765   AddNodeIDOpcode(ID, N->getOpcode());
766   // Add the return value info.
767   AddNodeIDValueTypes(ID, N->getVTList());
768   // Add the operand info.
769   AddNodeIDOperands(ID, N->ops());
770 
771   // Handle SDNode leafs with special info.
772   AddNodeIDCustom(ID, N);
773 }
774 
775 //===----------------------------------------------------------------------===//
776 //                              SelectionDAG Class
777 //===----------------------------------------------------------------------===//
778 
779 /// doNotCSE - Return true if CSE should not be performed for this node.
780 static bool doNotCSE(SDNode *N) {
781   if (N->getValueType(0) == MVT::Glue)
782     return true; // Never CSE anything that produces a flag.
783 
784   switch (N->getOpcode()) {
785   default: break;
786   case ISD::HANDLENODE:
787   case ISD::EH_LABEL:
788     return true;   // Never CSE these nodes.
789   }
790 
791   // Check that remaining values produced are not flags.
792   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
793     if (N->getValueType(i) == MVT::Glue)
794       return true; // Never CSE anything that produces a flag.
795 
796   return false;
797 }
798 
799 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
800 /// SelectionDAG.
801 void SelectionDAG::RemoveDeadNodes() {
802   // Create a dummy node (which is not added to allnodes), that adds a reference
803   // to the root node, preventing it from being deleted.
804   HandleSDNode Dummy(getRoot());
805 
806   SmallVector<SDNode*, 128> DeadNodes;
807 
808   // Add all obviously-dead nodes to the DeadNodes worklist.
809   for (SDNode &Node : allnodes())
810     if (Node.use_empty())
811       DeadNodes.push_back(&Node);
812 
813   RemoveDeadNodes(DeadNodes);
814 
815   // If the root changed (e.g. it was a dead load, update the root).
816   setRoot(Dummy.getValue());
817 }
818 
819 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
820 /// given list, and any nodes that become unreachable as a result.
821 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
822 
823   // Process the worklist, deleting the nodes and adding their uses to the
824   // worklist.
825   while (!DeadNodes.empty()) {
826     SDNode *N = DeadNodes.pop_back_val();
827     // Skip to next node if we've already managed to delete the node. This could
828     // happen if replacing a node causes a node previously added to the node to
829     // be deleted.
830     if (N->getOpcode() == ISD::DELETED_NODE)
831       continue;
832 
833     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
834       DUL->NodeDeleted(N, nullptr);
835 
836     // Take the node out of the appropriate CSE map.
837     RemoveNodeFromCSEMaps(N);
838 
839     // Next, brutally remove the operand list.  This is safe to do, as there are
840     // no cycles in the graph.
841     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
842       SDUse &Use = *I++;
843       SDNode *Operand = Use.getNode();
844       Use.set(SDValue());
845 
846       // Now that we removed this operand, see if there are no uses of it left.
847       if (Operand->use_empty())
848         DeadNodes.push_back(Operand);
849     }
850 
851     DeallocateNode(N);
852   }
853 }
854 
855 void SelectionDAG::RemoveDeadNode(SDNode *N){
856   SmallVector<SDNode*, 16> DeadNodes(1, N);
857 
858   // Create a dummy node that adds a reference to the root node, preventing
859   // it from being deleted.  (This matters if the root is an operand of the
860   // dead node.)
861   HandleSDNode Dummy(getRoot());
862 
863   RemoveDeadNodes(DeadNodes);
864 }
865 
866 void SelectionDAG::DeleteNode(SDNode *N) {
867   // First take this out of the appropriate CSE map.
868   RemoveNodeFromCSEMaps(N);
869 
870   // Finally, remove uses due to operands of this node, remove from the
871   // AllNodes list, and delete the node.
872   DeleteNodeNotInCSEMaps(N);
873 }
874 
875 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
876   assert(N->getIterator() != AllNodes.begin() &&
877          "Cannot delete the entry node!");
878   assert(N->use_empty() && "Cannot delete a node that is not dead!");
879 
880   // Drop all of the operands and decrement used node's use counts.
881   N->DropOperands();
882 
883   DeallocateNode(N);
884 }
885 
886 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
887   assert(!(V->isVariadic() && isParameter));
888   if (isParameter)
889     ByvalParmDbgValues.push_back(V);
890   else
891     DbgValues.push_back(V);
892   for (const SDNode *Node : V->getSDNodes())
893     if (Node)
894       DbgValMap[Node].push_back(V);
895 }
896 
897 void SDDbgInfo::erase(const SDNode *Node) {
898   DbgValMapType::iterator I = DbgValMap.find(Node);
899   if (I == DbgValMap.end())
900     return;
901   for (auto &Val: I->second)
902     Val->setIsInvalidated();
903   DbgValMap.erase(I);
904 }
905 
906 void SelectionDAG::DeallocateNode(SDNode *N) {
907   // If we have operands, deallocate them.
908   removeOperands(N);
909 
910   NodeAllocator.Deallocate(AllNodes.remove(N));
911 
912   // Set the opcode to DELETED_NODE to help catch bugs when node
913   // memory is reallocated.
914   // FIXME: There are places in SDag that have grown a dependency on the opcode
915   // value in the released node.
916   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
917   N->NodeType = ISD::DELETED_NODE;
918 
919   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
920   // them and forget about that node.
921   DbgInfo->erase(N);
922 }
923 
924 #ifndef NDEBUG
925 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
926 static void VerifySDNode(SDNode *N) {
927   switch (N->getOpcode()) {
928   default:
929     break;
930   case ISD::BUILD_PAIR: {
931     EVT VT = N->getValueType(0);
932     assert(N->getNumValues() == 1 && "Too many results!");
933     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
934            "Wrong return type!");
935     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
936     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
937            "Mismatched operand types!");
938     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
939            "Wrong operand type!");
940     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
941            "Wrong return type size");
942     break;
943   }
944   case ISD::BUILD_VECTOR: {
945     assert(N->getNumValues() == 1 && "Too many results!");
946     assert(N->getValueType(0).isVector() && "Wrong return type!");
947     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
948            "Wrong number of operands!");
949     EVT EltVT = N->getValueType(0).getVectorElementType();
950     for (const SDUse &Op : N->ops()) {
951       assert((Op.getValueType() == EltVT ||
952               (EltVT.isInteger() && Op.getValueType().isInteger() &&
953                EltVT.bitsLE(Op.getValueType()))) &&
954              "Wrong operand type!");
955       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
956              "Operands must all have the same type");
957     }
958     break;
959   }
960   }
961 }
962 #endif // NDEBUG
963 
964 /// Insert a newly allocated node into the DAG.
965 ///
966 /// Handles insertion into the all nodes list and CSE map, as well as
967 /// verification and other common operations when a new node is allocated.
968 void SelectionDAG::InsertNode(SDNode *N) {
969   AllNodes.push_back(N);
970 #ifndef NDEBUG
971   N->PersistentId = NextPersistentId++;
972   VerifySDNode(N);
973 #endif
974   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
975     DUL->NodeInserted(N);
976 }
977 
978 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
979 /// correspond to it.  This is useful when we're about to delete or repurpose
980 /// the node.  We don't want future request for structurally identical nodes
981 /// to return N anymore.
982 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
983   bool Erased = false;
984   switch (N->getOpcode()) {
985   case ISD::HANDLENODE: return false;  // noop.
986   case ISD::CONDCODE:
987     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
988            "Cond code doesn't exist!");
989     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
990     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
991     break;
992   case ISD::ExternalSymbol:
993     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
994     break;
995   case ISD::TargetExternalSymbol: {
996     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
997     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
998         ESN->getSymbol(), ESN->getTargetFlags()));
999     break;
1000   }
1001   case ISD::MCSymbol: {
1002     auto *MCSN = cast<MCSymbolSDNode>(N);
1003     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1004     break;
1005   }
1006   case ISD::VALUETYPE: {
1007     EVT VT = cast<VTSDNode>(N)->getVT();
1008     if (VT.isExtended()) {
1009       Erased = ExtendedValueTypeNodes.erase(VT);
1010     } else {
1011       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1012       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1013     }
1014     break;
1015   }
1016   default:
1017     // Remove it from the CSE Map.
1018     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1019     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1020     Erased = CSEMap.RemoveNode(N);
1021     break;
1022   }
1023 #ifndef NDEBUG
1024   // Verify that the node was actually in one of the CSE maps, unless it has a
1025   // flag result (which cannot be CSE'd) or is one of the special cases that are
1026   // not subject to CSE.
1027   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1028       !N->isMachineOpcode() && !doNotCSE(N)) {
1029     N->dump(this);
1030     dbgs() << "\n";
1031     llvm_unreachable("Node is not in map!");
1032   }
1033 #endif
1034   return Erased;
1035 }
1036 
1037 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1038 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1039 /// node already exists, in which case transfer all its users to the existing
1040 /// node. This transfer can potentially trigger recursive merging.
1041 void
1042 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1043   // For node types that aren't CSE'd, just act as if no identical node
1044   // already exists.
1045   if (!doNotCSE(N)) {
1046     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1047     if (Existing != N) {
1048       // If there was already an existing matching node, use ReplaceAllUsesWith
1049       // to replace the dead one with the existing one.  This can cause
1050       // recursive merging of other unrelated nodes down the line.
1051       ReplaceAllUsesWith(N, Existing);
1052 
1053       // N is now dead. Inform the listeners and delete it.
1054       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1055         DUL->NodeDeleted(N, Existing);
1056       DeleteNodeNotInCSEMaps(N);
1057       return;
1058     }
1059   }
1060 
1061   // If the node doesn't already exist, we updated it.  Inform listeners.
1062   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1063     DUL->NodeUpdated(N);
1064 }
1065 
1066 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1067 /// were replaced with those specified.  If this node is never memoized,
1068 /// return null, otherwise return a pointer to the slot it would take.  If a
1069 /// node already exists with these operands, the slot will be non-null.
1070 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1071                                            void *&InsertPos) {
1072   if (doNotCSE(N))
1073     return nullptr;
1074 
1075   SDValue Ops[] = { Op };
1076   FoldingSetNodeID ID;
1077   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1078   AddNodeIDCustom(ID, N);
1079   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1080   if (Node)
1081     Node->intersectFlagsWith(N->getFlags());
1082   return Node;
1083 }
1084 
1085 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1086 /// were replaced with those specified.  If this node is never memoized,
1087 /// return null, otherwise return a pointer to the slot it would take.  If a
1088 /// node already exists with these operands, the slot will be non-null.
1089 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1090                                            SDValue Op1, SDValue Op2,
1091                                            void *&InsertPos) {
1092   if (doNotCSE(N))
1093     return nullptr;
1094 
1095   SDValue Ops[] = { Op1, Op2 };
1096   FoldingSetNodeID ID;
1097   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1098   AddNodeIDCustom(ID, N);
1099   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1100   if (Node)
1101     Node->intersectFlagsWith(N->getFlags());
1102   return Node;
1103 }
1104 
1105 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1106 /// were replaced with those specified.  If this node is never memoized,
1107 /// return null, otherwise return a pointer to the slot it would take.  If a
1108 /// node already exists with these operands, the slot will be non-null.
1109 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1110                                            void *&InsertPos) {
1111   if (doNotCSE(N))
1112     return nullptr;
1113 
1114   FoldingSetNodeID ID;
1115   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1116   AddNodeIDCustom(ID, N);
1117   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1118   if (Node)
1119     Node->intersectFlagsWith(N->getFlags());
1120   return Node;
1121 }
1122 
1123 Align SelectionDAG::getEVTAlign(EVT VT) const {
1124   Type *Ty = VT == MVT::iPTR ?
1125                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1126                    VT.getTypeForEVT(*getContext());
1127 
1128   return getDataLayout().getABITypeAlign(Ty);
1129 }
1130 
1131 // EntryNode could meaningfully have debug info if we can find it...
1132 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1133     : TM(tm), OptLevel(OL),
1134       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1135       Root(getEntryNode()) {
1136   InsertNode(&EntryNode);
1137   DbgInfo = new SDDbgInfo();
1138 }
1139 
1140 void SelectionDAG::init(MachineFunction &NewMF,
1141                         OptimizationRemarkEmitter &NewORE,
1142                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1143                         LegacyDivergenceAnalysis * Divergence,
1144                         ProfileSummaryInfo *PSIin,
1145                         BlockFrequencyInfo *BFIin) {
1146   MF = &NewMF;
1147   SDAGISelPass = PassPtr;
1148   ORE = &NewORE;
1149   TLI = getSubtarget().getTargetLowering();
1150   TSI = getSubtarget().getSelectionDAGInfo();
1151   LibInfo = LibraryInfo;
1152   Context = &MF->getFunction().getContext();
1153   DA = Divergence;
1154   PSI = PSIin;
1155   BFI = BFIin;
1156 }
1157 
1158 SelectionDAG::~SelectionDAG() {
1159   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1160   allnodes_clear();
1161   OperandRecycler.clear(OperandAllocator);
1162   delete DbgInfo;
1163 }
1164 
1165 bool SelectionDAG::shouldOptForSize() const {
1166   return MF->getFunction().hasOptSize() ||
1167       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1168 }
1169 
1170 void SelectionDAG::allnodes_clear() {
1171   assert(&*AllNodes.begin() == &EntryNode);
1172   AllNodes.remove(AllNodes.begin());
1173   while (!AllNodes.empty())
1174     DeallocateNode(&AllNodes.front());
1175 #ifndef NDEBUG
1176   NextPersistentId = 0;
1177 #endif
1178 }
1179 
1180 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1181                                           void *&InsertPos) {
1182   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1183   if (N) {
1184     switch (N->getOpcode()) {
1185     default: break;
1186     case ISD::Constant:
1187     case ISD::ConstantFP:
1188       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1189                        "debug location.  Use another overload.");
1190     }
1191   }
1192   return N;
1193 }
1194 
1195 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1196                                           const SDLoc &DL, void *&InsertPos) {
1197   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1198   if (N) {
1199     switch (N->getOpcode()) {
1200     case ISD::Constant:
1201     case ISD::ConstantFP:
1202       // Erase debug location from the node if the node is used at several
1203       // different places. Do not propagate one location to all uses as it
1204       // will cause a worse single stepping debugging experience.
1205       if (N->getDebugLoc() != DL.getDebugLoc())
1206         N->setDebugLoc(DebugLoc());
1207       break;
1208     default:
1209       // When the node's point of use is located earlier in the instruction
1210       // sequence than its prior point of use, update its debug info to the
1211       // earlier location.
1212       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1213         N->setDebugLoc(DL.getDebugLoc());
1214       break;
1215     }
1216   }
1217   return N;
1218 }
1219 
1220 void SelectionDAG::clear() {
1221   allnodes_clear();
1222   OperandRecycler.clear(OperandAllocator);
1223   OperandAllocator.Reset();
1224   CSEMap.clear();
1225 
1226   ExtendedValueTypeNodes.clear();
1227   ExternalSymbols.clear();
1228   TargetExternalSymbols.clear();
1229   MCSymbols.clear();
1230   SDCallSiteDbgInfo.clear();
1231   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1232             static_cast<CondCodeSDNode*>(nullptr));
1233   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1234             static_cast<SDNode*>(nullptr));
1235 
1236   EntryNode.UseList = nullptr;
1237   InsertNode(&EntryNode);
1238   Root = getEntryNode();
1239   DbgInfo->clear();
1240 }
1241 
1242 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1243   return VT.bitsGT(Op.getValueType())
1244              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1245              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1246 }
1247 
1248 std::pair<SDValue, SDValue>
1249 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1250                                        const SDLoc &DL, EVT VT) {
1251   assert(!VT.bitsEq(Op.getValueType()) &&
1252          "Strict no-op FP extend/round not allowed.");
1253   SDValue Res =
1254       VT.bitsGT(Op.getValueType())
1255           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1256           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1257                     {Chain, Op, getIntPtrConstant(0, DL)});
1258 
1259   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1260 }
1261 
1262 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1263   return VT.bitsGT(Op.getValueType()) ?
1264     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1265     getNode(ISD::TRUNCATE, DL, VT, Op);
1266 }
1267 
1268 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1269   return VT.bitsGT(Op.getValueType()) ?
1270     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1271     getNode(ISD::TRUNCATE, DL, VT, Op);
1272 }
1273 
1274 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1275   return VT.bitsGT(Op.getValueType()) ?
1276     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1277     getNode(ISD::TRUNCATE, DL, VT, Op);
1278 }
1279 
1280 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1281                                         EVT OpVT) {
1282   if (VT.bitsLE(Op.getValueType()))
1283     return getNode(ISD::TRUNCATE, SL, VT, Op);
1284 
1285   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1286   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1287 }
1288 
1289 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1290   EVT OpVT = Op.getValueType();
1291   assert(VT.isInteger() && OpVT.isInteger() &&
1292          "Cannot getZeroExtendInReg FP types");
1293   assert(VT.isVector() == OpVT.isVector() &&
1294          "getZeroExtendInReg type should be vector iff the operand "
1295          "type is vector!");
1296   assert((!VT.isVector() ||
1297           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1298          "Vector element counts must match in getZeroExtendInReg");
1299   assert(VT.bitsLE(OpVT) && "Not extending!");
1300   if (OpVT == VT)
1301     return Op;
1302   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1303                                    VT.getScalarSizeInBits());
1304   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1305 }
1306 
1307 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1308   // Only unsigned pointer semantics are supported right now. In the future this
1309   // might delegate to TLI to check pointer signedness.
1310   return getZExtOrTrunc(Op, DL, VT);
1311 }
1312 
1313 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1314   // Only unsigned pointer semantics are supported right now. In the future this
1315   // might delegate to TLI to check pointer signedness.
1316   return getZeroExtendInReg(Op, DL, VT);
1317 }
1318 
1319 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1320 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1321   EVT EltVT = VT.getScalarType();
1322   SDValue NegOne =
1323     getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1324   return getNode(ISD::XOR, DL, VT, Val, NegOne);
1325 }
1326 
1327 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1328   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1329   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1330 }
1331 
1332 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1333                                       EVT OpVT) {
1334   if (!V)
1335     return getConstant(0, DL, VT);
1336 
1337   switch (TLI->getBooleanContents(OpVT)) {
1338   case TargetLowering::ZeroOrOneBooleanContent:
1339   case TargetLowering::UndefinedBooleanContent:
1340     return getConstant(1, DL, VT);
1341   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1342     return getAllOnesConstant(DL, VT);
1343   }
1344   llvm_unreachable("Unexpected boolean content enum!");
1345 }
1346 
1347 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1348                                   bool isT, bool isO) {
1349   EVT EltVT = VT.getScalarType();
1350   assert((EltVT.getSizeInBits() >= 64 ||
1351           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1352          "getConstant with a uint64_t value that doesn't fit in the type!");
1353   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1354 }
1355 
1356 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1357                                   bool isT, bool isO) {
1358   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1359 }
1360 
1361 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1362                                   EVT VT, bool isT, bool isO) {
1363   assert(VT.isInteger() && "Cannot create FP integer constant!");
1364 
1365   EVT EltVT = VT.getScalarType();
1366   const ConstantInt *Elt = &Val;
1367 
1368   // In some cases the vector type is legal but the element type is illegal and
1369   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1370   // inserted value (the type does not need to match the vector element type).
1371   // Any extra bits introduced will be truncated away.
1372   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1373                            TargetLowering::TypePromoteInteger) {
1374     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1375     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1376     Elt = ConstantInt::get(*getContext(), NewVal);
1377   }
1378   // In other cases the element type is illegal and needs to be expanded, for
1379   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1380   // the value into n parts and use a vector type with n-times the elements.
1381   // Then bitcast to the type requested.
1382   // Legalizing constants too early makes the DAGCombiner's job harder so we
1383   // only legalize if the DAG tells us we must produce legal types.
1384   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1385            TLI->getTypeAction(*getContext(), EltVT) ==
1386                TargetLowering::TypeExpandInteger) {
1387     const APInt &NewVal = Elt->getValue();
1388     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1389     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1390 
1391     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1392     if (VT.isScalableVector()) {
1393       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1394              "Can only handle an even split!");
1395       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1396 
1397       SmallVector<SDValue, 2> ScalarParts;
1398       for (unsigned i = 0; i != Parts; ++i)
1399         ScalarParts.push_back(getConstant(
1400             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1401             ViaEltVT, isT, isO));
1402 
1403       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1404     }
1405 
1406     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1407     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1408 
1409     // Check the temporary vector is the correct size. If this fails then
1410     // getTypeToTransformTo() probably returned a type whose size (in bits)
1411     // isn't a power-of-2 factor of the requested type size.
1412     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1413 
1414     SmallVector<SDValue, 2> EltParts;
1415     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1416       EltParts.push_back(getConstant(
1417           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1418           ViaEltVT, isT, isO));
1419 
1420     // EltParts is currently in little endian order. If we actually want
1421     // big-endian order then reverse it now.
1422     if (getDataLayout().isBigEndian())
1423       std::reverse(EltParts.begin(), EltParts.end());
1424 
1425     // The elements must be reversed when the element order is different
1426     // to the endianness of the elements (because the BITCAST is itself a
1427     // vector shuffle in this situation). However, we do not need any code to
1428     // perform this reversal because getConstant() is producing a vector
1429     // splat.
1430     // This situation occurs in MIPS MSA.
1431 
1432     SmallVector<SDValue, 8> Ops;
1433     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1434       llvm::append_range(Ops, EltParts);
1435 
1436     SDValue V =
1437         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1438     return V;
1439   }
1440 
1441   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1442          "APInt size does not match type size!");
1443   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1444   FoldingSetNodeID ID;
1445   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1446   ID.AddPointer(Elt);
1447   ID.AddBoolean(isO);
1448   void *IP = nullptr;
1449   SDNode *N = nullptr;
1450   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1451     if (!VT.isVector())
1452       return SDValue(N, 0);
1453 
1454   if (!N) {
1455     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1456     CSEMap.InsertNode(N, IP);
1457     InsertNode(N);
1458     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1459   }
1460 
1461   SDValue Result(N, 0);
1462   if (VT.isScalableVector())
1463     Result = getSplatVector(VT, DL, Result);
1464   else if (VT.isVector())
1465     Result = getSplatBuildVector(VT, DL, Result);
1466 
1467   return Result;
1468 }
1469 
1470 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1471                                         bool isTarget) {
1472   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1473 }
1474 
1475 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1476                                              const SDLoc &DL, bool LegalTypes) {
1477   assert(VT.isInteger() && "Shift amount is not an integer type!");
1478   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1479   return getConstant(Val, DL, ShiftVT);
1480 }
1481 
1482 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1483                                            bool isTarget) {
1484   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1485 }
1486 
1487 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1488                                     bool isTarget) {
1489   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1490 }
1491 
1492 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1493                                     EVT VT, bool isTarget) {
1494   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1495 
1496   EVT EltVT = VT.getScalarType();
1497 
1498   // Do the map lookup using the actual bit pattern for the floating point
1499   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1500   // we don't have issues with SNANs.
1501   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1502   FoldingSetNodeID ID;
1503   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1504   ID.AddPointer(&V);
1505   void *IP = nullptr;
1506   SDNode *N = nullptr;
1507   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1508     if (!VT.isVector())
1509       return SDValue(N, 0);
1510 
1511   if (!N) {
1512     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1513     CSEMap.InsertNode(N, IP);
1514     InsertNode(N);
1515   }
1516 
1517   SDValue Result(N, 0);
1518   if (VT.isScalableVector())
1519     Result = getSplatVector(VT, DL, Result);
1520   else if (VT.isVector())
1521     Result = getSplatBuildVector(VT, DL, Result);
1522   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1523   return Result;
1524 }
1525 
1526 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1527                                     bool isTarget) {
1528   EVT EltVT = VT.getScalarType();
1529   if (EltVT == MVT::f32)
1530     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1531   if (EltVT == MVT::f64)
1532     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1533   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1534       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1535     bool Ignored;
1536     APFloat APF = APFloat(Val);
1537     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1538                 &Ignored);
1539     return getConstantFP(APF, DL, VT, isTarget);
1540   }
1541   llvm_unreachable("Unsupported type in getConstantFP");
1542 }
1543 
1544 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1545                                        EVT VT, int64_t Offset, bool isTargetGA,
1546                                        unsigned TargetFlags) {
1547   assert((TargetFlags == 0 || isTargetGA) &&
1548          "Cannot set target flags on target-independent globals");
1549 
1550   // Truncate (with sign-extension) the offset value to the pointer size.
1551   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1552   if (BitWidth < 64)
1553     Offset = SignExtend64(Offset, BitWidth);
1554 
1555   unsigned Opc;
1556   if (GV->isThreadLocal())
1557     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1558   else
1559     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1560 
1561   FoldingSetNodeID ID;
1562   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1563   ID.AddPointer(GV);
1564   ID.AddInteger(Offset);
1565   ID.AddInteger(TargetFlags);
1566   void *IP = nullptr;
1567   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1568     return SDValue(E, 0);
1569 
1570   auto *N = newSDNode<GlobalAddressSDNode>(
1571       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1572   CSEMap.InsertNode(N, IP);
1573     InsertNode(N);
1574   return SDValue(N, 0);
1575 }
1576 
1577 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1578   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1579   FoldingSetNodeID ID;
1580   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1581   ID.AddInteger(FI);
1582   void *IP = nullptr;
1583   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1584     return SDValue(E, 0);
1585 
1586   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1587   CSEMap.InsertNode(N, IP);
1588   InsertNode(N);
1589   return SDValue(N, 0);
1590 }
1591 
1592 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1593                                    unsigned TargetFlags) {
1594   assert((TargetFlags == 0 || isTarget) &&
1595          "Cannot set target flags on target-independent jump tables");
1596   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1597   FoldingSetNodeID ID;
1598   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1599   ID.AddInteger(JTI);
1600   ID.AddInteger(TargetFlags);
1601   void *IP = nullptr;
1602   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1603     return SDValue(E, 0);
1604 
1605   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1606   CSEMap.InsertNode(N, IP);
1607   InsertNode(N);
1608   return SDValue(N, 0);
1609 }
1610 
1611 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1612                                       MaybeAlign Alignment, int Offset,
1613                                       bool isTarget, unsigned TargetFlags) {
1614   assert((TargetFlags == 0 || isTarget) &&
1615          "Cannot set target flags on target-independent globals");
1616   if (!Alignment)
1617     Alignment = shouldOptForSize()
1618                     ? getDataLayout().getABITypeAlign(C->getType())
1619                     : getDataLayout().getPrefTypeAlign(C->getType());
1620   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1621   FoldingSetNodeID ID;
1622   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1623   ID.AddInteger(Alignment->value());
1624   ID.AddInteger(Offset);
1625   ID.AddPointer(C);
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<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1632                                           TargetFlags);
1633   CSEMap.InsertNode(N, IP);
1634   InsertNode(N);
1635   SDValue V = SDValue(N, 0);
1636   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1637   return V;
1638 }
1639 
1640 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1641                                       MaybeAlign Alignment, int Offset,
1642                                       bool isTarget, unsigned TargetFlags) {
1643   assert((TargetFlags == 0 || isTarget) &&
1644          "Cannot set target flags on target-independent globals");
1645   if (!Alignment)
1646     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1647   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1648   FoldingSetNodeID ID;
1649   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1650   ID.AddInteger(Alignment->value());
1651   ID.AddInteger(Offset);
1652   C->addSelectionDAGCSEId(ID);
1653   ID.AddInteger(TargetFlags);
1654   void *IP = nullptr;
1655   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1656     return SDValue(E, 0);
1657 
1658   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1659                                           TargetFlags);
1660   CSEMap.InsertNode(N, IP);
1661   InsertNode(N);
1662   return SDValue(N, 0);
1663 }
1664 
1665 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1666                                      unsigned TargetFlags) {
1667   FoldingSetNodeID ID;
1668   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1669   ID.AddInteger(Index);
1670   ID.AddInteger(Offset);
1671   ID.AddInteger(TargetFlags);
1672   void *IP = nullptr;
1673   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1674     return SDValue(E, 0);
1675 
1676   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1677   CSEMap.InsertNode(N, IP);
1678   InsertNode(N);
1679   return SDValue(N, 0);
1680 }
1681 
1682 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1683   FoldingSetNodeID ID;
1684   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1685   ID.AddPointer(MBB);
1686   void *IP = nullptr;
1687   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1688     return SDValue(E, 0);
1689 
1690   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1691   CSEMap.InsertNode(N, IP);
1692   InsertNode(N);
1693   return SDValue(N, 0);
1694 }
1695 
1696 SDValue SelectionDAG::getValueType(EVT VT) {
1697   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1698       ValueTypeNodes.size())
1699     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1700 
1701   SDNode *&N = VT.isExtended() ?
1702     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1703 
1704   if (N) return SDValue(N, 0);
1705   N = newSDNode<VTSDNode>(VT);
1706   InsertNode(N);
1707   return SDValue(N, 0);
1708 }
1709 
1710 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1711   SDNode *&N = ExternalSymbols[Sym];
1712   if (N) return SDValue(N, 0);
1713   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1714   InsertNode(N);
1715   return SDValue(N, 0);
1716 }
1717 
1718 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1719   SDNode *&N = MCSymbols[Sym];
1720   if (N)
1721     return SDValue(N, 0);
1722   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1723   InsertNode(N);
1724   return SDValue(N, 0);
1725 }
1726 
1727 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1728                                               unsigned TargetFlags) {
1729   SDNode *&N =
1730       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1731   if (N) return SDValue(N, 0);
1732   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1733   InsertNode(N);
1734   return SDValue(N, 0);
1735 }
1736 
1737 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1738   if ((unsigned)Cond >= CondCodeNodes.size())
1739     CondCodeNodes.resize(Cond+1);
1740 
1741   if (!CondCodeNodes[Cond]) {
1742     auto *N = newSDNode<CondCodeSDNode>(Cond);
1743     CondCodeNodes[Cond] = N;
1744     InsertNode(N);
1745   }
1746 
1747   return SDValue(CondCodeNodes[Cond], 0);
1748 }
1749 
1750 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1751   EVT OpVT = TLI->getTypeToTransformTo(*getContext(), ResVT.getScalarType());
1752   return getStepVector(DL, ResVT, getConstant(1, DL, OpVT));
1753 }
1754 
1755 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, SDValue Step) {
1756   if (ResVT.isScalableVector())
1757     return getNode(ISD::STEP_VECTOR, DL, ResVT, Step);
1758 
1759   EVT OpVT = Step.getValueType();
1760   APInt StepVal = cast<ConstantSDNode>(Step)->getAPIntValue();
1761   SmallVector<SDValue, 16> OpsStepConstants;
1762   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1763     OpsStepConstants.push_back(getConstant(StepVal * i, DL, OpVT));
1764   return getBuildVector(ResVT, DL, OpsStepConstants);
1765 }
1766 
1767 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1768 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1769 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1770   std::swap(N1, N2);
1771   ShuffleVectorSDNode::commuteMask(M);
1772 }
1773 
1774 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1775                                        SDValue N2, ArrayRef<int> Mask) {
1776   assert(VT.getVectorNumElements() == Mask.size() &&
1777          "Must have the same number of vector elements as mask elements!");
1778   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1779          "Invalid VECTOR_SHUFFLE");
1780 
1781   // Canonicalize shuffle undef, undef -> undef
1782   if (N1.isUndef() && N2.isUndef())
1783     return getUNDEF(VT);
1784 
1785   // Validate that all indices in Mask are within the range of the elements
1786   // input to the shuffle.
1787   int NElts = Mask.size();
1788   assert(llvm::all_of(Mask,
1789                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1790          "Index out of range");
1791 
1792   // Copy the mask so we can do any needed cleanup.
1793   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1794 
1795   // Canonicalize shuffle v, v -> v, undef
1796   if (N1 == N2) {
1797     N2 = getUNDEF(VT);
1798     for (int i = 0; i != NElts; ++i)
1799       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1800   }
1801 
1802   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1803   if (N1.isUndef())
1804     commuteShuffle(N1, N2, MaskVec);
1805 
1806   if (TLI->hasVectorBlend()) {
1807     // If shuffling a splat, try to blend the splat instead. We do this here so
1808     // that even when this arises during lowering we don't have to re-handle it.
1809     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1810       BitVector UndefElements;
1811       SDValue Splat = BV->getSplatValue(&UndefElements);
1812       if (!Splat)
1813         return;
1814 
1815       for (int i = 0; i < NElts; ++i) {
1816         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1817           continue;
1818 
1819         // If this input comes from undef, mark it as such.
1820         if (UndefElements[MaskVec[i] - Offset]) {
1821           MaskVec[i] = -1;
1822           continue;
1823         }
1824 
1825         // If we can blend a non-undef lane, use that instead.
1826         if (!UndefElements[i])
1827           MaskVec[i] = i + Offset;
1828       }
1829     };
1830     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1831       BlendSplat(N1BV, 0);
1832     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1833       BlendSplat(N2BV, NElts);
1834   }
1835 
1836   // Canonicalize all index into lhs, -> shuffle lhs, undef
1837   // Canonicalize all index into rhs, -> shuffle rhs, undef
1838   bool AllLHS = true, AllRHS = true;
1839   bool N2Undef = N2.isUndef();
1840   for (int i = 0; i != NElts; ++i) {
1841     if (MaskVec[i] >= NElts) {
1842       if (N2Undef)
1843         MaskVec[i] = -1;
1844       else
1845         AllLHS = false;
1846     } else if (MaskVec[i] >= 0) {
1847       AllRHS = false;
1848     }
1849   }
1850   if (AllLHS && AllRHS)
1851     return getUNDEF(VT);
1852   if (AllLHS && !N2Undef)
1853     N2 = getUNDEF(VT);
1854   if (AllRHS) {
1855     N1 = getUNDEF(VT);
1856     commuteShuffle(N1, N2, MaskVec);
1857   }
1858   // Reset our undef status after accounting for the mask.
1859   N2Undef = N2.isUndef();
1860   // Re-check whether both sides ended up undef.
1861   if (N1.isUndef() && N2Undef)
1862     return getUNDEF(VT);
1863 
1864   // If Identity shuffle return that node.
1865   bool Identity = true, AllSame = true;
1866   for (int i = 0; i != NElts; ++i) {
1867     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1868     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1869   }
1870   if (Identity && NElts)
1871     return N1;
1872 
1873   // Shuffling a constant splat doesn't change the result.
1874   if (N2Undef) {
1875     SDValue V = N1;
1876 
1877     // Look through any bitcasts. We check that these don't change the number
1878     // (and size) of elements and just changes their types.
1879     while (V.getOpcode() == ISD::BITCAST)
1880       V = V->getOperand(0);
1881 
1882     // A splat should always show up as a build vector node.
1883     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1884       BitVector UndefElements;
1885       SDValue Splat = BV->getSplatValue(&UndefElements);
1886       // If this is a splat of an undef, shuffling it is also undef.
1887       if (Splat && Splat.isUndef())
1888         return getUNDEF(VT);
1889 
1890       bool SameNumElts =
1891           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1892 
1893       // We only have a splat which can skip shuffles if there is a splatted
1894       // value and no undef lanes rearranged by the shuffle.
1895       if (Splat && UndefElements.none()) {
1896         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1897         // number of elements match or the value splatted is a zero constant.
1898         if (SameNumElts)
1899           return N1;
1900         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1901           if (C->isNullValue())
1902             return N1;
1903       }
1904 
1905       // If the shuffle itself creates a splat, build the vector directly.
1906       if (AllSame && SameNumElts) {
1907         EVT BuildVT = BV->getValueType(0);
1908         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1909         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1910 
1911         // We may have jumped through bitcasts, so the type of the
1912         // BUILD_VECTOR may not match the type of the shuffle.
1913         if (BuildVT != VT)
1914           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1915         return NewBV;
1916       }
1917     }
1918   }
1919 
1920   FoldingSetNodeID ID;
1921   SDValue Ops[2] = { N1, N2 };
1922   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1923   for (int i = 0; i != NElts; ++i)
1924     ID.AddInteger(MaskVec[i]);
1925 
1926   void* IP = nullptr;
1927   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1928     return SDValue(E, 0);
1929 
1930   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1931   // SDNode doesn't have access to it.  This memory will be "leaked" when
1932   // the node is deallocated, but recovered when the NodeAllocator is released.
1933   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1934   llvm::copy(MaskVec, MaskAlloc);
1935 
1936   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1937                                            dl.getDebugLoc(), MaskAlloc);
1938   createOperands(N, Ops);
1939 
1940   CSEMap.InsertNode(N, IP);
1941   InsertNode(N);
1942   SDValue V = SDValue(N, 0);
1943   NewSDValueDbgMsg(V, "Creating new node: ", this);
1944   return V;
1945 }
1946 
1947 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1948   EVT VT = SV.getValueType(0);
1949   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1950   ShuffleVectorSDNode::commuteMask(MaskVec);
1951 
1952   SDValue Op0 = SV.getOperand(0);
1953   SDValue Op1 = SV.getOperand(1);
1954   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1955 }
1956 
1957 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1958   FoldingSetNodeID ID;
1959   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1960   ID.AddInteger(RegNo);
1961   void *IP = nullptr;
1962   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1963     return SDValue(E, 0);
1964 
1965   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1966   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1967   CSEMap.InsertNode(N, IP);
1968   InsertNode(N);
1969   return SDValue(N, 0);
1970 }
1971 
1972 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1973   FoldingSetNodeID ID;
1974   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1975   ID.AddPointer(RegMask);
1976   void *IP = nullptr;
1977   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1978     return SDValue(E, 0);
1979 
1980   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1981   CSEMap.InsertNode(N, IP);
1982   InsertNode(N);
1983   return SDValue(N, 0);
1984 }
1985 
1986 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1987                                  MCSymbol *Label) {
1988   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1989 }
1990 
1991 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1992                                    SDValue Root, MCSymbol *Label) {
1993   FoldingSetNodeID ID;
1994   SDValue Ops[] = { Root };
1995   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1996   ID.AddPointer(Label);
1997   void *IP = nullptr;
1998   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1999     return SDValue(E, 0);
2000 
2001   auto *N =
2002       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2003   createOperands(N, Ops);
2004 
2005   CSEMap.InsertNode(N, IP);
2006   InsertNode(N);
2007   return SDValue(N, 0);
2008 }
2009 
2010 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2011                                       int64_t Offset, bool isTarget,
2012                                       unsigned TargetFlags) {
2013   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2014 
2015   FoldingSetNodeID ID;
2016   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2017   ID.AddPointer(BA);
2018   ID.AddInteger(Offset);
2019   ID.AddInteger(TargetFlags);
2020   void *IP = nullptr;
2021   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2022     return SDValue(E, 0);
2023 
2024   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2025   CSEMap.InsertNode(N, IP);
2026   InsertNode(N);
2027   return SDValue(N, 0);
2028 }
2029 
2030 SDValue SelectionDAG::getSrcValue(const Value *V) {
2031   FoldingSetNodeID ID;
2032   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2033   ID.AddPointer(V);
2034 
2035   void *IP = nullptr;
2036   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2037     return SDValue(E, 0);
2038 
2039   auto *N = newSDNode<SrcValueSDNode>(V);
2040   CSEMap.InsertNode(N, IP);
2041   InsertNode(N);
2042   return SDValue(N, 0);
2043 }
2044 
2045 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2046   FoldingSetNodeID ID;
2047   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2048   ID.AddPointer(MD);
2049 
2050   void *IP = nullptr;
2051   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2052     return SDValue(E, 0);
2053 
2054   auto *N = newSDNode<MDNodeSDNode>(MD);
2055   CSEMap.InsertNode(N, IP);
2056   InsertNode(N);
2057   return SDValue(N, 0);
2058 }
2059 
2060 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2061   if (VT == V.getValueType())
2062     return V;
2063 
2064   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2065 }
2066 
2067 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2068                                        unsigned SrcAS, unsigned DestAS) {
2069   SDValue Ops[] = {Ptr};
2070   FoldingSetNodeID ID;
2071   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2072   ID.AddInteger(SrcAS);
2073   ID.AddInteger(DestAS);
2074 
2075   void *IP = nullptr;
2076   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2077     return SDValue(E, 0);
2078 
2079   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2080                                            VT, SrcAS, DestAS);
2081   createOperands(N, Ops);
2082 
2083   CSEMap.InsertNode(N, IP);
2084   InsertNode(N);
2085   return SDValue(N, 0);
2086 }
2087 
2088 SDValue SelectionDAG::getFreeze(SDValue V) {
2089   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2090 }
2091 
2092 /// getShiftAmountOperand - Return the specified value casted to
2093 /// the target's desired shift amount type.
2094 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2095   EVT OpTy = Op.getValueType();
2096   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2097   if (OpTy == ShTy || OpTy.isVector()) return Op;
2098 
2099   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2100 }
2101 
2102 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2103   SDLoc dl(Node);
2104   const TargetLowering &TLI = getTargetLoweringInfo();
2105   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2106   EVT VT = Node->getValueType(0);
2107   SDValue Tmp1 = Node->getOperand(0);
2108   SDValue Tmp2 = Node->getOperand(1);
2109   const MaybeAlign MA(Node->getConstantOperandVal(3));
2110 
2111   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2112                                Tmp2, MachinePointerInfo(V));
2113   SDValue VAList = VAListLoad;
2114 
2115   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2116     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2117                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2118 
2119     VAList =
2120         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2121                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2122   }
2123 
2124   // Increment the pointer, VAList, to the next vaarg
2125   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2126                  getConstant(getDataLayout().getTypeAllocSize(
2127                                                VT.getTypeForEVT(*getContext())),
2128                              dl, VAList.getValueType()));
2129   // Store the incremented VAList to the legalized pointer
2130   Tmp1 =
2131       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2132   // Load the actual argument out of the pointer VAList
2133   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2134 }
2135 
2136 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2137   SDLoc dl(Node);
2138   const TargetLowering &TLI = getTargetLoweringInfo();
2139   // This defaults to loading a pointer from the input and storing it to the
2140   // output, returning the chain.
2141   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2142   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2143   SDValue Tmp1 =
2144       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2145               Node->getOperand(2), MachinePointerInfo(VS));
2146   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2147                   MachinePointerInfo(VD));
2148 }
2149 
2150 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2151   const DataLayout &DL = getDataLayout();
2152   Type *Ty = VT.getTypeForEVT(*getContext());
2153   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2154 
2155   if (TLI->isTypeLegal(VT) || !VT.isVector())
2156     return RedAlign;
2157 
2158   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2159   const Align StackAlign = TFI->getStackAlign();
2160 
2161   // See if we can choose a smaller ABI alignment in cases where it's an
2162   // illegal vector type that will get broken down.
2163   if (RedAlign > StackAlign) {
2164     EVT IntermediateVT;
2165     MVT RegisterVT;
2166     unsigned NumIntermediates;
2167     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2168                                 NumIntermediates, RegisterVT);
2169     Ty = IntermediateVT.getTypeForEVT(*getContext());
2170     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2171     if (RedAlign2 < RedAlign)
2172       RedAlign = RedAlign2;
2173   }
2174 
2175   return RedAlign;
2176 }
2177 
2178 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2179   MachineFrameInfo &MFI = MF->getFrameInfo();
2180   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2181   int StackID = 0;
2182   if (Bytes.isScalable())
2183     StackID = TFI->getStackIDForScalableVectors();
2184   // The stack id gives an indication of whether the object is scalable or
2185   // not, so it's safe to pass in the minimum size here.
2186   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2187                                        false, nullptr, StackID);
2188   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2189 }
2190 
2191 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2192   Type *Ty = VT.getTypeForEVT(*getContext());
2193   Align StackAlign =
2194       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2195   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2196 }
2197 
2198 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2199   TypeSize VT1Size = VT1.getStoreSize();
2200   TypeSize VT2Size = VT2.getStoreSize();
2201   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2202          "Don't know how to choose the maximum size when creating a stack "
2203          "temporary");
2204   TypeSize Bytes =
2205       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2206 
2207   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2208   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2209   const DataLayout &DL = getDataLayout();
2210   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2211   return CreateStackTemporary(Bytes, Align);
2212 }
2213 
2214 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2215                                 ISD::CondCode Cond, const SDLoc &dl) {
2216   EVT OpVT = N1.getValueType();
2217 
2218   // These setcc operations always fold.
2219   switch (Cond) {
2220   default: break;
2221   case ISD::SETFALSE:
2222   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2223   case ISD::SETTRUE:
2224   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2225 
2226   case ISD::SETOEQ:
2227   case ISD::SETOGT:
2228   case ISD::SETOGE:
2229   case ISD::SETOLT:
2230   case ISD::SETOLE:
2231   case ISD::SETONE:
2232   case ISD::SETO:
2233   case ISD::SETUO:
2234   case ISD::SETUEQ:
2235   case ISD::SETUNE:
2236     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2237     break;
2238   }
2239 
2240   if (OpVT.isInteger()) {
2241     // For EQ and NE, we can always pick a value for the undef to make the
2242     // predicate pass or fail, so we can return undef.
2243     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2244     // icmp eq/ne X, undef -> undef.
2245     if ((N1.isUndef() || N2.isUndef()) &&
2246         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2247       return getUNDEF(VT);
2248 
2249     // If both operands are undef, we can return undef for int comparison.
2250     // icmp undef, undef -> undef.
2251     if (N1.isUndef() && N2.isUndef())
2252       return getUNDEF(VT);
2253 
2254     // icmp X, X -> true/false
2255     // icmp X, undef -> true/false because undef could be X.
2256     if (N1 == N2)
2257       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2258   }
2259 
2260   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2261     const APInt &C2 = N2C->getAPIntValue();
2262     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2263       const APInt &C1 = N1C->getAPIntValue();
2264 
2265       switch (Cond) {
2266       default: llvm_unreachable("Unknown integer setcc!");
2267       case ISD::SETEQ:  return getBoolConstant(C1 == C2, dl, VT, OpVT);
2268       case ISD::SETNE:  return getBoolConstant(C1 != C2, dl, VT, OpVT);
2269       case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2270       case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2271       case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2272       case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2273       case ISD::SETLT:  return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2274       case ISD::SETGT:  return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2275       case ISD::SETLE:  return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2276       case ISD::SETGE:  return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2277       }
2278     }
2279   }
2280 
2281   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2282   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2283 
2284   if (N1CFP && N2CFP) {
2285     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2286     switch (Cond) {
2287     default: break;
2288     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2289                         return getUNDEF(VT);
2290                       LLVM_FALLTHROUGH;
2291     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2292                                              OpVT);
2293     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2294                         return getUNDEF(VT);
2295                       LLVM_FALLTHROUGH;
2296     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2297                                              R==APFloat::cmpLessThan, dl, VT,
2298                                              OpVT);
2299     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2300                         return getUNDEF(VT);
2301                       LLVM_FALLTHROUGH;
2302     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2303                                              OpVT);
2304     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2305                         return getUNDEF(VT);
2306                       LLVM_FALLTHROUGH;
2307     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2308                                              VT, OpVT);
2309     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2310                         return getUNDEF(VT);
2311                       LLVM_FALLTHROUGH;
2312     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2313                                              R==APFloat::cmpEqual, dl, VT,
2314                                              OpVT);
2315     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2316                         return getUNDEF(VT);
2317                       LLVM_FALLTHROUGH;
2318     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2319                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2320     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2321                                              OpVT);
2322     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2323                                              OpVT);
2324     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2325                                              R==APFloat::cmpEqual, dl, VT,
2326                                              OpVT);
2327     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2328                                              OpVT);
2329     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2330                                              R==APFloat::cmpLessThan, dl, VT,
2331                                              OpVT);
2332     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2333                                              R==APFloat::cmpUnordered, dl, VT,
2334                                              OpVT);
2335     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2336                                              VT, OpVT);
2337     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2338                                              OpVT);
2339     }
2340   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2341     // Ensure that the constant occurs on the RHS.
2342     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2343     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2344       return SDValue();
2345     return getSetCC(dl, VT, N2, N1, SwappedCond);
2346   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2347              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2348     // If an operand is known to be a nan (or undef that could be a nan), we can
2349     // fold it.
2350     // Choosing NaN for the undef will always make unordered comparison succeed
2351     // and ordered comparison fails.
2352     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2353     switch (ISD::getUnorderedFlavor(Cond)) {
2354     default:
2355       llvm_unreachable("Unknown flavor!");
2356     case 0: // Known false.
2357       return getBoolConstant(false, dl, VT, OpVT);
2358     case 1: // Known true.
2359       return getBoolConstant(true, dl, VT, OpVT);
2360     case 2: // Undefined.
2361       return getUNDEF(VT);
2362     }
2363   }
2364 
2365   // Could not fold it.
2366   return SDValue();
2367 }
2368 
2369 /// See if the specified operand can be simplified with the knowledge that only
2370 /// the bits specified by DemandedBits are used.
2371 /// TODO: really we should be making this into the DAG equivalent of
2372 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2373 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2374   EVT VT = V.getValueType();
2375 
2376   if (VT.isScalableVector())
2377     return SDValue();
2378 
2379   APInt DemandedElts = VT.isVector()
2380                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2381                            : APInt(1, 1);
2382   return GetDemandedBits(V, DemandedBits, DemandedElts);
2383 }
2384 
2385 /// See if the specified operand can be simplified with the knowledge that only
2386 /// the bits specified by DemandedBits are used in the elements specified by
2387 /// DemandedElts.
2388 /// TODO: really we should be making this into the DAG equivalent of
2389 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2390 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2391                                       const APInt &DemandedElts) {
2392   switch (V.getOpcode()) {
2393   default:
2394     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2395                                                 *this, 0);
2396   case ISD::Constant: {
2397     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2398     APInt NewVal = CVal & DemandedBits;
2399     if (NewVal != CVal)
2400       return getConstant(NewVal, SDLoc(V), V.getValueType());
2401     break;
2402   }
2403   case ISD::SRL:
2404     // Only look at single-use SRLs.
2405     if (!V.getNode()->hasOneUse())
2406       break;
2407     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2408       // See if we can recursively simplify the LHS.
2409       unsigned Amt = RHSC->getZExtValue();
2410 
2411       // Watch out for shift count overflow though.
2412       if (Amt >= DemandedBits.getBitWidth())
2413         break;
2414       APInt SrcDemandedBits = DemandedBits << Amt;
2415       if (SDValue SimplifyLHS =
2416               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2417         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2418                        V.getOperand(1));
2419     }
2420     break;
2421   }
2422   return SDValue();
2423 }
2424 
2425 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2426 /// use this predicate to simplify operations downstream.
2427 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2428   unsigned BitWidth = Op.getScalarValueSizeInBits();
2429   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2430 }
2431 
2432 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2433 /// this predicate to simplify operations downstream.  Mask is known to be zero
2434 /// for bits that V cannot have.
2435 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2436                                      unsigned Depth) const {
2437   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2438 }
2439 
2440 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2441 /// DemandedElts.  We use this predicate to simplify operations downstream.
2442 /// Mask is known to be zero for bits that V cannot have.
2443 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2444                                      const APInt &DemandedElts,
2445                                      unsigned Depth) const {
2446   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2447 }
2448 
2449 /// Return true if the DemandedElts of the vector Op are all zero.  We
2450 /// use this predicate to simplify operations downstream.
2451 bool SelectionDAG::MaskedElementsAreZero(SDValue Op, const APInt &DemandedElts,
2452                                          unsigned Depth) const {
2453   unsigned BitWidth = Op.getScalarValueSizeInBits();
2454   APInt DemandedBits = APInt::getAllOnesValue(BitWidth);
2455   return MaskedValueIsZero(Op, DemandedBits, DemandedElts, Depth);
2456 }
2457 
2458 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2459 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2460                                         unsigned Depth) const {
2461   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2462 }
2463 
2464 /// isSplatValue - Return true if the vector V has the same value
2465 /// across all DemandedElts. For scalable vectors it does not make
2466 /// sense to specify which elements are demanded or undefined, therefore
2467 /// they are simply ignored.
2468 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2469                                 APInt &UndefElts, unsigned Depth) {
2470   EVT VT = V.getValueType();
2471   assert(VT.isVector() && "Vector type expected");
2472 
2473   if (!VT.isScalableVector() && !DemandedElts)
2474     return false; // No demanded elts, better to assume we don't know anything.
2475 
2476   if (Depth >= MaxRecursionDepth)
2477     return false; // Limit search depth.
2478 
2479   // Deal with some common cases here that work for both fixed and scalable
2480   // vector types.
2481   switch (V.getOpcode()) {
2482   case ISD::SPLAT_VECTOR:
2483     UndefElts = V.getOperand(0).isUndef()
2484                     ? APInt::getAllOnesValue(DemandedElts.getBitWidth())
2485                     : APInt(DemandedElts.getBitWidth(), 0);
2486     return true;
2487   case ISD::ADD:
2488   case ISD::SUB:
2489   case ISD::AND:
2490   case ISD::XOR:
2491   case ISD::OR: {
2492     APInt UndefLHS, UndefRHS;
2493     SDValue LHS = V.getOperand(0);
2494     SDValue RHS = V.getOperand(1);
2495     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2496         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2497       UndefElts = UndefLHS | UndefRHS;
2498       return true;
2499     }
2500     return false;
2501   }
2502   case ISD::ABS:
2503   case ISD::TRUNCATE:
2504   case ISD::SIGN_EXTEND:
2505   case ISD::ZERO_EXTEND:
2506     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2507   }
2508 
2509   // We don't support other cases than those above for scalable vectors at
2510   // the moment.
2511   if (VT.isScalableVector())
2512     return false;
2513 
2514   unsigned NumElts = VT.getVectorNumElements();
2515   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2516   UndefElts = APInt::getNullValue(NumElts);
2517 
2518   switch (V.getOpcode()) {
2519   case ISD::BUILD_VECTOR: {
2520     SDValue Scl;
2521     for (unsigned i = 0; i != NumElts; ++i) {
2522       SDValue Op = V.getOperand(i);
2523       if (Op.isUndef()) {
2524         UndefElts.setBit(i);
2525         continue;
2526       }
2527       if (!DemandedElts[i])
2528         continue;
2529       if (Scl && Scl != Op)
2530         return false;
2531       Scl = Op;
2532     }
2533     return true;
2534   }
2535   case ISD::VECTOR_SHUFFLE: {
2536     // Check if this is a shuffle node doing a splat.
2537     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2538     int SplatIndex = -1;
2539     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2540     for (int i = 0; i != (int)NumElts; ++i) {
2541       int M = Mask[i];
2542       if (M < 0) {
2543         UndefElts.setBit(i);
2544         continue;
2545       }
2546       if (!DemandedElts[i])
2547         continue;
2548       if (0 <= SplatIndex && SplatIndex != M)
2549         return false;
2550       SplatIndex = M;
2551     }
2552     return true;
2553   }
2554   case ISD::EXTRACT_SUBVECTOR: {
2555     // Offset the demanded elts by the subvector index.
2556     SDValue Src = V.getOperand(0);
2557     // We don't support scalable vectors at the moment.
2558     if (Src.getValueType().isScalableVector())
2559       return false;
2560     uint64_t Idx = V.getConstantOperandVal(1);
2561     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2562     APInt UndefSrcElts;
2563     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2564     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2565       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2566       return true;
2567     }
2568     break;
2569   }
2570   }
2571 
2572   return false;
2573 }
2574 
2575 /// Helper wrapper to main isSplatValue function.
2576 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2577   EVT VT = V.getValueType();
2578   assert(VT.isVector() && "Vector type expected");
2579 
2580   APInt UndefElts;
2581   APInt DemandedElts;
2582 
2583   // For now we don't support this with scalable vectors.
2584   if (!VT.isScalableVector())
2585     DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2586   return isSplatValue(V, DemandedElts, UndefElts) &&
2587          (AllowUndefs || !UndefElts);
2588 }
2589 
2590 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2591   V = peekThroughExtractSubvectors(V);
2592 
2593   EVT VT = V.getValueType();
2594   unsigned Opcode = V.getOpcode();
2595   switch (Opcode) {
2596   default: {
2597     APInt UndefElts;
2598     APInt DemandedElts;
2599 
2600     if (!VT.isScalableVector())
2601       DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2602 
2603     if (isSplatValue(V, DemandedElts, UndefElts)) {
2604       if (VT.isScalableVector()) {
2605         // DemandedElts and UndefElts are ignored for scalable vectors, since
2606         // the only supported cases are SPLAT_VECTOR nodes.
2607         SplatIdx = 0;
2608       } else {
2609         // Handle case where all demanded elements are UNDEF.
2610         if (DemandedElts.isSubsetOf(UndefElts)) {
2611           SplatIdx = 0;
2612           return getUNDEF(VT);
2613         }
2614         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2615       }
2616       return V;
2617     }
2618     break;
2619   }
2620   case ISD::SPLAT_VECTOR:
2621     SplatIdx = 0;
2622     return V;
2623   case ISD::VECTOR_SHUFFLE: {
2624     if (VT.isScalableVector())
2625       return SDValue();
2626 
2627     // Check if this is a shuffle node doing a splat.
2628     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2629     // getTargetVShiftNode currently struggles without the splat source.
2630     auto *SVN = cast<ShuffleVectorSDNode>(V);
2631     if (!SVN->isSplat())
2632       break;
2633     int Idx = SVN->getSplatIndex();
2634     int NumElts = V.getValueType().getVectorNumElements();
2635     SplatIdx = Idx % NumElts;
2636     return V.getOperand(Idx / NumElts);
2637   }
2638   }
2639 
2640   return SDValue();
2641 }
2642 
2643 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2644   int SplatIdx;
2645   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2646     EVT SVT = SrcVector.getValueType().getScalarType();
2647     EVT LegalSVT = SVT;
2648     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2649       if (!SVT.isInteger())
2650         return SDValue();
2651       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2652       if (LegalSVT.bitsLT(SVT))
2653         return SDValue();
2654     }
2655     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2656                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2657   }
2658   return SDValue();
2659 }
2660 
2661 const APInt *
2662 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2663                                           const APInt &DemandedElts) const {
2664   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2665           V.getOpcode() == ISD::SRA) &&
2666          "Unknown shift node");
2667   unsigned BitWidth = V.getScalarValueSizeInBits();
2668   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2669     // Shifting more than the bitwidth is not valid.
2670     const APInt &ShAmt = SA->getAPIntValue();
2671     if (ShAmt.ult(BitWidth))
2672       return &ShAmt;
2673   }
2674   return nullptr;
2675 }
2676 
2677 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2678     SDValue V, const APInt &DemandedElts) const {
2679   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2680           V.getOpcode() == ISD::SRA) &&
2681          "Unknown shift node");
2682   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2683     return ValidAmt;
2684   unsigned BitWidth = V.getScalarValueSizeInBits();
2685   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2686   if (!BV)
2687     return nullptr;
2688   const APInt *MinShAmt = nullptr;
2689   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2690     if (!DemandedElts[i])
2691       continue;
2692     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2693     if (!SA)
2694       return nullptr;
2695     // Shifting more than the bitwidth is not valid.
2696     const APInt &ShAmt = SA->getAPIntValue();
2697     if (ShAmt.uge(BitWidth))
2698       return nullptr;
2699     if (MinShAmt && MinShAmt->ule(ShAmt))
2700       continue;
2701     MinShAmt = &ShAmt;
2702   }
2703   return MinShAmt;
2704 }
2705 
2706 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2707     SDValue V, const APInt &DemandedElts) const {
2708   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2709           V.getOpcode() == ISD::SRA) &&
2710          "Unknown shift node");
2711   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2712     return ValidAmt;
2713   unsigned BitWidth = V.getScalarValueSizeInBits();
2714   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2715   if (!BV)
2716     return nullptr;
2717   const APInt *MaxShAmt = nullptr;
2718   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2719     if (!DemandedElts[i])
2720       continue;
2721     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2722     if (!SA)
2723       return nullptr;
2724     // Shifting more than the bitwidth is not valid.
2725     const APInt &ShAmt = SA->getAPIntValue();
2726     if (ShAmt.uge(BitWidth))
2727       return nullptr;
2728     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2729       continue;
2730     MaxShAmt = &ShAmt;
2731   }
2732   return MaxShAmt;
2733 }
2734 
2735 /// Determine which bits of Op are known to be either zero or one and return
2736 /// them in Known. For vectors, the known bits are those that are shared by
2737 /// every vector element.
2738 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2739   EVT VT = Op.getValueType();
2740 
2741   // TOOD: Until we have a plan for how to represent demanded elements for
2742   // scalable vectors, we can just bail out for now.
2743   if (Op.getValueType().isScalableVector()) {
2744     unsigned BitWidth = Op.getScalarValueSizeInBits();
2745     return KnownBits(BitWidth);
2746   }
2747 
2748   APInt DemandedElts = VT.isVector()
2749                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2750                            : APInt(1, 1);
2751   return computeKnownBits(Op, DemandedElts, Depth);
2752 }
2753 
2754 /// Determine which bits of Op are known to be either zero or one and return
2755 /// them in Known. The DemandedElts argument allows us to only collect the known
2756 /// bits that are shared by the requested vector elements.
2757 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2758                                          unsigned Depth) const {
2759   unsigned BitWidth = Op.getScalarValueSizeInBits();
2760 
2761   KnownBits Known(BitWidth);   // Don't know anything.
2762 
2763   // TOOD: Until we have a plan for how to represent demanded elements for
2764   // scalable vectors, we can just bail out for now.
2765   if (Op.getValueType().isScalableVector())
2766     return Known;
2767 
2768   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2769     // We know all of the bits for a constant!
2770     return KnownBits::makeConstant(C->getAPIntValue());
2771   }
2772   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2773     // We know all of the bits for a constant fp!
2774     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2775   }
2776 
2777   if (Depth >= MaxRecursionDepth)
2778     return Known;  // Limit search depth.
2779 
2780   KnownBits Known2;
2781   unsigned NumElts = DemandedElts.getBitWidth();
2782   assert((!Op.getValueType().isVector() ||
2783           NumElts == Op.getValueType().getVectorNumElements()) &&
2784          "Unexpected vector size");
2785 
2786   if (!DemandedElts)
2787     return Known;  // No demanded elts, better to assume we don't know anything.
2788 
2789   unsigned Opcode = Op.getOpcode();
2790   switch (Opcode) {
2791   case ISD::BUILD_VECTOR:
2792     // Collect the known bits that are shared by every demanded vector element.
2793     Known.Zero.setAllBits(); Known.One.setAllBits();
2794     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2795       if (!DemandedElts[i])
2796         continue;
2797 
2798       SDValue SrcOp = Op.getOperand(i);
2799       Known2 = computeKnownBits(SrcOp, Depth + 1);
2800 
2801       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2802       if (SrcOp.getValueSizeInBits() != BitWidth) {
2803         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2804                "Expected BUILD_VECTOR implicit truncation");
2805         Known2 = Known2.trunc(BitWidth);
2806       }
2807 
2808       // Known bits are the values that are shared by every demanded element.
2809       Known = KnownBits::commonBits(Known, Known2);
2810 
2811       // If we don't know any bits, early out.
2812       if (Known.isUnknown())
2813         break;
2814     }
2815     break;
2816   case ISD::VECTOR_SHUFFLE: {
2817     // Collect the known bits that are shared by every vector element referenced
2818     // by the shuffle.
2819     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2820     Known.Zero.setAllBits(); Known.One.setAllBits();
2821     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2822     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2823     for (unsigned i = 0; i != NumElts; ++i) {
2824       if (!DemandedElts[i])
2825         continue;
2826 
2827       int M = SVN->getMaskElt(i);
2828       if (M < 0) {
2829         // For UNDEF elements, we don't know anything about the common state of
2830         // the shuffle result.
2831         Known.resetAll();
2832         DemandedLHS.clearAllBits();
2833         DemandedRHS.clearAllBits();
2834         break;
2835       }
2836 
2837       if ((unsigned)M < NumElts)
2838         DemandedLHS.setBit((unsigned)M % NumElts);
2839       else
2840         DemandedRHS.setBit((unsigned)M % NumElts);
2841     }
2842     // Known bits are the values that are shared by every demanded element.
2843     if (!!DemandedLHS) {
2844       SDValue LHS = Op.getOperand(0);
2845       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2846       Known = KnownBits::commonBits(Known, Known2);
2847     }
2848     // If we don't know any bits, early out.
2849     if (Known.isUnknown())
2850       break;
2851     if (!!DemandedRHS) {
2852       SDValue RHS = Op.getOperand(1);
2853       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2854       Known = KnownBits::commonBits(Known, Known2);
2855     }
2856     break;
2857   }
2858   case ISD::CONCAT_VECTORS: {
2859     // Split DemandedElts and test each of the demanded subvectors.
2860     Known.Zero.setAllBits(); Known.One.setAllBits();
2861     EVT SubVectorVT = Op.getOperand(0).getValueType();
2862     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2863     unsigned NumSubVectors = Op.getNumOperands();
2864     for (unsigned i = 0; i != NumSubVectors; ++i) {
2865       APInt DemandedSub =
2866           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2867       if (!!DemandedSub) {
2868         SDValue Sub = Op.getOperand(i);
2869         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2870         Known = KnownBits::commonBits(Known, Known2);
2871       }
2872       // If we don't know any bits, early out.
2873       if (Known.isUnknown())
2874         break;
2875     }
2876     break;
2877   }
2878   case ISD::INSERT_SUBVECTOR: {
2879     // Demand any elements from the subvector and the remainder from the src its
2880     // inserted into.
2881     SDValue Src = Op.getOperand(0);
2882     SDValue Sub = Op.getOperand(1);
2883     uint64_t Idx = Op.getConstantOperandVal(2);
2884     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2885     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2886     APInt DemandedSrcElts = DemandedElts;
2887     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2888 
2889     Known.One.setAllBits();
2890     Known.Zero.setAllBits();
2891     if (!!DemandedSubElts) {
2892       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2893       if (Known.isUnknown())
2894         break; // early-out.
2895     }
2896     if (!!DemandedSrcElts) {
2897       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2898       Known = KnownBits::commonBits(Known, Known2);
2899     }
2900     break;
2901   }
2902   case ISD::EXTRACT_SUBVECTOR: {
2903     // Offset the demanded elts by the subvector index.
2904     SDValue Src = Op.getOperand(0);
2905     // Bail until we can represent demanded elements for scalable vectors.
2906     if (Src.getValueType().isScalableVector())
2907       break;
2908     uint64_t Idx = Op.getConstantOperandVal(1);
2909     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2910     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2911     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2912     break;
2913   }
2914   case ISD::SCALAR_TO_VECTOR: {
2915     // We know about scalar_to_vector as much as we know about it source,
2916     // which becomes the first element of otherwise unknown vector.
2917     if (DemandedElts != 1)
2918       break;
2919 
2920     SDValue N0 = Op.getOperand(0);
2921     Known = computeKnownBits(N0, Depth + 1);
2922     if (N0.getValueSizeInBits() != BitWidth)
2923       Known = Known.trunc(BitWidth);
2924 
2925     break;
2926   }
2927   case ISD::BITCAST: {
2928     SDValue N0 = Op.getOperand(0);
2929     EVT SubVT = N0.getValueType();
2930     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2931 
2932     // Ignore bitcasts from unsupported types.
2933     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2934       break;
2935 
2936     // Fast handling of 'identity' bitcasts.
2937     if (BitWidth == SubBitWidth) {
2938       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2939       break;
2940     }
2941 
2942     bool IsLE = getDataLayout().isLittleEndian();
2943 
2944     // Bitcast 'small element' vector to 'large element' scalar/vector.
2945     if ((BitWidth % SubBitWidth) == 0) {
2946       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2947 
2948       // Collect known bits for the (larger) output by collecting the known
2949       // bits from each set of sub elements and shift these into place.
2950       // We need to separately call computeKnownBits for each set of
2951       // sub elements as the knownbits for each is likely to be different.
2952       unsigned SubScale = BitWidth / SubBitWidth;
2953       APInt SubDemandedElts(NumElts * SubScale, 0);
2954       for (unsigned i = 0; i != NumElts; ++i)
2955         if (DemandedElts[i])
2956           SubDemandedElts.setBit(i * SubScale);
2957 
2958       for (unsigned i = 0; i != SubScale; ++i) {
2959         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2960                          Depth + 1);
2961         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2962         Known.insertBits(Known2, SubBitWidth * Shifts);
2963       }
2964     }
2965 
2966     // Bitcast 'large element' scalar/vector to 'small element' vector.
2967     if ((SubBitWidth % BitWidth) == 0) {
2968       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2969 
2970       // Collect known bits for the (smaller) output by collecting the known
2971       // bits from the overlapping larger input elements and extracting the
2972       // sub sections we actually care about.
2973       unsigned SubScale = SubBitWidth / BitWidth;
2974       APInt SubDemandedElts(NumElts / SubScale, 0);
2975       for (unsigned i = 0; i != NumElts; ++i)
2976         if (DemandedElts[i])
2977           SubDemandedElts.setBit(i / SubScale);
2978 
2979       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2980 
2981       Known.Zero.setAllBits(); Known.One.setAllBits();
2982       for (unsigned i = 0; i != NumElts; ++i)
2983         if (DemandedElts[i]) {
2984           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2985           unsigned Offset = (Shifts % SubScale) * BitWidth;
2986           Known = KnownBits::commonBits(Known,
2987                                         Known2.extractBits(BitWidth, Offset));
2988           // If we don't know any bits, early out.
2989           if (Known.isUnknown())
2990             break;
2991         }
2992     }
2993     break;
2994   }
2995   case ISD::AND:
2996     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2997     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2998 
2999     Known &= Known2;
3000     break;
3001   case ISD::OR:
3002     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3003     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3004 
3005     Known |= Known2;
3006     break;
3007   case ISD::XOR:
3008     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3009     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3010 
3011     Known ^= Known2;
3012     break;
3013   case ISD::MUL: {
3014     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3015     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3016     Known = KnownBits::mul(Known, Known2);
3017     break;
3018   }
3019   case ISD::MULHU: {
3020     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3021     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3022     Known = KnownBits::mulhu(Known, Known2);
3023     break;
3024   }
3025   case ISD::MULHS: {
3026     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3027     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3028     Known = KnownBits::mulhs(Known, Known2);
3029     break;
3030   }
3031   case ISD::UMUL_LOHI: {
3032     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3033     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3034     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3035     if (Op.getResNo() == 0)
3036       Known = KnownBits::mul(Known, Known2);
3037     else
3038       Known = KnownBits::mulhu(Known, Known2);
3039     break;
3040   }
3041   case ISD::SMUL_LOHI: {
3042     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3043     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3044     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3045     if (Op.getResNo() == 0)
3046       Known = KnownBits::mul(Known, Known2);
3047     else
3048       Known = KnownBits::mulhs(Known, Known2);
3049     break;
3050   }
3051   case ISD::UDIV: {
3052     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3053     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3054     Known = KnownBits::udiv(Known, Known2);
3055     break;
3056   }
3057   case ISD::SELECT:
3058   case ISD::VSELECT:
3059     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3060     // If we don't know any bits, early out.
3061     if (Known.isUnknown())
3062       break;
3063     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3064 
3065     // Only known if known in both the LHS and RHS.
3066     Known = KnownBits::commonBits(Known, Known2);
3067     break;
3068   case ISD::SELECT_CC:
3069     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3070     // If we don't know any bits, early out.
3071     if (Known.isUnknown())
3072       break;
3073     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3074 
3075     // Only known if known in both the LHS and RHS.
3076     Known = KnownBits::commonBits(Known, Known2);
3077     break;
3078   case ISD::SMULO:
3079   case ISD::UMULO:
3080     if (Op.getResNo() != 1)
3081       break;
3082     // The boolean result conforms to getBooleanContents.
3083     // If we know the result of a setcc has the top bits zero, use this info.
3084     // We know that we have an integer-based boolean since these operations
3085     // are only available for integer.
3086     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3087             TargetLowering::ZeroOrOneBooleanContent &&
3088         BitWidth > 1)
3089       Known.Zero.setBitsFrom(1);
3090     break;
3091   case ISD::SETCC:
3092   case ISD::STRICT_FSETCC:
3093   case ISD::STRICT_FSETCCS: {
3094     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3095     // If we know the result of a setcc has the top bits zero, use this info.
3096     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3097             TargetLowering::ZeroOrOneBooleanContent &&
3098         BitWidth > 1)
3099       Known.Zero.setBitsFrom(1);
3100     break;
3101   }
3102   case ISD::SHL:
3103     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3104     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3105     Known = KnownBits::shl(Known, Known2);
3106 
3107     // Minimum shift low bits are known zero.
3108     if (const APInt *ShMinAmt =
3109             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3110       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3111     break;
3112   case ISD::SRL:
3113     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3114     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3115     Known = KnownBits::lshr(Known, Known2);
3116 
3117     // Minimum shift high bits are known zero.
3118     if (const APInt *ShMinAmt =
3119             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3120       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3121     break;
3122   case ISD::SRA:
3123     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3124     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3125     Known = KnownBits::ashr(Known, Known2);
3126     // TODO: Add minimum shift high known sign bits.
3127     break;
3128   case ISD::FSHL:
3129   case ISD::FSHR:
3130     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3131       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3132 
3133       // For fshl, 0-shift returns the 1st arg.
3134       // For fshr, 0-shift returns the 2nd arg.
3135       if (Amt == 0) {
3136         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3137                                  DemandedElts, Depth + 1);
3138         break;
3139       }
3140 
3141       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3142       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3143       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3144       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3145       if (Opcode == ISD::FSHL) {
3146         Known.One <<= Amt;
3147         Known.Zero <<= Amt;
3148         Known2.One.lshrInPlace(BitWidth - Amt);
3149         Known2.Zero.lshrInPlace(BitWidth - Amt);
3150       } else {
3151         Known.One <<= BitWidth - Amt;
3152         Known.Zero <<= BitWidth - Amt;
3153         Known2.One.lshrInPlace(Amt);
3154         Known2.Zero.lshrInPlace(Amt);
3155       }
3156       Known.One |= Known2.One;
3157       Known.Zero |= Known2.Zero;
3158     }
3159     break;
3160   case ISD::SIGN_EXTEND_INREG: {
3161     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3162     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3163     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3164     break;
3165   }
3166   case ISD::CTTZ:
3167   case ISD::CTTZ_ZERO_UNDEF: {
3168     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3169     // If we have a known 1, its position is our upper bound.
3170     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3171     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3172     Known.Zero.setBitsFrom(LowBits);
3173     break;
3174   }
3175   case ISD::CTLZ:
3176   case ISD::CTLZ_ZERO_UNDEF: {
3177     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3178     // If we have a known 1, its position is our upper bound.
3179     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3180     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3181     Known.Zero.setBitsFrom(LowBits);
3182     break;
3183   }
3184   case ISD::CTPOP: {
3185     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3186     // If we know some of the bits are zero, they can't be one.
3187     unsigned PossibleOnes = Known2.countMaxPopulation();
3188     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3189     break;
3190   }
3191   case ISD::PARITY: {
3192     // Parity returns 0 everywhere but the LSB.
3193     Known.Zero.setBitsFrom(1);
3194     break;
3195   }
3196   case ISD::LOAD: {
3197     LoadSDNode *LD = cast<LoadSDNode>(Op);
3198     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3199     if (ISD::isNON_EXTLoad(LD) && Cst) {
3200       // Determine any common known bits from the loaded constant pool value.
3201       Type *CstTy = Cst->getType();
3202       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3203         // If its a vector splat, then we can (quickly) reuse the scalar path.
3204         // NOTE: We assume all elements match and none are UNDEF.
3205         if (CstTy->isVectorTy()) {
3206           if (const Constant *Splat = Cst->getSplatValue()) {
3207             Cst = Splat;
3208             CstTy = Cst->getType();
3209           }
3210         }
3211         // TODO - do we need to handle different bitwidths?
3212         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3213           // Iterate across all vector elements finding common known bits.
3214           Known.One.setAllBits();
3215           Known.Zero.setAllBits();
3216           for (unsigned i = 0; i != NumElts; ++i) {
3217             if (!DemandedElts[i])
3218               continue;
3219             if (Constant *Elt = Cst->getAggregateElement(i)) {
3220               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3221                 const APInt &Value = CInt->getValue();
3222                 Known.One &= Value;
3223                 Known.Zero &= ~Value;
3224                 continue;
3225               }
3226               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3227                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3228                 Known.One &= Value;
3229                 Known.Zero &= ~Value;
3230                 continue;
3231               }
3232             }
3233             Known.One.clearAllBits();
3234             Known.Zero.clearAllBits();
3235             break;
3236           }
3237         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3238           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3239             Known = KnownBits::makeConstant(CInt->getValue());
3240           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3241             Known =
3242                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3243           }
3244         }
3245       }
3246     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3247       // If this is a ZEXTLoad and we are looking at the loaded value.
3248       EVT VT = LD->getMemoryVT();
3249       unsigned MemBits = VT.getScalarSizeInBits();
3250       Known.Zero.setBitsFrom(MemBits);
3251     } else if (const MDNode *Ranges = LD->getRanges()) {
3252       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3253         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3254     }
3255     break;
3256   }
3257   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3258     EVT InVT = Op.getOperand(0).getValueType();
3259     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3260     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3261     Known = Known.zext(BitWidth);
3262     break;
3263   }
3264   case ISD::ZERO_EXTEND: {
3265     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3266     Known = Known.zext(BitWidth);
3267     break;
3268   }
3269   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3270     EVT InVT = Op.getOperand(0).getValueType();
3271     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3272     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3273     // If the sign bit is known to be zero or one, then sext will extend
3274     // it to the top bits, else it will just zext.
3275     Known = Known.sext(BitWidth);
3276     break;
3277   }
3278   case ISD::SIGN_EXTEND: {
3279     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3280     // If the sign bit is known to be zero or one, then sext will extend
3281     // it to the top bits, else it will just zext.
3282     Known = Known.sext(BitWidth);
3283     break;
3284   }
3285   case ISD::ANY_EXTEND_VECTOR_INREG: {
3286     EVT InVT = Op.getOperand(0).getValueType();
3287     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3288     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3289     Known = Known.anyext(BitWidth);
3290     break;
3291   }
3292   case ISD::ANY_EXTEND: {
3293     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3294     Known = Known.anyext(BitWidth);
3295     break;
3296   }
3297   case ISD::TRUNCATE: {
3298     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3299     Known = Known.trunc(BitWidth);
3300     break;
3301   }
3302   case ISD::AssertZext: {
3303     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3304     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3305     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3306     Known.Zero |= (~InMask);
3307     Known.One  &= (~Known.Zero);
3308     break;
3309   }
3310   case ISD::AssertAlign: {
3311     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3312     assert(LogOfAlign != 0);
3313     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3314     // well as clearing one bits.
3315     Known.Zero.setLowBits(LogOfAlign);
3316     Known.One.clearLowBits(LogOfAlign);
3317     break;
3318   }
3319   case ISD::FGETSIGN:
3320     // All bits are zero except the low bit.
3321     Known.Zero.setBitsFrom(1);
3322     break;
3323   case ISD::USUBO:
3324   case ISD::SSUBO:
3325     if (Op.getResNo() == 1) {
3326       // If we know the result of a setcc has the top bits zero, use this info.
3327       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3328               TargetLowering::ZeroOrOneBooleanContent &&
3329           BitWidth > 1)
3330         Known.Zero.setBitsFrom(1);
3331       break;
3332     }
3333     LLVM_FALLTHROUGH;
3334   case ISD::SUB:
3335   case ISD::SUBC: {
3336     assert(Op.getResNo() == 0 &&
3337            "We only compute knownbits for the difference here.");
3338 
3339     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3340     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3341     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3342                                         Known, Known2);
3343     break;
3344   }
3345   case ISD::UADDO:
3346   case ISD::SADDO:
3347   case ISD::ADDCARRY:
3348     if (Op.getResNo() == 1) {
3349       // If we know the result of a setcc has the top bits zero, use this info.
3350       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3351               TargetLowering::ZeroOrOneBooleanContent &&
3352           BitWidth > 1)
3353         Known.Zero.setBitsFrom(1);
3354       break;
3355     }
3356     LLVM_FALLTHROUGH;
3357   case ISD::ADD:
3358   case ISD::ADDC:
3359   case ISD::ADDE: {
3360     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3361 
3362     // With ADDE and ADDCARRY, a carry bit may be added in.
3363     KnownBits Carry(1);
3364     if (Opcode == ISD::ADDE)
3365       // Can't track carry from glue, set carry to unknown.
3366       Carry.resetAll();
3367     else if (Opcode == ISD::ADDCARRY)
3368       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3369       // the trouble (how often will we find a known carry bit). And I haven't
3370       // tested this very much yet, but something like this might work:
3371       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3372       //   Carry = Carry.zextOrTrunc(1, false);
3373       Carry.resetAll();
3374     else
3375       Carry.setAllZero();
3376 
3377     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3378     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3379     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3380     break;
3381   }
3382   case ISD::SREM: {
3383     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3384     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3385     Known = KnownBits::srem(Known, Known2);
3386     break;
3387   }
3388   case ISD::UREM: {
3389     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3390     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3391     Known = KnownBits::urem(Known, Known2);
3392     break;
3393   }
3394   case ISD::EXTRACT_ELEMENT: {
3395     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3396     const unsigned Index = Op.getConstantOperandVal(1);
3397     const unsigned EltBitWidth = Op.getValueSizeInBits();
3398 
3399     // Remove low part of known bits mask
3400     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3401     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3402 
3403     // Remove high part of known bit mask
3404     Known = Known.trunc(EltBitWidth);
3405     break;
3406   }
3407   case ISD::EXTRACT_VECTOR_ELT: {
3408     SDValue InVec = Op.getOperand(0);
3409     SDValue EltNo = Op.getOperand(1);
3410     EVT VecVT = InVec.getValueType();
3411     // computeKnownBits not yet implemented for scalable vectors.
3412     if (VecVT.isScalableVector())
3413       break;
3414     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3415     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3416 
3417     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3418     // anything about the extended bits.
3419     if (BitWidth > EltBitWidth)
3420       Known = Known.trunc(EltBitWidth);
3421 
3422     // If we know the element index, just demand that vector element, else for
3423     // an unknown element index, ignore DemandedElts and demand them all.
3424     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3425     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3426     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3427       DemandedSrcElts =
3428           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3429 
3430     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3431     if (BitWidth > EltBitWidth)
3432       Known = Known.anyext(BitWidth);
3433     break;
3434   }
3435   case ISD::INSERT_VECTOR_ELT: {
3436     // If we know the element index, split the demand between the
3437     // source vector and the inserted element, otherwise assume we need
3438     // the original demanded vector elements and the value.
3439     SDValue InVec = Op.getOperand(0);
3440     SDValue InVal = Op.getOperand(1);
3441     SDValue EltNo = Op.getOperand(2);
3442     bool DemandedVal = true;
3443     APInt DemandedVecElts = DemandedElts;
3444     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3445     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3446       unsigned EltIdx = CEltNo->getZExtValue();
3447       DemandedVal = !!DemandedElts[EltIdx];
3448       DemandedVecElts.clearBit(EltIdx);
3449     }
3450     Known.One.setAllBits();
3451     Known.Zero.setAllBits();
3452     if (DemandedVal) {
3453       Known2 = computeKnownBits(InVal, Depth + 1);
3454       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3455     }
3456     if (!!DemandedVecElts) {
3457       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3458       Known = KnownBits::commonBits(Known, Known2);
3459     }
3460     break;
3461   }
3462   case ISD::BITREVERSE: {
3463     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3464     Known = Known2.reverseBits();
3465     break;
3466   }
3467   case ISD::BSWAP: {
3468     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3469     Known = Known2.byteSwap();
3470     break;
3471   }
3472   case ISD::ABS: {
3473     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3474     Known = Known2.abs();
3475     break;
3476   }
3477   case ISD::USUBSAT: {
3478     // The result of usubsat will never be larger than the LHS.
3479     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3480     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3481     break;
3482   }
3483   case ISD::UMIN: {
3484     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3485     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3486     Known = KnownBits::umin(Known, Known2);
3487     break;
3488   }
3489   case ISD::UMAX: {
3490     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3491     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3492     Known = KnownBits::umax(Known, Known2);
3493     break;
3494   }
3495   case ISD::SMIN:
3496   case ISD::SMAX: {
3497     // If we have a clamp pattern, we know that the number of sign bits will be
3498     // the minimum of the clamp min/max range.
3499     bool IsMax = (Opcode == ISD::SMAX);
3500     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3501     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3502       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3503         CstHigh =
3504             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3505     if (CstLow && CstHigh) {
3506       if (!IsMax)
3507         std::swap(CstLow, CstHigh);
3508 
3509       const APInt &ValueLow = CstLow->getAPIntValue();
3510       const APInt &ValueHigh = CstHigh->getAPIntValue();
3511       if (ValueLow.sle(ValueHigh)) {
3512         unsigned LowSignBits = ValueLow.getNumSignBits();
3513         unsigned HighSignBits = ValueHigh.getNumSignBits();
3514         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3515         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3516           Known.One.setHighBits(MinSignBits);
3517           break;
3518         }
3519         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3520           Known.Zero.setHighBits(MinSignBits);
3521           break;
3522         }
3523       }
3524     }
3525 
3526     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3527     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3528     if (IsMax)
3529       Known = KnownBits::smax(Known, Known2);
3530     else
3531       Known = KnownBits::smin(Known, Known2);
3532     break;
3533   }
3534   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3535     if (Op.getResNo() == 1) {
3536       // The boolean result conforms to getBooleanContents.
3537       // If we know the result of a setcc has the top bits zero, use this info.
3538       // We know that we have an integer-based boolean since these operations
3539       // are only available for integer.
3540       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3541               TargetLowering::ZeroOrOneBooleanContent &&
3542           BitWidth > 1)
3543         Known.Zero.setBitsFrom(1);
3544       break;
3545     }
3546     LLVM_FALLTHROUGH;
3547   case ISD::ATOMIC_CMP_SWAP:
3548   case ISD::ATOMIC_SWAP:
3549   case ISD::ATOMIC_LOAD_ADD:
3550   case ISD::ATOMIC_LOAD_SUB:
3551   case ISD::ATOMIC_LOAD_AND:
3552   case ISD::ATOMIC_LOAD_CLR:
3553   case ISD::ATOMIC_LOAD_OR:
3554   case ISD::ATOMIC_LOAD_XOR:
3555   case ISD::ATOMIC_LOAD_NAND:
3556   case ISD::ATOMIC_LOAD_MIN:
3557   case ISD::ATOMIC_LOAD_MAX:
3558   case ISD::ATOMIC_LOAD_UMIN:
3559   case ISD::ATOMIC_LOAD_UMAX:
3560   case ISD::ATOMIC_LOAD: {
3561     unsigned MemBits =
3562         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3563     // If we are looking at the loaded value.
3564     if (Op.getResNo() == 0) {
3565       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3566         Known.Zero.setBitsFrom(MemBits);
3567     }
3568     break;
3569   }
3570   case ISD::FrameIndex:
3571   case ISD::TargetFrameIndex:
3572     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3573                                        Known, getMachineFunction());
3574     break;
3575 
3576   default:
3577     if (Opcode < ISD::BUILTIN_OP_END)
3578       break;
3579     LLVM_FALLTHROUGH;
3580   case ISD::INTRINSIC_WO_CHAIN:
3581   case ISD::INTRINSIC_W_CHAIN:
3582   case ISD::INTRINSIC_VOID:
3583     // Allow the target to implement this method for its nodes.
3584     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3585     break;
3586   }
3587 
3588   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3589   return Known;
3590 }
3591 
3592 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3593                                                              SDValue N1) const {
3594   // X + 0 never overflow
3595   if (isNullConstant(N1))
3596     return OFK_Never;
3597 
3598   KnownBits N1Known = computeKnownBits(N1);
3599   if (N1Known.Zero.getBoolValue()) {
3600     KnownBits N0Known = computeKnownBits(N0);
3601 
3602     bool overflow;
3603     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3604     if (!overflow)
3605       return OFK_Never;
3606   }
3607 
3608   // mulhi + 1 never overflow
3609   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3610       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3611     return OFK_Never;
3612 
3613   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3614     KnownBits N0Known = computeKnownBits(N0);
3615 
3616     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3617       return OFK_Never;
3618   }
3619 
3620   return OFK_Sometime;
3621 }
3622 
3623 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3624   EVT OpVT = Val.getValueType();
3625   unsigned BitWidth = OpVT.getScalarSizeInBits();
3626 
3627   // Is the constant a known power of 2?
3628   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3629     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3630 
3631   // A left-shift of a constant one will have exactly one bit set because
3632   // shifting the bit off the end is undefined.
3633   if (Val.getOpcode() == ISD::SHL) {
3634     auto *C = isConstOrConstSplat(Val.getOperand(0));
3635     if (C && C->getAPIntValue() == 1)
3636       return true;
3637   }
3638 
3639   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3640   // one bit set.
3641   if (Val.getOpcode() == ISD::SRL) {
3642     auto *C = isConstOrConstSplat(Val.getOperand(0));
3643     if (C && C->getAPIntValue().isSignMask())
3644       return true;
3645   }
3646 
3647   // Are all operands of a build vector constant powers of two?
3648   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3649     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3650           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3651             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3652           return false;
3653         }))
3654       return true;
3655 
3656   // More could be done here, though the above checks are enough
3657   // to handle some common cases.
3658 
3659   // Fall back to computeKnownBits to catch other known cases.
3660   KnownBits Known = computeKnownBits(Val);
3661   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3662 }
3663 
3664 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3665   EVT VT = Op.getValueType();
3666 
3667   // TODO: Assume we don't know anything for now.
3668   if (VT.isScalableVector())
3669     return 1;
3670 
3671   APInt DemandedElts = VT.isVector()
3672                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
3673                            : APInt(1, 1);
3674   return ComputeNumSignBits(Op, DemandedElts, Depth);
3675 }
3676 
3677 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3678                                           unsigned Depth) const {
3679   EVT VT = Op.getValueType();
3680   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3681   unsigned VTBits = VT.getScalarSizeInBits();
3682   unsigned NumElts = DemandedElts.getBitWidth();
3683   unsigned Tmp, Tmp2;
3684   unsigned FirstAnswer = 1;
3685 
3686   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3687     const APInt &Val = C->getAPIntValue();
3688     return Val.getNumSignBits();
3689   }
3690 
3691   if (Depth >= MaxRecursionDepth)
3692     return 1;  // Limit search depth.
3693 
3694   if (!DemandedElts || VT.isScalableVector())
3695     return 1;  // No demanded elts, better to assume we don't know anything.
3696 
3697   unsigned Opcode = Op.getOpcode();
3698   switch (Opcode) {
3699   default: break;
3700   case ISD::AssertSext:
3701     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3702     return VTBits-Tmp+1;
3703   case ISD::AssertZext:
3704     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3705     return VTBits-Tmp;
3706 
3707   case ISD::BUILD_VECTOR:
3708     Tmp = VTBits;
3709     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3710       if (!DemandedElts[i])
3711         continue;
3712 
3713       SDValue SrcOp = Op.getOperand(i);
3714       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3715 
3716       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3717       if (SrcOp.getValueSizeInBits() != VTBits) {
3718         assert(SrcOp.getValueSizeInBits() > VTBits &&
3719                "Expected BUILD_VECTOR implicit truncation");
3720         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3721         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3722       }
3723       Tmp = std::min(Tmp, Tmp2);
3724     }
3725     return Tmp;
3726 
3727   case ISD::VECTOR_SHUFFLE: {
3728     // Collect the minimum number of sign bits that are shared by every vector
3729     // element referenced by the shuffle.
3730     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3731     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3732     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3733     for (unsigned i = 0; i != NumElts; ++i) {
3734       int M = SVN->getMaskElt(i);
3735       if (!DemandedElts[i])
3736         continue;
3737       // For UNDEF elements, we don't know anything about the common state of
3738       // the shuffle result.
3739       if (M < 0)
3740         return 1;
3741       if ((unsigned)M < NumElts)
3742         DemandedLHS.setBit((unsigned)M % NumElts);
3743       else
3744         DemandedRHS.setBit((unsigned)M % NumElts);
3745     }
3746     Tmp = std::numeric_limits<unsigned>::max();
3747     if (!!DemandedLHS)
3748       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3749     if (!!DemandedRHS) {
3750       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3751       Tmp = std::min(Tmp, Tmp2);
3752     }
3753     // If we don't know anything, early out and try computeKnownBits fall-back.
3754     if (Tmp == 1)
3755       break;
3756     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3757     return Tmp;
3758   }
3759 
3760   case ISD::BITCAST: {
3761     SDValue N0 = Op.getOperand(0);
3762     EVT SrcVT = N0.getValueType();
3763     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3764 
3765     // Ignore bitcasts from unsupported types..
3766     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3767       break;
3768 
3769     // Fast handling of 'identity' bitcasts.
3770     if (VTBits == SrcBits)
3771       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3772 
3773     bool IsLE = getDataLayout().isLittleEndian();
3774 
3775     // Bitcast 'large element' scalar/vector to 'small element' vector.
3776     if ((SrcBits % VTBits) == 0) {
3777       assert(VT.isVector() && "Expected bitcast to vector");
3778 
3779       unsigned Scale = SrcBits / VTBits;
3780       APInt SrcDemandedElts(NumElts / Scale, 0);
3781       for (unsigned i = 0; i != NumElts; ++i)
3782         if (DemandedElts[i])
3783           SrcDemandedElts.setBit(i / Scale);
3784 
3785       // Fast case - sign splat can be simply split across the small elements.
3786       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3787       if (Tmp == SrcBits)
3788         return VTBits;
3789 
3790       // Slow case - determine how far the sign extends into each sub-element.
3791       Tmp2 = VTBits;
3792       for (unsigned i = 0; i != NumElts; ++i)
3793         if (DemandedElts[i]) {
3794           unsigned SubOffset = i % Scale;
3795           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3796           SubOffset = SubOffset * VTBits;
3797           if (Tmp <= SubOffset)
3798             return 1;
3799           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3800         }
3801       return Tmp2;
3802     }
3803     break;
3804   }
3805 
3806   case ISD::SIGN_EXTEND:
3807     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3808     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3809   case ISD::SIGN_EXTEND_INREG:
3810     // Max of the input and what this extends.
3811     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3812     Tmp = VTBits-Tmp+1;
3813     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3814     return std::max(Tmp, Tmp2);
3815   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3816     SDValue Src = Op.getOperand(0);
3817     EVT SrcVT = Src.getValueType();
3818     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3819     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3820     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3821   }
3822   case ISD::SRA:
3823     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3824     // SRA X, C -> adds C sign bits.
3825     if (const APInt *ShAmt =
3826             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3827       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3828     return Tmp;
3829   case ISD::SHL:
3830     if (const APInt *ShAmt =
3831             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3832       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3833       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3834       if (ShAmt->ult(Tmp))
3835         return Tmp - ShAmt->getZExtValue();
3836     }
3837     break;
3838   case ISD::AND:
3839   case ISD::OR:
3840   case ISD::XOR:    // NOT is handled here.
3841     // Logical binary ops preserve the number of sign bits at the worst.
3842     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3843     if (Tmp != 1) {
3844       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3845       FirstAnswer = std::min(Tmp, Tmp2);
3846       // We computed what we know about the sign bits as our first
3847       // answer. Now proceed to the generic code that uses
3848       // computeKnownBits, and pick whichever answer is better.
3849     }
3850     break;
3851 
3852   case ISD::SELECT:
3853   case ISD::VSELECT:
3854     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3855     if (Tmp == 1) return 1;  // Early out.
3856     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3857     return std::min(Tmp, Tmp2);
3858   case ISD::SELECT_CC:
3859     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3860     if (Tmp == 1) return 1;  // Early out.
3861     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3862     return std::min(Tmp, Tmp2);
3863 
3864   case ISD::SMIN:
3865   case ISD::SMAX: {
3866     // If we have a clamp pattern, we know that the number of sign bits will be
3867     // the minimum of the clamp min/max range.
3868     bool IsMax = (Opcode == ISD::SMAX);
3869     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3870     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3871       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3872         CstHigh =
3873             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3874     if (CstLow && CstHigh) {
3875       if (!IsMax)
3876         std::swap(CstLow, CstHigh);
3877       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3878         Tmp = CstLow->getAPIntValue().getNumSignBits();
3879         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3880         return std::min(Tmp, Tmp2);
3881       }
3882     }
3883 
3884     // Fallback - just get the minimum number of sign bits of the operands.
3885     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3886     if (Tmp == 1)
3887       return 1;  // Early out.
3888     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3889     return std::min(Tmp, Tmp2);
3890   }
3891   case ISD::UMIN:
3892   case ISD::UMAX:
3893     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3894     if (Tmp == 1)
3895       return 1;  // Early out.
3896     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3897     return std::min(Tmp, Tmp2);
3898   case ISD::SADDO:
3899   case ISD::UADDO:
3900   case ISD::SSUBO:
3901   case ISD::USUBO:
3902   case ISD::SMULO:
3903   case ISD::UMULO:
3904     if (Op.getResNo() != 1)
3905       break;
3906     // The boolean result conforms to getBooleanContents.  Fall through.
3907     // If setcc returns 0/-1, all bits are sign bits.
3908     // We know that we have an integer-based boolean since these operations
3909     // are only available for integer.
3910     if (TLI->getBooleanContents(VT.isVector(), false) ==
3911         TargetLowering::ZeroOrNegativeOneBooleanContent)
3912       return VTBits;
3913     break;
3914   case ISD::SETCC:
3915   case ISD::STRICT_FSETCC:
3916   case ISD::STRICT_FSETCCS: {
3917     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3918     // If setcc returns 0/-1, all bits are sign bits.
3919     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3920         TargetLowering::ZeroOrNegativeOneBooleanContent)
3921       return VTBits;
3922     break;
3923   }
3924   case ISD::ROTL:
3925   case ISD::ROTR:
3926     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3927 
3928     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3929     if (Tmp == VTBits)
3930       return VTBits;
3931 
3932     if (ConstantSDNode *C =
3933             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3934       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3935 
3936       // Handle rotate right by N like a rotate left by 32-N.
3937       if (Opcode == ISD::ROTR)
3938         RotAmt = (VTBits - RotAmt) % VTBits;
3939 
3940       // If we aren't rotating out all of the known-in sign bits, return the
3941       // number that are left.  This handles rotl(sext(x), 1) for example.
3942       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3943     }
3944     break;
3945   case ISD::ADD:
3946   case ISD::ADDC:
3947     // Add can have at most one carry bit.  Thus we know that the output
3948     // is, at worst, one more bit than the inputs.
3949     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3950     if (Tmp == 1) return 1; // Early out.
3951 
3952     // Special case decrementing a value (ADD X, -1):
3953     if (ConstantSDNode *CRHS =
3954             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3955       if (CRHS->isAllOnesValue()) {
3956         KnownBits Known =
3957             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3958 
3959         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3960         // sign bits set.
3961         if ((Known.Zero | 1).isAllOnesValue())
3962           return VTBits;
3963 
3964         // If we are subtracting one from a positive number, there is no carry
3965         // out of the result.
3966         if (Known.isNonNegative())
3967           return Tmp;
3968       }
3969 
3970     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3971     if (Tmp2 == 1) return 1; // Early out.
3972     return std::min(Tmp, Tmp2) - 1;
3973   case ISD::SUB:
3974     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3975     if (Tmp2 == 1) return 1; // Early out.
3976 
3977     // Handle NEG.
3978     if (ConstantSDNode *CLHS =
3979             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
3980       if (CLHS->isNullValue()) {
3981         KnownBits Known =
3982             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3983         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3984         // sign bits set.
3985         if ((Known.Zero | 1).isAllOnesValue())
3986           return VTBits;
3987 
3988         // If the input is known to be positive (the sign bit is known clear),
3989         // the output of the NEG has the same number of sign bits as the input.
3990         if (Known.isNonNegative())
3991           return Tmp2;
3992 
3993         // Otherwise, we treat this like a SUB.
3994       }
3995 
3996     // Sub can have at most one carry bit.  Thus we know that the output
3997     // is, at worst, one more bit than the inputs.
3998     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3999     if (Tmp == 1) return 1; // Early out.
4000     return std::min(Tmp, Tmp2) - 1;
4001   case ISD::MUL: {
4002     // The output of the Mul can be at most twice the valid bits in the inputs.
4003     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4004     if (SignBitsOp0 == 1)
4005       break;
4006     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4007     if (SignBitsOp1 == 1)
4008       break;
4009     unsigned OutValidBits =
4010         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4011     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4012   }
4013   case ISD::SREM:
4014     // The sign bit is the LHS's sign bit, except when the result of the
4015     // remainder is zero. The magnitude of the result should be less than or
4016     // equal to the magnitude of the LHS. Therefore, the result should have
4017     // at least as many sign bits as the left hand side.
4018     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4019   case ISD::TRUNCATE: {
4020     // Check if the sign bits of source go down as far as the truncated value.
4021     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4022     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4023     if (NumSrcSignBits > (NumSrcBits - VTBits))
4024       return NumSrcSignBits - (NumSrcBits - VTBits);
4025     break;
4026   }
4027   case ISD::EXTRACT_ELEMENT: {
4028     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4029     const int BitWidth = Op.getValueSizeInBits();
4030     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4031 
4032     // Get reverse index (starting from 1), Op1 value indexes elements from
4033     // little end. Sign starts at big end.
4034     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4035 
4036     // If the sign portion ends in our element the subtraction gives correct
4037     // result. Otherwise it gives either negative or > bitwidth result
4038     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4039   }
4040   case ISD::INSERT_VECTOR_ELT: {
4041     // If we know the element index, split the demand between the
4042     // source vector and the inserted element, otherwise assume we need
4043     // the original demanded vector elements and the value.
4044     SDValue InVec = Op.getOperand(0);
4045     SDValue InVal = Op.getOperand(1);
4046     SDValue EltNo = Op.getOperand(2);
4047     bool DemandedVal = true;
4048     APInt DemandedVecElts = DemandedElts;
4049     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4050     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4051       unsigned EltIdx = CEltNo->getZExtValue();
4052       DemandedVal = !!DemandedElts[EltIdx];
4053       DemandedVecElts.clearBit(EltIdx);
4054     }
4055     Tmp = std::numeric_limits<unsigned>::max();
4056     if (DemandedVal) {
4057       // TODO - handle implicit truncation of inserted elements.
4058       if (InVal.getScalarValueSizeInBits() != VTBits)
4059         break;
4060       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4061       Tmp = std::min(Tmp, Tmp2);
4062     }
4063     if (!!DemandedVecElts) {
4064       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4065       Tmp = std::min(Tmp, Tmp2);
4066     }
4067     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4068     return Tmp;
4069   }
4070   case ISD::EXTRACT_VECTOR_ELT: {
4071     SDValue InVec = Op.getOperand(0);
4072     SDValue EltNo = Op.getOperand(1);
4073     EVT VecVT = InVec.getValueType();
4074     // ComputeNumSignBits not yet implemented for scalable vectors.
4075     if (VecVT.isScalableVector())
4076       break;
4077     const unsigned BitWidth = Op.getValueSizeInBits();
4078     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4079     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4080 
4081     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4082     // anything about sign bits. But if the sizes match we can derive knowledge
4083     // about sign bits from the vector operand.
4084     if (BitWidth != EltBitWidth)
4085       break;
4086 
4087     // If we know the element index, just demand that vector element, else for
4088     // an unknown element index, ignore DemandedElts and demand them all.
4089     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
4090     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4091     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4092       DemandedSrcElts =
4093           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4094 
4095     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4096   }
4097   case ISD::EXTRACT_SUBVECTOR: {
4098     // Offset the demanded elts by the subvector index.
4099     SDValue Src = Op.getOperand(0);
4100     // Bail until we can represent demanded elements for scalable vectors.
4101     if (Src.getValueType().isScalableVector())
4102       break;
4103     uint64_t Idx = Op.getConstantOperandVal(1);
4104     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4105     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4106     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4107   }
4108   case ISD::CONCAT_VECTORS: {
4109     // Determine the minimum number of sign bits across all demanded
4110     // elts of the input vectors. Early out if the result is already 1.
4111     Tmp = std::numeric_limits<unsigned>::max();
4112     EVT SubVectorVT = Op.getOperand(0).getValueType();
4113     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4114     unsigned NumSubVectors = Op.getNumOperands();
4115     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4116       APInt DemandedSub =
4117           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4118       if (!DemandedSub)
4119         continue;
4120       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4121       Tmp = std::min(Tmp, Tmp2);
4122     }
4123     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4124     return Tmp;
4125   }
4126   case ISD::INSERT_SUBVECTOR: {
4127     // Demand any elements from the subvector and the remainder from the src its
4128     // inserted into.
4129     SDValue Src = Op.getOperand(0);
4130     SDValue Sub = Op.getOperand(1);
4131     uint64_t Idx = Op.getConstantOperandVal(2);
4132     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4133     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4134     APInt DemandedSrcElts = DemandedElts;
4135     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
4136 
4137     Tmp = std::numeric_limits<unsigned>::max();
4138     if (!!DemandedSubElts) {
4139       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4140       if (Tmp == 1)
4141         return 1; // early-out
4142     }
4143     if (!!DemandedSrcElts) {
4144       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4145       Tmp = std::min(Tmp, Tmp2);
4146     }
4147     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4148     return Tmp;
4149   }
4150   case ISD::ATOMIC_CMP_SWAP:
4151   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4152   case ISD::ATOMIC_SWAP:
4153   case ISD::ATOMIC_LOAD_ADD:
4154   case ISD::ATOMIC_LOAD_SUB:
4155   case ISD::ATOMIC_LOAD_AND:
4156   case ISD::ATOMIC_LOAD_CLR:
4157   case ISD::ATOMIC_LOAD_OR:
4158   case ISD::ATOMIC_LOAD_XOR:
4159   case ISD::ATOMIC_LOAD_NAND:
4160   case ISD::ATOMIC_LOAD_MIN:
4161   case ISD::ATOMIC_LOAD_MAX:
4162   case ISD::ATOMIC_LOAD_UMIN:
4163   case ISD::ATOMIC_LOAD_UMAX:
4164   case ISD::ATOMIC_LOAD: {
4165     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4166     // If we are looking at the loaded value.
4167     if (Op.getResNo() == 0) {
4168       if (Tmp == VTBits)
4169         return 1; // early-out
4170       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4171         return VTBits - Tmp + 1;
4172       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4173         return VTBits - Tmp;
4174     }
4175     break;
4176   }
4177   }
4178 
4179   // If we are looking at the loaded value of the SDNode.
4180   if (Op.getResNo() == 0) {
4181     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4182     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4183       unsigned ExtType = LD->getExtensionType();
4184       switch (ExtType) {
4185       default: break;
4186       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4187         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4188         return VTBits - Tmp + 1;
4189       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4190         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4191         return VTBits - Tmp;
4192       case ISD::NON_EXTLOAD:
4193         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4194           // We only need to handle vectors - computeKnownBits should handle
4195           // scalar cases.
4196           Type *CstTy = Cst->getType();
4197           if (CstTy->isVectorTy() &&
4198               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4199             Tmp = VTBits;
4200             for (unsigned i = 0; i != NumElts; ++i) {
4201               if (!DemandedElts[i])
4202                 continue;
4203               if (Constant *Elt = Cst->getAggregateElement(i)) {
4204                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4205                   const APInt &Value = CInt->getValue();
4206                   Tmp = std::min(Tmp, Value.getNumSignBits());
4207                   continue;
4208                 }
4209                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4210                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4211                   Tmp = std::min(Tmp, Value.getNumSignBits());
4212                   continue;
4213                 }
4214               }
4215               // Unknown type. Conservatively assume no bits match sign bit.
4216               return 1;
4217             }
4218             return Tmp;
4219           }
4220         }
4221         break;
4222       }
4223     }
4224   }
4225 
4226   // Allow the target to implement this method for its nodes.
4227   if (Opcode >= ISD::BUILTIN_OP_END ||
4228       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4229       Opcode == ISD::INTRINSIC_W_CHAIN ||
4230       Opcode == ISD::INTRINSIC_VOID) {
4231     unsigned NumBits =
4232         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4233     if (NumBits > 1)
4234       FirstAnswer = std::max(FirstAnswer, NumBits);
4235   }
4236 
4237   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4238   // use this information.
4239   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4240 
4241   APInt Mask;
4242   if (Known.isNonNegative()) {        // sign bit is 0
4243     Mask = Known.Zero;
4244   } else if (Known.isNegative()) {  // sign bit is 1;
4245     Mask = Known.One;
4246   } else {
4247     // Nothing known.
4248     return FirstAnswer;
4249   }
4250 
4251   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4252   // the number of identical bits in the top of the input value.
4253   Mask <<= Mask.getBitWidth()-VTBits;
4254   return std::max(FirstAnswer, Mask.countLeadingOnes());
4255 }
4256 
4257 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4258   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4259       !isa<ConstantSDNode>(Op.getOperand(1)))
4260     return false;
4261 
4262   if (Op.getOpcode() == ISD::OR &&
4263       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4264     return false;
4265 
4266   return true;
4267 }
4268 
4269 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4270   // If we're told that NaNs won't happen, assume they won't.
4271   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4272     return true;
4273 
4274   if (Depth >= MaxRecursionDepth)
4275     return false; // Limit search depth.
4276 
4277   // TODO: Handle vectors.
4278   // If the value is a constant, we can obviously see if it is a NaN or not.
4279   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4280     return !C->getValueAPF().isNaN() ||
4281            (SNaN && !C->getValueAPF().isSignaling());
4282   }
4283 
4284   unsigned Opcode = Op.getOpcode();
4285   switch (Opcode) {
4286   case ISD::FADD:
4287   case ISD::FSUB:
4288   case ISD::FMUL:
4289   case ISD::FDIV:
4290   case ISD::FREM:
4291   case ISD::FSIN:
4292   case ISD::FCOS: {
4293     if (SNaN)
4294       return true;
4295     // TODO: Need isKnownNeverInfinity
4296     return false;
4297   }
4298   case ISD::FCANONICALIZE:
4299   case ISD::FEXP:
4300   case ISD::FEXP2:
4301   case ISD::FTRUNC:
4302   case ISD::FFLOOR:
4303   case ISD::FCEIL:
4304   case ISD::FROUND:
4305   case ISD::FROUNDEVEN:
4306   case ISD::FRINT:
4307   case ISD::FNEARBYINT: {
4308     if (SNaN)
4309       return true;
4310     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4311   }
4312   case ISD::FABS:
4313   case ISD::FNEG:
4314   case ISD::FCOPYSIGN: {
4315     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4316   }
4317   case ISD::SELECT:
4318     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4319            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4320   case ISD::FP_EXTEND:
4321   case ISD::FP_ROUND: {
4322     if (SNaN)
4323       return true;
4324     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4325   }
4326   case ISD::SINT_TO_FP:
4327   case ISD::UINT_TO_FP:
4328     return true;
4329   case ISD::FMA:
4330   case ISD::FMAD: {
4331     if (SNaN)
4332       return true;
4333     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4334            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4335            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4336   }
4337   case ISD::FSQRT: // Need is known positive
4338   case ISD::FLOG:
4339   case ISD::FLOG2:
4340   case ISD::FLOG10:
4341   case ISD::FPOWI:
4342   case ISD::FPOW: {
4343     if (SNaN)
4344       return true;
4345     // TODO: Refine on operand
4346     return false;
4347   }
4348   case ISD::FMINNUM:
4349   case ISD::FMAXNUM: {
4350     // Only one needs to be known not-nan, since it will be returned if the
4351     // other ends up being one.
4352     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4353            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4354   }
4355   case ISD::FMINNUM_IEEE:
4356   case ISD::FMAXNUM_IEEE: {
4357     if (SNaN)
4358       return true;
4359     // This can return a NaN if either operand is an sNaN, or if both operands
4360     // are NaN.
4361     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4362             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4363            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4364             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4365   }
4366   case ISD::FMINIMUM:
4367   case ISD::FMAXIMUM: {
4368     // TODO: Does this quiet or return the origina NaN as-is?
4369     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4370            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4371   }
4372   case ISD::EXTRACT_VECTOR_ELT: {
4373     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4374   }
4375   default:
4376     if (Opcode >= ISD::BUILTIN_OP_END ||
4377         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4378         Opcode == ISD::INTRINSIC_W_CHAIN ||
4379         Opcode == ISD::INTRINSIC_VOID) {
4380       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4381     }
4382 
4383     return false;
4384   }
4385 }
4386 
4387 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4388   assert(Op.getValueType().isFloatingPoint() &&
4389          "Floating point type expected");
4390 
4391   // If the value is a constant, we can obviously see if it is a zero or not.
4392   // TODO: Add BuildVector support.
4393   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4394     return !C->isZero();
4395   return false;
4396 }
4397 
4398 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4399   assert(!Op.getValueType().isFloatingPoint() &&
4400          "Floating point types unsupported - use isKnownNeverZeroFloat");
4401 
4402   // If the value is a constant, we can obviously see if it is a zero or not.
4403   if (ISD::matchUnaryPredicate(
4404           Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4405     return true;
4406 
4407   // TODO: Recognize more cases here.
4408   switch (Op.getOpcode()) {
4409   default: break;
4410   case ISD::OR:
4411     if (isKnownNeverZero(Op.getOperand(1)) ||
4412         isKnownNeverZero(Op.getOperand(0)))
4413       return true;
4414     break;
4415   }
4416 
4417   return false;
4418 }
4419 
4420 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4421   // Check the obvious case.
4422   if (A == B) return true;
4423 
4424   // For for negative and positive zero.
4425   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4426     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4427       if (CA->isZero() && CB->isZero()) return true;
4428 
4429   // Otherwise they may not be equal.
4430   return false;
4431 }
4432 
4433 // FIXME: unify with llvm::haveNoCommonBitsSet.
4434 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4435 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4436   assert(A.getValueType() == B.getValueType() &&
4437          "Values must have the same type");
4438   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4439                                         computeKnownBits(B));
4440 }
4441 
4442 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4443                                SelectionDAG &DAG) {
4444   if (cast<ConstantSDNode>(Step)->isNullValue())
4445     return DAG.getConstant(0, DL, VT);
4446 
4447   return SDValue();
4448 }
4449 
4450 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4451                                 ArrayRef<SDValue> Ops,
4452                                 SelectionDAG &DAG) {
4453   int NumOps = Ops.size();
4454   assert(NumOps != 0 && "Can't build an empty vector!");
4455   assert(!VT.isScalableVector() &&
4456          "BUILD_VECTOR cannot be used with scalable types");
4457   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4458          "Incorrect element count in BUILD_VECTOR!");
4459 
4460   // BUILD_VECTOR of UNDEFs is UNDEF.
4461   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4462     return DAG.getUNDEF(VT);
4463 
4464   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4465   SDValue IdentitySrc;
4466   bool IsIdentity = true;
4467   for (int i = 0; i != NumOps; ++i) {
4468     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4469         Ops[i].getOperand(0).getValueType() != VT ||
4470         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4471         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4472         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4473       IsIdentity = false;
4474       break;
4475     }
4476     IdentitySrc = Ops[i].getOperand(0);
4477   }
4478   if (IsIdentity)
4479     return IdentitySrc;
4480 
4481   return SDValue();
4482 }
4483 
4484 /// Try to simplify vector concatenation to an input value, undef, or build
4485 /// vector.
4486 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4487                                   ArrayRef<SDValue> Ops,
4488                                   SelectionDAG &DAG) {
4489   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4490   assert(llvm::all_of(Ops,
4491                       [Ops](SDValue Op) {
4492                         return Ops[0].getValueType() == Op.getValueType();
4493                       }) &&
4494          "Concatenation of vectors with inconsistent value types!");
4495   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4496              VT.getVectorElementCount() &&
4497          "Incorrect element count in vector concatenation!");
4498 
4499   if (Ops.size() == 1)
4500     return Ops[0];
4501 
4502   // Concat of UNDEFs is UNDEF.
4503   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4504     return DAG.getUNDEF(VT);
4505 
4506   // Scan the operands and look for extract operations from a single source
4507   // that correspond to insertion at the same location via this concatenation:
4508   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4509   SDValue IdentitySrc;
4510   bool IsIdentity = true;
4511   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4512     SDValue Op = Ops[i];
4513     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4514     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4515         Op.getOperand(0).getValueType() != VT ||
4516         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4517         Op.getConstantOperandVal(1) != IdentityIndex) {
4518       IsIdentity = false;
4519       break;
4520     }
4521     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4522            "Unexpected identity source vector for concat of extracts");
4523     IdentitySrc = Op.getOperand(0);
4524   }
4525   if (IsIdentity) {
4526     assert(IdentitySrc && "Failed to set source vector of extracts");
4527     return IdentitySrc;
4528   }
4529 
4530   // The code below this point is only designed to work for fixed width
4531   // vectors, so we bail out for now.
4532   if (VT.isScalableVector())
4533     return SDValue();
4534 
4535   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4536   // simplified to one big BUILD_VECTOR.
4537   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4538   EVT SVT = VT.getScalarType();
4539   SmallVector<SDValue, 16> Elts;
4540   for (SDValue Op : Ops) {
4541     EVT OpVT = Op.getValueType();
4542     if (Op.isUndef())
4543       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4544     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4545       Elts.append(Op->op_begin(), Op->op_end());
4546     else
4547       return SDValue();
4548   }
4549 
4550   // BUILD_VECTOR requires all inputs to be of the same type, find the
4551   // maximum type and extend them all.
4552   for (SDValue Op : Elts)
4553     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4554 
4555   if (SVT.bitsGT(VT.getScalarType())) {
4556     for (SDValue &Op : Elts) {
4557       if (Op.isUndef())
4558         Op = DAG.getUNDEF(SVT);
4559       else
4560         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4561                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4562                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4563     }
4564   }
4565 
4566   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4567   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4568   return V;
4569 }
4570 
4571 /// Gets or creates the specified node.
4572 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4573   FoldingSetNodeID ID;
4574   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4575   void *IP = nullptr;
4576   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4577     return SDValue(E, 0);
4578 
4579   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4580                               getVTList(VT));
4581   CSEMap.InsertNode(N, IP);
4582 
4583   InsertNode(N);
4584   SDValue V = SDValue(N, 0);
4585   NewSDValueDbgMsg(V, "Creating new node: ", this);
4586   return V;
4587 }
4588 
4589 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4590                               SDValue Operand) {
4591   SDNodeFlags Flags;
4592   if (Inserter)
4593     Flags = Inserter->getFlags();
4594   return getNode(Opcode, DL, VT, Operand, Flags);
4595 }
4596 
4597 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4598                               SDValue Operand, const SDNodeFlags Flags) {
4599   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4600          "Operand is DELETED_NODE!");
4601   // Constant fold unary operations with an integer constant operand. Even
4602   // opaque constant will be folded, because the folding of unary operations
4603   // doesn't create new constants with different values. Nevertheless, the
4604   // opaque flag is preserved during folding to prevent future folding with
4605   // other constants.
4606   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4607     const APInt &Val = C->getAPIntValue();
4608     switch (Opcode) {
4609     default: break;
4610     case ISD::SIGN_EXTEND:
4611       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4612                          C->isTargetOpcode(), C->isOpaque());
4613     case ISD::TRUNCATE:
4614       if (C->isOpaque())
4615         break;
4616       LLVM_FALLTHROUGH;
4617     case ISD::ANY_EXTEND:
4618     case ISD::ZERO_EXTEND:
4619       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4620                          C->isTargetOpcode(), C->isOpaque());
4621     case ISD::UINT_TO_FP:
4622     case ISD::SINT_TO_FP: {
4623       APFloat apf(EVTToAPFloatSemantics(VT),
4624                   APInt::getNullValue(VT.getSizeInBits()));
4625       (void)apf.convertFromAPInt(Val,
4626                                  Opcode==ISD::SINT_TO_FP,
4627                                  APFloat::rmNearestTiesToEven);
4628       return getConstantFP(apf, DL, VT);
4629     }
4630     case ISD::BITCAST:
4631       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4632         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4633       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4634         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4635       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4636         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4637       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4638         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4639       break;
4640     case ISD::ABS:
4641       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4642                          C->isOpaque());
4643     case ISD::BITREVERSE:
4644       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4645                          C->isOpaque());
4646     case ISD::BSWAP:
4647       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4648                          C->isOpaque());
4649     case ISD::CTPOP:
4650       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4651                          C->isOpaque());
4652     case ISD::CTLZ:
4653     case ISD::CTLZ_ZERO_UNDEF:
4654       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4655                          C->isOpaque());
4656     case ISD::CTTZ:
4657     case ISD::CTTZ_ZERO_UNDEF:
4658       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4659                          C->isOpaque());
4660     case ISD::FP16_TO_FP: {
4661       bool Ignored;
4662       APFloat FPV(APFloat::IEEEhalf(),
4663                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4664 
4665       // This can return overflow, underflow, or inexact; we don't care.
4666       // FIXME need to be more flexible about rounding mode.
4667       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4668                         APFloat::rmNearestTiesToEven, &Ignored);
4669       return getConstantFP(FPV, DL, VT);
4670     }
4671     case ISD::STEP_VECTOR: {
4672       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4673         return V;
4674       break;
4675     }
4676     }
4677   }
4678 
4679   // Constant fold unary operations with a floating point constant operand.
4680   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4681     APFloat V = C->getValueAPF();    // make copy
4682     switch (Opcode) {
4683     case ISD::FNEG:
4684       V.changeSign();
4685       return getConstantFP(V, DL, VT);
4686     case ISD::FABS:
4687       V.clearSign();
4688       return getConstantFP(V, DL, VT);
4689     case ISD::FCEIL: {
4690       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4691       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4692         return getConstantFP(V, DL, VT);
4693       break;
4694     }
4695     case ISD::FTRUNC: {
4696       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4697       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4698         return getConstantFP(V, DL, VT);
4699       break;
4700     }
4701     case ISD::FFLOOR: {
4702       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4703       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4704         return getConstantFP(V, DL, VT);
4705       break;
4706     }
4707     case ISD::FP_EXTEND: {
4708       bool ignored;
4709       // This can return overflow, underflow, or inexact; we don't care.
4710       // FIXME need to be more flexible about rounding mode.
4711       (void)V.convert(EVTToAPFloatSemantics(VT),
4712                       APFloat::rmNearestTiesToEven, &ignored);
4713       return getConstantFP(V, DL, VT);
4714     }
4715     case ISD::FP_TO_SINT:
4716     case ISD::FP_TO_UINT: {
4717       bool ignored;
4718       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4719       // FIXME need to be more flexible about rounding mode.
4720       APFloat::opStatus s =
4721           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4722       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4723         break;
4724       return getConstant(IntVal, DL, VT);
4725     }
4726     case ISD::BITCAST:
4727       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4728         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4729       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4730         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4731       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4732         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4733       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4734         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4735       break;
4736     case ISD::FP_TO_FP16: {
4737       bool Ignored;
4738       // This can return overflow, underflow, or inexact; we don't care.
4739       // FIXME need to be more flexible about rounding mode.
4740       (void)V.convert(APFloat::IEEEhalf(),
4741                       APFloat::rmNearestTiesToEven, &Ignored);
4742       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4743     }
4744     }
4745   }
4746 
4747   // Constant fold unary operations with a vector integer or float operand.
4748   switch (Opcode) {
4749   default:
4750     // FIXME: Entirely reasonable to perform folding of other unary
4751     // operations here as the need arises.
4752     break;
4753   case ISD::FNEG:
4754   case ISD::FABS:
4755   case ISD::FCEIL:
4756   case ISD::FTRUNC:
4757   case ISD::FFLOOR:
4758   case ISD::FP_EXTEND:
4759   case ISD::FP_TO_SINT:
4760   case ISD::FP_TO_UINT:
4761   case ISD::TRUNCATE:
4762   case ISD::ANY_EXTEND:
4763   case ISD::ZERO_EXTEND:
4764   case ISD::SIGN_EXTEND:
4765   case ISD::UINT_TO_FP:
4766   case ISD::SINT_TO_FP:
4767   case ISD::ABS:
4768   case ISD::BITREVERSE:
4769   case ISD::BSWAP:
4770   case ISD::CTLZ:
4771   case ISD::CTLZ_ZERO_UNDEF:
4772   case ISD::CTTZ:
4773   case ISD::CTTZ_ZERO_UNDEF:
4774   case ISD::CTPOP: {
4775     SDValue Ops = {Operand};
4776     if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4777       return Fold;
4778   }
4779   }
4780 
4781   unsigned OpOpcode = Operand.getNode()->getOpcode();
4782   switch (Opcode) {
4783   case ISD::STEP_VECTOR:
4784     assert(VT.isScalableVector() &&
4785            "STEP_VECTOR can only be used with scalable types");
4786     assert(VT.getScalarSizeInBits() >= 8 &&
4787            "STEP_VECTOR can only be used with vectors of integers that are at "
4788            "least 8 bits wide");
4789     assert(isa<ConstantSDNode>(Operand) &&
4790            cast<ConstantSDNode>(Operand)->getAPIntValue().isSignedIntN(
4791                VT.getScalarSizeInBits()) &&
4792            "Expected STEP_VECTOR integer constant to fit in "
4793            "the vector element type");
4794     break;
4795   case ISD::FREEZE:
4796     assert(VT == Operand.getValueType() && "Unexpected VT!");
4797     break;
4798   case ISD::TokenFactor:
4799   case ISD::MERGE_VALUES:
4800   case ISD::CONCAT_VECTORS:
4801     return Operand;         // Factor, merge or concat of one node?  No need.
4802   case ISD::BUILD_VECTOR: {
4803     // Attempt to simplify BUILD_VECTOR.
4804     SDValue Ops[] = {Operand};
4805     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4806       return V;
4807     break;
4808   }
4809   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4810   case ISD::FP_EXTEND:
4811     assert(VT.isFloatingPoint() &&
4812            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4813     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4814     assert((!VT.isVector() ||
4815             VT.getVectorElementCount() ==
4816             Operand.getValueType().getVectorElementCount()) &&
4817            "Vector element count mismatch!");
4818     assert(Operand.getValueType().bitsLT(VT) &&
4819            "Invalid fpext node, dst < src!");
4820     if (Operand.isUndef())
4821       return getUNDEF(VT);
4822     break;
4823   case ISD::FP_TO_SINT:
4824   case ISD::FP_TO_UINT:
4825     if (Operand.isUndef())
4826       return getUNDEF(VT);
4827     break;
4828   case ISD::SINT_TO_FP:
4829   case ISD::UINT_TO_FP:
4830     // [us]itofp(undef) = 0, because the result value is bounded.
4831     if (Operand.isUndef())
4832       return getConstantFP(0.0, DL, VT);
4833     break;
4834   case ISD::SIGN_EXTEND:
4835     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4836            "Invalid SIGN_EXTEND!");
4837     assert(VT.isVector() == Operand.getValueType().isVector() &&
4838            "SIGN_EXTEND result type type should be vector iff the operand "
4839            "type is vector!");
4840     if (Operand.getValueType() == VT) return Operand;   // noop extension
4841     assert((!VT.isVector() ||
4842             VT.getVectorElementCount() ==
4843                 Operand.getValueType().getVectorElementCount()) &&
4844            "Vector element count mismatch!");
4845     assert(Operand.getValueType().bitsLT(VT) &&
4846            "Invalid sext node, dst < src!");
4847     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4848       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4849     if (OpOpcode == ISD::UNDEF)
4850       // sext(undef) = 0, because the top bits will all be the same.
4851       return getConstant(0, DL, VT);
4852     break;
4853   case ISD::ZERO_EXTEND:
4854     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4855            "Invalid ZERO_EXTEND!");
4856     assert(VT.isVector() == Operand.getValueType().isVector() &&
4857            "ZERO_EXTEND result type type should be vector iff the operand "
4858            "type is vector!");
4859     if (Operand.getValueType() == VT) return Operand;   // noop extension
4860     assert((!VT.isVector() ||
4861             VT.getVectorElementCount() ==
4862                 Operand.getValueType().getVectorElementCount()) &&
4863            "Vector element count mismatch!");
4864     assert(Operand.getValueType().bitsLT(VT) &&
4865            "Invalid zext node, dst < src!");
4866     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4867       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4868     if (OpOpcode == ISD::UNDEF)
4869       // zext(undef) = 0, because the top bits will be zero.
4870       return getConstant(0, DL, VT);
4871     break;
4872   case ISD::ANY_EXTEND:
4873     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4874            "Invalid ANY_EXTEND!");
4875     assert(VT.isVector() == Operand.getValueType().isVector() &&
4876            "ANY_EXTEND result type type should be vector iff the operand "
4877            "type is vector!");
4878     if (Operand.getValueType() == VT) return Operand;   // noop extension
4879     assert((!VT.isVector() ||
4880             VT.getVectorElementCount() ==
4881                 Operand.getValueType().getVectorElementCount()) &&
4882            "Vector element count mismatch!");
4883     assert(Operand.getValueType().bitsLT(VT) &&
4884            "Invalid anyext node, dst < src!");
4885 
4886     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4887         OpOpcode == ISD::ANY_EXTEND)
4888       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4889       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4890     if (OpOpcode == ISD::UNDEF)
4891       return getUNDEF(VT);
4892 
4893     // (ext (trunc x)) -> x
4894     if (OpOpcode == ISD::TRUNCATE) {
4895       SDValue OpOp = Operand.getOperand(0);
4896       if (OpOp.getValueType() == VT) {
4897         transferDbgValues(Operand, OpOp);
4898         return OpOp;
4899       }
4900     }
4901     break;
4902   case ISD::TRUNCATE:
4903     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4904            "Invalid TRUNCATE!");
4905     assert(VT.isVector() == Operand.getValueType().isVector() &&
4906            "TRUNCATE result type type should be vector iff the operand "
4907            "type is vector!");
4908     if (Operand.getValueType() == VT) return Operand;   // noop truncate
4909     assert((!VT.isVector() ||
4910             VT.getVectorElementCount() ==
4911                 Operand.getValueType().getVectorElementCount()) &&
4912            "Vector element count mismatch!");
4913     assert(Operand.getValueType().bitsGT(VT) &&
4914            "Invalid truncate node, src < dst!");
4915     if (OpOpcode == ISD::TRUNCATE)
4916       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4917     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4918         OpOpcode == ISD::ANY_EXTEND) {
4919       // If the source is smaller than the dest, we still need an extend.
4920       if (Operand.getOperand(0).getValueType().getScalarType()
4921             .bitsLT(VT.getScalarType()))
4922         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4923       if (Operand.getOperand(0).getValueType().bitsGT(VT))
4924         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4925       return Operand.getOperand(0);
4926     }
4927     if (OpOpcode == ISD::UNDEF)
4928       return getUNDEF(VT);
4929     break;
4930   case ISD::ANY_EXTEND_VECTOR_INREG:
4931   case ISD::ZERO_EXTEND_VECTOR_INREG:
4932   case ISD::SIGN_EXTEND_VECTOR_INREG:
4933     assert(VT.isVector() && "This DAG node is restricted to vector types.");
4934     assert(Operand.getValueType().bitsLE(VT) &&
4935            "The input must be the same size or smaller than the result.");
4936     assert(VT.getVectorMinNumElements() <
4937                Operand.getValueType().getVectorMinNumElements() &&
4938            "The destination vector type must have fewer lanes than the input.");
4939     break;
4940   case ISD::ABS:
4941     assert(VT.isInteger() && VT == Operand.getValueType() &&
4942            "Invalid ABS!");
4943     if (OpOpcode == ISD::UNDEF)
4944       return getUNDEF(VT);
4945     break;
4946   case ISD::BSWAP:
4947     assert(VT.isInteger() && VT == Operand.getValueType() &&
4948            "Invalid BSWAP!");
4949     assert((VT.getScalarSizeInBits() % 16 == 0) &&
4950            "BSWAP types must be a multiple of 16 bits!");
4951     if (OpOpcode == ISD::UNDEF)
4952       return getUNDEF(VT);
4953     break;
4954   case ISD::BITREVERSE:
4955     assert(VT.isInteger() && VT == Operand.getValueType() &&
4956            "Invalid BITREVERSE!");
4957     if (OpOpcode == ISD::UNDEF)
4958       return getUNDEF(VT);
4959     break;
4960   case ISD::BITCAST:
4961     // Basic sanity checking.
4962     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4963            "Cannot BITCAST between types of different sizes!");
4964     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
4965     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
4966       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4967     if (OpOpcode == ISD::UNDEF)
4968       return getUNDEF(VT);
4969     break;
4970   case ISD::SCALAR_TO_VECTOR:
4971     assert(VT.isVector() && !Operand.getValueType().isVector() &&
4972            (VT.getVectorElementType() == Operand.getValueType() ||
4973             (VT.getVectorElementType().isInteger() &&
4974              Operand.getValueType().isInteger() &&
4975              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4976            "Illegal SCALAR_TO_VECTOR node!");
4977     if (OpOpcode == ISD::UNDEF)
4978       return getUNDEF(VT);
4979     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4980     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4981         isa<ConstantSDNode>(Operand.getOperand(1)) &&
4982         Operand.getConstantOperandVal(1) == 0 &&
4983         Operand.getOperand(0).getValueType() == VT)
4984       return Operand.getOperand(0);
4985     break;
4986   case ISD::FNEG:
4987     // Negation of an unknown bag of bits is still completely undefined.
4988     if (OpOpcode == ISD::UNDEF)
4989       return getUNDEF(VT);
4990 
4991     if (OpOpcode == ISD::FNEG)  // --X -> X
4992       return Operand.getOperand(0);
4993     break;
4994   case ISD::FABS:
4995     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
4996       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4997     break;
4998   case ISD::VSCALE:
4999     assert(VT == Operand.getValueType() && "Unexpected VT!");
5000     break;
5001   case ISD::CTPOP:
5002     if (Operand.getValueType().getScalarType() == MVT::i1)
5003       return Operand;
5004     break;
5005   case ISD::CTLZ:
5006   case ISD::CTTZ:
5007     if (Operand.getValueType().getScalarType() == MVT::i1)
5008       return getNOT(DL, Operand, Operand.getValueType());
5009     break;
5010   case ISD::VECREDUCE_SMIN:
5011   case ISD::VECREDUCE_UMAX:
5012     if (Operand.getValueType().getScalarType() == MVT::i1)
5013       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5014     break;
5015   case ISD::VECREDUCE_SMAX:
5016   case ISD::VECREDUCE_UMIN:
5017     if (Operand.getValueType().getScalarType() == MVT::i1)
5018       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5019     break;
5020   }
5021 
5022   SDNode *N;
5023   SDVTList VTs = getVTList(VT);
5024   SDValue Ops[] = {Operand};
5025   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5026     FoldingSetNodeID ID;
5027     AddNodeIDNode(ID, Opcode, VTs, Ops);
5028     void *IP = nullptr;
5029     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5030       E->intersectFlagsWith(Flags);
5031       return SDValue(E, 0);
5032     }
5033 
5034     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5035     N->setFlags(Flags);
5036     createOperands(N, Ops);
5037     CSEMap.InsertNode(N, IP);
5038   } else {
5039     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5040     createOperands(N, Ops);
5041   }
5042 
5043   InsertNode(N);
5044   SDValue V = SDValue(N, 0);
5045   NewSDValueDbgMsg(V, "Creating new node: ", this);
5046   return V;
5047 }
5048 
5049 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5050                                        const APInt &C2) {
5051   switch (Opcode) {
5052   case ISD::ADD:  return C1 + C2;
5053   case ISD::SUB:  return C1 - C2;
5054   case ISD::MUL:  return C1 * C2;
5055   case ISD::AND:  return C1 & C2;
5056   case ISD::OR:   return C1 | C2;
5057   case ISD::XOR:  return C1 ^ C2;
5058   case ISD::SHL:  return C1 << C2;
5059   case ISD::SRL:  return C1.lshr(C2);
5060   case ISD::SRA:  return C1.ashr(C2);
5061   case ISD::ROTL: return C1.rotl(C2);
5062   case ISD::ROTR: return C1.rotr(C2);
5063   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5064   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5065   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5066   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5067   case ISD::SADDSAT: return C1.sadd_sat(C2);
5068   case ISD::UADDSAT: return C1.uadd_sat(C2);
5069   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5070   case ISD::USUBSAT: return C1.usub_sat(C2);
5071   case ISD::UDIV:
5072     if (!C2.getBoolValue())
5073       break;
5074     return C1.udiv(C2);
5075   case ISD::UREM:
5076     if (!C2.getBoolValue())
5077       break;
5078     return C1.urem(C2);
5079   case ISD::SDIV:
5080     if (!C2.getBoolValue())
5081       break;
5082     return C1.sdiv(C2);
5083   case ISD::SREM:
5084     if (!C2.getBoolValue())
5085       break;
5086     return C1.srem(C2);
5087   case ISD::MULHS: {
5088     unsigned FullWidth = C1.getBitWidth() * 2;
5089     APInt C1Ext = C1.sext(FullWidth);
5090     APInt C2Ext = C2.sext(FullWidth);
5091     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5092   }
5093   case ISD::MULHU: {
5094     unsigned FullWidth = C1.getBitWidth() * 2;
5095     APInt C1Ext = C1.zext(FullWidth);
5096     APInt C2Ext = C2.zext(FullWidth);
5097     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5098   }
5099   }
5100   return llvm::None;
5101 }
5102 
5103 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5104                                        const GlobalAddressSDNode *GA,
5105                                        const SDNode *N2) {
5106   if (GA->getOpcode() != ISD::GlobalAddress)
5107     return SDValue();
5108   if (!TLI->isOffsetFoldingLegal(GA))
5109     return SDValue();
5110   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5111   if (!C2)
5112     return SDValue();
5113   int64_t Offset = C2->getSExtValue();
5114   switch (Opcode) {
5115   case ISD::ADD: break;
5116   case ISD::SUB: Offset = -uint64_t(Offset); break;
5117   default: return SDValue();
5118   }
5119   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5120                           GA->getOffset() + uint64_t(Offset));
5121 }
5122 
5123 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5124   switch (Opcode) {
5125   case ISD::SDIV:
5126   case ISD::UDIV:
5127   case ISD::SREM:
5128   case ISD::UREM: {
5129     // If a divisor is zero/undef or any element of a divisor vector is
5130     // zero/undef, the whole op is undef.
5131     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5132     SDValue Divisor = Ops[1];
5133     if (Divisor.isUndef() || isNullConstant(Divisor))
5134       return true;
5135 
5136     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5137            llvm::any_of(Divisor->op_values(),
5138                         [](SDValue V) { return V.isUndef() ||
5139                                         isNullConstant(V); });
5140     // TODO: Handle signed overflow.
5141   }
5142   // TODO: Handle oversized shifts.
5143   default:
5144     return false;
5145   }
5146 }
5147 
5148 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5149                                              EVT VT, ArrayRef<SDValue> Ops) {
5150   // If the opcode is a target-specific ISD node, there's nothing we can
5151   // do here and the operand rules may not line up with the below, so
5152   // bail early.
5153   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5154   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5155   // foldCONCAT_VECTORS in getNode before this is called.
5156   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5157     return SDValue();
5158 
5159   // For now, the array Ops should only contain two values.
5160   // This enforcement will be removed once this function is merged with
5161   // FoldConstantVectorArithmetic
5162   if (Ops.size() != 2)
5163     return SDValue();
5164 
5165   if (isUndef(Opcode, Ops))
5166     return getUNDEF(VT);
5167 
5168   SDNode *N1 = Ops[0].getNode();
5169   SDNode *N2 = Ops[1].getNode();
5170 
5171   // Handle the case of two scalars.
5172   if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
5173     if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
5174       if (C1->isOpaque() || C2->isOpaque())
5175         return SDValue();
5176 
5177       Optional<APInt> FoldAttempt =
5178           FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5179       if (!FoldAttempt)
5180         return SDValue();
5181 
5182       SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5183       assert((!Folded || !VT.isVector()) &&
5184              "Can't fold vectors ops with scalar operands");
5185       return Folded;
5186     }
5187   }
5188 
5189   // fold (add Sym, c) -> Sym+c
5190   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
5191     return FoldSymbolOffset(Opcode, VT, GA, N2);
5192   if (TLI->isCommutativeBinOp(Opcode))
5193     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
5194       return FoldSymbolOffset(Opcode, VT, GA, N1);
5195 
5196   // For fixed width vectors, extract each constant element and fold them
5197   // individually. Either input may be an undef value.
5198   bool IsBVOrSV1 = N1->getOpcode() == ISD::BUILD_VECTOR ||
5199                    N1->getOpcode() == ISD::SPLAT_VECTOR;
5200   if (!IsBVOrSV1 && !N1->isUndef())
5201     return SDValue();
5202   bool IsBVOrSV2 = N2->getOpcode() == ISD::BUILD_VECTOR ||
5203                    N2->getOpcode() == ISD::SPLAT_VECTOR;
5204   if (!IsBVOrSV2 && !N2->isUndef())
5205     return SDValue();
5206   // If both operands are undef, that's handled the same way as scalars.
5207   if (!IsBVOrSV1 && !IsBVOrSV2)
5208     return SDValue();
5209 
5210   EVT SVT = VT.getScalarType();
5211   EVT LegalSVT = SVT;
5212   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5213     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5214     if (LegalSVT.bitsLT(SVT))
5215       return SDValue();
5216   }
5217 
5218   SmallVector<SDValue, 4> Outputs;
5219   unsigned NumOps = 0;
5220   if (IsBVOrSV1)
5221     NumOps = std::max(NumOps, N1->getNumOperands());
5222   if (IsBVOrSV2)
5223     NumOps = std::max(NumOps, N2->getNumOperands());
5224   assert(NumOps != 0 && "Expected non-zero operands");
5225   // Scalable vectors should only be SPLAT_VECTOR or UNDEF here. We only need
5226   // one iteration for that.
5227   assert((!VT.isScalableVector() || NumOps == 1) &&
5228          "Scalable vector should only have one scalar");
5229 
5230   for (unsigned I = 0; I != NumOps; ++I) {
5231     // We can have a fixed length SPLAT_VECTOR and a BUILD_VECTOR so we need
5232     // to use operand 0 of the SPLAT_VECTOR for each fixed element.
5233     SDValue V1;
5234     if (N1->getOpcode() == ISD::BUILD_VECTOR)
5235       V1 = N1->getOperand(I);
5236     else if (N1->getOpcode() == ISD::SPLAT_VECTOR)
5237       V1 = N1->getOperand(0);
5238     else
5239       V1 = getUNDEF(SVT);
5240 
5241     SDValue V2;
5242     if (N2->getOpcode() == ISD::BUILD_VECTOR)
5243       V2 = N2->getOperand(I);
5244     else if (N2->getOpcode() == ISD::SPLAT_VECTOR)
5245       V2 = N2->getOperand(0);
5246     else
5247       V2 = getUNDEF(SVT);
5248 
5249     if (SVT.isInteger()) {
5250       if (V1.getValueType().bitsGT(SVT))
5251         V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
5252       if (V2.getValueType().bitsGT(SVT))
5253         V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
5254     }
5255 
5256     if (V1.getValueType() != SVT || V2.getValueType() != SVT)
5257       return SDValue();
5258 
5259     // Fold one vector element.
5260     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
5261     if (LegalSVT != SVT)
5262       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5263 
5264     // Scalar folding only succeeded if the result is a constant or UNDEF.
5265     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5266         ScalarResult.getOpcode() != ISD::ConstantFP)
5267       return SDValue();
5268     Outputs.push_back(ScalarResult);
5269   }
5270 
5271   if (N1->getOpcode() == ISD::BUILD_VECTOR ||
5272       N2->getOpcode() == ISD::BUILD_VECTOR) {
5273     assert(VT.getVectorNumElements() == Outputs.size() &&
5274            "Vector size mismatch!");
5275 
5276     // Build a big vector out of the scalar elements we generated.
5277     return getBuildVector(VT, SDLoc(), Outputs);
5278   }
5279 
5280   assert((N1->getOpcode() == ISD::SPLAT_VECTOR ||
5281           N2->getOpcode() == ISD::SPLAT_VECTOR) &&
5282          "One operand should be a splat vector");
5283 
5284   assert(Outputs.size() == 1 && "Vector size mismatch!");
5285   return getSplatVector(VT, SDLoc(), Outputs[0]);
5286 }
5287 
5288 // TODO: Merge with FoldConstantArithmetic
5289 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
5290                                                    const SDLoc &DL, EVT VT,
5291                                                    ArrayRef<SDValue> Ops,
5292                                                    const SDNodeFlags Flags) {
5293   // If the opcode is a target-specific ISD node, there's nothing we can
5294   // do here and the operand rules may not line up with the below, so
5295   // bail early.
5296   if (Opcode >= ISD::BUILTIN_OP_END)
5297     return SDValue();
5298 
5299   if (isUndef(Opcode, Ops))
5300     return getUNDEF(VT);
5301 
5302   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
5303   if (!VT.isVector())
5304     return SDValue();
5305 
5306   ElementCount NumElts = VT.getVectorElementCount();
5307 
5308   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5309     return !Op.getValueType().isVector() ||
5310            Op.getValueType().getVectorElementCount() == NumElts;
5311   };
5312 
5313   auto IsConstantBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5314     APInt SplatVal;
5315     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
5316     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5317            (BV && BV->isConstant()) ||
5318            (Op.getOpcode() == ISD::SPLAT_VECTOR &&
5319             ISD::isConstantSplatVector(Op.getNode(), SplatVal));
5320   };
5321 
5322   // All operands must be vector types with the same number of elements as
5323   // the result type and must be either UNDEF or a build vector of constant
5324   // or UNDEF scalars.
5325   if (!llvm::all_of(Ops, IsConstantBuildVectorSplatVectorOrUndef) ||
5326       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5327     return SDValue();
5328 
5329   // If we are comparing vectors, then the result needs to be a i1 boolean
5330   // that is then sign-extended back to the legal result type.
5331   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5332 
5333   // Find legal integer scalar type for constant promotion and
5334   // ensure that its scalar size is at least as large as source.
5335   EVT LegalSVT = VT.getScalarType();
5336   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5337     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5338     if (LegalSVT.bitsLT(VT.getScalarType()))
5339       return SDValue();
5340   }
5341 
5342   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5343   // only have one operand to check. For fixed-length vector types we may have
5344   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5345   unsigned NumOperands = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5346 
5347   // Constant fold each scalar lane separately.
5348   SmallVector<SDValue, 4> ScalarResults;
5349   for (unsigned I = 0; I != NumOperands; I++) {
5350     SmallVector<SDValue, 4> ScalarOps;
5351     for (SDValue Op : Ops) {
5352       EVT InSVT = Op.getValueType().getScalarType();
5353       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5354           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5355         // We've checked that this is UNDEF or a constant of some kind.
5356         if (Op.isUndef())
5357           ScalarOps.push_back(getUNDEF(InSVT));
5358         else
5359           ScalarOps.push_back(Op);
5360         continue;
5361       }
5362 
5363       SDValue ScalarOp =
5364           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5365       EVT ScalarVT = ScalarOp.getValueType();
5366 
5367       // Build vector (integer) scalar operands may need implicit
5368       // truncation - do this before constant folding.
5369       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5370         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5371 
5372       ScalarOps.push_back(ScalarOp);
5373     }
5374 
5375     // Constant fold the scalar operands.
5376     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
5377 
5378     // Legalize the (integer) scalar constant if necessary.
5379     if (LegalSVT != SVT)
5380       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5381 
5382     // Scalar folding only succeeded if the result is a constant or UNDEF.
5383     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5384         ScalarResult.getOpcode() != ISD::ConstantFP)
5385       return SDValue();
5386     ScalarResults.push_back(ScalarResult);
5387   }
5388 
5389   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5390                                    : getBuildVector(VT, DL, ScalarResults);
5391   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5392   return V;
5393 }
5394 
5395 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5396                                          EVT VT, SDValue N1, SDValue N2) {
5397   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5398   //       should. That will require dealing with a potentially non-default
5399   //       rounding mode, checking the "opStatus" return value from the APFloat
5400   //       math calculations, and possibly other variations.
5401   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5402   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5403   if (N1CFP && N2CFP) {
5404     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5405     switch (Opcode) {
5406     case ISD::FADD:
5407       C1.add(C2, APFloat::rmNearestTiesToEven);
5408       return getConstantFP(C1, DL, VT);
5409     case ISD::FSUB:
5410       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5411       return getConstantFP(C1, DL, VT);
5412     case ISD::FMUL:
5413       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5414       return getConstantFP(C1, DL, VT);
5415     case ISD::FDIV:
5416       C1.divide(C2, APFloat::rmNearestTiesToEven);
5417       return getConstantFP(C1, DL, VT);
5418     case ISD::FREM:
5419       C1.mod(C2);
5420       return getConstantFP(C1, DL, VT);
5421     case ISD::FCOPYSIGN:
5422       C1.copySign(C2);
5423       return getConstantFP(C1, DL, VT);
5424     default: break;
5425     }
5426   }
5427   if (N1CFP && Opcode == ISD::FP_ROUND) {
5428     APFloat C1 = N1CFP->getValueAPF();    // make copy
5429     bool Unused;
5430     // This can return overflow, underflow, or inexact; we don't care.
5431     // FIXME need to be more flexible about rounding mode.
5432     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5433                       &Unused);
5434     return getConstantFP(C1, DL, VT);
5435   }
5436 
5437   switch (Opcode) {
5438   case ISD::FSUB:
5439     // -0.0 - undef --> undef (consistent with "fneg undef")
5440     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5441       return getUNDEF(VT);
5442     LLVM_FALLTHROUGH;
5443 
5444   case ISD::FADD:
5445   case ISD::FMUL:
5446   case ISD::FDIV:
5447   case ISD::FREM:
5448     // If both operands are undef, the result is undef. If 1 operand is undef,
5449     // the result is NaN. This should match the behavior of the IR optimizer.
5450     if (N1.isUndef() && N2.isUndef())
5451       return getUNDEF(VT);
5452     if (N1.isUndef() || N2.isUndef())
5453       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5454   }
5455   return SDValue();
5456 }
5457 
5458 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5459   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5460 
5461   // There's no need to assert on a byte-aligned pointer. All pointers are at
5462   // least byte aligned.
5463   if (A == Align(1))
5464     return Val;
5465 
5466   FoldingSetNodeID ID;
5467   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5468   ID.AddInteger(A.value());
5469 
5470   void *IP = nullptr;
5471   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5472     return SDValue(E, 0);
5473 
5474   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5475                                          Val.getValueType(), A);
5476   createOperands(N, {Val});
5477 
5478   CSEMap.InsertNode(N, IP);
5479   InsertNode(N);
5480 
5481   SDValue V(N, 0);
5482   NewSDValueDbgMsg(V, "Creating new node: ", this);
5483   return V;
5484 }
5485 
5486 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5487                               SDValue N1, SDValue N2) {
5488   SDNodeFlags Flags;
5489   if (Inserter)
5490     Flags = Inserter->getFlags();
5491   return getNode(Opcode, DL, VT, N1, N2, Flags);
5492 }
5493 
5494 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5495                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5496   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5497          N2.getOpcode() != ISD::DELETED_NODE &&
5498          "Operand is DELETED_NODE!");
5499   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5500   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5501   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5502   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5503 
5504   // Canonicalize constant to RHS if commutative.
5505   if (TLI->isCommutativeBinOp(Opcode)) {
5506     if (N1C && !N2C) {
5507       std::swap(N1C, N2C);
5508       std::swap(N1, N2);
5509     } else if (N1CFP && !N2CFP) {
5510       std::swap(N1CFP, N2CFP);
5511       std::swap(N1, N2);
5512     }
5513   }
5514 
5515   switch (Opcode) {
5516   default: break;
5517   case ISD::TokenFactor:
5518     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5519            N2.getValueType() == MVT::Other && "Invalid token factor!");
5520     // Fold trivial token factors.
5521     if (N1.getOpcode() == ISD::EntryToken) return N2;
5522     if (N2.getOpcode() == ISD::EntryToken) return N1;
5523     if (N1 == N2) return N1;
5524     break;
5525   case ISD::BUILD_VECTOR: {
5526     // Attempt to simplify BUILD_VECTOR.
5527     SDValue Ops[] = {N1, N2};
5528     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5529       return V;
5530     break;
5531   }
5532   case ISD::CONCAT_VECTORS: {
5533     SDValue Ops[] = {N1, N2};
5534     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5535       return V;
5536     break;
5537   }
5538   case ISD::AND:
5539     assert(VT.isInteger() && "This operator does not apply to FP types!");
5540     assert(N1.getValueType() == N2.getValueType() &&
5541            N1.getValueType() == VT && "Binary operator types must match!");
5542     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5543     // worth handling here.
5544     if (N2C && N2C->isNullValue())
5545       return N2;
5546     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
5547       return N1;
5548     break;
5549   case ISD::OR:
5550   case ISD::XOR:
5551   case ISD::ADD:
5552   case ISD::SUB:
5553     assert(VT.isInteger() && "This operator does not apply to FP types!");
5554     assert(N1.getValueType() == N2.getValueType() &&
5555            N1.getValueType() == VT && "Binary operator types must match!");
5556     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5557     // it's worth handling here.
5558     if (N2C && N2C->isNullValue())
5559       return N1;
5560     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5561         VT.getVectorElementType() == MVT::i1)
5562       return getNode(ISD::XOR, DL, VT, N1, N2);
5563     break;
5564   case ISD::MUL:
5565     assert(VT.isInteger() && "This operator does not apply to FP types!");
5566     assert(N1.getValueType() == N2.getValueType() &&
5567            N1.getValueType() == VT && "Binary operator types must match!");
5568     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5569       return getNode(ISD::AND, DL, VT, N1, N2);
5570     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5571       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5572       const APInt &N2CImm = N2C->getAPIntValue();
5573       return getVScale(DL, VT, MulImm * N2CImm);
5574     }
5575     break;
5576   case ISD::UDIV:
5577   case ISD::UREM:
5578   case ISD::MULHU:
5579   case ISD::MULHS:
5580   case ISD::SDIV:
5581   case ISD::SREM:
5582   case ISD::SADDSAT:
5583   case ISD::SSUBSAT:
5584   case ISD::UADDSAT:
5585   case ISD::USUBSAT:
5586     assert(VT.isInteger() && "This operator does not apply to FP types!");
5587     assert(N1.getValueType() == N2.getValueType() &&
5588            N1.getValueType() == VT && "Binary operator types must match!");
5589     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5590       // fold (add_sat x, y) -> (or x, y) for bool types.
5591       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5592         return getNode(ISD::OR, DL, VT, N1, N2);
5593       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5594       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5595         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5596     }
5597     break;
5598   case ISD::SMIN:
5599   case ISD::UMAX:
5600     assert(VT.isInteger() && "This operator does not apply to FP types!");
5601     assert(N1.getValueType() == N2.getValueType() &&
5602            N1.getValueType() == VT && "Binary operator types must match!");
5603     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5604       return getNode(ISD::OR, DL, VT, N1, N2);
5605     break;
5606   case ISD::SMAX:
5607   case ISD::UMIN:
5608     assert(VT.isInteger() && "This operator does not apply to FP types!");
5609     assert(N1.getValueType() == N2.getValueType() &&
5610            N1.getValueType() == VT && "Binary operator types must match!");
5611     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5612       return getNode(ISD::AND, DL, VT, N1, N2);
5613     break;
5614   case ISD::FADD:
5615   case ISD::FSUB:
5616   case ISD::FMUL:
5617   case ISD::FDIV:
5618   case ISD::FREM:
5619     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5620     assert(N1.getValueType() == N2.getValueType() &&
5621            N1.getValueType() == VT && "Binary operator types must match!");
5622     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5623       return V;
5624     break;
5625   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5626     assert(N1.getValueType() == VT &&
5627            N1.getValueType().isFloatingPoint() &&
5628            N2.getValueType().isFloatingPoint() &&
5629            "Invalid FCOPYSIGN!");
5630     break;
5631   case ISD::SHL:
5632     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5633       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5634       const APInt &ShiftImm = N2C->getAPIntValue();
5635       return getVScale(DL, VT, MulImm << ShiftImm);
5636     }
5637     LLVM_FALLTHROUGH;
5638   case ISD::SRA:
5639   case ISD::SRL:
5640     if (SDValue V = simplifyShift(N1, N2))
5641       return V;
5642     LLVM_FALLTHROUGH;
5643   case ISD::ROTL:
5644   case ISD::ROTR:
5645     assert(VT == N1.getValueType() &&
5646            "Shift operators return type must be the same as their first arg");
5647     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5648            "Shifts only work on integers");
5649     assert((!VT.isVector() || VT == N2.getValueType()) &&
5650            "Vector shift amounts must be in the same as their first arg");
5651     // Verify that the shift amount VT is big enough to hold valid shift
5652     // amounts.  This catches things like trying to shift an i1024 value by an
5653     // i8, which is easy to fall into in generic code that uses
5654     // TLI.getShiftAmount().
5655     assert(N2.getValueType().getScalarSizeInBits() >=
5656                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5657            "Invalid use of small shift amount with oversized value!");
5658 
5659     // Always fold shifts of i1 values so the code generator doesn't need to
5660     // handle them.  Since we know the size of the shift has to be less than the
5661     // size of the value, the shift/rotate count is guaranteed to be zero.
5662     if (VT == MVT::i1)
5663       return N1;
5664     if (N2C && N2C->isNullValue())
5665       return N1;
5666     break;
5667   case ISD::FP_ROUND:
5668     assert(VT.isFloatingPoint() &&
5669            N1.getValueType().isFloatingPoint() &&
5670            VT.bitsLE(N1.getValueType()) &&
5671            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5672            "Invalid FP_ROUND!");
5673     if (N1.getValueType() == VT) return N1;  // noop conversion.
5674     break;
5675   case ISD::AssertSext:
5676   case ISD::AssertZext: {
5677     EVT EVT = cast<VTSDNode>(N2)->getVT();
5678     assert(VT == N1.getValueType() && "Not an inreg extend!");
5679     assert(VT.isInteger() && EVT.isInteger() &&
5680            "Cannot *_EXTEND_INREG FP types");
5681     assert(!EVT.isVector() &&
5682            "AssertSExt/AssertZExt type should be the vector element type "
5683            "rather than the vector type!");
5684     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5685     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5686     break;
5687   }
5688   case ISD::SIGN_EXTEND_INREG: {
5689     EVT EVT = cast<VTSDNode>(N2)->getVT();
5690     assert(VT == N1.getValueType() && "Not an inreg extend!");
5691     assert(VT.isInteger() && EVT.isInteger() &&
5692            "Cannot *_EXTEND_INREG FP types");
5693     assert(EVT.isVector() == VT.isVector() &&
5694            "SIGN_EXTEND_INREG type should be vector iff the operand "
5695            "type is vector!");
5696     assert((!EVT.isVector() ||
5697             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5698            "Vector element counts must match in SIGN_EXTEND_INREG");
5699     assert(EVT.bitsLE(VT) && "Not extending!");
5700     if (EVT == VT) return N1;  // Not actually extending
5701 
5702     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5703       unsigned FromBits = EVT.getScalarSizeInBits();
5704       Val <<= Val.getBitWidth() - FromBits;
5705       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5706       return getConstant(Val, DL, ConstantVT);
5707     };
5708 
5709     if (N1C) {
5710       const APInt &Val = N1C->getAPIntValue();
5711       return SignExtendInReg(Val, VT);
5712     }
5713 
5714     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5715       SmallVector<SDValue, 8> Ops;
5716       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5717       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5718         SDValue Op = N1.getOperand(i);
5719         if (Op.isUndef()) {
5720           Ops.push_back(getUNDEF(OpVT));
5721           continue;
5722         }
5723         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5724         APInt Val = C->getAPIntValue();
5725         Ops.push_back(SignExtendInReg(Val, OpVT));
5726       }
5727       return getBuildVector(VT, DL, Ops);
5728     }
5729     break;
5730   }
5731   case ISD::FP_TO_SINT_SAT:
5732   case ISD::FP_TO_UINT_SAT: {
5733     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5734            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5735     assert(N1.getValueType().isVector() == VT.isVector() &&
5736            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5737            "vector!");
5738     assert((!VT.isVector() || VT.getVectorNumElements() ==
5739                                   N1.getValueType().getVectorNumElements()) &&
5740            "Vector element counts must match in FP_TO_*INT_SAT");
5741     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5742            "Type to saturate to must be a scalar.");
5743     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5744            "Not extending!");
5745     break;
5746   }
5747   case ISD::EXTRACT_VECTOR_ELT:
5748     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5749            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5750              element type of the vector.");
5751 
5752     // Extract from an undefined value or using an undefined index is undefined.
5753     if (N1.isUndef() || N2.isUndef())
5754       return getUNDEF(VT);
5755 
5756     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5757     // vectors. For scalable vectors we will provide appropriate support for
5758     // dealing with arbitrary indices.
5759     if (N2C && N1.getValueType().isFixedLengthVector() &&
5760         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5761       return getUNDEF(VT);
5762 
5763     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5764     // expanding copies of large vectors from registers. This only works for
5765     // fixed length vectors, since we need to know the exact number of
5766     // elements.
5767     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5768         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5769       unsigned Factor =
5770         N1.getOperand(0).getValueType().getVectorNumElements();
5771       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5772                      N1.getOperand(N2C->getZExtValue() / Factor),
5773                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5774     }
5775 
5776     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5777     // lowering is expanding large vector constants.
5778     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5779                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5780       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5781               N1.getValueType().isFixedLengthVector()) &&
5782              "BUILD_VECTOR used for scalable vectors");
5783       unsigned Index =
5784           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5785       SDValue Elt = N1.getOperand(Index);
5786 
5787       if (VT != Elt.getValueType())
5788         // If the vector element type is not legal, the BUILD_VECTOR operands
5789         // are promoted and implicitly truncated, and the result implicitly
5790         // extended. Make that explicit here.
5791         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5792 
5793       return Elt;
5794     }
5795 
5796     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5797     // operations are lowered to scalars.
5798     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5799       // If the indices are the same, return the inserted element else
5800       // if the indices are known different, extract the element from
5801       // the original vector.
5802       SDValue N1Op2 = N1.getOperand(2);
5803       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5804 
5805       if (N1Op2C && N2C) {
5806         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5807           if (VT == N1.getOperand(1).getValueType())
5808             return N1.getOperand(1);
5809           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5810         }
5811         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5812       }
5813     }
5814 
5815     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5816     // when vector types are scalarized and v1iX is legal.
5817     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5818     // Here we are completely ignoring the extract element index (N2),
5819     // which is fine for fixed width vectors, since any index other than 0
5820     // is undefined anyway. However, this cannot be ignored for scalable
5821     // vectors - in theory we could support this, but we don't want to do this
5822     // without a profitability check.
5823     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5824         N1.getValueType().isFixedLengthVector() &&
5825         N1.getValueType().getVectorNumElements() == 1) {
5826       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5827                      N1.getOperand(1));
5828     }
5829     break;
5830   case ISD::EXTRACT_ELEMENT:
5831     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5832     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5833            (N1.getValueType().isInteger() == VT.isInteger()) &&
5834            N1.getValueType() != VT &&
5835            "Wrong types for EXTRACT_ELEMENT!");
5836 
5837     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5838     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5839     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5840     if (N1.getOpcode() == ISD::BUILD_PAIR)
5841       return N1.getOperand(N2C->getZExtValue());
5842 
5843     // EXTRACT_ELEMENT of a constant int is also very common.
5844     if (N1C) {
5845       unsigned ElementSize = VT.getSizeInBits();
5846       unsigned Shift = ElementSize * N2C->getZExtValue();
5847       const APInt &Val = N1C->getAPIntValue();
5848       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5849     }
5850     break;
5851   case ISD::EXTRACT_SUBVECTOR: {
5852     EVT N1VT = N1.getValueType();
5853     assert(VT.isVector() && N1VT.isVector() &&
5854            "Extract subvector VTs must be vectors!");
5855     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5856            "Extract subvector VTs must have the same element type!");
5857     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5858            "Cannot extract a scalable vector from a fixed length vector!");
5859     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5860             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5861            "Extract subvector must be from larger vector to smaller vector!");
5862     assert(N2C && "Extract subvector index must be a constant");
5863     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5864             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5865                 N1VT.getVectorMinNumElements()) &&
5866            "Extract subvector overflow!");
5867     assert(N2C->getAPIntValue().getBitWidth() ==
5868                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5869            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5870 
5871     // Trivial extraction.
5872     if (VT == N1VT)
5873       return N1;
5874 
5875     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5876     if (N1.isUndef())
5877       return getUNDEF(VT);
5878 
5879     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5880     // the concat have the same type as the extract.
5881     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5882         VT == N1.getOperand(0).getValueType()) {
5883       unsigned Factor = VT.getVectorMinNumElements();
5884       return N1.getOperand(N2C->getZExtValue() / Factor);
5885     }
5886 
5887     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5888     // during shuffle legalization.
5889     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5890         VT == N1.getOperand(1).getValueType())
5891       return N1.getOperand(1);
5892     break;
5893   }
5894   }
5895 
5896   // Perform trivial constant folding.
5897   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5898     return SV;
5899 
5900   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5901     return V;
5902 
5903   // Canonicalize an UNDEF to the RHS, even over a constant.
5904   if (N1.isUndef()) {
5905     if (TLI->isCommutativeBinOp(Opcode)) {
5906       std::swap(N1, N2);
5907     } else {
5908       switch (Opcode) {
5909       case ISD::SIGN_EXTEND_INREG:
5910       case ISD::SUB:
5911         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5912       case ISD::UDIV:
5913       case ISD::SDIV:
5914       case ISD::UREM:
5915       case ISD::SREM:
5916       case ISD::SSUBSAT:
5917       case ISD::USUBSAT:
5918         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5919       }
5920     }
5921   }
5922 
5923   // Fold a bunch of operators when the RHS is undef.
5924   if (N2.isUndef()) {
5925     switch (Opcode) {
5926     case ISD::XOR:
5927       if (N1.isUndef())
5928         // Handle undef ^ undef -> 0 special case. This is a common
5929         // idiom (misuse).
5930         return getConstant(0, DL, VT);
5931       LLVM_FALLTHROUGH;
5932     case ISD::ADD:
5933     case ISD::SUB:
5934     case ISD::UDIV:
5935     case ISD::SDIV:
5936     case ISD::UREM:
5937     case ISD::SREM:
5938       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5939     case ISD::MUL:
5940     case ISD::AND:
5941     case ISD::SSUBSAT:
5942     case ISD::USUBSAT:
5943       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5944     case ISD::OR:
5945     case ISD::SADDSAT:
5946     case ISD::UADDSAT:
5947       return getAllOnesConstant(DL, VT);
5948     }
5949   }
5950 
5951   // Memoize this node if possible.
5952   SDNode *N;
5953   SDVTList VTs = getVTList(VT);
5954   SDValue Ops[] = {N1, N2};
5955   if (VT != MVT::Glue) {
5956     FoldingSetNodeID ID;
5957     AddNodeIDNode(ID, Opcode, VTs, Ops);
5958     void *IP = nullptr;
5959     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5960       E->intersectFlagsWith(Flags);
5961       return SDValue(E, 0);
5962     }
5963 
5964     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5965     N->setFlags(Flags);
5966     createOperands(N, Ops);
5967     CSEMap.InsertNode(N, IP);
5968   } else {
5969     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5970     createOperands(N, Ops);
5971   }
5972 
5973   InsertNode(N);
5974   SDValue V = SDValue(N, 0);
5975   NewSDValueDbgMsg(V, "Creating new node: ", this);
5976   return V;
5977 }
5978 
5979 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5980                               SDValue N1, SDValue N2, SDValue N3) {
5981   SDNodeFlags Flags;
5982   if (Inserter)
5983     Flags = Inserter->getFlags();
5984   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
5985 }
5986 
5987 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5988                               SDValue N1, SDValue N2, SDValue N3,
5989                               const SDNodeFlags Flags) {
5990   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5991          N2.getOpcode() != ISD::DELETED_NODE &&
5992          N3.getOpcode() != ISD::DELETED_NODE &&
5993          "Operand is DELETED_NODE!");
5994   // Perform various simplifications.
5995   switch (Opcode) {
5996   case ISD::FMA: {
5997     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5998     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5999            N3.getValueType() == VT && "FMA types must match!");
6000     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6001     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6002     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6003     if (N1CFP && N2CFP && N3CFP) {
6004       APFloat  V1 = N1CFP->getValueAPF();
6005       const APFloat &V2 = N2CFP->getValueAPF();
6006       const APFloat &V3 = N3CFP->getValueAPF();
6007       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6008       return getConstantFP(V1, DL, VT);
6009     }
6010     break;
6011   }
6012   case ISD::BUILD_VECTOR: {
6013     // Attempt to simplify BUILD_VECTOR.
6014     SDValue Ops[] = {N1, N2, N3};
6015     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6016       return V;
6017     break;
6018   }
6019   case ISD::CONCAT_VECTORS: {
6020     SDValue Ops[] = {N1, N2, N3};
6021     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6022       return V;
6023     break;
6024   }
6025   case ISD::SETCC: {
6026     assert(VT.isInteger() && "SETCC result type must be an integer!");
6027     assert(N1.getValueType() == N2.getValueType() &&
6028            "SETCC operands must have the same type!");
6029     assert(VT.isVector() == N1.getValueType().isVector() &&
6030            "SETCC type should be vector iff the operand type is vector!");
6031     assert((!VT.isVector() || VT.getVectorElementCount() ==
6032                                   N1.getValueType().getVectorElementCount()) &&
6033            "SETCC vector element counts must match!");
6034     // Use FoldSetCC to simplify SETCC's.
6035     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6036       return V;
6037     // Vector constant folding.
6038     SDValue Ops[] = {N1, N2, N3};
6039     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
6040       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6041       return V;
6042     }
6043     break;
6044   }
6045   case ISD::SELECT:
6046   case ISD::VSELECT:
6047     if (SDValue V = simplifySelect(N1, N2, N3))
6048       return V;
6049     break;
6050   case ISD::VECTOR_SHUFFLE:
6051     llvm_unreachable("should use getVectorShuffle constructor!");
6052   case ISD::INSERT_VECTOR_ELT: {
6053     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6054     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6055     // for scalable vectors where we will generate appropriate code to
6056     // deal with out-of-bounds cases correctly.
6057     if (N3C && N1.getValueType().isFixedLengthVector() &&
6058         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6059       return getUNDEF(VT);
6060 
6061     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6062     if (N3.isUndef())
6063       return getUNDEF(VT);
6064 
6065     // If the inserted element is an UNDEF, just use the input vector.
6066     if (N2.isUndef())
6067       return N1;
6068 
6069     break;
6070   }
6071   case ISD::INSERT_SUBVECTOR: {
6072     // Inserting undef into undef is still undef.
6073     if (N1.isUndef() && N2.isUndef())
6074       return getUNDEF(VT);
6075 
6076     EVT N2VT = N2.getValueType();
6077     assert(VT == N1.getValueType() &&
6078            "Dest and insert subvector source types must match!");
6079     assert(VT.isVector() && N2VT.isVector() &&
6080            "Insert subvector VTs must be vectors!");
6081     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6082            "Cannot insert a scalable vector into a fixed length vector!");
6083     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6084             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6085            "Insert subvector must be from smaller vector to larger vector!");
6086     assert(isa<ConstantSDNode>(N3) &&
6087            "Insert subvector index must be constant");
6088     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6089             (N2VT.getVectorMinNumElements() +
6090              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6091                 VT.getVectorMinNumElements()) &&
6092            "Insert subvector overflow!");
6093     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6094                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6095            "Constant index for INSERT_SUBVECTOR has an invalid size");
6096 
6097     // Trivial insertion.
6098     if (VT == N2VT)
6099       return N2;
6100 
6101     // If this is an insert of an extracted vector into an undef vector, we
6102     // can just use the input to the extract.
6103     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6104         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6105       return N2.getOperand(0);
6106     break;
6107   }
6108   case ISD::BITCAST:
6109     // Fold bit_convert nodes from a type to themselves.
6110     if (N1.getValueType() == VT)
6111       return N1;
6112     break;
6113   }
6114 
6115   // Memoize node if it doesn't produce a flag.
6116   SDNode *N;
6117   SDVTList VTs = getVTList(VT);
6118   SDValue Ops[] = {N1, N2, N3};
6119   if (VT != MVT::Glue) {
6120     FoldingSetNodeID ID;
6121     AddNodeIDNode(ID, Opcode, VTs, Ops);
6122     void *IP = nullptr;
6123     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6124       E->intersectFlagsWith(Flags);
6125       return SDValue(E, 0);
6126     }
6127 
6128     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6129     N->setFlags(Flags);
6130     createOperands(N, Ops);
6131     CSEMap.InsertNode(N, IP);
6132   } else {
6133     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6134     createOperands(N, Ops);
6135   }
6136 
6137   InsertNode(N);
6138   SDValue V = SDValue(N, 0);
6139   NewSDValueDbgMsg(V, "Creating new node: ", this);
6140   return V;
6141 }
6142 
6143 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6144                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6145   SDValue Ops[] = { N1, N2, N3, N4 };
6146   return getNode(Opcode, DL, VT, Ops);
6147 }
6148 
6149 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6150                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6151                               SDValue N5) {
6152   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6153   return getNode(Opcode, DL, VT, Ops);
6154 }
6155 
6156 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6157 /// the incoming stack arguments to be loaded from the stack.
6158 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6159   SmallVector<SDValue, 8> ArgChains;
6160 
6161   // Include the original chain at the beginning of the list. When this is
6162   // used by target LowerCall hooks, this helps legalize find the
6163   // CALLSEQ_BEGIN node.
6164   ArgChains.push_back(Chain);
6165 
6166   // Add a chain value for each stack argument.
6167   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
6168        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
6169     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
6170       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6171         if (FI->getIndex() < 0)
6172           ArgChains.push_back(SDValue(L, 1));
6173 
6174   // Build a tokenfactor for all the chains.
6175   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6176 }
6177 
6178 /// getMemsetValue - Vectorized representation of the memset value
6179 /// operand.
6180 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6181                               const SDLoc &dl) {
6182   assert(!Value.isUndef());
6183 
6184   unsigned NumBits = VT.getScalarSizeInBits();
6185   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6186     assert(C->getAPIntValue().getBitWidth() == 8);
6187     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6188     if (VT.isInteger()) {
6189       bool IsOpaque = VT.getSizeInBits() > 64 ||
6190           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6191       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6192     }
6193     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6194                              VT);
6195   }
6196 
6197   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6198   EVT IntVT = VT.getScalarType();
6199   if (!IntVT.isInteger())
6200     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6201 
6202   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6203   if (NumBits > 8) {
6204     // Use a multiplication with 0x010101... to extend the input to the
6205     // required length.
6206     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6207     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6208                         DAG.getConstant(Magic, dl, IntVT));
6209   }
6210 
6211   if (VT != Value.getValueType() && !VT.isInteger())
6212     Value = DAG.getBitcast(VT.getScalarType(), Value);
6213   if (VT != Value.getValueType())
6214     Value = DAG.getSplatBuildVector(VT, dl, Value);
6215 
6216   return Value;
6217 }
6218 
6219 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6220 /// used when a memcpy is turned into a memset when the source is a constant
6221 /// string ptr.
6222 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6223                                   const TargetLowering &TLI,
6224                                   const ConstantDataArraySlice &Slice) {
6225   // Handle vector with all elements zero.
6226   if (Slice.Array == nullptr) {
6227     if (VT.isInteger())
6228       return DAG.getConstant(0, dl, VT);
6229     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6230       return DAG.getConstantFP(0.0, dl, VT);
6231     if (VT.isVector()) {
6232       unsigned NumElts = VT.getVectorNumElements();
6233       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6234       return DAG.getNode(ISD::BITCAST, dl, VT,
6235                          DAG.getConstant(0, dl,
6236                                          EVT::getVectorVT(*DAG.getContext(),
6237                                                           EltVT, NumElts)));
6238     }
6239     llvm_unreachable("Expected type!");
6240   }
6241 
6242   assert(!VT.isVector() && "Can't handle vector type here!");
6243   unsigned NumVTBits = VT.getSizeInBits();
6244   unsigned NumVTBytes = NumVTBits / 8;
6245   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6246 
6247   APInt Val(NumVTBits, 0);
6248   if (DAG.getDataLayout().isLittleEndian()) {
6249     for (unsigned i = 0; i != NumBytes; ++i)
6250       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6251   } else {
6252     for (unsigned i = 0; i != NumBytes; ++i)
6253       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6254   }
6255 
6256   // If the "cost" of materializing the integer immediate is less than the cost
6257   // of a load, then it is cost effective to turn the load into the immediate.
6258   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6259   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6260     return DAG.getConstant(Val, dl, VT);
6261   return SDValue(nullptr, 0);
6262 }
6263 
6264 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6265                                            const SDLoc &DL,
6266                                            const SDNodeFlags Flags) {
6267   EVT VT = Base.getValueType();
6268   SDValue Index;
6269 
6270   if (Offset.isScalable())
6271     Index = getVScale(DL, Base.getValueType(),
6272                       APInt(Base.getValueSizeInBits().getFixedSize(),
6273                             Offset.getKnownMinSize()));
6274   else
6275     Index = getConstant(Offset.getFixedSize(), DL, VT);
6276 
6277   return getMemBasePlusOffset(Base, Index, DL, Flags);
6278 }
6279 
6280 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6281                                            const SDLoc &DL,
6282                                            const SDNodeFlags Flags) {
6283   assert(Offset.getValueType().isInteger());
6284   EVT BasePtrVT = Ptr.getValueType();
6285   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6286 }
6287 
6288 /// Returns true if memcpy source is constant data.
6289 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6290   uint64_t SrcDelta = 0;
6291   GlobalAddressSDNode *G = nullptr;
6292   if (Src.getOpcode() == ISD::GlobalAddress)
6293     G = cast<GlobalAddressSDNode>(Src);
6294   else if (Src.getOpcode() == ISD::ADD &&
6295            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6296            Src.getOperand(1).getOpcode() == ISD::Constant) {
6297     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6298     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6299   }
6300   if (!G)
6301     return false;
6302 
6303   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6304                                   SrcDelta + G->getOffset());
6305 }
6306 
6307 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6308                                       SelectionDAG &DAG) {
6309   // On Darwin, -Os means optimize for size without hurting performance, so
6310   // only really optimize for size when -Oz (MinSize) is used.
6311   if (MF.getTarget().getTargetTriple().isOSDarwin())
6312     return MF.getFunction().hasMinSize();
6313   return DAG.shouldOptForSize();
6314 }
6315 
6316 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6317                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6318                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6319                           SmallVector<SDValue, 16> &OutStoreChains) {
6320   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6321   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6322   SmallVector<SDValue, 16> GluedLoadChains;
6323   for (unsigned i = From; i < To; ++i) {
6324     OutChains.push_back(OutLoadChains[i]);
6325     GluedLoadChains.push_back(OutLoadChains[i]);
6326   }
6327 
6328   // Chain for all loads.
6329   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6330                                   GluedLoadChains);
6331 
6332   for (unsigned i = From; i < To; ++i) {
6333     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6334     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6335                                   ST->getBasePtr(), ST->getMemoryVT(),
6336                                   ST->getMemOperand());
6337     OutChains.push_back(NewStore);
6338   }
6339 }
6340 
6341 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6342                                        SDValue Chain, SDValue Dst, SDValue Src,
6343                                        uint64_t Size, Align Alignment,
6344                                        bool isVol, bool AlwaysInline,
6345                                        MachinePointerInfo DstPtrInfo,
6346                                        MachinePointerInfo SrcPtrInfo,
6347                                        const AAMDNodes &AAInfo) {
6348   // Turn a memcpy of undef to nop.
6349   // FIXME: We need to honor volatile even is Src is undef.
6350   if (Src.isUndef())
6351     return Chain;
6352 
6353   // Expand memcpy to a series of load and store ops if the size operand falls
6354   // below a certain threshold.
6355   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6356   // rather than maybe a humongous number of loads and stores.
6357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6358   const DataLayout &DL = DAG.getDataLayout();
6359   LLVMContext &C = *DAG.getContext();
6360   std::vector<EVT> MemOps;
6361   bool DstAlignCanChange = false;
6362   MachineFunction &MF = DAG.getMachineFunction();
6363   MachineFrameInfo &MFI = MF.getFrameInfo();
6364   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6365   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6366   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6367     DstAlignCanChange = true;
6368   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6369   if (!SrcAlign || Alignment > *SrcAlign)
6370     SrcAlign = Alignment;
6371   assert(SrcAlign && "SrcAlign must be set");
6372   ConstantDataArraySlice Slice;
6373   // If marked as volatile, perform a copy even when marked as constant.
6374   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6375   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6376   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6377   const MemOp Op = isZeroConstant
6378                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6379                                     /*IsZeroMemset*/ true, isVol)
6380                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6381                                      *SrcAlign, isVol, CopyFromConstant);
6382   if (!TLI.findOptimalMemOpLowering(
6383           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6384           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6385     return SDValue();
6386 
6387   if (DstAlignCanChange) {
6388     Type *Ty = MemOps[0].getTypeForEVT(C);
6389     Align NewAlign = DL.getABITypeAlign(Ty);
6390 
6391     // Don't promote to an alignment that would require dynamic stack
6392     // realignment.
6393     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6394     if (!TRI->hasStackRealignment(MF))
6395       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6396         NewAlign = NewAlign / 2;
6397 
6398     if (NewAlign > Alignment) {
6399       // Give the stack frame object a larger alignment if needed.
6400       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6401         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6402       Alignment = NewAlign;
6403     }
6404   }
6405 
6406   // Prepare AAInfo for loads/stores after lowering this memcpy.
6407   AAMDNodes NewAAInfo = AAInfo;
6408   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6409 
6410   MachineMemOperand::Flags MMOFlags =
6411       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6412   SmallVector<SDValue, 16> OutLoadChains;
6413   SmallVector<SDValue, 16> OutStoreChains;
6414   SmallVector<SDValue, 32> OutChains;
6415   unsigned NumMemOps = MemOps.size();
6416   uint64_t SrcOff = 0, DstOff = 0;
6417   for (unsigned i = 0; i != NumMemOps; ++i) {
6418     EVT VT = MemOps[i];
6419     unsigned VTSize = VT.getSizeInBits() / 8;
6420     SDValue Value, Store;
6421 
6422     if (VTSize > Size) {
6423       // Issuing an unaligned load / store pair  that overlaps with the previous
6424       // pair. Adjust the offset accordingly.
6425       assert(i == NumMemOps-1 && i != 0);
6426       SrcOff -= VTSize - Size;
6427       DstOff -= VTSize - Size;
6428     }
6429 
6430     if (CopyFromConstant &&
6431         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6432       // It's unlikely a store of a vector immediate can be done in a single
6433       // instruction. It would require a load from a constantpool first.
6434       // We only handle zero vectors here.
6435       // FIXME: Handle other cases where store of vector immediate is done in
6436       // a single instruction.
6437       ConstantDataArraySlice SubSlice;
6438       if (SrcOff < Slice.Length) {
6439         SubSlice = Slice;
6440         SubSlice.move(SrcOff);
6441       } else {
6442         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6443         SubSlice.Array = nullptr;
6444         SubSlice.Offset = 0;
6445         SubSlice.Length = VTSize;
6446       }
6447       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6448       if (Value.getNode()) {
6449         Store = DAG.getStore(
6450             Chain, dl, Value,
6451             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6452             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6453         OutChains.push_back(Store);
6454       }
6455     }
6456 
6457     if (!Store.getNode()) {
6458       // The type might not be legal for the target.  This should only happen
6459       // if the type is smaller than a legal type, as on PPC, so the right
6460       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6461       // to Load/Store if NVT==VT.
6462       // FIXME does the case above also need this?
6463       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6464       assert(NVT.bitsGE(VT));
6465 
6466       bool isDereferenceable =
6467         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6468       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6469       if (isDereferenceable)
6470         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6471 
6472       Value = DAG.getExtLoad(
6473           ISD::EXTLOAD, dl, NVT, Chain,
6474           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6475           SrcPtrInfo.getWithOffset(SrcOff), VT,
6476           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6477       OutLoadChains.push_back(Value.getValue(1));
6478 
6479       Store = DAG.getTruncStore(
6480           Chain, dl, Value,
6481           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6482           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6483       OutStoreChains.push_back(Store);
6484     }
6485     SrcOff += VTSize;
6486     DstOff += VTSize;
6487     Size -= VTSize;
6488   }
6489 
6490   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6491                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6492   unsigned NumLdStInMemcpy = OutStoreChains.size();
6493 
6494   if (NumLdStInMemcpy) {
6495     // It may be that memcpy might be converted to memset if it's memcpy
6496     // of constants. In such a case, we won't have loads and stores, but
6497     // just stores. In the absence of loads, there is nothing to gang up.
6498     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6499       // If target does not care, just leave as it.
6500       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6501         OutChains.push_back(OutLoadChains[i]);
6502         OutChains.push_back(OutStoreChains[i]);
6503       }
6504     } else {
6505       // Ld/St less than/equal limit set by target.
6506       if (NumLdStInMemcpy <= GluedLdStLimit) {
6507           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6508                                         NumLdStInMemcpy, OutLoadChains,
6509                                         OutStoreChains);
6510       } else {
6511         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6512         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6513         unsigned GlueIter = 0;
6514 
6515         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6516           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6517           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6518 
6519           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6520                                        OutLoadChains, OutStoreChains);
6521           GlueIter += GluedLdStLimit;
6522         }
6523 
6524         // Residual ld/st.
6525         if (RemainingLdStInMemcpy) {
6526           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6527                                         RemainingLdStInMemcpy, OutLoadChains,
6528                                         OutStoreChains);
6529         }
6530       }
6531     }
6532   }
6533   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6534 }
6535 
6536 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6537                                         SDValue Chain, SDValue Dst, SDValue Src,
6538                                         uint64_t Size, Align Alignment,
6539                                         bool isVol, bool AlwaysInline,
6540                                         MachinePointerInfo DstPtrInfo,
6541                                         MachinePointerInfo SrcPtrInfo,
6542                                         const AAMDNodes &AAInfo) {
6543   // Turn a memmove of undef to nop.
6544   // FIXME: We need to honor volatile even is Src is undef.
6545   if (Src.isUndef())
6546     return Chain;
6547 
6548   // Expand memmove to a series of load and store ops if the size operand falls
6549   // below a certain threshold.
6550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6551   const DataLayout &DL = DAG.getDataLayout();
6552   LLVMContext &C = *DAG.getContext();
6553   std::vector<EVT> MemOps;
6554   bool DstAlignCanChange = false;
6555   MachineFunction &MF = DAG.getMachineFunction();
6556   MachineFrameInfo &MFI = MF.getFrameInfo();
6557   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6558   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6559   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6560     DstAlignCanChange = true;
6561   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6562   if (!SrcAlign || Alignment > *SrcAlign)
6563     SrcAlign = Alignment;
6564   assert(SrcAlign && "SrcAlign must be set");
6565   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6566   if (!TLI.findOptimalMemOpLowering(
6567           MemOps, Limit,
6568           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6569                       /*IsVolatile*/ true),
6570           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6571           MF.getFunction().getAttributes()))
6572     return SDValue();
6573 
6574   if (DstAlignCanChange) {
6575     Type *Ty = MemOps[0].getTypeForEVT(C);
6576     Align NewAlign = DL.getABITypeAlign(Ty);
6577     if (NewAlign > Alignment) {
6578       // Give the stack frame object a larger alignment if needed.
6579       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6580         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6581       Alignment = NewAlign;
6582     }
6583   }
6584 
6585   // Prepare AAInfo for loads/stores after lowering this memmove.
6586   AAMDNodes NewAAInfo = AAInfo;
6587   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6588 
6589   MachineMemOperand::Flags MMOFlags =
6590       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6591   uint64_t SrcOff = 0, DstOff = 0;
6592   SmallVector<SDValue, 8> LoadValues;
6593   SmallVector<SDValue, 8> LoadChains;
6594   SmallVector<SDValue, 8> OutChains;
6595   unsigned NumMemOps = MemOps.size();
6596   for (unsigned i = 0; i < NumMemOps; i++) {
6597     EVT VT = MemOps[i];
6598     unsigned VTSize = VT.getSizeInBits() / 8;
6599     SDValue Value;
6600 
6601     bool isDereferenceable =
6602       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6603     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6604     if (isDereferenceable)
6605       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6606 
6607     Value = DAG.getLoad(
6608         VT, dl, Chain,
6609         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6610         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6611     LoadValues.push_back(Value);
6612     LoadChains.push_back(Value.getValue(1));
6613     SrcOff += VTSize;
6614   }
6615   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6616   OutChains.clear();
6617   for (unsigned i = 0; i < NumMemOps; i++) {
6618     EVT VT = MemOps[i];
6619     unsigned VTSize = VT.getSizeInBits() / 8;
6620     SDValue Store;
6621 
6622     Store = DAG.getStore(
6623         Chain, dl, LoadValues[i],
6624         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6625         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6626     OutChains.push_back(Store);
6627     DstOff += VTSize;
6628   }
6629 
6630   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6631 }
6632 
6633 /// Lower the call to 'memset' intrinsic function into a series of store
6634 /// operations.
6635 ///
6636 /// \param DAG Selection DAG where lowered code is placed.
6637 /// \param dl Link to corresponding IR location.
6638 /// \param Chain Control flow dependency.
6639 /// \param Dst Pointer to destination memory location.
6640 /// \param Src Value of byte to write into the memory.
6641 /// \param Size Number of bytes to write.
6642 /// \param Alignment Alignment of the destination in bytes.
6643 /// \param isVol True if destination is volatile.
6644 /// \param DstPtrInfo IR information on the memory pointer.
6645 /// \returns New head in the control flow, if lowering was successful, empty
6646 /// SDValue otherwise.
6647 ///
6648 /// The function tries to replace 'llvm.memset' intrinsic with several store
6649 /// operations and value calculation code. This is usually profitable for small
6650 /// memory size.
6651 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6652                                SDValue Chain, SDValue Dst, SDValue Src,
6653                                uint64_t Size, Align Alignment, bool isVol,
6654                                MachinePointerInfo DstPtrInfo,
6655                                const AAMDNodes &AAInfo) {
6656   // Turn a memset of undef to nop.
6657   // FIXME: We need to honor volatile even is Src is undef.
6658   if (Src.isUndef())
6659     return Chain;
6660 
6661   // Expand memset to a series of load/store ops if the size operand
6662   // falls below a certain threshold.
6663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6664   std::vector<EVT> MemOps;
6665   bool DstAlignCanChange = false;
6666   MachineFunction &MF = DAG.getMachineFunction();
6667   MachineFrameInfo &MFI = MF.getFrameInfo();
6668   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6669   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6670   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6671     DstAlignCanChange = true;
6672   bool IsZeroVal =
6673     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6674   if (!TLI.findOptimalMemOpLowering(
6675           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6676           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6677           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6678     return SDValue();
6679 
6680   if (DstAlignCanChange) {
6681     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6682     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6683     if (NewAlign > Alignment) {
6684       // Give the stack frame object a larger alignment if needed.
6685       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6686         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6687       Alignment = NewAlign;
6688     }
6689   }
6690 
6691   SmallVector<SDValue, 8> OutChains;
6692   uint64_t DstOff = 0;
6693   unsigned NumMemOps = MemOps.size();
6694 
6695   // Find the largest store and generate the bit pattern for it.
6696   EVT LargestVT = MemOps[0];
6697   for (unsigned i = 1; i < NumMemOps; i++)
6698     if (MemOps[i].bitsGT(LargestVT))
6699       LargestVT = MemOps[i];
6700   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6701 
6702   // Prepare AAInfo for loads/stores after lowering this memset.
6703   AAMDNodes NewAAInfo = AAInfo;
6704   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6705 
6706   for (unsigned i = 0; i < NumMemOps; i++) {
6707     EVT VT = MemOps[i];
6708     unsigned VTSize = VT.getSizeInBits() / 8;
6709     if (VTSize > Size) {
6710       // Issuing an unaligned load / store pair  that overlaps with the previous
6711       // pair. Adjust the offset accordingly.
6712       assert(i == NumMemOps-1 && i != 0);
6713       DstOff -= VTSize - Size;
6714     }
6715 
6716     // If this store is smaller than the largest store see whether we can get
6717     // the smaller value for free with a truncate.
6718     SDValue Value = MemSetValue;
6719     if (VT.bitsLT(LargestVT)) {
6720       if (!LargestVT.isVector() && !VT.isVector() &&
6721           TLI.isTruncateFree(LargestVT, VT))
6722         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6723       else
6724         Value = getMemsetValue(Src, VT, DAG, dl);
6725     }
6726     assert(Value.getValueType() == VT && "Value with wrong type.");
6727     SDValue Store = DAG.getStore(
6728         Chain, dl, Value,
6729         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6730         DstPtrInfo.getWithOffset(DstOff), Alignment,
6731         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6732         NewAAInfo);
6733     OutChains.push_back(Store);
6734     DstOff += VT.getSizeInBits() / 8;
6735     Size -= VTSize;
6736   }
6737 
6738   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6739 }
6740 
6741 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6742                                             unsigned AS) {
6743   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6744   // pointer operands can be losslessly bitcasted to pointers of address space 0
6745   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6746     report_fatal_error("cannot lower memory intrinsic in address space " +
6747                        Twine(AS));
6748   }
6749 }
6750 
6751 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6752                                 SDValue Src, SDValue Size, Align Alignment,
6753                                 bool isVol, bool AlwaysInline, bool isTailCall,
6754                                 MachinePointerInfo DstPtrInfo,
6755                                 MachinePointerInfo SrcPtrInfo,
6756                                 const AAMDNodes &AAInfo) {
6757   // Check to see if we should lower the memcpy to loads and stores first.
6758   // For cases within the target-specified limits, this is the best choice.
6759   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6760   if (ConstantSize) {
6761     // Memcpy with size zero? Just return the original chain.
6762     if (ConstantSize->isNullValue())
6763       return Chain;
6764 
6765     SDValue Result = getMemcpyLoadsAndStores(
6766         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6767         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6768     if (Result.getNode())
6769       return Result;
6770   }
6771 
6772   // Then check to see if we should lower the memcpy with target-specific
6773   // code. If the target chooses to do this, this is the next best.
6774   if (TSI) {
6775     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6776         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6777         DstPtrInfo, SrcPtrInfo);
6778     if (Result.getNode())
6779       return Result;
6780   }
6781 
6782   // If we really need inline code and the target declined to provide it,
6783   // use a (potentially long) sequence of loads and stores.
6784   if (AlwaysInline) {
6785     assert(ConstantSize && "AlwaysInline requires a constant size!");
6786     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6787                                    ConstantSize->getZExtValue(), Alignment,
6788                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6789   }
6790 
6791   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6792   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6793 
6794   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6795   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6796   // respect volatile, so they may do things like read or write memory
6797   // beyond the given memory regions. But fixing this isn't easy, and most
6798   // people don't care.
6799 
6800   // Emit a library call.
6801   TargetLowering::ArgListTy Args;
6802   TargetLowering::ArgListEntry Entry;
6803   Entry.Ty = Type::getInt8PtrTy(*getContext());
6804   Entry.Node = Dst; Args.push_back(Entry);
6805   Entry.Node = Src; Args.push_back(Entry);
6806 
6807   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6808   Entry.Node = Size; Args.push_back(Entry);
6809   // FIXME: pass in SDLoc
6810   TargetLowering::CallLoweringInfo CLI(*this);
6811   CLI.setDebugLoc(dl)
6812       .setChain(Chain)
6813       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6814                     Dst.getValueType().getTypeForEVT(*getContext()),
6815                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6816                                       TLI->getPointerTy(getDataLayout())),
6817                     std::move(Args))
6818       .setDiscardResult()
6819       .setTailCall(isTailCall);
6820 
6821   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6822   return CallResult.second;
6823 }
6824 
6825 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6826                                       SDValue Dst, unsigned DstAlign,
6827                                       SDValue Src, unsigned SrcAlign,
6828                                       SDValue Size, Type *SizeTy,
6829                                       unsigned ElemSz, bool isTailCall,
6830                                       MachinePointerInfo DstPtrInfo,
6831                                       MachinePointerInfo SrcPtrInfo) {
6832   // Emit a library call.
6833   TargetLowering::ArgListTy Args;
6834   TargetLowering::ArgListEntry Entry;
6835   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6836   Entry.Node = Dst;
6837   Args.push_back(Entry);
6838 
6839   Entry.Node = Src;
6840   Args.push_back(Entry);
6841 
6842   Entry.Ty = SizeTy;
6843   Entry.Node = Size;
6844   Args.push_back(Entry);
6845 
6846   RTLIB::Libcall LibraryCall =
6847       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6848   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6849     report_fatal_error("Unsupported element size");
6850 
6851   TargetLowering::CallLoweringInfo CLI(*this);
6852   CLI.setDebugLoc(dl)
6853       .setChain(Chain)
6854       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6855                     Type::getVoidTy(*getContext()),
6856                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6857                                       TLI->getPointerTy(getDataLayout())),
6858                     std::move(Args))
6859       .setDiscardResult()
6860       .setTailCall(isTailCall);
6861 
6862   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6863   return CallResult.second;
6864 }
6865 
6866 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6867                                  SDValue Src, SDValue Size, Align Alignment,
6868                                  bool isVol, bool isTailCall,
6869                                  MachinePointerInfo DstPtrInfo,
6870                                  MachinePointerInfo SrcPtrInfo,
6871                                  const AAMDNodes &AAInfo) {
6872   // Check to see if we should lower the memmove to loads and stores first.
6873   // For cases within the target-specified limits, this is the best choice.
6874   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6875   if (ConstantSize) {
6876     // Memmove with size zero? Just return the original chain.
6877     if (ConstantSize->isNullValue())
6878       return Chain;
6879 
6880     SDValue Result = getMemmoveLoadsAndStores(
6881         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6882         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6883     if (Result.getNode())
6884       return Result;
6885   }
6886 
6887   // Then check to see if we should lower the memmove with target-specific
6888   // code. If the target chooses to do this, this is the next best.
6889   if (TSI) {
6890     SDValue Result =
6891         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6892                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6893     if (Result.getNode())
6894       return Result;
6895   }
6896 
6897   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6898   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6899 
6900   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6901   // not be safe.  See memcpy above for more details.
6902 
6903   // Emit a library call.
6904   TargetLowering::ArgListTy Args;
6905   TargetLowering::ArgListEntry Entry;
6906   Entry.Ty = Type::getInt8PtrTy(*getContext());
6907   Entry.Node = Dst; Args.push_back(Entry);
6908   Entry.Node = Src; Args.push_back(Entry);
6909 
6910   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6911   Entry.Node = Size; Args.push_back(Entry);
6912   // FIXME:  pass in SDLoc
6913   TargetLowering::CallLoweringInfo CLI(*this);
6914   CLI.setDebugLoc(dl)
6915       .setChain(Chain)
6916       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6917                     Dst.getValueType().getTypeForEVT(*getContext()),
6918                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6919                                       TLI->getPointerTy(getDataLayout())),
6920                     std::move(Args))
6921       .setDiscardResult()
6922       .setTailCall(isTailCall);
6923 
6924   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6925   return CallResult.second;
6926 }
6927 
6928 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6929                                        SDValue Dst, unsigned DstAlign,
6930                                        SDValue Src, unsigned SrcAlign,
6931                                        SDValue Size, Type *SizeTy,
6932                                        unsigned ElemSz, bool isTailCall,
6933                                        MachinePointerInfo DstPtrInfo,
6934                                        MachinePointerInfo SrcPtrInfo) {
6935   // Emit a library call.
6936   TargetLowering::ArgListTy Args;
6937   TargetLowering::ArgListEntry Entry;
6938   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6939   Entry.Node = Dst;
6940   Args.push_back(Entry);
6941 
6942   Entry.Node = Src;
6943   Args.push_back(Entry);
6944 
6945   Entry.Ty = SizeTy;
6946   Entry.Node = Size;
6947   Args.push_back(Entry);
6948 
6949   RTLIB::Libcall LibraryCall =
6950       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6951   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6952     report_fatal_error("Unsupported element size");
6953 
6954   TargetLowering::CallLoweringInfo CLI(*this);
6955   CLI.setDebugLoc(dl)
6956       .setChain(Chain)
6957       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6958                     Type::getVoidTy(*getContext()),
6959                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6960                                       TLI->getPointerTy(getDataLayout())),
6961                     std::move(Args))
6962       .setDiscardResult()
6963       .setTailCall(isTailCall);
6964 
6965   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6966   return CallResult.second;
6967 }
6968 
6969 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6970                                 SDValue Src, SDValue Size, Align Alignment,
6971                                 bool isVol, bool isTailCall,
6972                                 MachinePointerInfo DstPtrInfo,
6973                                 const AAMDNodes &AAInfo) {
6974   // Check to see if we should lower the memset to stores first.
6975   // For cases within the target-specified limits, this is the best choice.
6976   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6977   if (ConstantSize) {
6978     // Memset with size zero? Just return the original chain.
6979     if (ConstantSize->isNullValue())
6980       return Chain;
6981 
6982     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
6983                                      ConstantSize->getZExtValue(), Alignment,
6984                                      isVol, DstPtrInfo, AAInfo);
6985 
6986     if (Result.getNode())
6987       return Result;
6988   }
6989 
6990   // Then check to see if we should lower the memset with target-specific
6991   // code. If the target chooses to do this, this is the next best.
6992   if (TSI) {
6993     SDValue Result = TSI->EmitTargetCodeForMemset(
6994         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
6995     if (Result.getNode())
6996       return Result;
6997   }
6998 
6999   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7000 
7001   // Emit a library call.
7002   TargetLowering::ArgListTy Args;
7003   TargetLowering::ArgListEntry Entry;
7004   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7005   Args.push_back(Entry);
7006   Entry.Node = Src;
7007   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7008   Args.push_back(Entry);
7009   Entry.Node = Size;
7010   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7011   Args.push_back(Entry);
7012 
7013   // FIXME: pass in SDLoc
7014   TargetLowering::CallLoweringInfo CLI(*this);
7015   CLI.setDebugLoc(dl)
7016       .setChain(Chain)
7017       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7018                     Dst.getValueType().getTypeForEVT(*getContext()),
7019                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7020                                       TLI->getPointerTy(getDataLayout())),
7021                     std::move(Args))
7022       .setDiscardResult()
7023       .setTailCall(isTailCall);
7024 
7025   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7026   return CallResult.second;
7027 }
7028 
7029 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7030                                       SDValue Dst, unsigned DstAlign,
7031                                       SDValue Value, SDValue Size, Type *SizeTy,
7032                                       unsigned ElemSz, bool isTailCall,
7033                                       MachinePointerInfo DstPtrInfo) {
7034   // Emit a library call.
7035   TargetLowering::ArgListTy Args;
7036   TargetLowering::ArgListEntry Entry;
7037   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7038   Entry.Node = Dst;
7039   Args.push_back(Entry);
7040 
7041   Entry.Ty = Type::getInt8Ty(*getContext());
7042   Entry.Node = Value;
7043   Args.push_back(Entry);
7044 
7045   Entry.Ty = SizeTy;
7046   Entry.Node = Size;
7047   Args.push_back(Entry);
7048 
7049   RTLIB::Libcall LibraryCall =
7050       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7051   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7052     report_fatal_error("Unsupported element size");
7053 
7054   TargetLowering::CallLoweringInfo CLI(*this);
7055   CLI.setDebugLoc(dl)
7056       .setChain(Chain)
7057       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7058                     Type::getVoidTy(*getContext()),
7059                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7060                                       TLI->getPointerTy(getDataLayout())),
7061                     std::move(Args))
7062       .setDiscardResult()
7063       .setTailCall(isTailCall);
7064 
7065   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7066   return CallResult.second;
7067 }
7068 
7069 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7070                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7071                                 MachineMemOperand *MMO) {
7072   FoldingSetNodeID ID;
7073   ID.AddInteger(MemVT.getRawBits());
7074   AddNodeIDNode(ID, Opcode, VTList, Ops);
7075   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7076   void* IP = nullptr;
7077   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7078     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7079     return SDValue(E, 0);
7080   }
7081 
7082   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7083                                     VTList, MemVT, MMO);
7084   createOperands(N, Ops);
7085 
7086   CSEMap.InsertNode(N, IP);
7087   InsertNode(N);
7088   return SDValue(N, 0);
7089 }
7090 
7091 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7092                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7093                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7094                                        MachineMemOperand *MMO) {
7095   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7096          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7097   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7098 
7099   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7100   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7101 }
7102 
7103 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7104                                 SDValue Chain, SDValue Ptr, SDValue Val,
7105                                 MachineMemOperand *MMO) {
7106   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7107           Opcode == ISD::ATOMIC_LOAD_SUB ||
7108           Opcode == ISD::ATOMIC_LOAD_AND ||
7109           Opcode == ISD::ATOMIC_LOAD_CLR ||
7110           Opcode == ISD::ATOMIC_LOAD_OR ||
7111           Opcode == ISD::ATOMIC_LOAD_XOR ||
7112           Opcode == ISD::ATOMIC_LOAD_NAND ||
7113           Opcode == ISD::ATOMIC_LOAD_MIN ||
7114           Opcode == ISD::ATOMIC_LOAD_MAX ||
7115           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7116           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7117           Opcode == ISD::ATOMIC_LOAD_FADD ||
7118           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7119           Opcode == ISD::ATOMIC_SWAP ||
7120           Opcode == ISD::ATOMIC_STORE) &&
7121          "Invalid Atomic Op");
7122 
7123   EVT VT = Val.getValueType();
7124 
7125   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7126                                                getVTList(VT, MVT::Other);
7127   SDValue Ops[] = {Chain, Ptr, Val};
7128   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7129 }
7130 
7131 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7132                                 EVT VT, SDValue Chain, SDValue Ptr,
7133                                 MachineMemOperand *MMO) {
7134   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7135 
7136   SDVTList VTs = getVTList(VT, MVT::Other);
7137   SDValue Ops[] = {Chain, Ptr};
7138   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7139 }
7140 
7141 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7142 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7143   if (Ops.size() == 1)
7144     return Ops[0];
7145 
7146   SmallVector<EVT, 4> VTs;
7147   VTs.reserve(Ops.size());
7148   for (const SDValue &Op : Ops)
7149     VTs.push_back(Op.getValueType());
7150   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7151 }
7152 
7153 SDValue SelectionDAG::getMemIntrinsicNode(
7154     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7155     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7156     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7157   if (!Size && MemVT.isScalableVector())
7158     Size = MemoryLocation::UnknownSize;
7159   else if (!Size)
7160     Size = MemVT.getStoreSize();
7161 
7162   MachineFunction &MF = getMachineFunction();
7163   MachineMemOperand *MMO =
7164       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7165 
7166   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7167 }
7168 
7169 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7170                                           SDVTList VTList,
7171                                           ArrayRef<SDValue> Ops, EVT MemVT,
7172                                           MachineMemOperand *MMO) {
7173   assert((Opcode == ISD::INTRINSIC_VOID ||
7174           Opcode == ISD::INTRINSIC_W_CHAIN ||
7175           Opcode == ISD::PREFETCH ||
7176           ((int)Opcode <= std::numeric_limits<int>::max() &&
7177            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7178          "Opcode is not a memory-accessing opcode!");
7179 
7180   // Memoize the node unless it returns a flag.
7181   MemIntrinsicSDNode *N;
7182   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7183     FoldingSetNodeID ID;
7184     AddNodeIDNode(ID, Opcode, VTList, Ops);
7185     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7186         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7187     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7188     void *IP = nullptr;
7189     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7190       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7191       return SDValue(E, 0);
7192     }
7193 
7194     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7195                                       VTList, MemVT, MMO);
7196     createOperands(N, Ops);
7197 
7198   CSEMap.InsertNode(N, IP);
7199   } else {
7200     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7201                                       VTList, MemVT, MMO);
7202     createOperands(N, Ops);
7203   }
7204   InsertNode(N);
7205   SDValue V(N, 0);
7206   NewSDValueDbgMsg(V, "Creating new node: ", this);
7207   return V;
7208 }
7209 
7210 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7211                                       SDValue Chain, int FrameIndex,
7212                                       int64_t Size, int64_t Offset) {
7213   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7214   const auto VTs = getVTList(MVT::Other);
7215   SDValue Ops[2] = {
7216       Chain,
7217       getFrameIndex(FrameIndex,
7218                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7219                     true)};
7220 
7221   FoldingSetNodeID ID;
7222   AddNodeIDNode(ID, Opcode, VTs, Ops);
7223   ID.AddInteger(FrameIndex);
7224   ID.AddInteger(Size);
7225   ID.AddInteger(Offset);
7226   void *IP = nullptr;
7227   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7228     return SDValue(E, 0);
7229 
7230   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7231       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7232   createOperands(N, Ops);
7233   CSEMap.InsertNode(N, IP);
7234   InsertNode(N);
7235   SDValue V(N, 0);
7236   NewSDValueDbgMsg(V, "Creating new node: ", this);
7237   return V;
7238 }
7239 
7240 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7241                                          uint64_t Guid, uint64_t Index,
7242                                          uint32_t Attr) {
7243   const unsigned Opcode = ISD::PSEUDO_PROBE;
7244   const auto VTs = getVTList(MVT::Other);
7245   SDValue Ops[] = {Chain};
7246   FoldingSetNodeID ID;
7247   AddNodeIDNode(ID, Opcode, VTs, Ops);
7248   ID.AddInteger(Guid);
7249   ID.AddInteger(Index);
7250   void *IP = nullptr;
7251   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7252     return SDValue(E, 0);
7253 
7254   auto *N = newSDNode<PseudoProbeSDNode>(
7255       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7256   createOperands(N, Ops);
7257   CSEMap.InsertNode(N, IP);
7258   InsertNode(N);
7259   SDValue V(N, 0);
7260   NewSDValueDbgMsg(V, "Creating new node: ", this);
7261   return V;
7262 }
7263 
7264 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7265 /// MachinePointerInfo record from it.  This is particularly useful because the
7266 /// code generator has many cases where it doesn't bother passing in a
7267 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7268 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7269                                            SelectionDAG &DAG, SDValue Ptr,
7270                                            int64_t Offset = 0) {
7271   // If this is FI+Offset, we can model it.
7272   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7273     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7274                                              FI->getIndex(), Offset);
7275 
7276   // If this is (FI+Offset1)+Offset2, we can model it.
7277   if (Ptr.getOpcode() != ISD::ADD ||
7278       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7279       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7280     return Info;
7281 
7282   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7283   return MachinePointerInfo::getFixedStack(
7284       DAG.getMachineFunction(), FI,
7285       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7286 }
7287 
7288 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7289 /// MachinePointerInfo record from it.  This is particularly useful because the
7290 /// code generator has many cases where it doesn't bother passing in a
7291 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7292 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7293                                            SelectionDAG &DAG, SDValue Ptr,
7294                                            SDValue OffsetOp) {
7295   // If the 'Offset' value isn't a constant, we can't handle this.
7296   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7297     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7298   if (OffsetOp.isUndef())
7299     return InferPointerInfo(Info, DAG, Ptr);
7300   return Info;
7301 }
7302 
7303 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7304                               EVT VT, const SDLoc &dl, SDValue Chain,
7305                               SDValue Ptr, SDValue Offset,
7306                               MachinePointerInfo PtrInfo, EVT MemVT,
7307                               Align Alignment,
7308                               MachineMemOperand::Flags MMOFlags,
7309                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7310   assert(Chain.getValueType() == MVT::Other &&
7311         "Invalid chain type");
7312 
7313   MMOFlags |= MachineMemOperand::MOLoad;
7314   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7315   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7316   // clients.
7317   if (PtrInfo.V.isNull())
7318     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7319 
7320   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7321   MachineFunction &MF = getMachineFunction();
7322   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7323                                                    Alignment, AAInfo, Ranges);
7324   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7325 }
7326 
7327 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7328                               EVT VT, const SDLoc &dl, SDValue Chain,
7329                               SDValue Ptr, SDValue Offset, EVT MemVT,
7330                               MachineMemOperand *MMO) {
7331   if (VT == MemVT) {
7332     ExtType = ISD::NON_EXTLOAD;
7333   } else if (ExtType == ISD::NON_EXTLOAD) {
7334     assert(VT == MemVT && "Non-extending load from different memory type!");
7335   } else {
7336     // Extending load.
7337     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7338            "Should only be an extending load, not truncating!");
7339     assert(VT.isInteger() == MemVT.isInteger() &&
7340            "Cannot convert from FP to Int or Int -> FP!");
7341     assert(VT.isVector() == MemVT.isVector() &&
7342            "Cannot use an ext load to convert to or from a vector!");
7343     assert((!VT.isVector() ||
7344             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7345            "Cannot use an ext load to change the number of vector elements!");
7346   }
7347 
7348   bool Indexed = AM != ISD::UNINDEXED;
7349   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7350 
7351   SDVTList VTs = Indexed ?
7352     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7353   SDValue Ops[] = { Chain, Ptr, Offset };
7354   FoldingSetNodeID ID;
7355   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7356   ID.AddInteger(MemVT.getRawBits());
7357   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7358       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7359   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7360   void *IP = nullptr;
7361   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7362     cast<LoadSDNode>(E)->refineAlignment(MMO);
7363     return SDValue(E, 0);
7364   }
7365   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7366                                   ExtType, MemVT, MMO);
7367   createOperands(N, Ops);
7368 
7369   CSEMap.InsertNode(N, IP);
7370   InsertNode(N);
7371   SDValue V(N, 0);
7372   NewSDValueDbgMsg(V, "Creating new node: ", this);
7373   return V;
7374 }
7375 
7376 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7377                               SDValue Ptr, MachinePointerInfo PtrInfo,
7378                               MaybeAlign Alignment,
7379                               MachineMemOperand::Flags MMOFlags,
7380                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7381   SDValue Undef = getUNDEF(Ptr.getValueType());
7382   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7383                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7384 }
7385 
7386 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7387                               SDValue Ptr, MachineMemOperand *MMO) {
7388   SDValue Undef = getUNDEF(Ptr.getValueType());
7389   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7390                  VT, MMO);
7391 }
7392 
7393 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7394                                  EVT VT, SDValue Chain, SDValue Ptr,
7395                                  MachinePointerInfo PtrInfo, EVT MemVT,
7396                                  MaybeAlign Alignment,
7397                                  MachineMemOperand::Flags MMOFlags,
7398                                  const AAMDNodes &AAInfo) {
7399   SDValue Undef = getUNDEF(Ptr.getValueType());
7400   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7401                  MemVT, Alignment, MMOFlags, AAInfo);
7402 }
7403 
7404 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7405                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7406                                  MachineMemOperand *MMO) {
7407   SDValue Undef = getUNDEF(Ptr.getValueType());
7408   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7409                  MemVT, MMO);
7410 }
7411 
7412 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7413                                      SDValue Base, SDValue Offset,
7414                                      ISD::MemIndexedMode AM) {
7415   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7416   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7417   // Don't propagate the invariant or dereferenceable flags.
7418   auto MMOFlags =
7419       LD->getMemOperand()->getFlags() &
7420       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7421   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7422                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7423                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7424 }
7425 
7426 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7427                                SDValue Ptr, MachinePointerInfo PtrInfo,
7428                                Align Alignment,
7429                                MachineMemOperand::Flags MMOFlags,
7430                                const AAMDNodes &AAInfo) {
7431   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7432 
7433   MMOFlags |= MachineMemOperand::MOStore;
7434   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7435 
7436   if (PtrInfo.V.isNull())
7437     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7438 
7439   MachineFunction &MF = getMachineFunction();
7440   uint64_t Size =
7441       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7442   MachineMemOperand *MMO =
7443       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7444   return getStore(Chain, dl, Val, Ptr, MMO);
7445 }
7446 
7447 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7448                                SDValue Ptr, MachineMemOperand *MMO) {
7449   assert(Chain.getValueType() == MVT::Other &&
7450         "Invalid chain type");
7451   EVT VT = Val.getValueType();
7452   SDVTList VTs = getVTList(MVT::Other);
7453   SDValue Undef = getUNDEF(Ptr.getValueType());
7454   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7455   FoldingSetNodeID ID;
7456   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7457   ID.AddInteger(VT.getRawBits());
7458   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7459       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7460   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7461   void *IP = nullptr;
7462   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7463     cast<StoreSDNode>(E)->refineAlignment(MMO);
7464     return SDValue(E, 0);
7465   }
7466   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7467                                    ISD::UNINDEXED, false, VT, MMO);
7468   createOperands(N, Ops);
7469 
7470   CSEMap.InsertNode(N, IP);
7471   InsertNode(N);
7472   SDValue V(N, 0);
7473   NewSDValueDbgMsg(V, "Creating new node: ", this);
7474   return V;
7475 }
7476 
7477 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7478                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7479                                     EVT SVT, Align Alignment,
7480                                     MachineMemOperand::Flags MMOFlags,
7481                                     const AAMDNodes &AAInfo) {
7482   assert(Chain.getValueType() == MVT::Other &&
7483         "Invalid chain type");
7484 
7485   MMOFlags |= MachineMemOperand::MOStore;
7486   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7487 
7488   if (PtrInfo.V.isNull())
7489     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7490 
7491   MachineFunction &MF = getMachineFunction();
7492   MachineMemOperand *MMO = MF.getMachineMemOperand(
7493       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7494       Alignment, AAInfo);
7495   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7496 }
7497 
7498 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7499                                     SDValue Ptr, EVT SVT,
7500                                     MachineMemOperand *MMO) {
7501   EVT VT = Val.getValueType();
7502 
7503   assert(Chain.getValueType() == MVT::Other &&
7504         "Invalid chain type");
7505   if (VT == SVT)
7506     return getStore(Chain, dl, Val, Ptr, MMO);
7507 
7508   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7509          "Should only be a truncating store, not extending!");
7510   assert(VT.isInteger() == SVT.isInteger() &&
7511          "Can't do FP-INT conversion!");
7512   assert(VT.isVector() == SVT.isVector() &&
7513          "Cannot use trunc store to convert to or from a vector!");
7514   assert((!VT.isVector() ||
7515           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7516          "Cannot use trunc store to change the number of vector elements!");
7517 
7518   SDVTList VTs = getVTList(MVT::Other);
7519   SDValue Undef = getUNDEF(Ptr.getValueType());
7520   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7521   FoldingSetNodeID ID;
7522   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7523   ID.AddInteger(SVT.getRawBits());
7524   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7525       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7526   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7527   void *IP = nullptr;
7528   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7529     cast<StoreSDNode>(E)->refineAlignment(MMO);
7530     return SDValue(E, 0);
7531   }
7532   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7533                                    ISD::UNINDEXED, true, SVT, MMO);
7534   createOperands(N, Ops);
7535 
7536   CSEMap.InsertNode(N, IP);
7537   InsertNode(N);
7538   SDValue V(N, 0);
7539   NewSDValueDbgMsg(V, "Creating new node: ", this);
7540   return V;
7541 }
7542 
7543 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7544                                       SDValue Base, SDValue Offset,
7545                                       ISD::MemIndexedMode AM) {
7546   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7547   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7548   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7549   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7550   FoldingSetNodeID ID;
7551   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7552   ID.AddInteger(ST->getMemoryVT().getRawBits());
7553   ID.AddInteger(ST->getRawSubclassData());
7554   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7555   void *IP = nullptr;
7556   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7557     return SDValue(E, 0);
7558 
7559   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7560                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7561                                    ST->getMemOperand());
7562   createOperands(N, Ops);
7563 
7564   CSEMap.InsertNode(N, IP);
7565   InsertNode(N);
7566   SDValue V(N, 0);
7567   NewSDValueDbgMsg(V, "Creating new node: ", this);
7568   return V;
7569 }
7570 
7571 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7572                                     SDValue Base, SDValue Offset, SDValue Mask,
7573                                     SDValue PassThru, EVT MemVT,
7574                                     MachineMemOperand *MMO,
7575                                     ISD::MemIndexedMode AM,
7576                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7577   bool Indexed = AM != ISD::UNINDEXED;
7578   assert((Indexed || Offset.isUndef()) &&
7579          "Unindexed masked load with an offset!");
7580   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
7581                          : getVTList(VT, MVT::Other);
7582   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
7583   FoldingSetNodeID ID;
7584   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
7585   ID.AddInteger(MemVT.getRawBits());
7586   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
7587       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
7588   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7589   void *IP = nullptr;
7590   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7591     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
7592     return SDValue(E, 0);
7593   }
7594   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7595                                         AM, ExtTy, isExpanding, MemVT, MMO);
7596   createOperands(N, Ops);
7597 
7598   CSEMap.InsertNode(N, IP);
7599   InsertNode(N);
7600   SDValue V(N, 0);
7601   NewSDValueDbgMsg(V, "Creating new node: ", this);
7602   return V;
7603 }
7604 
7605 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
7606                                            SDValue Base, SDValue Offset,
7607                                            ISD::MemIndexedMode AM) {
7608   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
7609   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
7610   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
7611                        Offset, LD->getMask(), LD->getPassThru(),
7612                        LD->getMemoryVT(), LD->getMemOperand(), AM,
7613                        LD->getExtensionType(), LD->isExpandingLoad());
7614 }
7615 
7616 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
7617                                      SDValue Val, SDValue Base, SDValue Offset,
7618                                      SDValue Mask, EVT MemVT,
7619                                      MachineMemOperand *MMO,
7620                                      ISD::MemIndexedMode AM, bool IsTruncating,
7621                                      bool IsCompressing) {
7622   assert(Chain.getValueType() == MVT::Other &&
7623         "Invalid chain type");
7624   bool Indexed = AM != ISD::UNINDEXED;
7625   assert((Indexed || Offset.isUndef()) &&
7626          "Unindexed masked store with an offset!");
7627   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
7628                          : getVTList(MVT::Other);
7629   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
7630   FoldingSetNodeID ID;
7631   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
7632   ID.AddInteger(MemVT.getRawBits());
7633   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
7634       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7635   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7636   void *IP = nullptr;
7637   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7638     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
7639     return SDValue(E, 0);
7640   }
7641   auto *N =
7642       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7643                                    IsTruncating, IsCompressing, MemVT, MMO);
7644   createOperands(N, Ops);
7645 
7646   CSEMap.InsertNode(N, IP);
7647   InsertNode(N);
7648   SDValue V(N, 0);
7649   NewSDValueDbgMsg(V, "Creating new node: ", this);
7650   return V;
7651 }
7652 
7653 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
7654                                             SDValue Base, SDValue Offset,
7655                                             ISD::MemIndexedMode AM) {
7656   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
7657   assert(ST->getOffset().isUndef() &&
7658          "Masked store is already a indexed store!");
7659   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
7660                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
7661                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
7662 }
7663 
7664 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
7665                                       ArrayRef<SDValue> Ops,
7666                                       MachineMemOperand *MMO,
7667                                       ISD::MemIndexType IndexType,
7668                                       ISD::LoadExtType ExtTy) {
7669   assert(Ops.size() == 6 && "Incompatible number of operands");
7670 
7671   FoldingSetNodeID ID;
7672   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7673   ID.AddInteger(MemVT.getRawBits());
7674   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7675       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
7676   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7677   void *IP = nullptr;
7678   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7679     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7680     return SDValue(E, 0);
7681   }
7682 
7683   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
7684   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7685                                           VTs, MemVT, MMO, IndexType, ExtTy);
7686   createOperands(N, Ops);
7687 
7688   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7689          "Incompatible type of the PassThru value in MaskedGatherSDNode");
7690   assert(N->getMask().getValueType().getVectorElementCount() ==
7691              N->getValueType(0).getVectorElementCount() &&
7692          "Vector width mismatch between mask and data");
7693   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7694              N->getValueType(0).getVectorElementCount().isScalable() &&
7695          "Scalable flags of index and data do not match");
7696   assert(ElementCount::isKnownGE(
7697              N->getIndex().getValueType().getVectorElementCount(),
7698              N->getValueType(0).getVectorElementCount()) &&
7699          "Vector width mismatch between index and data");
7700   assert(isa<ConstantSDNode>(N->getScale()) &&
7701          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7702          "Scale should be a constant power of 2");
7703 
7704   CSEMap.InsertNode(N, IP);
7705   InsertNode(N);
7706   SDValue V(N, 0);
7707   NewSDValueDbgMsg(V, "Creating new node: ", this);
7708   return V;
7709 }
7710 
7711 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
7712                                        ArrayRef<SDValue> Ops,
7713                                        MachineMemOperand *MMO,
7714                                        ISD::MemIndexType IndexType,
7715                                        bool IsTrunc) {
7716   assert(Ops.size() == 6 && "Incompatible number of operands");
7717 
7718   FoldingSetNodeID ID;
7719   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7720   ID.AddInteger(MemVT.getRawBits());
7721   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7722       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
7723   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7724   void *IP = nullptr;
7725   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7726     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7727     return SDValue(E, 0);
7728   }
7729 
7730   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
7731   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7732                                            VTs, MemVT, MMO, IndexType, IsTrunc);
7733   createOperands(N, Ops);
7734 
7735   assert(N->getMask().getValueType().getVectorElementCount() ==
7736              N->getValue().getValueType().getVectorElementCount() &&
7737          "Vector width mismatch between mask and data");
7738   assert(
7739       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7740           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7741       "Scalable flags of index and data do not match");
7742   assert(ElementCount::isKnownGE(
7743              N->getIndex().getValueType().getVectorElementCount(),
7744              N->getValue().getValueType().getVectorElementCount()) &&
7745          "Vector width mismatch between index and data");
7746   assert(isa<ConstantSDNode>(N->getScale()) &&
7747          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7748          "Scale should be a constant power of 2");
7749 
7750   CSEMap.InsertNode(N, IP);
7751   InsertNode(N);
7752   SDValue V(N, 0);
7753   NewSDValueDbgMsg(V, "Creating new node: ", this);
7754   return V;
7755 }
7756 
7757 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7758   // select undef, T, F --> T (if T is a constant), otherwise F
7759   // select, ?, undef, F --> F
7760   // select, ?, T, undef --> T
7761   if (Cond.isUndef())
7762     return isConstantValueOfAnyType(T) ? T : F;
7763   if (T.isUndef())
7764     return F;
7765   if (F.isUndef())
7766     return T;
7767 
7768   // select true, T, F --> T
7769   // select false, T, F --> F
7770   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7771     return CondC->isNullValue() ? F : T;
7772 
7773   // TODO: This should simplify VSELECT with constant condition using something
7774   // like this (but check boolean contents to be complete?):
7775   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7776   //    return T;
7777   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7778   //    return F;
7779 
7780   // select ?, T, T --> T
7781   if (T == F)
7782     return T;
7783 
7784   return SDValue();
7785 }
7786 
7787 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7788   // shift undef, Y --> 0 (can always assume that the undef value is 0)
7789   if (X.isUndef())
7790     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7791   // shift X, undef --> undef (because it may shift by the bitwidth)
7792   if (Y.isUndef())
7793     return getUNDEF(X.getValueType());
7794 
7795   // shift 0, Y --> 0
7796   // shift X, 0 --> X
7797   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7798     return X;
7799 
7800   // shift X, C >= bitwidth(X) --> undef
7801   // All vector elements must be too big (or undef) to avoid partial undefs.
7802   auto isShiftTooBig = [X](ConstantSDNode *Val) {
7803     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7804   };
7805   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7806     return getUNDEF(X.getValueType());
7807 
7808   return SDValue();
7809 }
7810 
7811 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
7812                                       SDNodeFlags Flags) {
7813   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
7814   // (an undef operand can be chosen to be Nan/Inf), then the result of this
7815   // operation is poison. That result can be relaxed to undef.
7816   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
7817   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7818   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
7819                 (YC && YC->getValueAPF().isNaN());
7820   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
7821                 (YC && YC->getValueAPF().isInfinity());
7822 
7823   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
7824     return getUNDEF(X.getValueType());
7825 
7826   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
7827     return getUNDEF(X.getValueType());
7828 
7829   if (!YC)
7830     return SDValue();
7831 
7832   // X + -0.0 --> X
7833   if (Opcode == ISD::FADD)
7834     if (YC->getValueAPF().isNegZero())
7835       return X;
7836 
7837   // X - +0.0 --> X
7838   if (Opcode == ISD::FSUB)
7839     if (YC->getValueAPF().isPosZero())
7840       return X;
7841 
7842   // X * 1.0 --> X
7843   // X / 1.0 --> X
7844   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7845     if (YC->getValueAPF().isExactlyValue(1.0))
7846       return X;
7847 
7848   // X * 0.0 --> 0.0
7849   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
7850     if (YC->getValueAPF().isZero())
7851       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
7852 
7853   return SDValue();
7854 }
7855 
7856 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7857                                SDValue Ptr, SDValue SV, unsigned Align) {
7858   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7859   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7860 }
7861 
7862 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7863                               ArrayRef<SDUse> Ops) {
7864   switch (Ops.size()) {
7865   case 0: return getNode(Opcode, DL, VT);
7866   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7867   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7868   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7869   default: break;
7870   }
7871 
7872   // Copy from an SDUse array into an SDValue array for use with
7873   // the regular getNode logic.
7874   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7875   return getNode(Opcode, DL, VT, NewOps);
7876 }
7877 
7878 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7879                               ArrayRef<SDValue> Ops) {
7880   SDNodeFlags Flags;
7881   if (Inserter)
7882     Flags = Inserter->getFlags();
7883   return getNode(Opcode, DL, VT, Ops, Flags);
7884 }
7885 
7886 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7887                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7888   unsigned NumOps = Ops.size();
7889   switch (NumOps) {
7890   case 0: return getNode(Opcode, DL, VT);
7891   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7892   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7893   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7894   default: break;
7895   }
7896 
7897 #ifndef NDEBUG
7898   for (auto &Op : Ops)
7899     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7900            "Operand is DELETED_NODE!");
7901 #endif
7902 
7903   switch (Opcode) {
7904   default: break;
7905   case ISD::BUILD_VECTOR:
7906     // Attempt to simplify BUILD_VECTOR.
7907     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7908       return V;
7909     break;
7910   case ISD::CONCAT_VECTORS:
7911     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7912       return V;
7913     break;
7914   case ISD::SELECT_CC:
7915     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7916     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7917            "LHS and RHS of condition must have same type!");
7918     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7919            "True and False arms of SelectCC must have same type!");
7920     assert(Ops[2].getValueType() == VT &&
7921            "select_cc node must be of same type as true and false value!");
7922     break;
7923   case ISD::BR_CC:
7924     assert(NumOps == 5 && "BR_CC takes 5 operands!");
7925     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7926            "LHS/RHS of comparison should match types!");
7927     break;
7928   }
7929 
7930   // Memoize nodes.
7931   SDNode *N;
7932   SDVTList VTs = getVTList(VT);
7933 
7934   if (VT != MVT::Glue) {
7935     FoldingSetNodeID ID;
7936     AddNodeIDNode(ID, Opcode, VTs, Ops);
7937     void *IP = nullptr;
7938 
7939     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7940       return SDValue(E, 0);
7941 
7942     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7943     createOperands(N, Ops);
7944 
7945     CSEMap.InsertNode(N, IP);
7946   } else {
7947     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7948     createOperands(N, Ops);
7949   }
7950 
7951   N->setFlags(Flags);
7952   InsertNode(N);
7953   SDValue V(N, 0);
7954   NewSDValueDbgMsg(V, "Creating new node: ", this);
7955   return V;
7956 }
7957 
7958 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7959                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7960   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7961 }
7962 
7963 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7964                               ArrayRef<SDValue> Ops) {
7965   SDNodeFlags Flags;
7966   if (Inserter)
7967     Flags = Inserter->getFlags();
7968   return getNode(Opcode, DL, VTList, Ops, Flags);
7969 }
7970 
7971 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7972                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7973   if (VTList.NumVTs == 1)
7974     return getNode(Opcode, DL, VTList.VTs[0], Ops);
7975 
7976 #ifndef NDEBUG
7977   for (auto &Op : Ops)
7978     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7979            "Operand is DELETED_NODE!");
7980 #endif
7981 
7982   switch (Opcode) {
7983   case ISD::STRICT_FP_EXTEND:
7984     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
7985            "Invalid STRICT_FP_EXTEND!");
7986     assert(VTList.VTs[0].isFloatingPoint() &&
7987            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
7988     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7989            "STRICT_FP_EXTEND result type should be vector iff the operand "
7990            "type is vector!");
7991     assert((!VTList.VTs[0].isVector() ||
7992             VTList.VTs[0].getVectorNumElements() ==
7993             Ops[1].getValueType().getVectorNumElements()) &&
7994            "Vector element count mismatch!");
7995     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
7996            "Invalid fpext node, dst <= src!");
7997     break;
7998   case ISD::STRICT_FP_ROUND:
7999     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8000     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8001            "STRICT_FP_ROUND result type should be vector iff the operand "
8002            "type is vector!");
8003     assert((!VTList.VTs[0].isVector() ||
8004             VTList.VTs[0].getVectorNumElements() ==
8005             Ops[1].getValueType().getVectorNumElements()) &&
8006            "Vector element count mismatch!");
8007     assert(VTList.VTs[0].isFloatingPoint() &&
8008            Ops[1].getValueType().isFloatingPoint() &&
8009            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8010            isa<ConstantSDNode>(Ops[2]) &&
8011            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8012             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8013            "Invalid STRICT_FP_ROUND!");
8014     break;
8015 #if 0
8016   // FIXME: figure out how to safely handle things like
8017   // int foo(int x) { return 1 << (x & 255); }
8018   // int bar() { return foo(256); }
8019   case ISD::SRA_PARTS:
8020   case ISD::SRL_PARTS:
8021   case ISD::SHL_PARTS:
8022     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8023         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8024       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8025     else if (N3.getOpcode() == ISD::AND)
8026       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8027         // If the and is only masking out bits that cannot effect the shift,
8028         // eliminate the and.
8029         unsigned NumBits = VT.getScalarSizeInBits()*2;
8030         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8031           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8032       }
8033     break;
8034 #endif
8035   }
8036 
8037   // Memoize the node unless it returns a flag.
8038   SDNode *N;
8039   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8040     FoldingSetNodeID ID;
8041     AddNodeIDNode(ID, Opcode, VTList, Ops);
8042     void *IP = nullptr;
8043     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8044       return SDValue(E, 0);
8045 
8046     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8047     createOperands(N, Ops);
8048     CSEMap.InsertNode(N, IP);
8049   } else {
8050     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8051     createOperands(N, Ops);
8052   }
8053 
8054   N->setFlags(Flags);
8055   InsertNode(N);
8056   SDValue V(N, 0);
8057   NewSDValueDbgMsg(V, "Creating new node: ", this);
8058   return V;
8059 }
8060 
8061 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8062                               SDVTList VTList) {
8063   return getNode(Opcode, DL, VTList, None);
8064 }
8065 
8066 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8067                               SDValue N1) {
8068   SDValue Ops[] = { N1 };
8069   return getNode(Opcode, DL, VTList, Ops);
8070 }
8071 
8072 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8073                               SDValue N1, SDValue N2) {
8074   SDValue Ops[] = { N1, N2 };
8075   return getNode(Opcode, DL, VTList, Ops);
8076 }
8077 
8078 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8079                               SDValue N1, SDValue N2, SDValue N3) {
8080   SDValue Ops[] = { N1, N2, N3 };
8081   return getNode(Opcode, DL, VTList, Ops);
8082 }
8083 
8084 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8085                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8086   SDValue Ops[] = { N1, N2, N3, N4 };
8087   return getNode(Opcode, DL, VTList, Ops);
8088 }
8089 
8090 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8091                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8092                               SDValue N5) {
8093   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8094   return getNode(Opcode, DL, VTList, Ops);
8095 }
8096 
8097 SDVTList SelectionDAG::getVTList(EVT VT) {
8098   return makeVTList(SDNode::getValueTypeList(VT), 1);
8099 }
8100 
8101 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8102   FoldingSetNodeID ID;
8103   ID.AddInteger(2U);
8104   ID.AddInteger(VT1.getRawBits());
8105   ID.AddInteger(VT2.getRawBits());
8106 
8107   void *IP = nullptr;
8108   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8109   if (!Result) {
8110     EVT *Array = Allocator.Allocate<EVT>(2);
8111     Array[0] = VT1;
8112     Array[1] = VT2;
8113     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8114     VTListMap.InsertNode(Result, IP);
8115   }
8116   return Result->getSDVTList();
8117 }
8118 
8119 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8120   FoldingSetNodeID ID;
8121   ID.AddInteger(3U);
8122   ID.AddInteger(VT1.getRawBits());
8123   ID.AddInteger(VT2.getRawBits());
8124   ID.AddInteger(VT3.getRawBits());
8125 
8126   void *IP = nullptr;
8127   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8128   if (!Result) {
8129     EVT *Array = Allocator.Allocate<EVT>(3);
8130     Array[0] = VT1;
8131     Array[1] = VT2;
8132     Array[2] = VT3;
8133     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8134     VTListMap.InsertNode(Result, IP);
8135   }
8136   return Result->getSDVTList();
8137 }
8138 
8139 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8140   FoldingSetNodeID ID;
8141   ID.AddInteger(4U);
8142   ID.AddInteger(VT1.getRawBits());
8143   ID.AddInteger(VT2.getRawBits());
8144   ID.AddInteger(VT3.getRawBits());
8145   ID.AddInteger(VT4.getRawBits());
8146 
8147   void *IP = nullptr;
8148   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8149   if (!Result) {
8150     EVT *Array = Allocator.Allocate<EVT>(4);
8151     Array[0] = VT1;
8152     Array[1] = VT2;
8153     Array[2] = VT3;
8154     Array[3] = VT4;
8155     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8156     VTListMap.InsertNode(Result, IP);
8157   }
8158   return Result->getSDVTList();
8159 }
8160 
8161 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8162   unsigned NumVTs = VTs.size();
8163   FoldingSetNodeID ID;
8164   ID.AddInteger(NumVTs);
8165   for (unsigned index = 0; index < NumVTs; index++) {
8166     ID.AddInteger(VTs[index].getRawBits());
8167   }
8168 
8169   void *IP = nullptr;
8170   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8171   if (!Result) {
8172     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8173     llvm::copy(VTs, Array);
8174     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8175     VTListMap.InsertNode(Result, IP);
8176   }
8177   return Result->getSDVTList();
8178 }
8179 
8180 
8181 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8182 /// specified operands.  If the resultant node already exists in the DAG,
8183 /// this does not modify the specified node, instead it returns the node that
8184 /// already exists.  If the resultant node does not exist in the DAG, the
8185 /// input node is returned.  As a degenerate case, if you specify the same
8186 /// input operands as the node already has, the input node is returned.
8187 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8188   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8189 
8190   // Check to see if there is no change.
8191   if (Op == N->getOperand(0)) return N;
8192 
8193   // See if the modified node already exists.
8194   void *InsertPos = nullptr;
8195   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8196     return Existing;
8197 
8198   // Nope it doesn't.  Remove the node from its current place in the maps.
8199   if (InsertPos)
8200     if (!RemoveNodeFromCSEMaps(N))
8201       InsertPos = nullptr;
8202 
8203   // Now we update the operands.
8204   N->OperandList[0].set(Op);
8205 
8206   updateDivergence(N);
8207   // If this gets put into a CSE map, add it.
8208   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8209   return N;
8210 }
8211 
8212 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8213   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8214 
8215   // Check to see if there is no change.
8216   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8217     return N;   // No operands changed, just return the input node.
8218 
8219   // See if the modified node already exists.
8220   void *InsertPos = nullptr;
8221   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8222     return Existing;
8223 
8224   // Nope it doesn't.  Remove the node from its current place in the maps.
8225   if (InsertPos)
8226     if (!RemoveNodeFromCSEMaps(N))
8227       InsertPos = nullptr;
8228 
8229   // Now we update the operands.
8230   if (N->OperandList[0] != Op1)
8231     N->OperandList[0].set(Op1);
8232   if (N->OperandList[1] != Op2)
8233     N->OperandList[1].set(Op2);
8234 
8235   updateDivergence(N);
8236   // If this gets put into a CSE map, add it.
8237   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8238   return N;
8239 }
8240 
8241 SDNode *SelectionDAG::
8242 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8243   SDValue Ops[] = { Op1, Op2, Op3 };
8244   return UpdateNodeOperands(N, Ops);
8245 }
8246 
8247 SDNode *SelectionDAG::
8248 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8249                    SDValue Op3, SDValue Op4) {
8250   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8251   return UpdateNodeOperands(N, Ops);
8252 }
8253 
8254 SDNode *SelectionDAG::
8255 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8256                    SDValue Op3, SDValue Op4, SDValue Op5) {
8257   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8258   return UpdateNodeOperands(N, Ops);
8259 }
8260 
8261 SDNode *SelectionDAG::
8262 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8263   unsigned NumOps = Ops.size();
8264   assert(N->getNumOperands() == NumOps &&
8265          "Update with wrong number of operands");
8266 
8267   // If no operands changed just return the input node.
8268   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8269     return N;
8270 
8271   // See if the modified node already exists.
8272   void *InsertPos = nullptr;
8273   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8274     return Existing;
8275 
8276   // Nope it doesn't.  Remove the node from its current place in the maps.
8277   if (InsertPos)
8278     if (!RemoveNodeFromCSEMaps(N))
8279       InsertPos = nullptr;
8280 
8281   // Now we update the operands.
8282   for (unsigned i = 0; i != NumOps; ++i)
8283     if (N->OperandList[i] != Ops[i])
8284       N->OperandList[i].set(Ops[i]);
8285 
8286   updateDivergence(N);
8287   // If this gets put into a CSE map, add it.
8288   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8289   return N;
8290 }
8291 
8292 /// DropOperands - Release the operands and set this node to have
8293 /// zero operands.
8294 void SDNode::DropOperands() {
8295   // Unlike the code in MorphNodeTo that does this, we don't need to
8296   // watch for dead nodes here.
8297   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8298     SDUse &Use = *I++;
8299     Use.set(SDValue());
8300   }
8301 }
8302 
8303 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8304                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8305   if (NewMemRefs.empty()) {
8306     N->clearMemRefs();
8307     return;
8308   }
8309 
8310   // Check if we can avoid allocating by storing a single reference directly.
8311   if (NewMemRefs.size() == 1) {
8312     N->MemRefs = NewMemRefs[0];
8313     N->NumMemRefs = 1;
8314     return;
8315   }
8316 
8317   MachineMemOperand **MemRefsBuffer =
8318       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8319   llvm::copy(NewMemRefs, MemRefsBuffer);
8320   N->MemRefs = MemRefsBuffer;
8321   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8322 }
8323 
8324 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8325 /// machine opcode.
8326 ///
8327 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8328                                    EVT VT) {
8329   SDVTList VTs = getVTList(VT);
8330   return SelectNodeTo(N, MachineOpc, VTs, None);
8331 }
8332 
8333 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8334                                    EVT VT, SDValue Op1) {
8335   SDVTList VTs = getVTList(VT);
8336   SDValue Ops[] = { Op1 };
8337   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8338 }
8339 
8340 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8341                                    EVT VT, SDValue Op1,
8342                                    SDValue Op2) {
8343   SDVTList VTs = getVTList(VT);
8344   SDValue Ops[] = { Op1, Op2 };
8345   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8346 }
8347 
8348 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8349                                    EVT VT, SDValue Op1,
8350                                    SDValue Op2, SDValue Op3) {
8351   SDVTList VTs = getVTList(VT);
8352   SDValue Ops[] = { Op1, Op2, Op3 };
8353   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8354 }
8355 
8356 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8357                                    EVT VT, ArrayRef<SDValue> Ops) {
8358   SDVTList VTs = getVTList(VT);
8359   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8360 }
8361 
8362 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8363                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8364   SDVTList VTs = getVTList(VT1, VT2);
8365   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8366 }
8367 
8368 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8369                                    EVT VT1, EVT VT2) {
8370   SDVTList VTs = getVTList(VT1, VT2);
8371   return SelectNodeTo(N, MachineOpc, VTs, None);
8372 }
8373 
8374 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8375                                    EVT VT1, EVT VT2, EVT VT3,
8376                                    ArrayRef<SDValue> Ops) {
8377   SDVTList VTs = getVTList(VT1, VT2, VT3);
8378   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8379 }
8380 
8381 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8382                                    EVT VT1, EVT VT2,
8383                                    SDValue Op1, SDValue Op2) {
8384   SDVTList VTs = getVTList(VT1, VT2);
8385   SDValue Ops[] = { Op1, Op2 };
8386   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8387 }
8388 
8389 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8390                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8391   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8392   // Reset the NodeID to -1.
8393   New->setNodeId(-1);
8394   if (New != N) {
8395     ReplaceAllUsesWith(N, New);
8396     RemoveDeadNode(N);
8397   }
8398   return New;
8399 }
8400 
8401 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8402 /// the line number information on the merged node since it is not possible to
8403 /// preserve the information that operation is associated with multiple lines.
8404 /// This will make the debugger working better at -O0, were there is a higher
8405 /// probability having other instructions associated with that line.
8406 ///
8407 /// For IROrder, we keep the smaller of the two
8408 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8409   DebugLoc NLoc = N->getDebugLoc();
8410   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8411     N->setDebugLoc(DebugLoc());
8412   }
8413   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8414   N->setIROrder(Order);
8415   return N;
8416 }
8417 
8418 /// MorphNodeTo - This *mutates* the specified node to have the specified
8419 /// return type, opcode, and operands.
8420 ///
8421 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8422 /// node of the specified opcode and operands, it returns that node instead of
8423 /// the current one.  Note that the SDLoc need not be the same.
8424 ///
8425 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8426 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8427 /// node, and because it doesn't require CSE recalculation for any of
8428 /// the node's users.
8429 ///
8430 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8431 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8432 /// the legalizer which maintain worklists that would need to be updated when
8433 /// deleting things.
8434 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8435                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8436   // If an identical node already exists, use it.
8437   void *IP = nullptr;
8438   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8439     FoldingSetNodeID ID;
8440     AddNodeIDNode(ID, Opc, VTs, Ops);
8441     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8442       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8443   }
8444 
8445   if (!RemoveNodeFromCSEMaps(N))
8446     IP = nullptr;
8447 
8448   // Start the morphing.
8449   N->NodeType = Opc;
8450   N->ValueList = VTs.VTs;
8451   N->NumValues = VTs.NumVTs;
8452 
8453   // Clear the operands list, updating used nodes to remove this from their
8454   // use list.  Keep track of any operands that become dead as a result.
8455   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8456   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8457     SDUse &Use = *I++;
8458     SDNode *Used = Use.getNode();
8459     Use.set(SDValue());
8460     if (Used->use_empty())
8461       DeadNodeSet.insert(Used);
8462   }
8463 
8464   // For MachineNode, initialize the memory references information.
8465   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8466     MN->clearMemRefs();
8467 
8468   // Swap for an appropriately sized array from the recycler.
8469   removeOperands(N);
8470   createOperands(N, Ops);
8471 
8472   // Delete any nodes that are still dead after adding the uses for the
8473   // new operands.
8474   if (!DeadNodeSet.empty()) {
8475     SmallVector<SDNode *, 16> DeadNodes;
8476     for (SDNode *N : DeadNodeSet)
8477       if (N->use_empty())
8478         DeadNodes.push_back(N);
8479     RemoveDeadNodes(DeadNodes);
8480   }
8481 
8482   if (IP)
8483     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8484   return N;
8485 }
8486 
8487 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8488   unsigned OrigOpc = Node->getOpcode();
8489   unsigned NewOpc;
8490   switch (OrigOpc) {
8491   default:
8492     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8493 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8494   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8495 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8496   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8497 #include "llvm/IR/ConstrainedOps.def"
8498   }
8499 
8500   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8501 
8502   // We're taking this node out of the chain, so we need to re-link things.
8503   SDValue InputChain = Node->getOperand(0);
8504   SDValue OutputChain = SDValue(Node, 1);
8505   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8506 
8507   SmallVector<SDValue, 3> Ops;
8508   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8509     Ops.push_back(Node->getOperand(i));
8510 
8511   SDVTList VTs = getVTList(Node->getValueType(0));
8512   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8513 
8514   // MorphNodeTo can operate in two ways: if an existing node with the
8515   // specified operands exists, it can just return it.  Otherwise, it
8516   // updates the node in place to have the requested operands.
8517   if (Res == Node) {
8518     // If we updated the node in place, reset the node ID.  To the isel,
8519     // this should be just like a newly allocated machine node.
8520     Res->setNodeId(-1);
8521   } else {
8522     ReplaceAllUsesWith(Node, Res);
8523     RemoveDeadNode(Node);
8524   }
8525 
8526   return Res;
8527 }
8528 
8529 /// getMachineNode - These are used for target selectors to create a new node
8530 /// with specified return type(s), MachineInstr opcode, and operands.
8531 ///
8532 /// Note that getMachineNode returns the resultant node.  If there is already a
8533 /// node of the specified opcode and operands, it returns that node instead of
8534 /// the current one.
8535 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8536                                             EVT VT) {
8537   SDVTList VTs = getVTList(VT);
8538   return getMachineNode(Opcode, dl, VTs, None);
8539 }
8540 
8541 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8542                                             EVT VT, SDValue Op1) {
8543   SDVTList VTs = getVTList(VT);
8544   SDValue Ops[] = { Op1 };
8545   return getMachineNode(Opcode, dl, VTs, Ops);
8546 }
8547 
8548 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8549                                             EVT VT, SDValue Op1, SDValue Op2) {
8550   SDVTList VTs = getVTList(VT);
8551   SDValue Ops[] = { Op1, Op2 };
8552   return getMachineNode(Opcode, dl, VTs, Ops);
8553 }
8554 
8555 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8556                                             EVT VT, SDValue Op1, SDValue Op2,
8557                                             SDValue Op3) {
8558   SDVTList VTs = getVTList(VT);
8559   SDValue Ops[] = { Op1, Op2, Op3 };
8560   return getMachineNode(Opcode, dl, VTs, Ops);
8561 }
8562 
8563 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8564                                             EVT VT, ArrayRef<SDValue> Ops) {
8565   SDVTList VTs = getVTList(VT);
8566   return getMachineNode(Opcode, dl, VTs, Ops);
8567 }
8568 
8569 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8570                                             EVT VT1, EVT VT2, SDValue Op1,
8571                                             SDValue Op2) {
8572   SDVTList VTs = getVTList(VT1, VT2);
8573   SDValue Ops[] = { Op1, Op2 };
8574   return getMachineNode(Opcode, dl, VTs, Ops);
8575 }
8576 
8577 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8578                                             EVT VT1, EVT VT2, SDValue Op1,
8579                                             SDValue Op2, SDValue Op3) {
8580   SDVTList VTs = getVTList(VT1, VT2);
8581   SDValue Ops[] = { Op1, Op2, Op3 };
8582   return getMachineNode(Opcode, dl, VTs, Ops);
8583 }
8584 
8585 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8586                                             EVT VT1, EVT VT2,
8587                                             ArrayRef<SDValue> Ops) {
8588   SDVTList VTs = getVTList(VT1, VT2);
8589   return getMachineNode(Opcode, dl, VTs, Ops);
8590 }
8591 
8592 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8593                                             EVT VT1, EVT VT2, EVT VT3,
8594                                             SDValue Op1, SDValue Op2) {
8595   SDVTList VTs = getVTList(VT1, VT2, VT3);
8596   SDValue Ops[] = { Op1, Op2 };
8597   return getMachineNode(Opcode, dl, VTs, Ops);
8598 }
8599 
8600 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8601                                             EVT VT1, EVT VT2, EVT VT3,
8602                                             SDValue Op1, SDValue Op2,
8603                                             SDValue Op3) {
8604   SDVTList VTs = getVTList(VT1, VT2, VT3);
8605   SDValue Ops[] = { Op1, Op2, Op3 };
8606   return getMachineNode(Opcode, dl, VTs, Ops);
8607 }
8608 
8609 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8610                                             EVT VT1, EVT VT2, EVT VT3,
8611                                             ArrayRef<SDValue> Ops) {
8612   SDVTList VTs = getVTList(VT1, VT2, VT3);
8613   return getMachineNode(Opcode, dl, VTs, Ops);
8614 }
8615 
8616 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8617                                             ArrayRef<EVT> ResultTys,
8618                                             ArrayRef<SDValue> Ops) {
8619   SDVTList VTs = getVTList(ResultTys);
8620   return getMachineNode(Opcode, dl, VTs, Ops);
8621 }
8622 
8623 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
8624                                             SDVTList VTs,
8625                                             ArrayRef<SDValue> Ops) {
8626   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
8627   MachineSDNode *N;
8628   void *IP = nullptr;
8629 
8630   if (DoCSE) {
8631     FoldingSetNodeID ID;
8632     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
8633     IP = nullptr;
8634     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8635       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
8636     }
8637   }
8638 
8639   // Allocate a new MachineSDNode.
8640   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8641   createOperands(N, Ops);
8642 
8643   if (DoCSE)
8644     CSEMap.InsertNode(N, IP);
8645 
8646   InsertNode(N);
8647   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
8648   return N;
8649 }
8650 
8651 /// getTargetExtractSubreg - A convenience function for creating
8652 /// TargetOpcode::EXTRACT_SUBREG nodes.
8653 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8654                                              SDValue Operand) {
8655   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8656   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
8657                                   VT, Operand, SRIdxVal);
8658   return SDValue(Subreg, 0);
8659 }
8660 
8661 /// getTargetInsertSubreg - A convenience function for creating
8662 /// TargetOpcode::INSERT_SUBREG nodes.
8663 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8664                                             SDValue Operand, SDValue Subreg) {
8665   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8666   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
8667                                   VT, Operand, Subreg, SRIdxVal);
8668   return SDValue(Result, 0);
8669 }
8670 
8671 /// getNodeIfExists - Get the specified node if it's already available, or
8672 /// else return NULL.
8673 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8674                                       ArrayRef<SDValue> Ops) {
8675   SDNodeFlags Flags;
8676   if (Inserter)
8677     Flags = Inserter->getFlags();
8678   return getNodeIfExists(Opcode, VTList, Ops, Flags);
8679 }
8680 
8681 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8682                                       ArrayRef<SDValue> Ops,
8683                                       const SDNodeFlags Flags) {
8684   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8685     FoldingSetNodeID ID;
8686     AddNodeIDNode(ID, Opcode, VTList, Ops);
8687     void *IP = nullptr;
8688     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
8689       E->intersectFlagsWith(Flags);
8690       return E;
8691     }
8692   }
8693   return nullptr;
8694 }
8695 
8696 /// doesNodeExist - Check if a node exists without modifying its flags.
8697 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
8698                                  ArrayRef<SDValue> Ops) {
8699   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8700     FoldingSetNodeID ID;
8701     AddNodeIDNode(ID, Opcode, VTList, Ops);
8702     void *IP = nullptr;
8703     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
8704       return true;
8705   }
8706   return false;
8707 }
8708 
8709 /// getDbgValue - Creates a SDDbgValue node.
8710 ///
8711 /// SDNode
8712 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
8713                                       SDNode *N, unsigned R, bool IsIndirect,
8714                                       const DebugLoc &DL, unsigned O) {
8715   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8716          "Expected inlined-at fields to agree");
8717   return new (DbgInfo->getAlloc())
8718       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
8719                  {}, IsIndirect, DL, O,
8720                  /*IsVariadic=*/false);
8721 }
8722 
8723 /// Constant
8724 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
8725                                               DIExpression *Expr,
8726                                               const Value *C,
8727                                               const DebugLoc &DL, unsigned O) {
8728   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8729          "Expected inlined-at fields to agree");
8730   return new (DbgInfo->getAlloc())
8731       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
8732                  /*IsIndirect=*/false, DL, O,
8733                  /*IsVariadic=*/false);
8734 }
8735 
8736 /// FrameIndex
8737 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8738                                                 DIExpression *Expr, unsigned FI,
8739                                                 bool IsIndirect,
8740                                                 const DebugLoc &DL,
8741                                                 unsigned O) {
8742   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8743          "Expected inlined-at fields to agree");
8744   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
8745 }
8746 
8747 /// FrameIndex with dependencies
8748 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8749                                                 DIExpression *Expr, unsigned FI,
8750                                                 ArrayRef<SDNode *> Dependencies,
8751                                                 bool IsIndirect,
8752                                                 const DebugLoc &DL,
8753                                                 unsigned O) {
8754   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8755          "Expected inlined-at fields to agree");
8756   return new (DbgInfo->getAlloc())
8757       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
8758                  Dependencies, IsIndirect, DL, O,
8759                  /*IsVariadic=*/false);
8760 }
8761 
8762 /// VReg
8763 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
8764                                           unsigned VReg, bool IsIndirect,
8765                                           const DebugLoc &DL, unsigned O) {
8766   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8767          "Expected inlined-at fields to agree");
8768   return new (DbgInfo->getAlloc())
8769       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
8770                  {}, IsIndirect, DL, O,
8771                  /*IsVariadic=*/false);
8772 }
8773 
8774 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
8775                                           ArrayRef<SDDbgOperand> Locs,
8776                                           ArrayRef<SDNode *> Dependencies,
8777                                           bool IsIndirect, const DebugLoc &DL,
8778                                           unsigned O, bool IsVariadic) {
8779   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8780          "Expected inlined-at fields to agree");
8781   return new (DbgInfo->getAlloc())
8782       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
8783                  DL, O, IsVariadic);
8784 }
8785 
8786 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8787                                      unsigned OffsetInBits, unsigned SizeInBits,
8788                                      bool InvalidateDbg) {
8789   SDNode *FromNode = From.getNode();
8790   SDNode *ToNode = To.getNode();
8791   assert(FromNode && ToNode && "Can't modify dbg values");
8792 
8793   // PR35338
8794   // TODO: assert(From != To && "Redundant dbg value transfer");
8795   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8796   if (From == To || FromNode == ToNode)
8797     return;
8798 
8799   if (!FromNode->getHasDebugValue())
8800     return;
8801 
8802   SDDbgOperand FromLocOp =
8803       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
8804   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
8805 
8806   SmallVector<SDDbgValue *, 2> ClonedDVs;
8807   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8808     if (Dbg->isInvalidated())
8809       continue;
8810 
8811     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8812 
8813     // Create a new location ops vector that is equal to the old vector, but
8814     // with each instance of FromLocOp replaced with ToLocOp.
8815     bool Changed = false;
8816     auto NewLocOps = Dbg->copyLocationOps();
8817     std::replace_if(
8818         NewLocOps.begin(), NewLocOps.end(),
8819         [&Changed, FromLocOp](const SDDbgOperand &Op) {
8820           bool Match = Op == FromLocOp;
8821           Changed |= Match;
8822           return Match;
8823         },
8824         ToLocOp);
8825     // Ignore this SDDbgValue if we didn't find a matching location.
8826     if (!Changed)
8827       continue;
8828 
8829     DIVariable *Var = Dbg->getVariable();
8830     auto *Expr = Dbg->getExpression();
8831     // If a fragment is requested, update the expression.
8832     if (SizeInBits) {
8833       // When splitting a larger (e.g., sign-extended) value whose
8834       // lower bits are described with an SDDbgValue, do not attempt
8835       // to transfer the SDDbgValue to the upper bits.
8836       if (auto FI = Expr->getFragmentInfo())
8837         if (OffsetInBits + SizeInBits > FI->SizeInBits)
8838           continue;
8839       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8840                                                              SizeInBits);
8841       if (!Fragment)
8842         continue;
8843       Expr = *Fragment;
8844     }
8845 
8846     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
8847     // Clone the SDDbgValue and move it to To.
8848     SDDbgValue *Clone = getDbgValueList(
8849         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
8850         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
8851         Dbg->isVariadic());
8852     ClonedDVs.push_back(Clone);
8853 
8854     if (InvalidateDbg) {
8855       // Invalidate value and indicate the SDDbgValue should not be emitted.
8856       Dbg->setIsInvalidated();
8857       Dbg->setIsEmitted();
8858     }
8859   }
8860 
8861   for (SDDbgValue *Dbg : ClonedDVs) {
8862     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
8863            "Transferred DbgValues should depend on the new SDNode");
8864     AddDbgValue(Dbg, false);
8865   }
8866 }
8867 
8868 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8869   if (!N.getHasDebugValue())
8870     return;
8871 
8872   SmallVector<SDDbgValue *, 2> ClonedDVs;
8873   for (auto DV : GetDbgValues(&N)) {
8874     if (DV->isInvalidated())
8875       continue;
8876     switch (N.getOpcode()) {
8877     default:
8878       break;
8879     case ISD::ADD:
8880       SDValue N0 = N.getOperand(0);
8881       SDValue N1 = N.getOperand(1);
8882       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8883           isConstantIntBuildVectorOrConstantInt(N1)) {
8884         uint64_t Offset = N.getConstantOperandVal(1);
8885 
8886         // Rewrite an ADD constant node into a DIExpression. Since we are
8887         // performing arithmetic to compute the variable's *value* in the
8888         // DIExpression, we need to mark the expression with a
8889         // DW_OP_stack_value.
8890         auto *DIExpr = DV->getExpression();
8891         auto NewLocOps = DV->copyLocationOps();
8892         bool Changed = false;
8893         for (size_t i = 0; i < NewLocOps.size(); ++i) {
8894           // We're not given a ResNo to compare against because the whole
8895           // node is going away. We know that any ISD::ADD only has one
8896           // result, so we can assume any node match is using the result.
8897           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
8898               NewLocOps[i].getSDNode() != &N)
8899             continue;
8900           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
8901           SmallVector<uint64_t, 3> ExprOps;
8902           DIExpression::appendOffset(ExprOps, Offset);
8903           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
8904           Changed = true;
8905         }
8906         (void)Changed;
8907         assert(Changed && "Salvage target doesn't use N");
8908 
8909         auto AdditionalDependencies = DV->getAdditionalDependencies();
8910         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
8911                                             NewLocOps, AdditionalDependencies,
8912                                             DV->isIndirect(), DV->getDebugLoc(),
8913                                             DV->getOrder(), DV->isVariadic());
8914         ClonedDVs.push_back(Clone);
8915         DV->setIsInvalidated();
8916         DV->setIsEmitted();
8917         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8918                    N0.getNode()->dumprFull(this);
8919                    dbgs() << " into " << *DIExpr << '\n');
8920       }
8921     }
8922   }
8923 
8924   for (SDDbgValue *Dbg : ClonedDVs) {
8925     assert(!Dbg->getSDNodes().empty() &&
8926            "Salvaged DbgValue should depend on a new SDNode");
8927     AddDbgValue(Dbg, false);
8928   }
8929 }
8930 
8931 /// Creates a SDDbgLabel node.
8932 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8933                                       const DebugLoc &DL, unsigned O) {
8934   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8935          "Expected inlined-at fields to agree");
8936   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8937 }
8938 
8939 namespace {
8940 
8941 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8942 /// pointed to by a use iterator is deleted, increment the use iterator
8943 /// so that it doesn't dangle.
8944 ///
8945 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8946   SDNode::use_iterator &UI;
8947   SDNode::use_iterator &UE;
8948 
8949   void NodeDeleted(SDNode *N, SDNode *E) override {
8950     // Increment the iterator as needed.
8951     while (UI != UE && N == *UI)
8952       ++UI;
8953   }
8954 
8955 public:
8956   RAUWUpdateListener(SelectionDAG &d,
8957                      SDNode::use_iterator &ui,
8958                      SDNode::use_iterator &ue)
8959     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8960 };
8961 
8962 } // end anonymous namespace
8963 
8964 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8965 /// This can cause recursive merging of nodes in the DAG.
8966 ///
8967 /// This version assumes From has a single result value.
8968 ///
8969 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8970   SDNode *From = FromN.getNode();
8971   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8972          "Cannot replace with this method!");
8973   assert(From != To.getNode() && "Cannot replace uses of with self");
8974 
8975   // Preserve Debug Values
8976   transferDbgValues(FromN, To);
8977 
8978   // Iterate over all the existing uses of From. New uses will be added
8979   // to the beginning of the use list, which we avoid visiting.
8980   // This specifically avoids visiting uses of From that arise while the
8981   // replacement is happening, because any such uses would be the result
8982   // of CSE: If an existing node looks like From after one of its operands
8983   // is replaced by To, we don't want to replace of all its users with To
8984   // too. See PR3018 for more info.
8985   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8986   RAUWUpdateListener Listener(*this, UI, UE);
8987   while (UI != UE) {
8988     SDNode *User = *UI;
8989 
8990     // This node is about to morph, remove its old self from the CSE maps.
8991     RemoveNodeFromCSEMaps(User);
8992 
8993     // A user can appear in a use list multiple times, and when this
8994     // happens the uses are usually next to each other in the list.
8995     // To help reduce the number of CSE recomputations, process all
8996     // the uses of this user that we can find this way.
8997     do {
8998       SDUse &Use = UI.getUse();
8999       ++UI;
9000       Use.set(To);
9001       if (To->isDivergent() != From->isDivergent())
9002         updateDivergence(User);
9003     } while (UI != UE && *UI == User);
9004     // Now that we have modified User, add it back to the CSE maps.  If it
9005     // already exists there, recursively merge the results together.
9006     AddModifiedNodeToCSEMaps(User);
9007   }
9008 
9009   // If we just RAUW'd the root, take note.
9010   if (FromN == getRoot())
9011     setRoot(To);
9012 }
9013 
9014 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9015 /// This can cause recursive merging of nodes in the DAG.
9016 ///
9017 /// This version assumes that for each value of From, there is a
9018 /// corresponding value in To in the same position with the same type.
9019 ///
9020 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9021 #ifndef NDEBUG
9022   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9023     assert((!From->hasAnyUseOfValue(i) ||
9024             From->getValueType(i) == To->getValueType(i)) &&
9025            "Cannot use this version of ReplaceAllUsesWith!");
9026 #endif
9027 
9028   // Handle the trivial case.
9029   if (From == To)
9030     return;
9031 
9032   // Preserve Debug Info. Only do this if there's a use.
9033   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9034     if (From->hasAnyUseOfValue(i)) {
9035       assert((i < To->getNumValues()) && "Invalid To location");
9036       transferDbgValues(SDValue(From, i), SDValue(To, i));
9037     }
9038 
9039   // Iterate over just the existing users of From. See the comments in
9040   // the ReplaceAllUsesWith above.
9041   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9042   RAUWUpdateListener Listener(*this, UI, UE);
9043   while (UI != UE) {
9044     SDNode *User = *UI;
9045 
9046     // This node is about to morph, remove its old self from the CSE maps.
9047     RemoveNodeFromCSEMaps(User);
9048 
9049     // A user can appear in a use list multiple times, and when this
9050     // happens the uses are usually next to each other in the list.
9051     // To help reduce the number of CSE recomputations, process all
9052     // the uses of this user that we can find this way.
9053     do {
9054       SDUse &Use = UI.getUse();
9055       ++UI;
9056       Use.setNode(To);
9057       if (To->isDivergent() != From->isDivergent())
9058         updateDivergence(User);
9059     } while (UI != UE && *UI == User);
9060 
9061     // Now that we have modified User, add it back to the CSE maps.  If it
9062     // already exists there, recursively merge the results together.
9063     AddModifiedNodeToCSEMaps(User);
9064   }
9065 
9066   // If we just RAUW'd the root, take note.
9067   if (From == getRoot().getNode())
9068     setRoot(SDValue(To, getRoot().getResNo()));
9069 }
9070 
9071 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9072 /// This can cause recursive merging of nodes in the DAG.
9073 ///
9074 /// This version can replace From with any result values.  To must match the
9075 /// number and types of values returned by From.
9076 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9077   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9078     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9079 
9080   // Preserve Debug Info.
9081   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9082     transferDbgValues(SDValue(From, i), To[i]);
9083 
9084   // Iterate over just the existing users of From. See the comments in
9085   // the ReplaceAllUsesWith above.
9086   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9087   RAUWUpdateListener Listener(*this, UI, UE);
9088   while (UI != UE) {
9089     SDNode *User = *UI;
9090 
9091     // This node is about to morph, remove its old self from the CSE maps.
9092     RemoveNodeFromCSEMaps(User);
9093 
9094     // A user can appear in a use list multiple times, and when this happens the
9095     // uses are usually next to each other in the list.  To help reduce the
9096     // number of CSE and divergence recomputations, process all the uses of this
9097     // user that we can find this way.
9098     bool To_IsDivergent = false;
9099     do {
9100       SDUse &Use = UI.getUse();
9101       const SDValue &ToOp = To[Use.getResNo()];
9102       ++UI;
9103       Use.set(ToOp);
9104       To_IsDivergent |= ToOp->isDivergent();
9105     } while (UI != UE && *UI == User);
9106 
9107     if (To_IsDivergent != From->isDivergent())
9108       updateDivergence(User);
9109 
9110     // Now that we have modified User, add it back to the CSE maps.  If it
9111     // already exists there, recursively merge the results together.
9112     AddModifiedNodeToCSEMaps(User);
9113   }
9114 
9115   // If we just RAUW'd the root, take note.
9116   if (From == getRoot().getNode())
9117     setRoot(SDValue(To[getRoot().getResNo()]));
9118 }
9119 
9120 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9121 /// uses of other values produced by From.getNode() alone.  The Deleted
9122 /// vector is handled the same way as for ReplaceAllUsesWith.
9123 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9124   // Handle the really simple, really trivial case efficiently.
9125   if (From == To) return;
9126 
9127   // Handle the simple, trivial, case efficiently.
9128   if (From.getNode()->getNumValues() == 1) {
9129     ReplaceAllUsesWith(From, To);
9130     return;
9131   }
9132 
9133   // Preserve Debug Info.
9134   transferDbgValues(From, To);
9135 
9136   // Iterate over just the existing users of From. See the comments in
9137   // the ReplaceAllUsesWith above.
9138   SDNode::use_iterator UI = From.getNode()->use_begin(),
9139                        UE = From.getNode()->use_end();
9140   RAUWUpdateListener Listener(*this, UI, UE);
9141   while (UI != UE) {
9142     SDNode *User = *UI;
9143     bool UserRemovedFromCSEMaps = false;
9144 
9145     // A user can appear in a use list multiple times, and when this
9146     // happens the uses are usually next to each other in the list.
9147     // To help reduce the number of CSE recomputations, process all
9148     // the uses of this user that we can find this way.
9149     do {
9150       SDUse &Use = UI.getUse();
9151 
9152       // Skip uses of different values from the same node.
9153       if (Use.getResNo() != From.getResNo()) {
9154         ++UI;
9155         continue;
9156       }
9157 
9158       // If this node hasn't been modified yet, it's still in the CSE maps,
9159       // so remove its old self from the CSE maps.
9160       if (!UserRemovedFromCSEMaps) {
9161         RemoveNodeFromCSEMaps(User);
9162         UserRemovedFromCSEMaps = true;
9163       }
9164 
9165       ++UI;
9166       Use.set(To);
9167       if (To->isDivergent() != From->isDivergent())
9168         updateDivergence(User);
9169     } while (UI != UE && *UI == User);
9170     // We are iterating over all uses of the From node, so if a use
9171     // doesn't use the specific value, no changes are made.
9172     if (!UserRemovedFromCSEMaps)
9173       continue;
9174 
9175     // Now that we have modified User, add it back to the CSE maps.  If it
9176     // already exists there, recursively merge the results together.
9177     AddModifiedNodeToCSEMaps(User);
9178   }
9179 
9180   // If we just RAUW'd the root, take note.
9181   if (From == getRoot())
9182     setRoot(To);
9183 }
9184 
9185 namespace {
9186 
9187   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9188   /// to record information about a use.
9189   struct UseMemo {
9190     SDNode *User;
9191     unsigned Index;
9192     SDUse *Use;
9193   };
9194 
9195   /// operator< - Sort Memos by User.
9196   bool operator<(const UseMemo &L, const UseMemo &R) {
9197     return (intptr_t)L.User < (intptr_t)R.User;
9198   }
9199 
9200 } // end anonymous namespace
9201 
9202 bool SelectionDAG::calculateDivergence(SDNode *N) {
9203   if (TLI->isSDNodeAlwaysUniform(N)) {
9204     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9205            "Conflicting divergence information!");
9206     return false;
9207   }
9208   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9209     return true;
9210   for (auto &Op : N->ops()) {
9211     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9212       return true;
9213   }
9214   return false;
9215 }
9216 
9217 void SelectionDAG::updateDivergence(SDNode *N) {
9218   SmallVector<SDNode *, 16> Worklist(1, N);
9219   do {
9220     N = Worklist.pop_back_val();
9221     bool IsDivergent = calculateDivergence(N);
9222     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9223       N->SDNodeBits.IsDivergent = IsDivergent;
9224       llvm::append_range(Worklist, N->uses());
9225     }
9226   } while (!Worklist.empty());
9227 }
9228 
9229 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9230   DenseMap<SDNode *, unsigned> Degree;
9231   Order.reserve(AllNodes.size());
9232   for (auto &N : allnodes()) {
9233     unsigned NOps = N.getNumOperands();
9234     Degree[&N] = NOps;
9235     if (0 == NOps)
9236       Order.push_back(&N);
9237   }
9238   for (size_t I = 0; I != Order.size(); ++I) {
9239     SDNode *N = Order[I];
9240     for (auto U : N->uses()) {
9241       unsigned &UnsortedOps = Degree[U];
9242       if (0 == --UnsortedOps)
9243         Order.push_back(U);
9244     }
9245   }
9246 }
9247 
9248 #ifndef NDEBUG
9249 void SelectionDAG::VerifyDAGDiverence() {
9250   std::vector<SDNode *> TopoOrder;
9251   CreateTopologicalOrder(TopoOrder);
9252   for (auto *N : TopoOrder) {
9253     assert(calculateDivergence(N) == N->isDivergent() &&
9254            "Divergence bit inconsistency detected");
9255   }
9256 }
9257 #endif
9258 
9259 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9260 /// uses of other values produced by From.getNode() alone.  The same value
9261 /// may appear in both the From and To list.  The Deleted vector is
9262 /// handled the same way as for ReplaceAllUsesWith.
9263 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9264                                               const SDValue *To,
9265                                               unsigned Num){
9266   // Handle the simple, trivial case efficiently.
9267   if (Num == 1)
9268     return ReplaceAllUsesOfValueWith(*From, *To);
9269 
9270   transferDbgValues(*From, *To);
9271 
9272   // Read up all the uses and make records of them. This helps
9273   // processing new uses that are introduced during the
9274   // replacement process.
9275   SmallVector<UseMemo, 4> Uses;
9276   for (unsigned i = 0; i != Num; ++i) {
9277     unsigned FromResNo = From[i].getResNo();
9278     SDNode *FromNode = From[i].getNode();
9279     for (SDNode::use_iterator UI = FromNode->use_begin(),
9280          E = FromNode->use_end(); UI != E; ++UI) {
9281       SDUse &Use = UI.getUse();
9282       if (Use.getResNo() == FromResNo) {
9283         UseMemo Memo = { *UI, i, &Use };
9284         Uses.push_back(Memo);
9285       }
9286     }
9287   }
9288 
9289   // Sort the uses, so that all the uses from a given User are together.
9290   llvm::sort(Uses);
9291 
9292   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9293        UseIndex != UseIndexEnd; ) {
9294     // We know that this user uses some value of From.  If it is the right
9295     // value, update it.
9296     SDNode *User = Uses[UseIndex].User;
9297 
9298     // This node is about to morph, remove its old self from the CSE maps.
9299     RemoveNodeFromCSEMaps(User);
9300 
9301     // The Uses array is sorted, so all the uses for a given User
9302     // are next to each other in the list.
9303     // To help reduce the number of CSE recomputations, process all
9304     // the uses of this user that we can find this way.
9305     do {
9306       unsigned i = Uses[UseIndex].Index;
9307       SDUse &Use = *Uses[UseIndex].Use;
9308       ++UseIndex;
9309 
9310       Use.set(To[i]);
9311     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9312 
9313     // Now that we have modified User, add it back to the CSE maps.  If it
9314     // already exists there, recursively merge the results together.
9315     AddModifiedNodeToCSEMaps(User);
9316   }
9317 }
9318 
9319 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9320 /// based on their topological order. It returns the maximum id and a vector
9321 /// of the SDNodes* in assigned order by reference.
9322 unsigned SelectionDAG::AssignTopologicalOrder() {
9323   unsigned DAGSize = 0;
9324 
9325   // SortedPos tracks the progress of the algorithm. Nodes before it are
9326   // sorted, nodes after it are unsorted. When the algorithm completes
9327   // it is at the end of the list.
9328   allnodes_iterator SortedPos = allnodes_begin();
9329 
9330   // Visit all the nodes. Move nodes with no operands to the front of
9331   // the list immediately. Annotate nodes that do have operands with their
9332   // operand count. Before we do this, the Node Id fields of the nodes
9333   // may contain arbitrary values. After, the Node Id fields for nodes
9334   // before SortedPos will contain the topological sort index, and the
9335   // Node Id fields for nodes At SortedPos and after will contain the
9336   // count of outstanding operands.
9337   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
9338     SDNode *N = &*I++;
9339     checkForCycles(N, this);
9340     unsigned Degree = N->getNumOperands();
9341     if (Degree == 0) {
9342       // A node with no uses, add it to the result array immediately.
9343       N->setNodeId(DAGSize++);
9344       allnodes_iterator Q(N);
9345       if (Q != SortedPos)
9346         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9347       assert(SortedPos != AllNodes.end() && "Overran node list");
9348       ++SortedPos;
9349     } else {
9350       // Temporarily use the Node Id as scratch space for the degree count.
9351       N->setNodeId(Degree);
9352     }
9353   }
9354 
9355   // Visit all the nodes. As we iterate, move nodes into sorted order,
9356   // such that by the time the end is reached all nodes will be sorted.
9357   for (SDNode &Node : allnodes()) {
9358     SDNode *N = &Node;
9359     checkForCycles(N, this);
9360     // N is in sorted position, so all its uses have one less operand
9361     // that needs to be sorted.
9362     for (SDNode *P : N->uses()) {
9363       unsigned Degree = P->getNodeId();
9364       assert(Degree != 0 && "Invalid node degree");
9365       --Degree;
9366       if (Degree == 0) {
9367         // All of P's operands are sorted, so P may sorted now.
9368         P->setNodeId(DAGSize++);
9369         if (P->getIterator() != SortedPos)
9370           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9371         assert(SortedPos != AllNodes.end() && "Overran node list");
9372         ++SortedPos;
9373       } else {
9374         // Update P's outstanding operand count.
9375         P->setNodeId(Degree);
9376       }
9377     }
9378     if (Node.getIterator() == SortedPos) {
9379 #ifndef NDEBUG
9380       allnodes_iterator I(N);
9381       SDNode *S = &*++I;
9382       dbgs() << "Overran sorted position:\n";
9383       S->dumprFull(this); dbgs() << "\n";
9384       dbgs() << "Checking if this is due to cycles\n";
9385       checkForCycles(this, true);
9386 #endif
9387       llvm_unreachable(nullptr);
9388     }
9389   }
9390 
9391   assert(SortedPos == AllNodes.end() &&
9392          "Topological sort incomplete!");
9393   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9394          "First node in topological sort is not the entry token!");
9395   assert(AllNodes.front().getNodeId() == 0 &&
9396          "First node in topological sort has non-zero id!");
9397   assert(AllNodes.front().getNumOperands() == 0 &&
9398          "First node in topological sort has operands!");
9399   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9400          "Last node in topologic sort has unexpected id!");
9401   assert(AllNodes.back().use_empty() &&
9402          "Last node in topologic sort has users!");
9403   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9404   return DAGSize;
9405 }
9406 
9407 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9408 /// value is produced by SD.
9409 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9410   for (SDNode *SD : DB->getSDNodes()) {
9411     if (!SD)
9412       continue;
9413     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9414     SD->setHasDebugValue(true);
9415   }
9416   DbgInfo->add(DB, isParameter);
9417 }
9418 
9419 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9420 
9421 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9422                                                    SDValue NewMemOpChain) {
9423   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9424   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9425   // The new memory operation must have the same position as the old load in
9426   // terms of memory dependency. Create a TokenFactor for the old load and new
9427   // memory operation and update uses of the old load's output chain to use that
9428   // TokenFactor.
9429   if (OldChain == NewMemOpChain || OldChain.use_empty())
9430     return NewMemOpChain;
9431 
9432   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9433                                 OldChain, NewMemOpChain);
9434   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9435   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9436   return TokenFactor;
9437 }
9438 
9439 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9440                                                    SDValue NewMemOp) {
9441   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9442   SDValue OldChain = SDValue(OldLoad, 1);
9443   SDValue NewMemOpChain = NewMemOp.getValue(1);
9444   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9445 }
9446 
9447 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9448                                                      Function **OutFunction) {
9449   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9450 
9451   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9452   auto *Module = MF->getFunction().getParent();
9453   auto *Function = Module->getFunction(Symbol);
9454 
9455   if (OutFunction != nullptr)
9456       *OutFunction = Function;
9457 
9458   if (Function != nullptr) {
9459     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9460     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9461   }
9462 
9463   std::string ErrorStr;
9464   raw_string_ostream ErrorFormatter(ErrorStr);
9465 
9466   ErrorFormatter << "Undefined external symbol ";
9467   ErrorFormatter << '"' << Symbol << '"';
9468   ErrorFormatter.flush();
9469 
9470   report_fatal_error(ErrorStr);
9471 }
9472 
9473 //===----------------------------------------------------------------------===//
9474 //                              SDNode Class
9475 //===----------------------------------------------------------------------===//
9476 
9477 bool llvm::isNullConstant(SDValue V) {
9478   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9479   return Const != nullptr && Const->isNullValue();
9480 }
9481 
9482 bool llvm::isNullFPConstant(SDValue V) {
9483   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9484   return Const != nullptr && Const->isZero() && !Const->isNegative();
9485 }
9486 
9487 bool llvm::isAllOnesConstant(SDValue V) {
9488   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9489   return Const != nullptr && Const->isAllOnesValue();
9490 }
9491 
9492 bool llvm::isOneConstant(SDValue V) {
9493   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9494   return Const != nullptr && Const->isOne();
9495 }
9496 
9497 SDValue llvm::peekThroughBitcasts(SDValue V) {
9498   while (V.getOpcode() == ISD::BITCAST)
9499     V = V.getOperand(0);
9500   return V;
9501 }
9502 
9503 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9504   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9505     V = V.getOperand(0);
9506   return V;
9507 }
9508 
9509 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9510   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9511     V = V.getOperand(0);
9512   return V;
9513 }
9514 
9515 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9516   if (V.getOpcode() != ISD::XOR)
9517     return false;
9518   V = peekThroughBitcasts(V.getOperand(1));
9519   unsigned NumBits = V.getScalarValueSizeInBits();
9520   ConstantSDNode *C =
9521       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9522   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9523 }
9524 
9525 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9526                                           bool AllowTruncation) {
9527   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9528     return CN;
9529 
9530   // SplatVectors can truncate their operands. Ignore that case here unless
9531   // AllowTruncation is set.
9532   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9533     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9534     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9535       EVT CVT = CN->getValueType(0);
9536       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9537       if (AllowTruncation || CVT == VecEltVT)
9538         return CN;
9539     }
9540   }
9541 
9542   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9543     BitVector UndefElements;
9544     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9545 
9546     // BuildVectors can truncate their operands. Ignore that case here unless
9547     // AllowTruncation is set.
9548     if (CN && (UndefElements.none() || AllowUndefs)) {
9549       EVT CVT = CN->getValueType(0);
9550       EVT NSVT = N.getValueType().getScalarType();
9551       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9552       if (AllowTruncation || (CVT == NSVT))
9553         return CN;
9554     }
9555   }
9556 
9557   return nullptr;
9558 }
9559 
9560 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9561                                           bool AllowUndefs,
9562                                           bool AllowTruncation) {
9563   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9564     return CN;
9565 
9566   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9567     BitVector UndefElements;
9568     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9569 
9570     // BuildVectors can truncate their operands. Ignore that case here unless
9571     // AllowTruncation is set.
9572     if (CN && (UndefElements.none() || AllowUndefs)) {
9573       EVT CVT = CN->getValueType(0);
9574       EVT NSVT = N.getValueType().getScalarType();
9575       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9576       if (AllowTruncation || (CVT == NSVT))
9577         return CN;
9578     }
9579   }
9580 
9581   return nullptr;
9582 }
9583 
9584 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
9585   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9586     return CN;
9587 
9588   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9589     BitVector UndefElements;
9590     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
9591     if (CN && (UndefElements.none() || AllowUndefs))
9592       return CN;
9593   }
9594 
9595   if (N.getOpcode() == ISD::SPLAT_VECTOR)
9596     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
9597       return CN;
9598 
9599   return nullptr;
9600 }
9601 
9602 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
9603                                               const APInt &DemandedElts,
9604                                               bool AllowUndefs) {
9605   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9606     return CN;
9607 
9608   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9609     BitVector UndefElements;
9610     ConstantFPSDNode *CN =
9611         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
9612     if (CN && (UndefElements.none() || AllowUndefs))
9613       return CN;
9614   }
9615 
9616   return nullptr;
9617 }
9618 
9619 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
9620   // TODO: may want to use peekThroughBitcast() here.
9621   ConstantSDNode *C =
9622       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
9623   return C && C->isNullValue();
9624 }
9625 
9626 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
9627   // TODO: may want to use peekThroughBitcast() here.
9628   unsigned BitWidth = N.getScalarValueSizeInBits();
9629   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9630   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
9631 }
9632 
9633 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
9634   N = peekThroughBitcasts(N);
9635   unsigned BitWidth = N.getScalarValueSizeInBits();
9636   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9637   return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
9638 }
9639 
9640 HandleSDNode::~HandleSDNode() {
9641   DropOperands();
9642 }
9643 
9644 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
9645                                          const DebugLoc &DL,
9646                                          const GlobalValue *GA, EVT VT,
9647                                          int64_t o, unsigned TF)
9648     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
9649   TheGlobal = GA;
9650 }
9651 
9652 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
9653                                          EVT VT, unsigned SrcAS,
9654                                          unsigned DestAS)
9655     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
9656       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
9657 
9658 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
9659                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
9660     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
9661   MemSDNodeBits.IsVolatile = MMO->isVolatile();
9662   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
9663   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
9664   MemSDNodeBits.IsInvariant = MMO->isInvariant();
9665 
9666   // We check here that the size of the memory operand fits within the size of
9667   // the MMO. This is because the MMO might indicate only a possible address
9668   // range instead of specifying the affected memory addresses precisely.
9669   // TODO: Make MachineMemOperands aware of scalable vectors.
9670   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
9671          "Size mismatch!");
9672 }
9673 
9674 /// Profile - Gather unique data for the node.
9675 ///
9676 void SDNode::Profile(FoldingSetNodeID &ID) const {
9677   AddNodeIDNode(ID, this);
9678 }
9679 
9680 namespace {
9681 
9682   struct EVTArray {
9683     std::vector<EVT> VTs;
9684 
9685     EVTArray() {
9686       VTs.reserve(MVT::VALUETYPE_SIZE);
9687       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
9688         VTs.push_back(MVT((MVT::SimpleValueType)i));
9689     }
9690   };
9691 
9692 } // end anonymous namespace
9693 
9694 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
9695 static ManagedStatic<EVTArray> SimpleVTArray;
9696 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
9697 
9698 /// getValueTypeList - Return a pointer to the specified value type.
9699 ///
9700 const EVT *SDNode::getValueTypeList(EVT VT) {
9701   if (VT.isExtended()) {
9702     sys::SmartScopedLock<true> Lock(*VTMutex);
9703     return &(*EVTs->insert(VT).first);
9704   }
9705   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
9706   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
9707 }
9708 
9709 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
9710 /// indicated value.  This method ignores uses of other values defined by this
9711 /// operation.
9712 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
9713   assert(Value < getNumValues() && "Bad value!");
9714 
9715   // TODO: Only iterate over uses of a given value of the node
9716   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
9717     if (UI.getUse().getResNo() == Value) {
9718       if (NUses == 0)
9719         return false;
9720       --NUses;
9721     }
9722   }
9723 
9724   // Found exactly the right number of uses?
9725   return NUses == 0;
9726 }
9727 
9728 /// hasAnyUseOfValue - Return true if there are any use of the indicated
9729 /// value. This method ignores uses of other values defined by this operation.
9730 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
9731   assert(Value < getNumValues() && "Bad value!");
9732 
9733   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
9734     if (UI.getUse().getResNo() == Value)
9735       return true;
9736 
9737   return false;
9738 }
9739 
9740 /// isOnlyUserOf - Return true if this node is the only use of N.
9741 bool SDNode::isOnlyUserOf(const SDNode *N) const {
9742   bool Seen = false;
9743   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9744     SDNode *User = *I;
9745     if (User == this)
9746       Seen = true;
9747     else
9748       return false;
9749   }
9750 
9751   return Seen;
9752 }
9753 
9754 /// Return true if the only users of N are contained in Nodes.
9755 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
9756   bool Seen = false;
9757   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9758     SDNode *User = *I;
9759     if (llvm::is_contained(Nodes, User))
9760       Seen = true;
9761     else
9762       return false;
9763   }
9764 
9765   return Seen;
9766 }
9767 
9768 /// isOperand - Return true if this node is an operand of N.
9769 bool SDValue::isOperandOf(const SDNode *N) const {
9770   return is_contained(N->op_values(), *this);
9771 }
9772 
9773 bool SDNode::isOperandOf(const SDNode *N) const {
9774   return any_of(N->op_values(),
9775                 [this](SDValue Op) { return this == Op.getNode(); });
9776 }
9777 
9778 /// reachesChainWithoutSideEffects - Return true if this operand (which must
9779 /// be a chain) reaches the specified operand without crossing any
9780 /// side-effecting instructions on any chain path.  In practice, this looks
9781 /// through token factors and non-volatile loads.  In order to remain efficient,
9782 /// this only looks a couple of nodes in, it does not do an exhaustive search.
9783 ///
9784 /// Note that we only need to examine chains when we're searching for
9785 /// side-effects; SelectionDAG requires that all side-effects are represented
9786 /// by chains, even if another operand would force a specific ordering. This
9787 /// constraint is necessary to allow transformations like splitting loads.
9788 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
9789                                              unsigned Depth) const {
9790   if (*this == Dest) return true;
9791 
9792   // Don't search too deeply, we just want to be able to see through
9793   // TokenFactor's etc.
9794   if (Depth == 0) return false;
9795 
9796   // If this is a token factor, all inputs to the TF happen in parallel.
9797   if (getOpcode() == ISD::TokenFactor) {
9798     // First, try a shallow search.
9799     if (is_contained((*this)->ops(), Dest)) {
9800       // We found the chain we want as an operand of this TokenFactor.
9801       // Essentially, we reach the chain without side-effects if we could
9802       // serialize the TokenFactor into a simple chain of operations with
9803       // Dest as the last operation. This is automatically true if the
9804       // chain has one use: there are no other ordering constraints.
9805       // If the chain has more than one use, we give up: some other
9806       // use of Dest might force a side-effect between Dest and the current
9807       // node.
9808       if (Dest.hasOneUse())
9809         return true;
9810     }
9811     // Next, try a deep search: check whether every operand of the TokenFactor
9812     // reaches Dest.
9813     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
9814       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
9815     });
9816   }
9817 
9818   // Loads don't have side effects, look through them.
9819   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
9820     if (Ld->isUnordered())
9821       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
9822   }
9823   return false;
9824 }
9825 
9826 bool SDNode::hasPredecessor(const SDNode *N) const {
9827   SmallPtrSet<const SDNode *, 32> Visited;
9828   SmallVector<const SDNode *, 16> Worklist;
9829   Worklist.push_back(this);
9830   return hasPredecessorHelper(N, Visited, Worklist);
9831 }
9832 
9833 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
9834   this->Flags.intersectWith(Flags);
9835 }
9836 
9837 SDValue
9838 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
9839                                   ArrayRef<ISD::NodeType> CandidateBinOps,
9840                                   bool AllowPartials) {
9841   // The pattern must end in an extract from index 0.
9842   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9843       !isNullConstant(Extract->getOperand(1)))
9844     return SDValue();
9845 
9846   // Match against one of the candidate binary ops.
9847   SDValue Op = Extract->getOperand(0);
9848   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9849         return Op.getOpcode() == unsigned(BinOp);
9850       }))
9851     return SDValue();
9852 
9853   // Floating-point reductions may require relaxed constraints on the final step
9854   // of the reduction because they may reorder intermediate operations.
9855   unsigned CandidateBinOp = Op.getOpcode();
9856   if (Op.getValueType().isFloatingPoint()) {
9857     SDNodeFlags Flags = Op->getFlags();
9858     switch (CandidateBinOp) {
9859     case ISD::FADD:
9860       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
9861         return SDValue();
9862       break;
9863     default:
9864       llvm_unreachable("Unhandled FP opcode for binop reduction");
9865     }
9866   }
9867 
9868   // Matching failed - attempt to see if we did enough stages that a partial
9869   // reduction from a subvector is possible.
9870   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
9871     if (!AllowPartials || !Op)
9872       return SDValue();
9873     EVT OpVT = Op.getValueType();
9874     EVT OpSVT = OpVT.getScalarType();
9875     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
9876     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
9877       return SDValue();
9878     BinOp = (ISD::NodeType)CandidateBinOp;
9879     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
9880                    getVectorIdxConstant(0, SDLoc(Op)));
9881   };
9882 
9883   // At each stage, we're looking for something that looks like:
9884   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9885   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9886   //                               i32 undef, i32 undef, i32 undef, i32 undef>
9887   // %a = binop <8 x i32> %op, %s
9888   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9889   // we expect something like:
9890   // <4,5,6,7,u,u,u,u>
9891   // <2,3,u,u,u,u,u,u>
9892   // <1,u,u,u,u,u,u,u>
9893   // While a partial reduction match would be:
9894   // <2,3,u,u,u,u,u,u>
9895   // <1,u,u,u,u,u,u,u>
9896   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9897   SDValue PrevOp;
9898   for (unsigned i = 0; i < Stages; ++i) {
9899     unsigned MaskEnd = (1 << i);
9900 
9901     if (Op.getOpcode() != CandidateBinOp)
9902       return PartialReduction(PrevOp, MaskEnd);
9903 
9904     SDValue Op0 = Op.getOperand(0);
9905     SDValue Op1 = Op.getOperand(1);
9906 
9907     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9908     if (Shuffle) {
9909       Op = Op1;
9910     } else {
9911       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9912       Op = Op0;
9913     }
9914 
9915     // The first operand of the shuffle should be the same as the other operand
9916     // of the binop.
9917     if (!Shuffle || Shuffle->getOperand(0) != Op)
9918       return PartialReduction(PrevOp, MaskEnd);
9919 
9920     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9921     for (int Index = 0; Index < (int)MaskEnd; ++Index)
9922       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
9923         return PartialReduction(PrevOp, MaskEnd);
9924 
9925     PrevOp = Op;
9926   }
9927 
9928   // Handle subvector reductions, which tend to appear after the shuffle
9929   // reduction stages.
9930   while (Op.getOpcode() == CandidateBinOp) {
9931     unsigned NumElts = Op.getValueType().getVectorNumElements();
9932     SDValue Op0 = Op.getOperand(0);
9933     SDValue Op1 = Op.getOperand(1);
9934     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9935         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9936         Op0.getOperand(0) != Op1.getOperand(0))
9937       break;
9938     SDValue Src = Op0.getOperand(0);
9939     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
9940     if (NumSrcElts != (2 * NumElts))
9941       break;
9942     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
9943           Op1.getConstantOperandAPInt(1) == NumElts) &&
9944         !(Op1.getConstantOperandAPInt(1) == 0 &&
9945           Op0.getConstantOperandAPInt(1) == NumElts))
9946       break;
9947     Op = Src;
9948   }
9949 
9950   BinOp = (ISD::NodeType)CandidateBinOp;
9951   return Op;
9952 }
9953 
9954 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9955   assert(N->getNumValues() == 1 &&
9956          "Can't unroll a vector with multiple results!");
9957 
9958   EVT VT = N->getValueType(0);
9959   unsigned NE = VT.getVectorNumElements();
9960   EVT EltVT = VT.getVectorElementType();
9961   SDLoc dl(N);
9962 
9963   SmallVector<SDValue, 8> Scalars;
9964   SmallVector<SDValue, 4> Operands(N->getNumOperands());
9965 
9966   // If ResNE is 0, fully unroll the vector op.
9967   if (ResNE == 0)
9968     ResNE = NE;
9969   else if (NE > ResNE)
9970     NE = ResNE;
9971 
9972   unsigned i;
9973   for (i= 0; i != NE; ++i) {
9974     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9975       SDValue Operand = N->getOperand(j);
9976       EVT OperandVT = Operand.getValueType();
9977       if (OperandVT.isVector()) {
9978         // A vector operand; extract a single element.
9979         EVT OperandEltVT = OperandVT.getVectorElementType();
9980         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
9981                               Operand, getVectorIdxConstant(i, dl));
9982       } else {
9983         // A scalar operand; just use it as is.
9984         Operands[j] = Operand;
9985       }
9986     }
9987 
9988     switch (N->getOpcode()) {
9989     default: {
9990       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9991                                 N->getFlags()));
9992       break;
9993     }
9994     case ISD::VSELECT:
9995       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
9996       break;
9997     case ISD::SHL:
9998     case ISD::SRA:
9999     case ISD::SRL:
10000     case ISD::ROTL:
10001     case ISD::ROTR:
10002       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10003                                getShiftAmountOperand(Operands[0].getValueType(),
10004                                                      Operands[1])));
10005       break;
10006     case ISD::SIGN_EXTEND_INREG: {
10007       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10008       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10009                                 Operands[0],
10010                                 getValueType(ExtVT)));
10011     }
10012     }
10013   }
10014 
10015   for (; i < ResNE; ++i)
10016     Scalars.push_back(getUNDEF(EltVT));
10017 
10018   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10019   return getBuildVector(VecVT, dl, Scalars);
10020 }
10021 
10022 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10023     SDNode *N, unsigned ResNE) {
10024   unsigned Opcode = N->getOpcode();
10025   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10026           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10027           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10028          "Expected an overflow opcode");
10029 
10030   EVT ResVT = N->getValueType(0);
10031   EVT OvVT = N->getValueType(1);
10032   EVT ResEltVT = ResVT.getVectorElementType();
10033   EVT OvEltVT = OvVT.getVectorElementType();
10034   SDLoc dl(N);
10035 
10036   // If ResNE is 0, fully unroll the vector op.
10037   unsigned NE = ResVT.getVectorNumElements();
10038   if (ResNE == 0)
10039     ResNE = NE;
10040   else if (NE > ResNE)
10041     NE = ResNE;
10042 
10043   SmallVector<SDValue, 8> LHSScalars;
10044   SmallVector<SDValue, 8> RHSScalars;
10045   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10046   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10047 
10048   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10049   SDVTList VTs = getVTList(ResEltVT, SVT);
10050   SmallVector<SDValue, 8> ResScalars;
10051   SmallVector<SDValue, 8> OvScalars;
10052   for (unsigned i = 0; i < NE; ++i) {
10053     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10054     SDValue Ov =
10055         getSelect(dl, OvEltVT, Res.getValue(1),
10056                   getBoolConstant(true, dl, OvEltVT, ResVT),
10057                   getConstant(0, dl, OvEltVT));
10058 
10059     ResScalars.push_back(Res);
10060     OvScalars.push_back(Ov);
10061   }
10062 
10063   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10064   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10065 
10066   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10067   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10068   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10069                         getBuildVector(NewOvVT, dl, OvScalars));
10070 }
10071 
10072 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10073                                                   LoadSDNode *Base,
10074                                                   unsigned Bytes,
10075                                                   int Dist) const {
10076   if (LD->isVolatile() || Base->isVolatile())
10077     return false;
10078   // TODO: probably too restrictive for atomics, revisit
10079   if (!LD->isSimple())
10080     return false;
10081   if (LD->isIndexed() || Base->isIndexed())
10082     return false;
10083   if (LD->getChain() != Base->getChain())
10084     return false;
10085   EVT VT = LD->getValueType(0);
10086   if (VT.getSizeInBits() / 8 != Bytes)
10087     return false;
10088 
10089   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10090   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10091 
10092   int64_t Offset = 0;
10093   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10094     return (Dist * Bytes == Offset);
10095   return false;
10096 }
10097 
10098 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10099 /// if it cannot be inferred.
10100 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10101   // If this is a GlobalAddress + cst, return the alignment.
10102   const GlobalValue *GV = nullptr;
10103   int64_t GVOffset = 0;
10104   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10105     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10106     KnownBits Known(PtrWidth);
10107     llvm::computeKnownBits(GV, Known, getDataLayout());
10108     unsigned AlignBits = Known.countMinTrailingZeros();
10109     if (AlignBits)
10110       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10111   }
10112 
10113   // If this is a direct reference to a stack slot, use information about the
10114   // stack slot's alignment.
10115   int FrameIdx = INT_MIN;
10116   int64_t FrameOffset = 0;
10117   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10118     FrameIdx = FI->getIndex();
10119   } else if (isBaseWithConstantOffset(Ptr) &&
10120              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10121     // Handle FI+Cst
10122     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10123     FrameOffset = Ptr.getConstantOperandVal(1);
10124   }
10125 
10126   if (FrameIdx != INT_MIN) {
10127     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10128     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10129   }
10130 
10131   return None;
10132 }
10133 
10134 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10135 /// which is split (or expanded) into two not necessarily identical pieces.
10136 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10137   // Currently all types are split in half.
10138   EVT LoVT, HiVT;
10139   if (!VT.isVector())
10140     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10141   else
10142     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10143 
10144   return std::make_pair(LoVT, HiVT);
10145 }
10146 
10147 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10148 /// type, dependent on an enveloping VT that has been split into two identical
10149 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10150 std::pair<EVT, EVT>
10151 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10152                                        bool *HiIsEmpty) const {
10153   EVT EltTp = VT.getVectorElementType();
10154   // Examples:
10155   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10156   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10157   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10158   //   etc.
10159   ElementCount VTNumElts = VT.getVectorElementCount();
10160   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10161   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10162          "Mixing fixed width and scalable vectors when enveloping a type");
10163   EVT LoVT, HiVT;
10164   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10165     LoVT = EnvVT;
10166     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10167     *HiIsEmpty = false;
10168   } else {
10169     // Flag that hi type has zero storage size, but return split envelop type
10170     // (this would be easier if vector types with zero elements were allowed).
10171     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10172     HiVT = EnvVT;
10173     *HiIsEmpty = true;
10174   }
10175   return std::make_pair(LoVT, HiVT);
10176 }
10177 
10178 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10179 /// low/high part.
10180 std::pair<SDValue, SDValue>
10181 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10182                           const EVT &HiVT) {
10183   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10184          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10185          "Splitting vector with an invalid mixture of fixed and scalable "
10186          "vector types");
10187   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10188              N.getValueType().getVectorMinNumElements() &&
10189          "More vector elements requested than available!");
10190   SDValue Lo, Hi;
10191   Lo =
10192       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10193   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10194   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10195   // IDX with the runtime scaling factor of the result vector type. For
10196   // fixed-width result vectors, that runtime scaling factor is 1.
10197   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10198                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10199   return std::make_pair(Lo, Hi);
10200 }
10201 
10202 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10203 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10204   EVT VT = N.getValueType();
10205   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10206                                 NextPowerOf2(VT.getVectorNumElements()));
10207   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10208                  getVectorIdxConstant(0, DL));
10209 }
10210 
10211 void SelectionDAG::ExtractVectorElements(SDValue Op,
10212                                          SmallVectorImpl<SDValue> &Args,
10213                                          unsigned Start, unsigned Count,
10214                                          EVT EltVT) {
10215   EVT VT = Op.getValueType();
10216   if (Count == 0)
10217     Count = VT.getVectorNumElements();
10218   if (EltVT == EVT())
10219     EltVT = VT.getVectorElementType();
10220   SDLoc SL(Op);
10221   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10222     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10223                            getVectorIdxConstant(i, SL)));
10224   }
10225 }
10226 
10227 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10228 unsigned GlobalAddressSDNode::getAddressSpace() const {
10229   return getGlobal()->getType()->getAddressSpace();
10230 }
10231 
10232 Type *ConstantPoolSDNode::getType() const {
10233   if (isMachineConstantPoolEntry())
10234     return Val.MachineCPVal->getType();
10235   return Val.ConstVal->getType();
10236 }
10237 
10238 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10239                                         unsigned &SplatBitSize,
10240                                         bool &HasAnyUndefs,
10241                                         unsigned MinSplatBits,
10242                                         bool IsBigEndian) const {
10243   EVT VT = getValueType(0);
10244   assert(VT.isVector() && "Expected a vector type");
10245   unsigned VecWidth = VT.getSizeInBits();
10246   if (MinSplatBits > VecWidth)
10247     return false;
10248 
10249   // FIXME: The widths are based on this node's type, but build vectors can
10250   // truncate their operands.
10251   SplatValue = APInt(VecWidth, 0);
10252   SplatUndef = APInt(VecWidth, 0);
10253 
10254   // Get the bits. Bits with undefined values (when the corresponding element
10255   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10256   // in SplatValue. If any of the values are not constant, give up and return
10257   // false.
10258   unsigned int NumOps = getNumOperands();
10259   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10260   unsigned EltWidth = VT.getScalarSizeInBits();
10261 
10262   for (unsigned j = 0; j < NumOps; ++j) {
10263     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10264     SDValue OpVal = getOperand(i);
10265     unsigned BitPos = j * EltWidth;
10266 
10267     if (OpVal.isUndef())
10268       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10269     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10270       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10271     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10272       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10273     else
10274       return false;
10275   }
10276 
10277   // The build_vector is all constants or undefs. Find the smallest element
10278   // size that splats the vector.
10279   HasAnyUndefs = (SplatUndef != 0);
10280 
10281   // FIXME: This does not work for vectors with elements less than 8 bits.
10282   while (VecWidth > 8) {
10283     unsigned HalfSize = VecWidth / 2;
10284     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10285     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10286     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10287     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10288 
10289     // If the two halves do not match (ignoring undef bits), stop here.
10290     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10291         MinSplatBits > HalfSize)
10292       break;
10293 
10294     SplatValue = HighValue | LowValue;
10295     SplatUndef = HighUndef & LowUndef;
10296 
10297     VecWidth = HalfSize;
10298   }
10299 
10300   SplatBitSize = VecWidth;
10301   return true;
10302 }
10303 
10304 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10305                                          BitVector *UndefElements) const {
10306   unsigned NumOps = getNumOperands();
10307   if (UndefElements) {
10308     UndefElements->clear();
10309     UndefElements->resize(NumOps);
10310   }
10311   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10312   if (!DemandedElts)
10313     return SDValue();
10314   SDValue Splatted;
10315   for (unsigned i = 0; i != NumOps; ++i) {
10316     if (!DemandedElts[i])
10317       continue;
10318     SDValue Op = getOperand(i);
10319     if (Op.isUndef()) {
10320       if (UndefElements)
10321         (*UndefElements)[i] = true;
10322     } else if (!Splatted) {
10323       Splatted = Op;
10324     } else if (Splatted != Op) {
10325       return SDValue();
10326     }
10327   }
10328 
10329   if (!Splatted) {
10330     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10331     assert(getOperand(FirstDemandedIdx).isUndef() &&
10332            "Can only have a splat without a constant for all undefs.");
10333     return getOperand(FirstDemandedIdx);
10334   }
10335 
10336   return Splatted;
10337 }
10338 
10339 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10340   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10341   return getSplatValue(DemandedElts, UndefElements);
10342 }
10343 
10344 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10345                                             SmallVectorImpl<SDValue> &Sequence,
10346                                             BitVector *UndefElements) const {
10347   unsigned NumOps = getNumOperands();
10348   Sequence.clear();
10349   if (UndefElements) {
10350     UndefElements->clear();
10351     UndefElements->resize(NumOps);
10352   }
10353   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10354   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10355     return false;
10356 
10357   // Set the undefs even if we don't find a sequence (like getSplatValue).
10358   if (UndefElements)
10359     for (unsigned I = 0; I != NumOps; ++I)
10360       if (DemandedElts[I] && getOperand(I).isUndef())
10361         (*UndefElements)[I] = true;
10362 
10363   // Iteratively widen the sequence length looking for repetitions.
10364   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10365     Sequence.append(SeqLen, SDValue());
10366     for (unsigned I = 0; I != NumOps; ++I) {
10367       if (!DemandedElts[I])
10368         continue;
10369       SDValue &SeqOp = Sequence[I % SeqLen];
10370       SDValue Op = getOperand(I);
10371       if (Op.isUndef()) {
10372         if (!SeqOp)
10373           SeqOp = Op;
10374         continue;
10375       }
10376       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10377         Sequence.clear();
10378         break;
10379       }
10380       SeqOp = Op;
10381     }
10382     if (!Sequence.empty())
10383       return true;
10384   }
10385 
10386   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10387   return false;
10388 }
10389 
10390 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10391                                             BitVector *UndefElements) const {
10392   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10393   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10394 }
10395 
10396 ConstantSDNode *
10397 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10398                                         BitVector *UndefElements) const {
10399   return dyn_cast_or_null<ConstantSDNode>(
10400       getSplatValue(DemandedElts, UndefElements));
10401 }
10402 
10403 ConstantSDNode *
10404 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10405   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10406 }
10407 
10408 ConstantFPSDNode *
10409 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10410                                           BitVector *UndefElements) const {
10411   return dyn_cast_or_null<ConstantFPSDNode>(
10412       getSplatValue(DemandedElts, UndefElements));
10413 }
10414 
10415 ConstantFPSDNode *
10416 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10417   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10418 }
10419 
10420 int32_t
10421 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10422                                                    uint32_t BitWidth) const {
10423   if (ConstantFPSDNode *CN =
10424           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10425     bool IsExact;
10426     APSInt IntVal(BitWidth);
10427     const APFloat &APF = CN->getValueAPF();
10428     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10429             APFloat::opOK ||
10430         !IsExact)
10431       return -1;
10432 
10433     return IntVal.exactLogBase2();
10434   }
10435   return -1;
10436 }
10437 
10438 bool BuildVectorSDNode::isConstant() const {
10439   for (const SDValue &Op : op_values()) {
10440     unsigned Opc = Op.getOpcode();
10441     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10442       return false;
10443   }
10444   return true;
10445 }
10446 
10447 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10448   // Find the first non-undef value in the shuffle mask.
10449   unsigned i, e;
10450   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10451     /* search */;
10452 
10453   // If all elements are undefined, this shuffle can be considered a splat
10454   // (although it should eventually get simplified away completely).
10455   if (i == e)
10456     return true;
10457 
10458   // Make sure all remaining elements are either undef or the same as the first
10459   // non-undef value.
10460   for (int Idx = Mask[i]; i != e; ++i)
10461     if (Mask[i] >= 0 && Mask[i] != Idx)
10462       return false;
10463   return true;
10464 }
10465 
10466 // Returns the SDNode if it is a constant integer BuildVector
10467 // or constant integer.
10468 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10469   if (isa<ConstantSDNode>(N))
10470     return N.getNode();
10471   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10472     return N.getNode();
10473   // Treat a GlobalAddress supporting constant offset folding as a
10474   // constant integer.
10475   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10476     if (GA->getOpcode() == ISD::GlobalAddress &&
10477         TLI->isOffsetFoldingLegal(GA))
10478       return GA;
10479   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10480       isa<ConstantSDNode>(N.getOperand(0)))
10481     return N.getNode();
10482   return nullptr;
10483 }
10484 
10485 // Returns the SDNode if it is a constant float BuildVector
10486 // or constant float.
10487 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10488   if (isa<ConstantFPSDNode>(N))
10489     return N.getNode();
10490 
10491   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10492     return N.getNode();
10493 
10494   return nullptr;
10495 }
10496 
10497 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10498   assert(!Node->OperandList && "Node already has operands");
10499   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
10500          "too many operands to fit into SDNode");
10501   SDUse *Ops = OperandRecycler.allocate(
10502       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10503 
10504   bool IsDivergent = false;
10505   for (unsigned I = 0; I != Vals.size(); ++I) {
10506     Ops[I].setUser(Node);
10507     Ops[I].setInitial(Vals[I]);
10508     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10509       IsDivergent |= Ops[I].getNode()->isDivergent();
10510   }
10511   Node->NumOperands = Vals.size();
10512   Node->OperandList = Ops;
10513   if (!TLI->isSDNodeAlwaysUniform(Node)) {
10514     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10515     Node->SDNodeBits.IsDivergent = IsDivergent;
10516   }
10517   checkForCycles(Node);
10518 }
10519 
10520 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10521                                      SmallVectorImpl<SDValue> &Vals) {
10522   size_t Limit = SDNode::getMaxNumOperands();
10523   while (Vals.size() > Limit) {
10524     unsigned SliceIdx = Vals.size() - Limit;
10525     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
10526     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
10527     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
10528     Vals.emplace_back(NewTF);
10529   }
10530   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
10531 }
10532 
10533 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
10534                                         EVT VT, SDNodeFlags Flags) {
10535   switch (Opcode) {
10536   default:
10537     return SDValue();
10538   case ISD::ADD:
10539   case ISD::OR:
10540   case ISD::XOR:
10541   case ISD::UMAX:
10542     return getConstant(0, DL, VT);
10543   case ISD::MUL:
10544     return getConstant(1, DL, VT);
10545   case ISD::AND:
10546   case ISD::UMIN:
10547     return getAllOnesConstant(DL, VT);
10548   case ISD::SMAX:
10549     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
10550   case ISD::SMIN:
10551     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
10552   case ISD::FADD:
10553     return getConstantFP(-0.0, DL, VT);
10554   case ISD::FMUL:
10555     return getConstantFP(1.0, DL, VT);
10556   case ISD::FMINNUM:
10557   case ISD::FMAXNUM: {
10558     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
10559     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
10560     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
10561                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
10562                         APFloat::getLargest(Semantics);
10563     if (Opcode == ISD::FMAXNUM)
10564       NeutralAF.changeSign();
10565 
10566     return getConstantFP(NeutralAF, DL, VT);
10567   }
10568   }
10569 }
10570 
10571 #ifndef NDEBUG
10572 static void checkForCyclesHelper(const SDNode *N,
10573                                  SmallPtrSetImpl<const SDNode*> &Visited,
10574                                  SmallPtrSetImpl<const SDNode*> &Checked,
10575                                  const llvm::SelectionDAG *DAG) {
10576   // If this node has already been checked, don't check it again.
10577   if (Checked.count(N))
10578     return;
10579 
10580   // If a node has already been visited on this depth-first walk, reject it as
10581   // a cycle.
10582   if (!Visited.insert(N).second) {
10583     errs() << "Detected cycle in SelectionDAG\n";
10584     dbgs() << "Offending node:\n";
10585     N->dumprFull(DAG); dbgs() << "\n";
10586     abort();
10587   }
10588 
10589   for (const SDValue &Op : N->op_values())
10590     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
10591 
10592   Checked.insert(N);
10593   Visited.erase(N);
10594 }
10595 #endif
10596 
10597 void llvm::checkForCycles(const llvm::SDNode *N,
10598                           const llvm::SelectionDAG *DAG,
10599                           bool force) {
10600 #ifndef NDEBUG
10601   bool check = force;
10602 #ifdef EXPENSIVE_CHECKS
10603   check = true;
10604 #endif  // EXPENSIVE_CHECKS
10605   if (check) {
10606     assert(N && "Checking nonexistent SDNode");
10607     SmallPtrSet<const SDNode*, 32> visited;
10608     SmallPtrSet<const SDNode*, 32> checked;
10609     checkForCyclesHelper(N, visited, checked, DAG);
10610   }
10611 #endif  // !NDEBUG
10612 }
10613 
10614 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
10615   checkForCycles(DAG->getRoot().getNode(), DAG, force);
10616 }
10617