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.lshr(i * ViaEltSizeInBits).trunc(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.lshr(i * ViaEltSizeInBits).zextOrTrunc(ViaEltSizeInBits), DL,
1418           ViaEltVT, isT, isO));
1419     }
1420 
1421     // EltParts is currently in little endian order. If we actually want
1422     // big-endian order then reverse it now.
1423     if (getDataLayout().isBigEndian())
1424       std::reverse(EltParts.begin(), EltParts.end());
1425 
1426     // The elements must be reversed when the element order is different
1427     // to the endianness of the elements (because the BITCAST is itself a
1428     // vector shuffle in this situation). However, we do not need any code to
1429     // perform this reversal because getConstant() is producing a vector
1430     // splat.
1431     // This situation occurs in MIPS MSA.
1432 
1433     SmallVector<SDValue, 8> Ops;
1434     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1435       llvm::append_range(Ops, EltParts);
1436 
1437     SDValue V =
1438         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1439     return V;
1440   }
1441 
1442   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1443          "APInt size does not match type size!");
1444   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1445   FoldingSetNodeID ID;
1446   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1447   ID.AddPointer(Elt);
1448   ID.AddBoolean(isO);
1449   void *IP = nullptr;
1450   SDNode *N = nullptr;
1451   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1452     if (!VT.isVector())
1453       return SDValue(N, 0);
1454 
1455   if (!N) {
1456     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1457     CSEMap.InsertNode(N, IP);
1458     InsertNode(N);
1459     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1460   }
1461 
1462   SDValue Result(N, 0);
1463   if (VT.isScalableVector())
1464     Result = getSplatVector(VT, DL, Result);
1465   else if (VT.isVector())
1466     Result = getSplatBuildVector(VT, DL, Result);
1467 
1468   return Result;
1469 }
1470 
1471 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1472                                         bool isTarget) {
1473   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1474 }
1475 
1476 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1477                                              const SDLoc &DL, bool LegalTypes) {
1478   assert(VT.isInteger() && "Shift amount is not an integer type!");
1479   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1480   return getConstant(Val, DL, ShiftVT);
1481 }
1482 
1483 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1484                                            bool isTarget) {
1485   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1486 }
1487 
1488 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1489                                     bool isTarget) {
1490   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1491 }
1492 
1493 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1494                                     EVT VT, bool isTarget) {
1495   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1496 
1497   EVT EltVT = VT.getScalarType();
1498 
1499   // Do the map lookup using the actual bit pattern for the floating point
1500   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1501   // we don't have issues with SNANs.
1502   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1503   FoldingSetNodeID ID;
1504   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1505   ID.AddPointer(&V);
1506   void *IP = nullptr;
1507   SDNode *N = nullptr;
1508   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1509     if (!VT.isVector())
1510       return SDValue(N, 0);
1511 
1512   if (!N) {
1513     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1514     CSEMap.InsertNode(N, IP);
1515     InsertNode(N);
1516   }
1517 
1518   SDValue Result(N, 0);
1519   if (VT.isScalableVector())
1520     Result = getSplatVector(VT, DL, Result);
1521   else if (VT.isVector())
1522     Result = getSplatBuildVector(VT, DL, Result);
1523   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1524   return Result;
1525 }
1526 
1527 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1528                                     bool isTarget) {
1529   EVT EltVT = VT.getScalarType();
1530   if (EltVT == MVT::f32)
1531     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1532   if (EltVT == MVT::f64)
1533     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1534   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1535       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1536     bool Ignored;
1537     APFloat APF = APFloat(Val);
1538     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1539                 &Ignored);
1540     return getConstantFP(APF, DL, VT, isTarget);
1541   }
1542   llvm_unreachable("Unsupported type in getConstantFP");
1543 }
1544 
1545 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1546                                        EVT VT, int64_t Offset, bool isTargetGA,
1547                                        unsigned TargetFlags) {
1548   assert((TargetFlags == 0 || isTargetGA) &&
1549          "Cannot set target flags on target-independent globals");
1550 
1551   // Truncate (with sign-extension) the offset value to the pointer size.
1552   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1553   if (BitWidth < 64)
1554     Offset = SignExtend64(Offset, BitWidth);
1555 
1556   unsigned Opc;
1557   if (GV->isThreadLocal())
1558     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1559   else
1560     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1561 
1562   FoldingSetNodeID ID;
1563   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1564   ID.AddPointer(GV);
1565   ID.AddInteger(Offset);
1566   ID.AddInteger(TargetFlags);
1567   void *IP = nullptr;
1568   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1569     return SDValue(E, 0);
1570 
1571   auto *N = newSDNode<GlobalAddressSDNode>(
1572       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1573   CSEMap.InsertNode(N, IP);
1574     InsertNode(N);
1575   return SDValue(N, 0);
1576 }
1577 
1578 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1579   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1580   FoldingSetNodeID ID;
1581   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1582   ID.AddInteger(FI);
1583   void *IP = nullptr;
1584   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1585     return SDValue(E, 0);
1586 
1587   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1588   CSEMap.InsertNode(N, IP);
1589   InsertNode(N);
1590   return SDValue(N, 0);
1591 }
1592 
1593 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1594                                    unsigned TargetFlags) {
1595   assert((TargetFlags == 0 || isTarget) &&
1596          "Cannot set target flags on target-independent jump tables");
1597   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1598   FoldingSetNodeID ID;
1599   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1600   ID.AddInteger(JTI);
1601   ID.AddInteger(TargetFlags);
1602   void *IP = nullptr;
1603   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1604     return SDValue(E, 0);
1605 
1606   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1607   CSEMap.InsertNode(N, IP);
1608   InsertNode(N);
1609   return SDValue(N, 0);
1610 }
1611 
1612 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1613                                       MaybeAlign Alignment, int Offset,
1614                                       bool isTarget, unsigned TargetFlags) {
1615   assert((TargetFlags == 0 || isTarget) &&
1616          "Cannot set target flags on target-independent globals");
1617   if (!Alignment)
1618     Alignment = shouldOptForSize()
1619                     ? getDataLayout().getABITypeAlign(C->getType())
1620                     : getDataLayout().getPrefTypeAlign(C->getType());
1621   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1622   FoldingSetNodeID ID;
1623   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1624   ID.AddInteger(Alignment->value());
1625   ID.AddInteger(Offset);
1626   ID.AddPointer(C);
1627   ID.AddInteger(TargetFlags);
1628   void *IP = nullptr;
1629   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1630     return SDValue(E, 0);
1631 
1632   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1633                                           TargetFlags);
1634   CSEMap.InsertNode(N, IP);
1635   InsertNode(N);
1636   SDValue V = SDValue(N, 0);
1637   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1638   return V;
1639 }
1640 
1641 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1642                                       MaybeAlign Alignment, int Offset,
1643                                       bool isTarget, unsigned TargetFlags) {
1644   assert((TargetFlags == 0 || isTarget) &&
1645          "Cannot set target flags on target-independent globals");
1646   if (!Alignment)
1647     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1648   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1649   FoldingSetNodeID ID;
1650   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1651   ID.AddInteger(Alignment->value());
1652   ID.AddInteger(Offset);
1653   C->addSelectionDAGCSEId(ID);
1654   ID.AddInteger(TargetFlags);
1655   void *IP = nullptr;
1656   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1657     return SDValue(E, 0);
1658 
1659   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1660                                           TargetFlags);
1661   CSEMap.InsertNode(N, IP);
1662   InsertNode(N);
1663   return SDValue(N, 0);
1664 }
1665 
1666 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1667                                      unsigned TargetFlags) {
1668   FoldingSetNodeID ID;
1669   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1670   ID.AddInteger(Index);
1671   ID.AddInteger(Offset);
1672   ID.AddInteger(TargetFlags);
1673   void *IP = nullptr;
1674   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1675     return SDValue(E, 0);
1676 
1677   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1678   CSEMap.InsertNode(N, IP);
1679   InsertNode(N);
1680   return SDValue(N, 0);
1681 }
1682 
1683 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1684   FoldingSetNodeID ID;
1685   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1686   ID.AddPointer(MBB);
1687   void *IP = nullptr;
1688   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1689     return SDValue(E, 0);
1690 
1691   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1692   CSEMap.InsertNode(N, IP);
1693   InsertNode(N);
1694   return SDValue(N, 0);
1695 }
1696 
1697 SDValue SelectionDAG::getValueType(EVT VT) {
1698   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1699       ValueTypeNodes.size())
1700     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1701 
1702   SDNode *&N = VT.isExtended() ?
1703     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1704 
1705   if (N) return SDValue(N, 0);
1706   N = newSDNode<VTSDNode>(VT);
1707   InsertNode(N);
1708   return SDValue(N, 0);
1709 }
1710 
1711 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1712   SDNode *&N = ExternalSymbols[Sym];
1713   if (N) return SDValue(N, 0);
1714   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1715   InsertNode(N);
1716   return SDValue(N, 0);
1717 }
1718 
1719 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1720   SDNode *&N = MCSymbols[Sym];
1721   if (N)
1722     return SDValue(N, 0);
1723   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1724   InsertNode(N);
1725   return SDValue(N, 0);
1726 }
1727 
1728 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1729                                               unsigned TargetFlags) {
1730   SDNode *&N =
1731       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1732   if (N) return SDValue(N, 0);
1733   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1734   InsertNode(N);
1735   return SDValue(N, 0);
1736 }
1737 
1738 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1739   if ((unsigned)Cond >= CondCodeNodes.size())
1740     CondCodeNodes.resize(Cond+1);
1741 
1742   if (!CondCodeNodes[Cond]) {
1743     auto *N = newSDNode<CondCodeSDNode>(Cond);
1744     CondCodeNodes[Cond] = N;
1745     InsertNode(N);
1746   }
1747 
1748   return SDValue(CondCodeNodes[Cond], 0);
1749 }
1750 
1751 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, SDValue Step) {
1752   if (ResVT.isScalableVector())
1753     return getNode(ISD::STEP_VECTOR, DL, ResVT, Step);
1754 
1755   EVT OpVT = Step.getValueType();
1756   APInt StepVal = cast<ConstantSDNode>(Step)->getAPIntValue();
1757   SmallVector<SDValue, 16> OpsStepConstants;
1758   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1759     OpsStepConstants.push_back(getConstant(StepVal * i, DL, OpVT));
1760   return getBuildVector(ResVT, DL, OpsStepConstants);
1761 }
1762 
1763 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1764 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1765 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1766   std::swap(N1, N2);
1767   ShuffleVectorSDNode::commuteMask(M);
1768 }
1769 
1770 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1771                                        SDValue N2, ArrayRef<int> Mask) {
1772   assert(VT.getVectorNumElements() == Mask.size() &&
1773            "Must have the same number of vector elements as mask elements!");
1774   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1775          "Invalid VECTOR_SHUFFLE");
1776 
1777   // Canonicalize shuffle undef, undef -> undef
1778   if (N1.isUndef() && N2.isUndef())
1779     return getUNDEF(VT);
1780 
1781   // Validate that all indices in Mask are within the range of the elements
1782   // input to the shuffle.
1783   int NElts = Mask.size();
1784   assert(llvm::all_of(Mask,
1785                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1786          "Index out of range");
1787 
1788   // Copy the mask so we can do any needed cleanup.
1789   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1790 
1791   // Canonicalize shuffle v, v -> v, undef
1792   if (N1 == N2) {
1793     N2 = getUNDEF(VT);
1794     for (int i = 0; i != NElts; ++i)
1795       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1796   }
1797 
1798   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1799   if (N1.isUndef())
1800     commuteShuffle(N1, N2, MaskVec);
1801 
1802   if (TLI->hasVectorBlend()) {
1803     // If shuffling a splat, try to blend the splat instead. We do this here so
1804     // that even when this arises during lowering we don't have to re-handle it.
1805     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1806       BitVector UndefElements;
1807       SDValue Splat = BV->getSplatValue(&UndefElements);
1808       if (!Splat)
1809         return;
1810 
1811       for (int i = 0; i < NElts; ++i) {
1812         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1813           continue;
1814 
1815         // If this input comes from undef, mark it as such.
1816         if (UndefElements[MaskVec[i] - Offset]) {
1817           MaskVec[i] = -1;
1818           continue;
1819         }
1820 
1821         // If we can blend a non-undef lane, use that instead.
1822         if (!UndefElements[i])
1823           MaskVec[i] = i + Offset;
1824       }
1825     };
1826     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1827       BlendSplat(N1BV, 0);
1828     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1829       BlendSplat(N2BV, NElts);
1830   }
1831 
1832   // Canonicalize all index into lhs, -> shuffle lhs, undef
1833   // Canonicalize all index into rhs, -> shuffle rhs, undef
1834   bool AllLHS = true, AllRHS = true;
1835   bool N2Undef = N2.isUndef();
1836   for (int i = 0; i != NElts; ++i) {
1837     if (MaskVec[i] >= NElts) {
1838       if (N2Undef)
1839         MaskVec[i] = -1;
1840       else
1841         AllLHS = false;
1842     } else if (MaskVec[i] >= 0) {
1843       AllRHS = false;
1844     }
1845   }
1846   if (AllLHS && AllRHS)
1847     return getUNDEF(VT);
1848   if (AllLHS && !N2Undef)
1849     N2 = getUNDEF(VT);
1850   if (AllRHS) {
1851     N1 = getUNDEF(VT);
1852     commuteShuffle(N1, N2, MaskVec);
1853   }
1854   // Reset our undef status after accounting for the mask.
1855   N2Undef = N2.isUndef();
1856   // Re-check whether both sides ended up undef.
1857   if (N1.isUndef() && N2Undef)
1858     return getUNDEF(VT);
1859 
1860   // If Identity shuffle return that node.
1861   bool Identity = true, AllSame = true;
1862   for (int i = 0; i != NElts; ++i) {
1863     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1864     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1865   }
1866   if (Identity && NElts)
1867     return N1;
1868 
1869   // Shuffling a constant splat doesn't change the result.
1870   if (N2Undef) {
1871     SDValue V = N1;
1872 
1873     // Look through any bitcasts. We check that these don't change the number
1874     // (and size) of elements and just changes their types.
1875     while (V.getOpcode() == ISD::BITCAST)
1876       V = V->getOperand(0);
1877 
1878     // A splat should always show up as a build vector node.
1879     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1880       BitVector UndefElements;
1881       SDValue Splat = BV->getSplatValue(&UndefElements);
1882       // If this is a splat of an undef, shuffling it is also undef.
1883       if (Splat && Splat.isUndef())
1884         return getUNDEF(VT);
1885 
1886       bool SameNumElts =
1887           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1888 
1889       // We only have a splat which can skip shuffles if there is a splatted
1890       // value and no undef lanes rearranged by the shuffle.
1891       if (Splat && UndefElements.none()) {
1892         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1893         // number of elements match or the value splatted is a zero constant.
1894         if (SameNumElts)
1895           return N1;
1896         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1897           if (C->isNullValue())
1898             return N1;
1899       }
1900 
1901       // If the shuffle itself creates a splat, build the vector directly.
1902       if (AllSame && SameNumElts) {
1903         EVT BuildVT = BV->getValueType(0);
1904         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1905         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1906 
1907         // We may have jumped through bitcasts, so the type of the
1908         // BUILD_VECTOR may not match the type of the shuffle.
1909         if (BuildVT != VT)
1910           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1911         return NewBV;
1912       }
1913     }
1914   }
1915 
1916   FoldingSetNodeID ID;
1917   SDValue Ops[2] = { N1, N2 };
1918   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1919   for (int i = 0; i != NElts; ++i)
1920     ID.AddInteger(MaskVec[i]);
1921 
1922   void* IP = nullptr;
1923   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1924     return SDValue(E, 0);
1925 
1926   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1927   // SDNode doesn't have access to it.  This memory will be "leaked" when
1928   // the node is deallocated, but recovered when the NodeAllocator is released.
1929   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1930   llvm::copy(MaskVec, MaskAlloc);
1931 
1932   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1933                                            dl.getDebugLoc(), MaskAlloc);
1934   createOperands(N, Ops);
1935 
1936   CSEMap.InsertNode(N, IP);
1937   InsertNode(N);
1938   SDValue V = SDValue(N, 0);
1939   NewSDValueDbgMsg(V, "Creating new node: ", this);
1940   return V;
1941 }
1942 
1943 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1944   EVT VT = SV.getValueType(0);
1945   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1946   ShuffleVectorSDNode::commuteMask(MaskVec);
1947 
1948   SDValue Op0 = SV.getOperand(0);
1949   SDValue Op1 = SV.getOperand(1);
1950   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1951 }
1952 
1953 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1954   FoldingSetNodeID ID;
1955   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1956   ID.AddInteger(RegNo);
1957   void *IP = nullptr;
1958   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1959     return SDValue(E, 0);
1960 
1961   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1962   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1963   CSEMap.InsertNode(N, IP);
1964   InsertNode(N);
1965   return SDValue(N, 0);
1966 }
1967 
1968 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1969   FoldingSetNodeID ID;
1970   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1971   ID.AddPointer(RegMask);
1972   void *IP = nullptr;
1973   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1974     return SDValue(E, 0);
1975 
1976   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1977   CSEMap.InsertNode(N, IP);
1978   InsertNode(N);
1979   return SDValue(N, 0);
1980 }
1981 
1982 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1983                                  MCSymbol *Label) {
1984   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1985 }
1986 
1987 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1988                                    SDValue Root, MCSymbol *Label) {
1989   FoldingSetNodeID ID;
1990   SDValue Ops[] = { Root };
1991   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1992   ID.AddPointer(Label);
1993   void *IP = nullptr;
1994   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1995     return SDValue(E, 0);
1996 
1997   auto *N =
1998       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
1999   createOperands(N, Ops);
2000 
2001   CSEMap.InsertNode(N, IP);
2002   InsertNode(N);
2003   return SDValue(N, 0);
2004 }
2005 
2006 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2007                                       int64_t Offset, bool isTarget,
2008                                       unsigned TargetFlags) {
2009   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2010 
2011   FoldingSetNodeID ID;
2012   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2013   ID.AddPointer(BA);
2014   ID.AddInteger(Offset);
2015   ID.AddInteger(TargetFlags);
2016   void *IP = nullptr;
2017   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2018     return SDValue(E, 0);
2019 
2020   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2021   CSEMap.InsertNode(N, IP);
2022   InsertNode(N);
2023   return SDValue(N, 0);
2024 }
2025 
2026 SDValue SelectionDAG::getSrcValue(const Value *V) {
2027   FoldingSetNodeID ID;
2028   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2029   ID.AddPointer(V);
2030 
2031   void *IP = nullptr;
2032   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2033     return SDValue(E, 0);
2034 
2035   auto *N = newSDNode<SrcValueSDNode>(V);
2036   CSEMap.InsertNode(N, IP);
2037   InsertNode(N);
2038   return SDValue(N, 0);
2039 }
2040 
2041 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2042   FoldingSetNodeID ID;
2043   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2044   ID.AddPointer(MD);
2045 
2046   void *IP = nullptr;
2047   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2048     return SDValue(E, 0);
2049 
2050   auto *N = newSDNode<MDNodeSDNode>(MD);
2051   CSEMap.InsertNode(N, IP);
2052   InsertNode(N);
2053   return SDValue(N, 0);
2054 }
2055 
2056 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2057   if (VT == V.getValueType())
2058     return V;
2059 
2060   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2061 }
2062 
2063 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2064                                        unsigned SrcAS, unsigned DestAS) {
2065   SDValue Ops[] = {Ptr};
2066   FoldingSetNodeID ID;
2067   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2068   ID.AddInteger(SrcAS);
2069   ID.AddInteger(DestAS);
2070 
2071   void *IP = nullptr;
2072   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2073     return SDValue(E, 0);
2074 
2075   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2076                                            VT, SrcAS, DestAS);
2077   createOperands(N, Ops);
2078 
2079   CSEMap.InsertNode(N, IP);
2080   InsertNode(N);
2081   return SDValue(N, 0);
2082 }
2083 
2084 SDValue SelectionDAG::getFreeze(SDValue V) {
2085   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2086 }
2087 
2088 /// getShiftAmountOperand - Return the specified value casted to
2089 /// the target's desired shift amount type.
2090 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2091   EVT OpTy = Op.getValueType();
2092   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2093   if (OpTy == ShTy || OpTy.isVector()) return Op;
2094 
2095   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2096 }
2097 
2098 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2099   SDLoc dl(Node);
2100   const TargetLowering &TLI = getTargetLoweringInfo();
2101   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2102   EVT VT = Node->getValueType(0);
2103   SDValue Tmp1 = Node->getOperand(0);
2104   SDValue Tmp2 = Node->getOperand(1);
2105   const MaybeAlign MA(Node->getConstantOperandVal(3));
2106 
2107   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2108                                Tmp2, MachinePointerInfo(V));
2109   SDValue VAList = VAListLoad;
2110 
2111   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2112     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2113                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2114 
2115     VAList =
2116         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2117                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2118   }
2119 
2120   // Increment the pointer, VAList, to the next vaarg
2121   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2122                  getConstant(getDataLayout().getTypeAllocSize(
2123                                                VT.getTypeForEVT(*getContext())),
2124                              dl, VAList.getValueType()));
2125   // Store the incremented VAList to the legalized pointer
2126   Tmp1 =
2127       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2128   // Load the actual argument out of the pointer VAList
2129   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2130 }
2131 
2132 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2133   SDLoc dl(Node);
2134   const TargetLowering &TLI = getTargetLoweringInfo();
2135   // This defaults to loading a pointer from the input and storing it to the
2136   // output, returning the chain.
2137   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2138   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2139   SDValue Tmp1 =
2140       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2141               Node->getOperand(2), MachinePointerInfo(VS));
2142   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2143                   MachinePointerInfo(VD));
2144 }
2145 
2146 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2147   const DataLayout &DL = getDataLayout();
2148   Type *Ty = VT.getTypeForEVT(*getContext());
2149   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2150 
2151   if (TLI->isTypeLegal(VT) || !VT.isVector())
2152     return RedAlign;
2153 
2154   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2155   const Align StackAlign = TFI->getStackAlign();
2156 
2157   // See if we can choose a smaller ABI alignment in cases where it's an
2158   // illegal vector type that will get broken down.
2159   if (RedAlign > StackAlign) {
2160     EVT IntermediateVT;
2161     MVT RegisterVT;
2162     unsigned NumIntermediates;
2163     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2164                                 NumIntermediates, RegisterVT);
2165     Ty = IntermediateVT.getTypeForEVT(*getContext());
2166     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2167     if (RedAlign2 < RedAlign)
2168       RedAlign = RedAlign2;
2169   }
2170 
2171   return RedAlign;
2172 }
2173 
2174 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2175   MachineFrameInfo &MFI = MF->getFrameInfo();
2176   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2177   int StackID = 0;
2178   if (Bytes.isScalable())
2179     StackID = TFI->getStackIDForScalableVectors();
2180   // The stack id gives an indication of whether the object is scalable or
2181   // not, so it's safe to pass in the minimum size here.
2182   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2183                                        false, nullptr, StackID);
2184   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2185 }
2186 
2187 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2188   Type *Ty = VT.getTypeForEVT(*getContext());
2189   Align StackAlign =
2190       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2191   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2192 }
2193 
2194 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2195   TypeSize VT1Size = VT1.getStoreSize();
2196   TypeSize VT2Size = VT2.getStoreSize();
2197   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2198          "Don't know how to choose the maximum size when creating a stack "
2199          "temporary");
2200   TypeSize Bytes =
2201       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2202 
2203   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2204   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2205   const DataLayout &DL = getDataLayout();
2206   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2207   return CreateStackTemporary(Bytes, Align);
2208 }
2209 
2210 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2211                                 ISD::CondCode Cond, const SDLoc &dl) {
2212   EVT OpVT = N1.getValueType();
2213 
2214   // These setcc operations always fold.
2215   switch (Cond) {
2216   default: break;
2217   case ISD::SETFALSE:
2218   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2219   case ISD::SETTRUE:
2220   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2221 
2222   case ISD::SETOEQ:
2223   case ISD::SETOGT:
2224   case ISD::SETOGE:
2225   case ISD::SETOLT:
2226   case ISD::SETOLE:
2227   case ISD::SETONE:
2228   case ISD::SETO:
2229   case ISD::SETUO:
2230   case ISD::SETUEQ:
2231   case ISD::SETUNE:
2232     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2233     break;
2234   }
2235 
2236   if (OpVT.isInteger()) {
2237     // For EQ and NE, we can always pick a value for the undef to make the
2238     // predicate pass or fail, so we can return undef.
2239     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2240     // icmp eq/ne X, undef -> undef.
2241     if ((N1.isUndef() || N2.isUndef()) &&
2242         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2243       return getUNDEF(VT);
2244 
2245     // If both operands are undef, we can return undef for int comparison.
2246     // icmp undef, undef -> undef.
2247     if (N1.isUndef() && N2.isUndef())
2248       return getUNDEF(VT);
2249 
2250     // icmp X, X -> true/false
2251     // icmp X, undef -> true/false because undef could be X.
2252     if (N1 == N2)
2253       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2254   }
2255 
2256   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2257     const APInt &C2 = N2C->getAPIntValue();
2258     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2259       const APInt &C1 = N1C->getAPIntValue();
2260 
2261       switch (Cond) {
2262       default: llvm_unreachable("Unknown integer setcc!");
2263       case ISD::SETEQ:  return getBoolConstant(C1 == C2, dl, VT, OpVT);
2264       case ISD::SETNE:  return getBoolConstant(C1 != C2, dl, VT, OpVT);
2265       case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2266       case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2267       case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2268       case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2269       case ISD::SETLT:  return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2270       case ISD::SETGT:  return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2271       case ISD::SETLE:  return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2272       case ISD::SETGE:  return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2273       }
2274     }
2275   }
2276 
2277   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2278   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2279 
2280   if (N1CFP && N2CFP) {
2281     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2282     switch (Cond) {
2283     default: break;
2284     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2285                         return getUNDEF(VT);
2286                       LLVM_FALLTHROUGH;
2287     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2288                                              OpVT);
2289     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2290                         return getUNDEF(VT);
2291                       LLVM_FALLTHROUGH;
2292     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2293                                              R==APFloat::cmpLessThan, dl, VT,
2294                                              OpVT);
2295     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2296                         return getUNDEF(VT);
2297                       LLVM_FALLTHROUGH;
2298     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2299                                              OpVT);
2300     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2301                         return getUNDEF(VT);
2302                       LLVM_FALLTHROUGH;
2303     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2304                                              VT, OpVT);
2305     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2306                         return getUNDEF(VT);
2307                       LLVM_FALLTHROUGH;
2308     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2309                                              R==APFloat::cmpEqual, dl, VT,
2310                                              OpVT);
2311     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2312                         return getUNDEF(VT);
2313                       LLVM_FALLTHROUGH;
2314     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2315                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2316     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2317                                              OpVT);
2318     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2319                                              OpVT);
2320     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2321                                              R==APFloat::cmpEqual, dl, VT,
2322                                              OpVT);
2323     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2324                                              OpVT);
2325     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2326                                              R==APFloat::cmpLessThan, dl, VT,
2327                                              OpVT);
2328     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2329                                              R==APFloat::cmpUnordered, dl, VT,
2330                                              OpVT);
2331     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2332                                              VT, OpVT);
2333     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2334                                              OpVT);
2335     }
2336   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2337     // Ensure that the constant occurs on the RHS.
2338     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2339     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2340       return SDValue();
2341     return getSetCC(dl, VT, N2, N1, SwappedCond);
2342   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2343              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2344     // If an operand is known to be a nan (or undef that could be a nan), we can
2345     // fold it.
2346     // Choosing NaN for the undef will always make unordered comparison succeed
2347     // and ordered comparison fails.
2348     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2349     switch (ISD::getUnorderedFlavor(Cond)) {
2350     default:
2351       llvm_unreachable("Unknown flavor!");
2352     case 0: // Known false.
2353       return getBoolConstant(false, dl, VT, OpVT);
2354     case 1: // Known true.
2355       return getBoolConstant(true, dl, VT, OpVT);
2356     case 2: // Undefined.
2357       return getUNDEF(VT);
2358     }
2359   }
2360 
2361   // Could not fold it.
2362   return SDValue();
2363 }
2364 
2365 /// See if the specified operand can be simplified with the knowledge that only
2366 /// the bits specified by DemandedBits are used.
2367 /// TODO: really we should be making this into the DAG equivalent of
2368 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2369 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2370   EVT VT = V.getValueType();
2371 
2372   if (VT.isScalableVector())
2373     return SDValue();
2374 
2375   APInt DemandedElts = VT.isVector()
2376                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2377                            : APInt(1, 1);
2378   return GetDemandedBits(V, DemandedBits, DemandedElts);
2379 }
2380 
2381 /// See if the specified operand can be simplified with the knowledge that only
2382 /// the bits specified by DemandedBits are used in the elements specified by
2383 /// DemandedElts.
2384 /// TODO: really we should be making this into the DAG equivalent of
2385 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2386 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2387                                       const APInt &DemandedElts) {
2388   switch (V.getOpcode()) {
2389   default:
2390     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2391                                                 *this, 0);
2392   case ISD::Constant: {
2393     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2394     APInt NewVal = CVal & DemandedBits;
2395     if (NewVal != CVal)
2396       return getConstant(NewVal, SDLoc(V), V.getValueType());
2397     break;
2398   }
2399   case ISD::SRL:
2400     // Only look at single-use SRLs.
2401     if (!V.getNode()->hasOneUse())
2402       break;
2403     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2404       // See if we can recursively simplify the LHS.
2405       unsigned Amt = RHSC->getZExtValue();
2406 
2407       // Watch out for shift count overflow though.
2408       if (Amt >= DemandedBits.getBitWidth())
2409         break;
2410       APInt SrcDemandedBits = DemandedBits << Amt;
2411       if (SDValue SimplifyLHS =
2412               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2413         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2414                        V.getOperand(1));
2415     }
2416     break;
2417   }
2418   return SDValue();
2419 }
2420 
2421 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2422 /// use this predicate to simplify operations downstream.
2423 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2424   unsigned BitWidth = Op.getScalarValueSizeInBits();
2425   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2426 }
2427 
2428 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2429 /// this predicate to simplify operations downstream.  Mask is known to be zero
2430 /// for bits that V cannot have.
2431 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2432                                      unsigned Depth) const {
2433   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2434 }
2435 
2436 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2437 /// DemandedElts.  We use this predicate to simplify operations downstream.
2438 /// Mask is known to be zero for bits that V cannot have.
2439 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2440                                      const APInt &DemandedElts,
2441                                      unsigned Depth) const {
2442   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2443 }
2444 
2445 /// Return true if the DemandedElts of the vector Op are all zero.  We
2446 /// use this predicate to simplify operations downstream.
2447 bool SelectionDAG::MaskedElementsAreZero(SDValue Op, const APInt &DemandedElts,
2448                                          unsigned Depth) const {
2449   unsigned BitWidth = Op.getScalarValueSizeInBits();
2450   APInt DemandedBits = APInt::getAllOnesValue(BitWidth);
2451   return MaskedValueIsZero(Op, DemandedBits, DemandedElts, Depth);
2452 }
2453 
2454 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2455 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2456                                         unsigned Depth) const {
2457   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2458 }
2459 
2460 /// isSplatValue - Return true if the vector V has the same value
2461 /// across all DemandedElts. For scalable vectors it does not make
2462 /// sense to specify which elements are demanded or undefined, therefore
2463 /// they are simply ignored.
2464 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2465                                 APInt &UndefElts, unsigned Depth) {
2466   EVT VT = V.getValueType();
2467   assert(VT.isVector() && "Vector type expected");
2468 
2469   if (!VT.isScalableVector() && !DemandedElts)
2470     return false; // No demanded elts, better to assume we don't know anything.
2471 
2472   if (Depth >= MaxRecursionDepth)
2473     return false; // Limit search depth.
2474 
2475   // Deal with some common cases here that work for both fixed and scalable
2476   // vector types.
2477   switch (V.getOpcode()) {
2478   case ISD::SPLAT_VECTOR:
2479     UndefElts = V.getOperand(0).isUndef()
2480                     ? APInt::getAllOnesValue(DemandedElts.getBitWidth())
2481                     : APInt(DemandedElts.getBitWidth(), 0);
2482     return true;
2483   case ISD::ADD:
2484   case ISD::SUB:
2485   case ISD::AND:
2486   case ISD::XOR:
2487   case ISD::OR: {
2488     APInt UndefLHS, UndefRHS;
2489     SDValue LHS = V.getOperand(0);
2490     SDValue RHS = V.getOperand(1);
2491     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2492         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2493       UndefElts = UndefLHS | UndefRHS;
2494       return true;
2495     }
2496     return false;
2497   }
2498   case ISD::ABS:
2499   case ISD::TRUNCATE:
2500   case ISD::SIGN_EXTEND:
2501   case ISD::ZERO_EXTEND:
2502     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2503   }
2504 
2505   // We don't support other cases than those above for scalable vectors at
2506   // the moment.
2507   if (VT.isScalableVector())
2508     return false;
2509 
2510   unsigned NumElts = VT.getVectorNumElements();
2511   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2512   UndefElts = APInt::getNullValue(NumElts);
2513 
2514   switch (V.getOpcode()) {
2515   case ISD::BUILD_VECTOR: {
2516     SDValue Scl;
2517     for (unsigned i = 0; i != NumElts; ++i) {
2518       SDValue Op = V.getOperand(i);
2519       if (Op.isUndef()) {
2520         UndefElts.setBit(i);
2521         continue;
2522       }
2523       if (!DemandedElts[i])
2524         continue;
2525       if (Scl && Scl != Op)
2526         return false;
2527       Scl = Op;
2528     }
2529     return true;
2530   }
2531   case ISD::VECTOR_SHUFFLE: {
2532     // Check if this is a shuffle node doing a splat.
2533     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2534     int SplatIndex = -1;
2535     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2536     for (int i = 0; i != (int)NumElts; ++i) {
2537       int M = Mask[i];
2538       if (M < 0) {
2539         UndefElts.setBit(i);
2540         continue;
2541       }
2542       if (!DemandedElts[i])
2543         continue;
2544       if (0 <= SplatIndex && SplatIndex != M)
2545         return false;
2546       SplatIndex = M;
2547     }
2548     return true;
2549   }
2550   case ISD::EXTRACT_SUBVECTOR: {
2551     // Offset the demanded elts by the subvector index.
2552     SDValue Src = V.getOperand(0);
2553     // We don't support scalable vectors at the moment.
2554     if (Src.getValueType().isScalableVector())
2555       return false;
2556     uint64_t Idx = V.getConstantOperandVal(1);
2557     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2558     APInt UndefSrcElts;
2559     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2560     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2561       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2562       return true;
2563     }
2564     break;
2565   }
2566   }
2567 
2568   return false;
2569 }
2570 
2571 /// Helper wrapper to main isSplatValue function.
2572 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2573   EVT VT = V.getValueType();
2574   assert(VT.isVector() && "Vector type expected");
2575 
2576   APInt UndefElts;
2577   APInt DemandedElts;
2578 
2579   // For now we don't support this with scalable vectors.
2580   if (!VT.isScalableVector())
2581     DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2582   return isSplatValue(V, DemandedElts, UndefElts) &&
2583          (AllowUndefs || !UndefElts);
2584 }
2585 
2586 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2587   V = peekThroughExtractSubvectors(V);
2588 
2589   EVT VT = V.getValueType();
2590   unsigned Opcode = V.getOpcode();
2591   switch (Opcode) {
2592   default: {
2593     APInt UndefElts;
2594     APInt DemandedElts;
2595 
2596     if (!VT.isScalableVector())
2597       DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2598 
2599     if (isSplatValue(V, DemandedElts, UndefElts)) {
2600       if (VT.isScalableVector()) {
2601         // DemandedElts and UndefElts are ignored for scalable vectors, since
2602         // the only supported cases are SPLAT_VECTOR nodes.
2603         SplatIdx = 0;
2604       } else {
2605         // Handle case where all demanded elements are UNDEF.
2606         if (DemandedElts.isSubsetOf(UndefElts)) {
2607           SplatIdx = 0;
2608           return getUNDEF(VT);
2609         }
2610         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2611       }
2612       return V;
2613     }
2614     break;
2615   }
2616   case ISD::SPLAT_VECTOR:
2617     SplatIdx = 0;
2618     return V;
2619   case ISD::VECTOR_SHUFFLE: {
2620     if (VT.isScalableVector())
2621       return SDValue();
2622 
2623     // Check if this is a shuffle node doing a splat.
2624     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2625     // getTargetVShiftNode currently struggles without the splat source.
2626     auto *SVN = cast<ShuffleVectorSDNode>(V);
2627     if (!SVN->isSplat())
2628       break;
2629     int Idx = SVN->getSplatIndex();
2630     int NumElts = V.getValueType().getVectorNumElements();
2631     SplatIdx = Idx % NumElts;
2632     return V.getOperand(Idx / NumElts);
2633   }
2634   }
2635 
2636   return SDValue();
2637 }
2638 
2639 SDValue SelectionDAG::getSplatValue(SDValue V) {
2640   int SplatIdx;
2641   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
2642     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V),
2643                    SrcVector.getValueType().getScalarType(), SrcVector,
2644                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2645   return SDValue();
2646 }
2647 
2648 const APInt *
2649 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2650                                           const APInt &DemandedElts) const {
2651   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2652           V.getOpcode() == ISD::SRA) &&
2653          "Unknown shift node");
2654   unsigned BitWidth = V.getScalarValueSizeInBits();
2655   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2656     // Shifting more than the bitwidth is not valid.
2657     const APInt &ShAmt = SA->getAPIntValue();
2658     if (ShAmt.ult(BitWidth))
2659       return &ShAmt;
2660   }
2661   return nullptr;
2662 }
2663 
2664 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2665     SDValue V, const APInt &DemandedElts) const {
2666   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2667           V.getOpcode() == ISD::SRA) &&
2668          "Unknown shift node");
2669   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2670     return ValidAmt;
2671   unsigned BitWidth = V.getScalarValueSizeInBits();
2672   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2673   if (!BV)
2674     return nullptr;
2675   const APInt *MinShAmt = nullptr;
2676   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2677     if (!DemandedElts[i])
2678       continue;
2679     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2680     if (!SA)
2681       return nullptr;
2682     // Shifting more than the bitwidth is not valid.
2683     const APInt &ShAmt = SA->getAPIntValue();
2684     if (ShAmt.uge(BitWidth))
2685       return nullptr;
2686     if (MinShAmt && MinShAmt->ule(ShAmt))
2687       continue;
2688     MinShAmt = &ShAmt;
2689   }
2690   return MinShAmt;
2691 }
2692 
2693 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2694     SDValue V, const APInt &DemandedElts) const {
2695   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2696           V.getOpcode() == ISD::SRA) &&
2697          "Unknown shift node");
2698   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2699     return ValidAmt;
2700   unsigned BitWidth = V.getScalarValueSizeInBits();
2701   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2702   if (!BV)
2703     return nullptr;
2704   const APInt *MaxShAmt = nullptr;
2705   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2706     if (!DemandedElts[i])
2707       continue;
2708     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2709     if (!SA)
2710       return nullptr;
2711     // Shifting more than the bitwidth is not valid.
2712     const APInt &ShAmt = SA->getAPIntValue();
2713     if (ShAmt.uge(BitWidth))
2714       return nullptr;
2715     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2716       continue;
2717     MaxShAmt = &ShAmt;
2718   }
2719   return MaxShAmt;
2720 }
2721 
2722 /// Determine which bits of Op are known to be either zero or one and return
2723 /// them in Known. For vectors, the known bits are those that are shared by
2724 /// every vector element.
2725 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2726   EVT VT = Op.getValueType();
2727 
2728   // TOOD: Until we have a plan for how to represent demanded elements for
2729   // scalable vectors, we can just bail out for now.
2730   if (Op.getValueType().isScalableVector()) {
2731     unsigned BitWidth = Op.getScalarValueSizeInBits();
2732     return KnownBits(BitWidth);
2733   }
2734 
2735   APInt DemandedElts = VT.isVector()
2736                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2737                            : APInt(1, 1);
2738   return computeKnownBits(Op, DemandedElts, Depth);
2739 }
2740 
2741 /// Determine which bits of Op are known to be either zero or one and return
2742 /// them in Known. The DemandedElts argument allows us to only collect the known
2743 /// bits that are shared by the requested vector elements.
2744 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2745                                          unsigned Depth) const {
2746   unsigned BitWidth = Op.getScalarValueSizeInBits();
2747 
2748   KnownBits Known(BitWidth);   // Don't know anything.
2749 
2750   // TOOD: Until we have a plan for how to represent demanded elements for
2751   // scalable vectors, we can just bail out for now.
2752   if (Op.getValueType().isScalableVector())
2753     return Known;
2754 
2755   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2756     // We know all of the bits for a constant!
2757     return KnownBits::makeConstant(C->getAPIntValue());
2758   }
2759   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2760     // We know all of the bits for a constant fp!
2761     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2762   }
2763 
2764   if (Depth >= MaxRecursionDepth)
2765     return Known;  // Limit search depth.
2766 
2767   KnownBits Known2;
2768   unsigned NumElts = DemandedElts.getBitWidth();
2769   assert((!Op.getValueType().isVector() ||
2770           NumElts == Op.getValueType().getVectorNumElements()) &&
2771          "Unexpected vector size");
2772 
2773   if (!DemandedElts)
2774     return Known;  // No demanded elts, better to assume we don't know anything.
2775 
2776   unsigned Opcode = Op.getOpcode();
2777   switch (Opcode) {
2778   case ISD::BUILD_VECTOR:
2779     // Collect the known bits that are shared by every demanded vector element.
2780     Known.Zero.setAllBits(); Known.One.setAllBits();
2781     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2782       if (!DemandedElts[i])
2783         continue;
2784 
2785       SDValue SrcOp = Op.getOperand(i);
2786       Known2 = computeKnownBits(SrcOp, Depth + 1);
2787 
2788       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2789       if (SrcOp.getValueSizeInBits() != BitWidth) {
2790         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2791                "Expected BUILD_VECTOR implicit truncation");
2792         Known2 = Known2.trunc(BitWidth);
2793       }
2794 
2795       // Known bits are the values that are shared by every demanded element.
2796       Known = KnownBits::commonBits(Known, Known2);
2797 
2798       // If we don't know any bits, early out.
2799       if (Known.isUnknown())
2800         break;
2801     }
2802     break;
2803   case ISD::VECTOR_SHUFFLE: {
2804     // Collect the known bits that are shared by every vector element referenced
2805     // by the shuffle.
2806     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2807     Known.Zero.setAllBits(); Known.One.setAllBits();
2808     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2809     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2810     for (unsigned i = 0; i != NumElts; ++i) {
2811       if (!DemandedElts[i])
2812         continue;
2813 
2814       int M = SVN->getMaskElt(i);
2815       if (M < 0) {
2816         // For UNDEF elements, we don't know anything about the common state of
2817         // the shuffle result.
2818         Known.resetAll();
2819         DemandedLHS.clearAllBits();
2820         DemandedRHS.clearAllBits();
2821         break;
2822       }
2823 
2824       if ((unsigned)M < NumElts)
2825         DemandedLHS.setBit((unsigned)M % NumElts);
2826       else
2827         DemandedRHS.setBit((unsigned)M % NumElts);
2828     }
2829     // Known bits are the values that are shared by every demanded element.
2830     if (!!DemandedLHS) {
2831       SDValue LHS = Op.getOperand(0);
2832       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2833       Known = KnownBits::commonBits(Known, Known2);
2834     }
2835     // If we don't know any bits, early out.
2836     if (Known.isUnknown())
2837       break;
2838     if (!!DemandedRHS) {
2839       SDValue RHS = Op.getOperand(1);
2840       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2841       Known = KnownBits::commonBits(Known, Known2);
2842     }
2843     break;
2844   }
2845   case ISD::CONCAT_VECTORS: {
2846     // Split DemandedElts and test each of the demanded subvectors.
2847     Known.Zero.setAllBits(); Known.One.setAllBits();
2848     EVT SubVectorVT = Op.getOperand(0).getValueType();
2849     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2850     unsigned NumSubVectors = Op.getNumOperands();
2851     for (unsigned i = 0; i != NumSubVectors; ++i) {
2852       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2853       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2854       if (!!DemandedSub) {
2855         SDValue Sub = Op.getOperand(i);
2856         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2857         Known = KnownBits::commonBits(Known, Known2);
2858       }
2859       // If we don't know any bits, early out.
2860       if (Known.isUnknown())
2861         break;
2862     }
2863     break;
2864   }
2865   case ISD::INSERT_SUBVECTOR: {
2866     // Demand any elements from the subvector and the remainder from the src its
2867     // inserted into.
2868     SDValue Src = Op.getOperand(0);
2869     SDValue Sub = Op.getOperand(1);
2870     uint64_t Idx = Op.getConstantOperandVal(2);
2871     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2872     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2873     APInt DemandedSrcElts = DemandedElts;
2874     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2875 
2876     Known.One.setAllBits();
2877     Known.Zero.setAllBits();
2878     if (!!DemandedSubElts) {
2879       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2880       if (Known.isUnknown())
2881         break; // early-out.
2882     }
2883     if (!!DemandedSrcElts) {
2884       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2885       Known = KnownBits::commonBits(Known, Known2);
2886     }
2887     break;
2888   }
2889   case ISD::EXTRACT_SUBVECTOR: {
2890     // Offset the demanded elts by the subvector index.
2891     SDValue Src = Op.getOperand(0);
2892     // Bail until we can represent demanded elements for scalable vectors.
2893     if (Src.getValueType().isScalableVector())
2894       break;
2895     uint64_t Idx = Op.getConstantOperandVal(1);
2896     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2897     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2898     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2899     break;
2900   }
2901   case ISD::SCALAR_TO_VECTOR: {
2902     // We know about scalar_to_vector as much as we know about it source,
2903     // which becomes the first element of otherwise unknown vector.
2904     if (DemandedElts != 1)
2905       break;
2906 
2907     SDValue N0 = Op.getOperand(0);
2908     Known = computeKnownBits(N0, Depth + 1);
2909     if (N0.getValueSizeInBits() != BitWidth)
2910       Known = Known.trunc(BitWidth);
2911 
2912     break;
2913   }
2914   case ISD::BITCAST: {
2915     SDValue N0 = Op.getOperand(0);
2916     EVT SubVT = N0.getValueType();
2917     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2918 
2919     // Ignore bitcasts from unsupported types.
2920     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2921       break;
2922 
2923     // Fast handling of 'identity' bitcasts.
2924     if (BitWidth == SubBitWidth) {
2925       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2926       break;
2927     }
2928 
2929     bool IsLE = getDataLayout().isLittleEndian();
2930 
2931     // Bitcast 'small element' vector to 'large element' scalar/vector.
2932     if ((BitWidth % SubBitWidth) == 0) {
2933       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2934 
2935       // Collect known bits for the (larger) output by collecting the known
2936       // bits from each set of sub elements and shift these into place.
2937       // We need to separately call computeKnownBits for each set of
2938       // sub elements as the knownbits for each is likely to be different.
2939       unsigned SubScale = BitWidth / SubBitWidth;
2940       APInt SubDemandedElts(NumElts * SubScale, 0);
2941       for (unsigned i = 0; i != NumElts; ++i)
2942         if (DemandedElts[i])
2943           SubDemandedElts.setBit(i * SubScale);
2944 
2945       for (unsigned i = 0; i != SubScale; ++i) {
2946         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2947                          Depth + 1);
2948         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2949         Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2950         Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2951       }
2952     }
2953 
2954     // Bitcast 'large element' scalar/vector to 'small element' vector.
2955     if ((SubBitWidth % BitWidth) == 0) {
2956       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2957 
2958       // Collect known bits for the (smaller) output by collecting the known
2959       // bits from the overlapping larger input elements and extracting the
2960       // sub sections we actually care about.
2961       unsigned SubScale = SubBitWidth / BitWidth;
2962       APInt SubDemandedElts(NumElts / SubScale, 0);
2963       for (unsigned i = 0; i != NumElts; ++i)
2964         if (DemandedElts[i])
2965           SubDemandedElts.setBit(i / SubScale);
2966 
2967       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2968 
2969       Known.Zero.setAllBits(); Known.One.setAllBits();
2970       for (unsigned i = 0; i != NumElts; ++i)
2971         if (DemandedElts[i]) {
2972           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2973           unsigned Offset = (Shifts % SubScale) * BitWidth;
2974           Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2975           Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2976           // If we don't know any bits, early out.
2977           if (Known.isUnknown())
2978             break;
2979         }
2980     }
2981     break;
2982   }
2983   case ISD::AND:
2984     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2985     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2986 
2987     Known &= Known2;
2988     break;
2989   case ISD::OR:
2990     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2991     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2992 
2993     Known |= Known2;
2994     break;
2995   case ISD::XOR:
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::MUL: {
3002     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3003     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3004     Known = KnownBits::mul(Known, Known2);
3005     break;
3006   }
3007   case ISD::MULHU: {
3008     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3009     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3010     Known = KnownBits::mulhu(Known, Known2);
3011     break;
3012   }
3013   case ISD::MULHS: {
3014     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3015     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3016     Known = KnownBits::mulhs(Known, Known2);
3017     break;
3018   }
3019   case ISD::UMUL_LOHI: {
3020     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3021     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3022     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3023     if (Op.getResNo() == 0)
3024       Known = KnownBits::mul(Known, Known2);
3025     else
3026       Known = KnownBits::mulhu(Known, Known2);
3027     break;
3028   }
3029   case ISD::SMUL_LOHI: {
3030     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3031     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3032     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3033     if (Op.getResNo() == 0)
3034       Known = KnownBits::mul(Known, Known2);
3035     else
3036       Known = KnownBits::mulhs(Known, Known2);
3037     break;
3038   }
3039   case ISD::UDIV: {
3040     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3041     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3042     Known = KnownBits::udiv(Known, Known2);
3043     break;
3044   }
3045   case ISD::SELECT:
3046   case ISD::VSELECT:
3047     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3048     // If we don't know any bits, early out.
3049     if (Known.isUnknown())
3050       break;
3051     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3052 
3053     // Only known if known in both the LHS and RHS.
3054     Known = KnownBits::commonBits(Known, Known2);
3055     break;
3056   case ISD::SELECT_CC:
3057     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3058     // If we don't know any bits, early out.
3059     if (Known.isUnknown())
3060       break;
3061     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3062 
3063     // Only known if known in both the LHS and RHS.
3064     Known = KnownBits::commonBits(Known, Known2);
3065     break;
3066   case ISD::SMULO:
3067   case ISD::UMULO:
3068   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3069     if (Op.getResNo() != 1)
3070       break;
3071     // The boolean result conforms to getBooleanContents.
3072     // If we know the result of a setcc has the top bits zero, use this info.
3073     // We know that we have an integer-based boolean since these operations
3074     // are only available for integer.
3075     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3076             TargetLowering::ZeroOrOneBooleanContent &&
3077         BitWidth > 1)
3078       Known.Zero.setBitsFrom(1);
3079     break;
3080   case ISD::SETCC:
3081   case ISD::STRICT_FSETCC:
3082   case ISD::STRICT_FSETCCS: {
3083     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3084     // If we know the result of a setcc has the top bits zero, use this info.
3085     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3086             TargetLowering::ZeroOrOneBooleanContent &&
3087         BitWidth > 1)
3088       Known.Zero.setBitsFrom(1);
3089     break;
3090   }
3091   case ISD::SHL:
3092     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3093     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3094     Known = KnownBits::shl(Known, Known2);
3095 
3096     // Minimum shift low bits are known zero.
3097     if (const APInt *ShMinAmt =
3098             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3099       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3100     break;
3101   case ISD::SRL:
3102     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3103     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3104     Known = KnownBits::lshr(Known, Known2);
3105 
3106     // Minimum shift high bits are known zero.
3107     if (const APInt *ShMinAmt =
3108             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3109       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3110     break;
3111   case ISD::SRA:
3112     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3113     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3114     Known = KnownBits::ashr(Known, Known2);
3115     // TODO: Add minimum shift high known sign bits.
3116     break;
3117   case ISD::FSHL:
3118   case ISD::FSHR:
3119     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3120       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3121 
3122       // For fshl, 0-shift returns the 1st arg.
3123       // For fshr, 0-shift returns the 2nd arg.
3124       if (Amt == 0) {
3125         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3126                                  DemandedElts, Depth + 1);
3127         break;
3128       }
3129 
3130       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3131       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3132       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3133       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3134       if (Opcode == ISD::FSHL) {
3135         Known.One <<= Amt;
3136         Known.Zero <<= Amt;
3137         Known2.One.lshrInPlace(BitWidth - Amt);
3138         Known2.Zero.lshrInPlace(BitWidth - Amt);
3139       } else {
3140         Known.One <<= BitWidth - Amt;
3141         Known.Zero <<= BitWidth - Amt;
3142         Known2.One.lshrInPlace(Amt);
3143         Known2.Zero.lshrInPlace(Amt);
3144       }
3145       Known.One |= Known2.One;
3146       Known.Zero |= Known2.Zero;
3147     }
3148     break;
3149   case ISD::SIGN_EXTEND_INREG: {
3150     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3151     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3152     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3153     break;
3154   }
3155   case ISD::CTTZ:
3156   case ISD::CTTZ_ZERO_UNDEF: {
3157     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3158     // If we have a known 1, its position is our upper bound.
3159     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3160     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3161     Known.Zero.setBitsFrom(LowBits);
3162     break;
3163   }
3164   case ISD::CTLZ:
3165   case ISD::CTLZ_ZERO_UNDEF: {
3166     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3167     // If we have a known 1, its position is our upper bound.
3168     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3169     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3170     Known.Zero.setBitsFrom(LowBits);
3171     break;
3172   }
3173   case ISD::CTPOP: {
3174     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3175     // If we know some of the bits are zero, they can't be one.
3176     unsigned PossibleOnes = Known2.countMaxPopulation();
3177     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3178     break;
3179   }
3180   case ISD::PARITY: {
3181     // Parity returns 0 everywhere but the LSB.
3182     Known.Zero.setBitsFrom(1);
3183     break;
3184   }
3185   case ISD::LOAD: {
3186     LoadSDNode *LD = cast<LoadSDNode>(Op);
3187     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3188     if (ISD::isNON_EXTLoad(LD) && Cst) {
3189       // Determine any common known bits from the loaded constant pool value.
3190       Type *CstTy = Cst->getType();
3191       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3192         // If its a vector splat, then we can (quickly) reuse the scalar path.
3193         // NOTE: We assume all elements match and none are UNDEF.
3194         if (CstTy->isVectorTy()) {
3195           if (const Constant *Splat = Cst->getSplatValue()) {
3196             Cst = Splat;
3197             CstTy = Cst->getType();
3198           }
3199         }
3200         // TODO - do we need to handle different bitwidths?
3201         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3202           // Iterate across all vector elements finding common known bits.
3203           Known.One.setAllBits();
3204           Known.Zero.setAllBits();
3205           for (unsigned i = 0; i != NumElts; ++i) {
3206             if (!DemandedElts[i])
3207               continue;
3208             if (Constant *Elt = Cst->getAggregateElement(i)) {
3209               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3210                 const APInt &Value = CInt->getValue();
3211                 Known.One &= Value;
3212                 Known.Zero &= ~Value;
3213                 continue;
3214               }
3215               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3216                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3217                 Known.One &= Value;
3218                 Known.Zero &= ~Value;
3219                 continue;
3220               }
3221             }
3222             Known.One.clearAllBits();
3223             Known.Zero.clearAllBits();
3224             break;
3225           }
3226         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3227           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3228             Known = KnownBits::makeConstant(CInt->getValue());
3229           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3230             Known =
3231                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3232           }
3233         }
3234       }
3235     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3236       // If this is a ZEXTLoad and we are looking at the loaded value.
3237       EVT VT = LD->getMemoryVT();
3238       unsigned MemBits = VT.getScalarSizeInBits();
3239       Known.Zero.setBitsFrom(MemBits);
3240     } else if (const MDNode *Ranges = LD->getRanges()) {
3241       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3242         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3243     }
3244     break;
3245   }
3246   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3247     EVT InVT = Op.getOperand(0).getValueType();
3248     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3249     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3250     Known = Known.zext(BitWidth);
3251     break;
3252   }
3253   case ISD::ZERO_EXTEND: {
3254     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3255     Known = Known.zext(BitWidth);
3256     break;
3257   }
3258   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3259     EVT InVT = Op.getOperand(0).getValueType();
3260     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3261     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3262     // If the sign bit is known to be zero or one, then sext will extend
3263     // it to the top bits, else it will just zext.
3264     Known = Known.sext(BitWidth);
3265     break;
3266   }
3267   case ISD::SIGN_EXTEND: {
3268     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3269     // If the sign bit is known to be zero or one, then sext will extend
3270     // it to the top bits, else it will just zext.
3271     Known = Known.sext(BitWidth);
3272     break;
3273   }
3274   case ISD::ANY_EXTEND_VECTOR_INREG: {
3275     EVT InVT = Op.getOperand(0).getValueType();
3276     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3277     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3278     Known = Known.anyext(BitWidth);
3279     break;
3280   }
3281   case ISD::ANY_EXTEND: {
3282     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3283     Known = Known.anyext(BitWidth);
3284     break;
3285   }
3286   case ISD::TRUNCATE: {
3287     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3288     Known = Known.trunc(BitWidth);
3289     break;
3290   }
3291   case ISD::AssertZext: {
3292     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3293     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3294     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3295     Known.Zero |= (~InMask);
3296     Known.One  &= (~Known.Zero);
3297     break;
3298   }
3299   case ISD::AssertAlign: {
3300     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3301     assert(LogOfAlign != 0);
3302     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3303     // well as clearing one bits.
3304     Known.Zero.setLowBits(LogOfAlign);
3305     Known.One.clearLowBits(LogOfAlign);
3306     break;
3307   }
3308   case ISD::FGETSIGN:
3309     // All bits are zero except the low bit.
3310     Known.Zero.setBitsFrom(1);
3311     break;
3312   case ISD::USUBO:
3313   case ISD::SSUBO:
3314     if (Op.getResNo() == 1) {
3315       // If we know the result of a setcc has the top bits zero, use this info.
3316       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3317               TargetLowering::ZeroOrOneBooleanContent &&
3318           BitWidth > 1)
3319         Known.Zero.setBitsFrom(1);
3320       break;
3321     }
3322     LLVM_FALLTHROUGH;
3323   case ISD::SUB:
3324   case ISD::SUBC: {
3325     assert(Op.getResNo() == 0 &&
3326            "We only compute knownbits for the difference here.");
3327 
3328     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3329     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3330     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3331                                         Known, Known2);
3332     break;
3333   }
3334   case ISD::UADDO:
3335   case ISD::SADDO:
3336   case ISD::ADDCARRY:
3337     if (Op.getResNo() == 1) {
3338       // If we know the result of a setcc has the top bits zero, use this info.
3339       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3340               TargetLowering::ZeroOrOneBooleanContent &&
3341           BitWidth > 1)
3342         Known.Zero.setBitsFrom(1);
3343       break;
3344     }
3345     LLVM_FALLTHROUGH;
3346   case ISD::ADD:
3347   case ISD::ADDC:
3348   case ISD::ADDE: {
3349     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3350 
3351     // With ADDE and ADDCARRY, a carry bit may be added in.
3352     KnownBits Carry(1);
3353     if (Opcode == ISD::ADDE)
3354       // Can't track carry from glue, set carry to unknown.
3355       Carry.resetAll();
3356     else if (Opcode == ISD::ADDCARRY)
3357       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3358       // the trouble (how often will we find a known carry bit). And I haven't
3359       // tested this very much yet, but something like this might work:
3360       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3361       //   Carry = Carry.zextOrTrunc(1, false);
3362       Carry.resetAll();
3363     else
3364       Carry.setAllZero();
3365 
3366     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3367     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3368     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3369     break;
3370   }
3371   case ISD::SREM: {
3372     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3373     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3374     Known = KnownBits::srem(Known, Known2);
3375     break;
3376   }
3377   case ISD::UREM: {
3378     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3379     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3380     Known = KnownBits::urem(Known, Known2);
3381     break;
3382   }
3383   case ISD::EXTRACT_ELEMENT: {
3384     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3385     const unsigned Index = Op.getConstantOperandVal(1);
3386     const unsigned EltBitWidth = Op.getValueSizeInBits();
3387 
3388     // Remove low part of known bits mask
3389     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3390     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3391 
3392     // Remove high part of known bit mask
3393     Known = Known.trunc(EltBitWidth);
3394     break;
3395   }
3396   case ISD::EXTRACT_VECTOR_ELT: {
3397     SDValue InVec = Op.getOperand(0);
3398     SDValue EltNo = Op.getOperand(1);
3399     EVT VecVT = InVec.getValueType();
3400     // computeKnownBits not yet implemented for scalable vectors.
3401     if (VecVT.isScalableVector())
3402       break;
3403     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3404     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3405 
3406     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3407     // anything about the extended bits.
3408     if (BitWidth > EltBitWidth)
3409       Known = Known.trunc(EltBitWidth);
3410 
3411     // If we know the element index, just demand that vector element, else for
3412     // an unknown element index, ignore DemandedElts and demand them all.
3413     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3414     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3415     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3416       DemandedSrcElts =
3417           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3418 
3419     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3420     if (BitWidth > EltBitWidth)
3421       Known = Known.anyext(BitWidth);
3422     break;
3423   }
3424   case ISD::INSERT_VECTOR_ELT: {
3425     // If we know the element index, split the demand between the
3426     // source vector and the inserted element, otherwise assume we need
3427     // the original demanded vector elements and the value.
3428     SDValue InVec = Op.getOperand(0);
3429     SDValue InVal = Op.getOperand(1);
3430     SDValue EltNo = Op.getOperand(2);
3431     bool DemandedVal = true;
3432     APInt DemandedVecElts = DemandedElts;
3433     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3434     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3435       unsigned EltIdx = CEltNo->getZExtValue();
3436       DemandedVal = !!DemandedElts[EltIdx];
3437       DemandedVecElts.clearBit(EltIdx);
3438     }
3439     Known.One.setAllBits();
3440     Known.Zero.setAllBits();
3441     if (DemandedVal) {
3442       Known2 = computeKnownBits(InVal, Depth + 1);
3443       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3444     }
3445     if (!!DemandedVecElts) {
3446       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3447       Known = KnownBits::commonBits(Known, Known2);
3448     }
3449     break;
3450   }
3451   case ISD::BITREVERSE: {
3452     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3453     Known = Known2.reverseBits();
3454     break;
3455   }
3456   case ISD::BSWAP: {
3457     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3458     Known = Known2.byteSwap();
3459     break;
3460   }
3461   case ISD::ABS: {
3462     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3463     Known = Known2.abs();
3464     break;
3465   }
3466   case ISD::USUBSAT: {
3467     // The result of usubsat will never be larger than the LHS.
3468     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3469     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3470     break;
3471   }
3472   case ISD::UMIN: {
3473     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3474     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3475     Known = KnownBits::umin(Known, Known2);
3476     break;
3477   }
3478   case ISD::UMAX: {
3479     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3480     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3481     Known = KnownBits::umax(Known, Known2);
3482     break;
3483   }
3484   case ISD::SMIN:
3485   case ISD::SMAX: {
3486     // If we have a clamp pattern, we know that the number of sign bits will be
3487     // the minimum of the clamp min/max range.
3488     bool IsMax = (Opcode == ISD::SMAX);
3489     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3490     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3491       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3492         CstHigh =
3493             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3494     if (CstLow && CstHigh) {
3495       if (!IsMax)
3496         std::swap(CstLow, CstHigh);
3497 
3498       const APInt &ValueLow = CstLow->getAPIntValue();
3499       const APInt &ValueHigh = CstHigh->getAPIntValue();
3500       if (ValueLow.sle(ValueHigh)) {
3501         unsigned LowSignBits = ValueLow.getNumSignBits();
3502         unsigned HighSignBits = ValueHigh.getNumSignBits();
3503         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3504         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3505           Known.One.setHighBits(MinSignBits);
3506           break;
3507         }
3508         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3509           Known.Zero.setHighBits(MinSignBits);
3510           break;
3511         }
3512       }
3513     }
3514 
3515     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3516     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3517     if (IsMax)
3518       Known = KnownBits::smax(Known, Known2);
3519     else
3520       Known = KnownBits::smin(Known, Known2);
3521     break;
3522   }
3523   case ISD::FrameIndex:
3524   case ISD::TargetFrameIndex:
3525     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3526                                        Known, getMachineFunction());
3527     break;
3528 
3529   default:
3530     if (Opcode < ISD::BUILTIN_OP_END)
3531       break;
3532     LLVM_FALLTHROUGH;
3533   case ISD::INTRINSIC_WO_CHAIN:
3534   case ISD::INTRINSIC_W_CHAIN:
3535   case ISD::INTRINSIC_VOID:
3536     // Allow the target to implement this method for its nodes.
3537     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3538     break;
3539   }
3540 
3541   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3542   return Known;
3543 }
3544 
3545 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3546                                                              SDValue N1) const {
3547   // X + 0 never overflow
3548   if (isNullConstant(N1))
3549     return OFK_Never;
3550 
3551   KnownBits N1Known = computeKnownBits(N1);
3552   if (N1Known.Zero.getBoolValue()) {
3553     KnownBits N0Known = computeKnownBits(N0);
3554 
3555     bool overflow;
3556     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3557     if (!overflow)
3558       return OFK_Never;
3559   }
3560 
3561   // mulhi + 1 never overflow
3562   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3563       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3564     return OFK_Never;
3565 
3566   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3567     KnownBits N0Known = computeKnownBits(N0);
3568 
3569     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3570       return OFK_Never;
3571   }
3572 
3573   return OFK_Sometime;
3574 }
3575 
3576 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3577   EVT OpVT = Val.getValueType();
3578   unsigned BitWidth = OpVT.getScalarSizeInBits();
3579 
3580   // Is the constant a known power of 2?
3581   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3582     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3583 
3584   // A left-shift of a constant one will have exactly one bit set because
3585   // shifting the bit off the end is undefined.
3586   if (Val.getOpcode() == ISD::SHL) {
3587     auto *C = isConstOrConstSplat(Val.getOperand(0));
3588     if (C && C->getAPIntValue() == 1)
3589       return true;
3590   }
3591 
3592   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3593   // one bit set.
3594   if (Val.getOpcode() == ISD::SRL) {
3595     auto *C = isConstOrConstSplat(Val.getOperand(0));
3596     if (C && C->getAPIntValue().isSignMask())
3597       return true;
3598   }
3599 
3600   // Are all operands of a build vector constant powers of two?
3601   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3602     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3603           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3604             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3605           return false;
3606         }))
3607       return true;
3608 
3609   // More could be done here, though the above checks are enough
3610   // to handle some common cases.
3611 
3612   // Fall back to computeKnownBits to catch other known cases.
3613   KnownBits Known = computeKnownBits(Val);
3614   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3615 }
3616 
3617 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3618   EVT VT = Op.getValueType();
3619 
3620   // TODO: Assume we don't know anything for now.
3621   if (VT.isScalableVector())
3622     return 1;
3623 
3624   APInt DemandedElts = VT.isVector()
3625                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
3626                            : APInt(1, 1);
3627   return ComputeNumSignBits(Op, DemandedElts, Depth);
3628 }
3629 
3630 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3631                                           unsigned Depth) const {
3632   EVT VT = Op.getValueType();
3633   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3634   unsigned VTBits = VT.getScalarSizeInBits();
3635   unsigned NumElts = DemandedElts.getBitWidth();
3636   unsigned Tmp, Tmp2;
3637   unsigned FirstAnswer = 1;
3638 
3639   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3640     const APInt &Val = C->getAPIntValue();
3641     return Val.getNumSignBits();
3642   }
3643 
3644   if (Depth >= MaxRecursionDepth)
3645     return 1;  // Limit search depth.
3646 
3647   if (!DemandedElts || VT.isScalableVector())
3648     return 1;  // No demanded elts, better to assume we don't know anything.
3649 
3650   unsigned Opcode = Op.getOpcode();
3651   switch (Opcode) {
3652   default: break;
3653   case ISD::AssertSext:
3654     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3655     return VTBits-Tmp+1;
3656   case ISD::AssertZext:
3657     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3658     return VTBits-Tmp;
3659 
3660   case ISD::BUILD_VECTOR:
3661     Tmp = VTBits;
3662     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3663       if (!DemandedElts[i])
3664         continue;
3665 
3666       SDValue SrcOp = Op.getOperand(i);
3667       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3668 
3669       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3670       if (SrcOp.getValueSizeInBits() != VTBits) {
3671         assert(SrcOp.getValueSizeInBits() > VTBits &&
3672                "Expected BUILD_VECTOR implicit truncation");
3673         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3674         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3675       }
3676       Tmp = std::min(Tmp, Tmp2);
3677     }
3678     return Tmp;
3679 
3680   case ISD::VECTOR_SHUFFLE: {
3681     // Collect the minimum number of sign bits that are shared by every vector
3682     // element referenced by the shuffle.
3683     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3684     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3685     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3686     for (unsigned i = 0; i != NumElts; ++i) {
3687       int M = SVN->getMaskElt(i);
3688       if (!DemandedElts[i])
3689         continue;
3690       // For UNDEF elements, we don't know anything about the common state of
3691       // the shuffle result.
3692       if (M < 0)
3693         return 1;
3694       if ((unsigned)M < NumElts)
3695         DemandedLHS.setBit((unsigned)M % NumElts);
3696       else
3697         DemandedRHS.setBit((unsigned)M % NumElts);
3698     }
3699     Tmp = std::numeric_limits<unsigned>::max();
3700     if (!!DemandedLHS)
3701       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3702     if (!!DemandedRHS) {
3703       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3704       Tmp = std::min(Tmp, Tmp2);
3705     }
3706     // If we don't know anything, early out and try computeKnownBits fall-back.
3707     if (Tmp == 1)
3708       break;
3709     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3710     return Tmp;
3711   }
3712 
3713   case ISD::BITCAST: {
3714     SDValue N0 = Op.getOperand(0);
3715     EVT SrcVT = N0.getValueType();
3716     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3717 
3718     // Ignore bitcasts from unsupported types..
3719     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3720       break;
3721 
3722     // Fast handling of 'identity' bitcasts.
3723     if (VTBits == SrcBits)
3724       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3725 
3726     bool IsLE = getDataLayout().isLittleEndian();
3727 
3728     // Bitcast 'large element' scalar/vector to 'small element' vector.
3729     if ((SrcBits % VTBits) == 0) {
3730       assert(VT.isVector() && "Expected bitcast to vector");
3731 
3732       unsigned Scale = SrcBits / VTBits;
3733       APInt SrcDemandedElts(NumElts / Scale, 0);
3734       for (unsigned i = 0; i != NumElts; ++i)
3735         if (DemandedElts[i])
3736           SrcDemandedElts.setBit(i / Scale);
3737 
3738       // Fast case - sign splat can be simply split across the small elements.
3739       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3740       if (Tmp == SrcBits)
3741         return VTBits;
3742 
3743       // Slow case - determine how far the sign extends into each sub-element.
3744       Tmp2 = VTBits;
3745       for (unsigned i = 0; i != NumElts; ++i)
3746         if (DemandedElts[i]) {
3747           unsigned SubOffset = i % Scale;
3748           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3749           SubOffset = SubOffset * VTBits;
3750           if (Tmp <= SubOffset)
3751             return 1;
3752           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3753         }
3754       return Tmp2;
3755     }
3756     break;
3757   }
3758 
3759   case ISD::SIGN_EXTEND:
3760     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3761     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3762   case ISD::SIGN_EXTEND_INREG:
3763     // Max of the input and what this extends.
3764     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3765     Tmp = VTBits-Tmp+1;
3766     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3767     return std::max(Tmp, Tmp2);
3768   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3769     SDValue Src = Op.getOperand(0);
3770     EVT SrcVT = Src.getValueType();
3771     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3772     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3773     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3774   }
3775   case ISD::SRA:
3776     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3777     // SRA X, C -> adds C sign bits.
3778     if (const APInt *ShAmt =
3779             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3780       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3781     return Tmp;
3782   case ISD::SHL:
3783     if (const APInt *ShAmt =
3784             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3785       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3786       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3787       if (ShAmt->ult(Tmp))
3788         return Tmp - ShAmt->getZExtValue();
3789     }
3790     break;
3791   case ISD::AND:
3792   case ISD::OR:
3793   case ISD::XOR:    // NOT is handled here.
3794     // Logical binary ops preserve the number of sign bits at the worst.
3795     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3796     if (Tmp != 1) {
3797       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3798       FirstAnswer = std::min(Tmp, Tmp2);
3799       // We computed what we know about the sign bits as our first
3800       // answer. Now proceed to the generic code that uses
3801       // computeKnownBits, and pick whichever answer is better.
3802     }
3803     break;
3804 
3805   case ISD::SELECT:
3806   case ISD::VSELECT:
3807     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3808     if (Tmp == 1) return 1;  // Early out.
3809     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3810     return std::min(Tmp, Tmp2);
3811   case ISD::SELECT_CC:
3812     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3813     if (Tmp == 1) return 1;  // Early out.
3814     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3815     return std::min(Tmp, Tmp2);
3816 
3817   case ISD::SMIN:
3818   case ISD::SMAX: {
3819     // If we have a clamp pattern, we know that the number of sign bits will be
3820     // the minimum of the clamp min/max range.
3821     bool IsMax = (Opcode == ISD::SMAX);
3822     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3823     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3824       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3825         CstHigh =
3826             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3827     if (CstLow && CstHigh) {
3828       if (!IsMax)
3829         std::swap(CstLow, CstHigh);
3830       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3831         Tmp = CstLow->getAPIntValue().getNumSignBits();
3832         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3833         return std::min(Tmp, Tmp2);
3834       }
3835     }
3836 
3837     // Fallback - just get the minimum number of sign bits of the operands.
3838     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3839     if (Tmp == 1)
3840       return 1;  // Early out.
3841     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3842     return std::min(Tmp, Tmp2);
3843   }
3844   case ISD::UMIN:
3845   case ISD::UMAX:
3846     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3847     if (Tmp == 1)
3848       return 1;  // Early out.
3849     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3850     return std::min(Tmp, Tmp2);
3851   case ISD::SADDO:
3852   case ISD::UADDO:
3853   case ISD::SSUBO:
3854   case ISD::USUBO:
3855   case ISD::SMULO:
3856   case ISD::UMULO:
3857     if (Op.getResNo() != 1)
3858       break;
3859     // The boolean result conforms to getBooleanContents.  Fall through.
3860     // If setcc returns 0/-1, all bits are sign bits.
3861     // We know that we have an integer-based boolean since these operations
3862     // are only available for integer.
3863     if (TLI->getBooleanContents(VT.isVector(), false) ==
3864         TargetLowering::ZeroOrNegativeOneBooleanContent)
3865       return VTBits;
3866     break;
3867   case ISD::SETCC:
3868   case ISD::STRICT_FSETCC:
3869   case ISD::STRICT_FSETCCS: {
3870     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3871     // If setcc returns 0/-1, all bits are sign bits.
3872     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3873         TargetLowering::ZeroOrNegativeOneBooleanContent)
3874       return VTBits;
3875     break;
3876   }
3877   case ISD::ROTL:
3878   case ISD::ROTR:
3879     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3880 
3881     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3882     if (Tmp == VTBits)
3883       return VTBits;
3884 
3885     if (ConstantSDNode *C =
3886             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3887       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3888 
3889       // Handle rotate right by N like a rotate left by 32-N.
3890       if (Opcode == ISD::ROTR)
3891         RotAmt = (VTBits - RotAmt) % VTBits;
3892 
3893       // If we aren't rotating out all of the known-in sign bits, return the
3894       // number that are left.  This handles rotl(sext(x), 1) for example.
3895       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3896     }
3897     break;
3898   case ISD::ADD:
3899   case ISD::ADDC:
3900     // Add can have at most one carry bit.  Thus we know that the output
3901     // is, at worst, one more bit than the inputs.
3902     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3903     if (Tmp == 1) return 1; // Early out.
3904 
3905     // Special case decrementing a value (ADD X, -1):
3906     if (ConstantSDNode *CRHS =
3907             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3908       if (CRHS->isAllOnesValue()) {
3909         KnownBits Known =
3910             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3911 
3912         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3913         // sign bits set.
3914         if ((Known.Zero | 1).isAllOnesValue())
3915           return VTBits;
3916 
3917         // If we are subtracting one from a positive number, there is no carry
3918         // out of the result.
3919         if (Known.isNonNegative())
3920           return Tmp;
3921       }
3922 
3923     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3924     if (Tmp2 == 1) return 1; // Early out.
3925     return std::min(Tmp, Tmp2) - 1;
3926   case ISD::SUB:
3927     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3928     if (Tmp2 == 1) return 1; // Early out.
3929 
3930     // Handle NEG.
3931     if (ConstantSDNode *CLHS =
3932             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
3933       if (CLHS->isNullValue()) {
3934         KnownBits Known =
3935             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3936         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3937         // sign bits set.
3938         if ((Known.Zero | 1).isAllOnesValue())
3939           return VTBits;
3940 
3941         // If the input is known to be positive (the sign bit is known clear),
3942         // the output of the NEG has the same number of sign bits as the input.
3943         if (Known.isNonNegative())
3944           return Tmp2;
3945 
3946         // Otherwise, we treat this like a SUB.
3947       }
3948 
3949     // Sub can have at most one carry bit.  Thus we know that the output
3950     // is, at worst, one more bit than the inputs.
3951     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3952     if (Tmp == 1) return 1; // Early out.
3953     return std::min(Tmp, Tmp2) - 1;
3954   case ISD::MUL: {
3955     // The output of the Mul can be at most twice the valid bits in the inputs.
3956     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3957     if (SignBitsOp0 == 1)
3958       break;
3959     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3960     if (SignBitsOp1 == 1)
3961       break;
3962     unsigned OutValidBits =
3963         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
3964     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
3965   }
3966   case ISD::SREM:
3967     // The sign bit is the LHS's sign bit, except when the result of the
3968     // remainder is zero. The magnitude of the result should be less than or
3969     // equal to the magnitude of the LHS. Therefore, the result should have
3970     // at least as many sign bits as the left hand side.
3971     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3972   case ISD::TRUNCATE: {
3973     // Check if the sign bits of source go down as far as the truncated value.
3974     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3975     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3976     if (NumSrcSignBits > (NumSrcBits - VTBits))
3977       return NumSrcSignBits - (NumSrcBits - VTBits);
3978     break;
3979   }
3980   case ISD::EXTRACT_ELEMENT: {
3981     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3982     const int BitWidth = Op.getValueSizeInBits();
3983     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3984 
3985     // Get reverse index (starting from 1), Op1 value indexes elements from
3986     // little end. Sign starts at big end.
3987     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3988 
3989     // If the sign portion ends in our element the subtraction gives correct
3990     // result. Otherwise it gives either negative or > bitwidth result
3991     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3992   }
3993   case ISD::INSERT_VECTOR_ELT: {
3994     // If we know the element index, split the demand between the
3995     // source vector and the inserted element, otherwise assume we need
3996     // the original demanded vector elements and the value.
3997     SDValue InVec = Op.getOperand(0);
3998     SDValue InVal = Op.getOperand(1);
3999     SDValue EltNo = Op.getOperand(2);
4000     bool DemandedVal = true;
4001     APInt DemandedVecElts = DemandedElts;
4002     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4003     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4004       unsigned EltIdx = CEltNo->getZExtValue();
4005       DemandedVal = !!DemandedElts[EltIdx];
4006       DemandedVecElts.clearBit(EltIdx);
4007     }
4008     Tmp = std::numeric_limits<unsigned>::max();
4009     if (DemandedVal) {
4010       // TODO - handle implicit truncation of inserted elements.
4011       if (InVal.getScalarValueSizeInBits() != VTBits)
4012         break;
4013       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4014       Tmp = std::min(Tmp, Tmp2);
4015     }
4016     if (!!DemandedVecElts) {
4017       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4018       Tmp = std::min(Tmp, Tmp2);
4019     }
4020     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4021     return Tmp;
4022   }
4023   case ISD::EXTRACT_VECTOR_ELT: {
4024     SDValue InVec = Op.getOperand(0);
4025     SDValue EltNo = Op.getOperand(1);
4026     EVT VecVT = InVec.getValueType();
4027     // ComputeNumSignBits not yet implemented for scalable vectors.
4028     if (VecVT.isScalableVector())
4029       break;
4030     const unsigned BitWidth = Op.getValueSizeInBits();
4031     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4032     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4033 
4034     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4035     // anything about sign bits. But if the sizes match we can derive knowledge
4036     // about sign bits from the vector operand.
4037     if (BitWidth != EltBitWidth)
4038       break;
4039 
4040     // If we know the element index, just demand that vector element, else for
4041     // an unknown element index, ignore DemandedElts and demand them all.
4042     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
4043     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4044     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4045       DemandedSrcElts =
4046           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4047 
4048     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4049   }
4050   case ISD::EXTRACT_SUBVECTOR: {
4051     // Offset the demanded elts by the subvector index.
4052     SDValue Src = Op.getOperand(0);
4053     // Bail until we can represent demanded elements for scalable vectors.
4054     if (Src.getValueType().isScalableVector())
4055       break;
4056     uint64_t Idx = Op.getConstantOperandVal(1);
4057     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4058     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4059     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4060   }
4061   case ISD::CONCAT_VECTORS: {
4062     // Determine the minimum number of sign bits across all demanded
4063     // elts of the input vectors. Early out if the result is already 1.
4064     Tmp = std::numeric_limits<unsigned>::max();
4065     EVT SubVectorVT = Op.getOperand(0).getValueType();
4066     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4067     unsigned NumSubVectors = Op.getNumOperands();
4068     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4069       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
4070       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
4071       if (!DemandedSub)
4072         continue;
4073       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4074       Tmp = std::min(Tmp, Tmp2);
4075     }
4076     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4077     return Tmp;
4078   }
4079   case ISD::INSERT_SUBVECTOR: {
4080     // Demand any elements from the subvector and the remainder from the src its
4081     // inserted into.
4082     SDValue Src = Op.getOperand(0);
4083     SDValue Sub = Op.getOperand(1);
4084     uint64_t Idx = Op.getConstantOperandVal(2);
4085     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4086     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4087     APInt DemandedSrcElts = DemandedElts;
4088     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
4089 
4090     Tmp = std::numeric_limits<unsigned>::max();
4091     if (!!DemandedSubElts) {
4092       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4093       if (Tmp == 1)
4094         return 1; // early-out
4095     }
4096     if (!!DemandedSrcElts) {
4097       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4098       Tmp = std::min(Tmp, Tmp2);
4099     }
4100     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4101     return Tmp;
4102   }
4103   }
4104 
4105   // If we are looking at the loaded value of the SDNode.
4106   if (Op.getResNo() == 0) {
4107     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4108     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4109       unsigned ExtType = LD->getExtensionType();
4110       switch (ExtType) {
4111       default: break;
4112       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4113         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4114         return VTBits - Tmp + 1;
4115       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4116         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4117         return VTBits - Tmp;
4118       case ISD::NON_EXTLOAD:
4119         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4120           // We only need to handle vectors - computeKnownBits should handle
4121           // scalar cases.
4122           Type *CstTy = Cst->getType();
4123           if (CstTy->isVectorTy() &&
4124               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4125             Tmp = VTBits;
4126             for (unsigned i = 0; i != NumElts; ++i) {
4127               if (!DemandedElts[i])
4128                 continue;
4129               if (Constant *Elt = Cst->getAggregateElement(i)) {
4130                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4131                   const APInt &Value = CInt->getValue();
4132                   Tmp = std::min(Tmp, Value.getNumSignBits());
4133                   continue;
4134                 }
4135                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4136                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4137                   Tmp = std::min(Tmp, Value.getNumSignBits());
4138                   continue;
4139                 }
4140               }
4141               // Unknown type. Conservatively assume no bits match sign bit.
4142               return 1;
4143             }
4144             return Tmp;
4145           }
4146         }
4147         break;
4148       }
4149     }
4150   }
4151 
4152   // Allow the target to implement this method for its nodes.
4153   if (Opcode >= ISD::BUILTIN_OP_END ||
4154       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4155       Opcode == ISD::INTRINSIC_W_CHAIN ||
4156       Opcode == ISD::INTRINSIC_VOID) {
4157     unsigned NumBits =
4158         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4159     if (NumBits > 1)
4160       FirstAnswer = std::max(FirstAnswer, NumBits);
4161   }
4162 
4163   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4164   // use this information.
4165   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4166 
4167   APInt Mask;
4168   if (Known.isNonNegative()) {        // sign bit is 0
4169     Mask = Known.Zero;
4170   } else if (Known.isNegative()) {  // sign bit is 1;
4171     Mask = Known.One;
4172   } else {
4173     // Nothing known.
4174     return FirstAnswer;
4175   }
4176 
4177   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4178   // the number of identical bits in the top of the input value.
4179   Mask <<= Mask.getBitWidth()-VTBits;
4180   return std::max(FirstAnswer, Mask.countLeadingOnes());
4181 }
4182 
4183 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4184   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4185       !isa<ConstantSDNode>(Op.getOperand(1)))
4186     return false;
4187 
4188   if (Op.getOpcode() == ISD::OR &&
4189       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4190     return false;
4191 
4192   return true;
4193 }
4194 
4195 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4196   // If we're told that NaNs won't happen, assume they won't.
4197   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4198     return true;
4199 
4200   if (Depth >= MaxRecursionDepth)
4201     return false; // Limit search depth.
4202 
4203   // TODO: Handle vectors.
4204   // If the value is a constant, we can obviously see if it is a NaN or not.
4205   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4206     return !C->getValueAPF().isNaN() ||
4207            (SNaN && !C->getValueAPF().isSignaling());
4208   }
4209 
4210   unsigned Opcode = Op.getOpcode();
4211   switch (Opcode) {
4212   case ISD::FADD:
4213   case ISD::FSUB:
4214   case ISD::FMUL:
4215   case ISD::FDIV:
4216   case ISD::FREM:
4217   case ISD::FSIN:
4218   case ISD::FCOS: {
4219     if (SNaN)
4220       return true;
4221     // TODO: Need isKnownNeverInfinity
4222     return false;
4223   }
4224   case ISD::FCANONICALIZE:
4225   case ISD::FEXP:
4226   case ISD::FEXP2:
4227   case ISD::FTRUNC:
4228   case ISD::FFLOOR:
4229   case ISD::FCEIL:
4230   case ISD::FROUND:
4231   case ISD::FROUNDEVEN:
4232   case ISD::FRINT:
4233   case ISD::FNEARBYINT: {
4234     if (SNaN)
4235       return true;
4236     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4237   }
4238   case ISD::FABS:
4239   case ISD::FNEG:
4240   case ISD::FCOPYSIGN: {
4241     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4242   }
4243   case ISD::SELECT:
4244     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4245            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4246   case ISD::FP_EXTEND:
4247   case ISD::FP_ROUND: {
4248     if (SNaN)
4249       return true;
4250     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4251   }
4252   case ISD::SINT_TO_FP:
4253   case ISD::UINT_TO_FP:
4254     return true;
4255   case ISD::FMA:
4256   case ISD::FMAD: {
4257     if (SNaN)
4258       return true;
4259     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4260            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4261            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4262   }
4263   case ISD::FSQRT: // Need is known positive
4264   case ISD::FLOG:
4265   case ISD::FLOG2:
4266   case ISD::FLOG10:
4267   case ISD::FPOWI:
4268   case ISD::FPOW: {
4269     if (SNaN)
4270       return true;
4271     // TODO: Refine on operand
4272     return false;
4273   }
4274   case ISD::FMINNUM:
4275   case ISD::FMAXNUM: {
4276     // Only one needs to be known not-nan, since it will be returned if the
4277     // other ends up being one.
4278     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4279            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4280   }
4281   case ISD::FMINNUM_IEEE:
4282   case ISD::FMAXNUM_IEEE: {
4283     if (SNaN)
4284       return true;
4285     // This can return a NaN if either operand is an sNaN, or if both operands
4286     // are NaN.
4287     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4288             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4289            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4290             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4291   }
4292   case ISD::FMINIMUM:
4293   case ISD::FMAXIMUM: {
4294     // TODO: Does this quiet or return the origina NaN as-is?
4295     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4296            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4297   }
4298   case ISD::EXTRACT_VECTOR_ELT: {
4299     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4300   }
4301   default:
4302     if (Opcode >= ISD::BUILTIN_OP_END ||
4303         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4304         Opcode == ISD::INTRINSIC_W_CHAIN ||
4305         Opcode == ISD::INTRINSIC_VOID) {
4306       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4307     }
4308 
4309     return false;
4310   }
4311 }
4312 
4313 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4314   assert(Op.getValueType().isFloatingPoint() &&
4315          "Floating point type expected");
4316 
4317   // If the value is a constant, we can obviously see if it is a zero or not.
4318   // TODO: Add BuildVector support.
4319   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4320     return !C->isZero();
4321   return false;
4322 }
4323 
4324 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4325   assert(!Op.getValueType().isFloatingPoint() &&
4326          "Floating point types unsupported - use isKnownNeverZeroFloat");
4327 
4328   // If the value is a constant, we can obviously see if it is a zero or not.
4329   if (ISD::matchUnaryPredicate(
4330           Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4331     return true;
4332 
4333   // TODO: Recognize more cases here.
4334   switch (Op.getOpcode()) {
4335   default: break;
4336   case ISD::OR:
4337     if (isKnownNeverZero(Op.getOperand(1)) ||
4338         isKnownNeverZero(Op.getOperand(0)))
4339       return true;
4340     break;
4341   }
4342 
4343   return false;
4344 }
4345 
4346 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4347   // Check the obvious case.
4348   if (A == B) return true;
4349 
4350   // For for negative and positive zero.
4351   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4352     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4353       if (CA->isZero() && CB->isZero()) return true;
4354 
4355   // Otherwise they may not be equal.
4356   return false;
4357 }
4358 
4359 // FIXME: unify with llvm::haveNoCommonBitsSet.
4360 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4361 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4362   assert(A.getValueType() == B.getValueType() &&
4363          "Values must have the same type");
4364   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4365                                         computeKnownBits(B));
4366 }
4367 
4368 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4369                                SelectionDAG &DAG) {
4370   if (cast<ConstantSDNode>(Step)->isNullValue())
4371     return DAG.getConstant(0, DL, VT);
4372 
4373   return SDValue();
4374 }
4375 
4376 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4377                                 ArrayRef<SDValue> Ops,
4378                                 SelectionDAG &DAG) {
4379   int NumOps = Ops.size();
4380   assert(NumOps != 0 && "Can't build an empty vector!");
4381   assert(!VT.isScalableVector() &&
4382          "BUILD_VECTOR cannot be used with scalable types");
4383   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4384          "Incorrect element count in BUILD_VECTOR!");
4385 
4386   // BUILD_VECTOR of UNDEFs is UNDEF.
4387   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4388     return DAG.getUNDEF(VT);
4389 
4390   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4391   SDValue IdentitySrc;
4392   bool IsIdentity = true;
4393   for (int i = 0; i != NumOps; ++i) {
4394     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4395         Ops[i].getOperand(0).getValueType() != VT ||
4396         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4397         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4398         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4399       IsIdentity = false;
4400       break;
4401     }
4402     IdentitySrc = Ops[i].getOperand(0);
4403   }
4404   if (IsIdentity)
4405     return IdentitySrc;
4406 
4407   return SDValue();
4408 }
4409 
4410 /// Try to simplify vector concatenation to an input value, undef, or build
4411 /// vector.
4412 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4413                                   ArrayRef<SDValue> Ops,
4414                                   SelectionDAG &DAG) {
4415   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4416   assert(llvm::all_of(Ops,
4417                       [Ops](SDValue Op) {
4418                         return Ops[0].getValueType() == Op.getValueType();
4419                       }) &&
4420          "Concatenation of vectors with inconsistent value types!");
4421   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4422              VT.getVectorElementCount() &&
4423          "Incorrect element count in vector concatenation!");
4424 
4425   if (Ops.size() == 1)
4426     return Ops[0];
4427 
4428   // Concat of UNDEFs is UNDEF.
4429   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4430     return DAG.getUNDEF(VT);
4431 
4432   // Scan the operands and look for extract operations from a single source
4433   // that correspond to insertion at the same location via this concatenation:
4434   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4435   SDValue IdentitySrc;
4436   bool IsIdentity = true;
4437   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4438     SDValue Op = Ops[i];
4439     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4440     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4441         Op.getOperand(0).getValueType() != VT ||
4442         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4443         Op.getConstantOperandVal(1) != IdentityIndex) {
4444       IsIdentity = false;
4445       break;
4446     }
4447     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4448            "Unexpected identity source vector for concat of extracts");
4449     IdentitySrc = Op.getOperand(0);
4450   }
4451   if (IsIdentity) {
4452     assert(IdentitySrc && "Failed to set source vector of extracts");
4453     return IdentitySrc;
4454   }
4455 
4456   // The code below this point is only designed to work for fixed width
4457   // vectors, so we bail out for now.
4458   if (VT.isScalableVector())
4459     return SDValue();
4460 
4461   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4462   // simplified to one big BUILD_VECTOR.
4463   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4464   EVT SVT = VT.getScalarType();
4465   SmallVector<SDValue, 16> Elts;
4466   for (SDValue Op : Ops) {
4467     EVT OpVT = Op.getValueType();
4468     if (Op.isUndef())
4469       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4470     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4471       Elts.append(Op->op_begin(), Op->op_end());
4472     else
4473       return SDValue();
4474   }
4475 
4476   // BUILD_VECTOR requires all inputs to be of the same type, find the
4477   // maximum type and extend them all.
4478   for (SDValue Op : Elts)
4479     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4480 
4481   if (SVT.bitsGT(VT.getScalarType())) {
4482     for (SDValue &Op : Elts) {
4483       if (Op.isUndef())
4484         Op = DAG.getUNDEF(SVT);
4485       else
4486         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4487                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4488                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4489     }
4490   }
4491 
4492   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4493   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4494   return V;
4495 }
4496 
4497 /// Gets or creates the specified node.
4498 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4499   FoldingSetNodeID ID;
4500   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4501   void *IP = nullptr;
4502   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4503     return SDValue(E, 0);
4504 
4505   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4506                               getVTList(VT));
4507   CSEMap.InsertNode(N, IP);
4508 
4509   InsertNode(N);
4510   SDValue V = SDValue(N, 0);
4511   NewSDValueDbgMsg(V, "Creating new node: ", this);
4512   return V;
4513 }
4514 
4515 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4516                               SDValue Operand) {
4517   SDNodeFlags Flags;
4518   if (Inserter)
4519     Flags = Inserter->getFlags();
4520   return getNode(Opcode, DL, VT, Operand, Flags);
4521 }
4522 
4523 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4524                               SDValue Operand, const SDNodeFlags Flags) {
4525   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4526          "Operand is DELETED_NODE!");
4527   // Constant fold unary operations with an integer constant operand. Even
4528   // opaque constant will be folded, because the folding of unary operations
4529   // doesn't create new constants with different values. Nevertheless, the
4530   // opaque flag is preserved during folding to prevent future folding with
4531   // other constants.
4532   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4533     const APInt &Val = C->getAPIntValue();
4534     switch (Opcode) {
4535     default: break;
4536     case ISD::SIGN_EXTEND:
4537       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4538                          C->isTargetOpcode(), C->isOpaque());
4539     case ISD::TRUNCATE:
4540       if (C->isOpaque())
4541         break;
4542       LLVM_FALLTHROUGH;
4543     case ISD::ANY_EXTEND:
4544     case ISD::ZERO_EXTEND:
4545       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4546                          C->isTargetOpcode(), C->isOpaque());
4547     case ISD::UINT_TO_FP:
4548     case ISD::SINT_TO_FP: {
4549       APFloat apf(EVTToAPFloatSemantics(VT),
4550                   APInt::getNullValue(VT.getSizeInBits()));
4551       (void)apf.convertFromAPInt(Val,
4552                                  Opcode==ISD::SINT_TO_FP,
4553                                  APFloat::rmNearestTiesToEven);
4554       return getConstantFP(apf, DL, VT);
4555     }
4556     case ISD::BITCAST:
4557       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4558         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4559       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4560         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4561       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4562         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4563       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4564         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4565       break;
4566     case ISD::ABS:
4567       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4568                          C->isOpaque());
4569     case ISD::BITREVERSE:
4570       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4571                          C->isOpaque());
4572     case ISD::BSWAP:
4573       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4574                          C->isOpaque());
4575     case ISD::CTPOP:
4576       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4577                          C->isOpaque());
4578     case ISD::CTLZ:
4579     case ISD::CTLZ_ZERO_UNDEF:
4580       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4581                          C->isOpaque());
4582     case ISD::CTTZ:
4583     case ISD::CTTZ_ZERO_UNDEF:
4584       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4585                          C->isOpaque());
4586     case ISD::FP16_TO_FP: {
4587       bool Ignored;
4588       APFloat FPV(APFloat::IEEEhalf(),
4589                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4590 
4591       // This can return overflow, underflow, or inexact; we don't care.
4592       // FIXME need to be more flexible about rounding mode.
4593       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4594                         APFloat::rmNearestTiesToEven, &Ignored);
4595       return getConstantFP(FPV, DL, VT);
4596     }
4597     case ISD::STEP_VECTOR: {
4598       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4599         return V;
4600       break;
4601     }
4602     }
4603   }
4604 
4605   // Constant fold unary operations with a floating point constant operand.
4606   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4607     APFloat V = C->getValueAPF();    // make copy
4608     switch (Opcode) {
4609     case ISD::FNEG:
4610       V.changeSign();
4611       return getConstantFP(V, DL, VT);
4612     case ISD::FABS:
4613       V.clearSign();
4614       return getConstantFP(V, DL, VT);
4615     case ISD::FCEIL: {
4616       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4617       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4618         return getConstantFP(V, DL, VT);
4619       break;
4620     }
4621     case ISD::FTRUNC: {
4622       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4623       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4624         return getConstantFP(V, DL, VT);
4625       break;
4626     }
4627     case ISD::FFLOOR: {
4628       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4629       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4630         return getConstantFP(V, DL, VT);
4631       break;
4632     }
4633     case ISD::FP_EXTEND: {
4634       bool ignored;
4635       // This can return overflow, underflow, or inexact; we don't care.
4636       // FIXME need to be more flexible about rounding mode.
4637       (void)V.convert(EVTToAPFloatSemantics(VT),
4638                       APFloat::rmNearestTiesToEven, &ignored);
4639       return getConstantFP(V, DL, VT);
4640     }
4641     case ISD::FP_TO_SINT:
4642     case ISD::FP_TO_UINT: {
4643       bool ignored;
4644       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4645       // FIXME need to be more flexible about rounding mode.
4646       APFloat::opStatus s =
4647           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4648       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4649         break;
4650       return getConstant(IntVal, DL, VT);
4651     }
4652     case ISD::BITCAST:
4653       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4654         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4655       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4656         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4657       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4658         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4659       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4660         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4661       break;
4662     case ISD::FP_TO_FP16: {
4663       bool Ignored;
4664       // This can return overflow, underflow, or inexact; we don't care.
4665       // FIXME need to be more flexible about rounding mode.
4666       (void)V.convert(APFloat::IEEEhalf(),
4667                       APFloat::rmNearestTiesToEven, &Ignored);
4668       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4669     }
4670     }
4671   }
4672 
4673   // Constant fold unary operations with a vector integer or float operand.
4674   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4675     if (BV->isConstant()) {
4676       switch (Opcode) {
4677       default:
4678         // FIXME: Entirely reasonable to perform folding of other unary
4679         // operations here as the need arises.
4680         break;
4681       case ISD::FNEG:
4682       case ISD::FABS:
4683       case ISD::FCEIL:
4684       case ISD::FTRUNC:
4685       case ISD::FFLOOR:
4686       case ISD::FP_EXTEND:
4687       case ISD::FP_TO_SINT:
4688       case ISD::FP_TO_UINT:
4689       case ISD::TRUNCATE:
4690       case ISD::ANY_EXTEND:
4691       case ISD::ZERO_EXTEND:
4692       case ISD::SIGN_EXTEND:
4693       case ISD::UINT_TO_FP:
4694       case ISD::SINT_TO_FP:
4695       case ISD::ABS:
4696       case ISD::BITREVERSE:
4697       case ISD::BSWAP:
4698       case ISD::CTLZ:
4699       case ISD::CTLZ_ZERO_UNDEF:
4700       case ISD::CTTZ:
4701       case ISD::CTTZ_ZERO_UNDEF:
4702       case ISD::CTPOP: {
4703         SDValue Ops = { Operand };
4704         if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4705           return Fold;
4706       }
4707       }
4708     }
4709   }
4710 
4711   unsigned OpOpcode = Operand.getNode()->getOpcode();
4712   switch (Opcode) {
4713   case ISD::STEP_VECTOR:
4714     assert(VT.isScalableVector() &&
4715            "STEP_VECTOR can only be used with scalable types");
4716     assert(VT.getScalarSizeInBits() >= 8 &&
4717            "STEP_VECTOR can only be used with vectors of integers that are at "
4718            "least 8 bits wide");
4719     assert(isa<ConstantSDNode>(Operand) &&
4720            cast<ConstantSDNode>(Operand)->getAPIntValue().isSignedIntN(
4721                VT.getScalarSizeInBits()) &&
4722            "Expected STEP_VECTOR integer constant to fit in "
4723            "the vector element type");
4724     break;
4725   case ISD::FREEZE:
4726     assert(VT == Operand.getValueType() && "Unexpected VT!");
4727     break;
4728   case ISD::TokenFactor:
4729   case ISD::MERGE_VALUES:
4730   case ISD::CONCAT_VECTORS:
4731     return Operand;         // Factor, merge or concat of one node?  No need.
4732   case ISD::BUILD_VECTOR: {
4733     // Attempt to simplify BUILD_VECTOR.
4734     SDValue Ops[] = {Operand};
4735     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4736       return V;
4737     break;
4738   }
4739   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4740   case ISD::FP_EXTEND:
4741     assert(VT.isFloatingPoint() &&
4742            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4743     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4744     assert((!VT.isVector() ||
4745             VT.getVectorElementCount() ==
4746             Operand.getValueType().getVectorElementCount()) &&
4747            "Vector element count mismatch!");
4748     assert(Operand.getValueType().bitsLT(VT) &&
4749            "Invalid fpext node, dst < src!");
4750     if (Operand.isUndef())
4751       return getUNDEF(VT);
4752     break;
4753   case ISD::FP_TO_SINT:
4754   case ISD::FP_TO_UINT:
4755     if (Operand.isUndef())
4756       return getUNDEF(VT);
4757     break;
4758   case ISD::SINT_TO_FP:
4759   case ISD::UINT_TO_FP:
4760     // [us]itofp(undef) = 0, because the result value is bounded.
4761     if (Operand.isUndef())
4762       return getConstantFP(0.0, DL, VT);
4763     break;
4764   case ISD::SIGN_EXTEND:
4765     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4766            "Invalid SIGN_EXTEND!");
4767     assert(VT.isVector() == Operand.getValueType().isVector() &&
4768            "SIGN_EXTEND result type type should be vector iff the operand "
4769            "type is vector!");
4770     if (Operand.getValueType() == VT) return Operand;   // noop extension
4771     assert((!VT.isVector() ||
4772             VT.getVectorElementCount() ==
4773                 Operand.getValueType().getVectorElementCount()) &&
4774            "Vector element count mismatch!");
4775     assert(Operand.getValueType().bitsLT(VT) &&
4776            "Invalid sext node, dst < src!");
4777     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4778       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4779     if (OpOpcode == ISD::UNDEF)
4780       // sext(undef) = 0, because the top bits will all be the same.
4781       return getConstant(0, DL, VT);
4782     break;
4783   case ISD::ZERO_EXTEND:
4784     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4785            "Invalid ZERO_EXTEND!");
4786     assert(VT.isVector() == Operand.getValueType().isVector() &&
4787            "ZERO_EXTEND result type type should be vector iff the operand "
4788            "type is vector!");
4789     if (Operand.getValueType() == VT) return Operand;   // noop extension
4790     assert((!VT.isVector() ||
4791             VT.getVectorElementCount() ==
4792                 Operand.getValueType().getVectorElementCount()) &&
4793            "Vector element count mismatch!");
4794     assert(Operand.getValueType().bitsLT(VT) &&
4795            "Invalid zext node, dst < src!");
4796     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4797       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4798     if (OpOpcode == ISD::UNDEF)
4799       // zext(undef) = 0, because the top bits will be zero.
4800       return getConstant(0, DL, VT);
4801     break;
4802   case ISD::ANY_EXTEND:
4803     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4804            "Invalid ANY_EXTEND!");
4805     assert(VT.isVector() == Operand.getValueType().isVector() &&
4806            "ANY_EXTEND result type type should be vector iff the operand "
4807            "type is vector!");
4808     if (Operand.getValueType() == VT) return Operand;   // noop extension
4809     assert((!VT.isVector() ||
4810             VT.getVectorElementCount() ==
4811                 Operand.getValueType().getVectorElementCount()) &&
4812            "Vector element count mismatch!");
4813     assert(Operand.getValueType().bitsLT(VT) &&
4814            "Invalid anyext node, dst < src!");
4815 
4816     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4817         OpOpcode == ISD::ANY_EXTEND)
4818       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4819       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4820     if (OpOpcode == ISD::UNDEF)
4821       return getUNDEF(VT);
4822 
4823     // (ext (trunc x)) -> x
4824     if (OpOpcode == ISD::TRUNCATE) {
4825       SDValue OpOp = Operand.getOperand(0);
4826       if (OpOp.getValueType() == VT) {
4827         transferDbgValues(Operand, OpOp);
4828         return OpOp;
4829       }
4830     }
4831     break;
4832   case ISD::TRUNCATE:
4833     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4834            "Invalid TRUNCATE!");
4835     assert(VT.isVector() == Operand.getValueType().isVector() &&
4836            "TRUNCATE result type type should be vector iff the operand "
4837            "type is vector!");
4838     if (Operand.getValueType() == VT) return Operand;   // noop truncate
4839     assert((!VT.isVector() ||
4840             VT.getVectorElementCount() ==
4841                 Operand.getValueType().getVectorElementCount()) &&
4842            "Vector element count mismatch!");
4843     assert(Operand.getValueType().bitsGT(VT) &&
4844            "Invalid truncate node, src < dst!");
4845     if (OpOpcode == ISD::TRUNCATE)
4846       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4847     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4848         OpOpcode == ISD::ANY_EXTEND) {
4849       // If the source is smaller than the dest, we still need an extend.
4850       if (Operand.getOperand(0).getValueType().getScalarType()
4851             .bitsLT(VT.getScalarType()))
4852         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4853       if (Operand.getOperand(0).getValueType().bitsGT(VT))
4854         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4855       return Operand.getOperand(0);
4856     }
4857     if (OpOpcode == ISD::UNDEF)
4858       return getUNDEF(VT);
4859     break;
4860   case ISD::ANY_EXTEND_VECTOR_INREG:
4861   case ISD::ZERO_EXTEND_VECTOR_INREG:
4862   case ISD::SIGN_EXTEND_VECTOR_INREG:
4863     assert(VT.isVector() && "This DAG node is restricted to vector types.");
4864     assert(Operand.getValueType().bitsLE(VT) &&
4865            "The input must be the same size or smaller than the result.");
4866     assert(VT.getVectorMinNumElements() <
4867                Operand.getValueType().getVectorMinNumElements() &&
4868            "The destination vector type must have fewer lanes than the input.");
4869     break;
4870   case ISD::ABS:
4871     assert(VT.isInteger() && VT == Operand.getValueType() &&
4872            "Invalid ABS!");
4873     if (OpOpcode == ISD::UNDEF)
4874       return getUNDEF(VT);
4875     break;
4876   case ISD::BSWAP:
4877     assert(VT.isInteger() && VT == Operand.getValueType() &&
4878            "Invalid BSWAP!");
4879     assert((VT.getScalarSizeInBits() % 16 == 0) &&
4880            "BSWAP types must be a multiple of 16 bits!");
4881     if (OpOpcode == ISD::UNDEF)
4882       return getUNDEF(VT);
4883     break;
4884   case ISD::BITREVERSE:
4885     assert(VT.isInteger() && VT == Operand.getValueType() &&
4886            "Invalid BITREVERSE!");
4887     if (OpOpcode == ISD::UNDEF)
4888       return getUNDEF(VT);
4889     break;
4890   case ISD::BITCAST:
4891     // Basic sanity checking.
4892     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4893            "Cannot BITCAST between types of different sizes!");
4894     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
4895     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
4896       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4897     if (OpOpcode == ISD::UNDEF)
4898       return getUNDEF(VT);
4899     break;
4900   case ISD::SCALAR_TO_VECTOR:
4901     assert(VT.isVector() && !Operand.getValueType().isVector() &&
4902            (VT.getVectorElementType() == Operand.getValueType() ||
4903             (VT.getVectorElementType().isInteger() &&
4904              Operand.getValueType().isInteger() &&
4905              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4906            "Illegal SCALAR_TO_VECTOR node!");
4907     if (OpOpcode == ISD::UNDEF)
4908       return getUNDEF(VT);
4909     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4910     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4911         isa<ConstantSDNode>(Operand.getOperand(1)) &&
4912         Operand.getConstantOperandVal(1) == 0 &&
4913         Operand.getOperand(0).getValueType() == VT)
4914       return Operand.getOperand(0);
4915     break;
4916   case ISD::FNEG:
4917     // Negation of an unknown bag of bits is still completely undefined.
4918     if (OpOpcode == ISD::UNDEF)
4919       return getUNDEF(VT);
4920 
4921     if (OpOpcode == ISD::FNEG)  // --X -> X
4922       return Operand.getOperand(0);
4923     break;
4924   case ISD::FABS:
4925     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
4926       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4927     break;
4928   case ISD::VSCALE:
4929     assert(VT == Operand.getValueType() && "Unexpected VT!");
4930     break;
4931   case ISD::CTPOP:
4932     if (Operand.getValueType().getScalarType() == MVT::i1)
4933       return Operand;
4934     break;
4935   case ISD::CTLZ:
4936   case ISD::CTTZ:
4937     if (Operand.getValueType().getScalarType() == MVT::i1)
4938       return getNOT(DL, Operand, Operand.getValueType());
4939     break;
4940   case ISD::VECREDUCE_SMIN:
4941   case ISD::VECREDUCE_UMAX:
4942     if (Operand.getValueType().getScalarType() == MVT::i1)
4943       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
4944     break;
4945   case ISD::VECREDUCE_SMAX:
4946   case ISD::VECREDUCE_UMIN:
4947     if (Operand.getValueType().getScalarType() == MVT::i1)
4948       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
4949     break;
4950   }
4951 
4952   SDNode *N;
4953   SDVTList VTs = getVTList(VT);
4954   SDValue Ops[] = {Operand};
4955   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4956     FoldingSetNodeID ID;
4957     AddNodeIDNode(ID, Opcode, VTs, Ops);
4958     void *IP = nullptr;
4959     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4960       E->intersectFlagsWith(Flags);
4961       return SDValue(E, 0);
4962     }
4963 
4964     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4965     N->setFlags(Flags);
4966     createOperands(N, Ops);
4967     CSEMap.InsertNode(N, IP);
4968   } else {
4969     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4970     createOperands(N, Ops);
4971   }
4972 
4973   InsertNode(N);
4974   SDValue V = SDValue(N, 0);
4975   NewSDValueDbgMsg(V, "Creating new node: ", this);
4976   return V;
4977 }
4978 
4979 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
4980                                        const APInt &C2) {
4981   switch (Opcode) {
4982   case ISD::ADD:  return C1 + C2;
4983   case ISD::SUB:  return C1 - C2;
4984   case ISD::MUL:  return C1 * C2;
4985   case ISD::AND:  return C1 & C2;
4986   case ISD::OR:   return C1 | C2;
4987   case ISD::XOR:  return C1 ^ C2;
4988   case ISD::SHL:  return C1 << C2;
4989   case ISD::SRL:  return C1.lshr(C2);
4990   case ISD::SRA:  return C1.ashr(C2);
4991   case ISD::ROTL: return C1.rotl(C2);
4992   case ISD::ROTR: return C1.rotr(C2);
4993   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
4994   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
4995   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
4996   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
4997   case ISD::SADDSAT: return C1.sadd_sat(C2);
4998   case ISD::UADDSAT: return C1.uadd_sat(C2);
4999   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5000   case ISD::USUBSAT: return C1.usub_sat(C2);
5001   case ISD::UDIV:
5002     if (!C2.getBoolValue())
5003       break;
5004     return C1.udiv(C2);
5005   case ISD::UREM:
5006     if (!C2.getBoolValue())
5007       break;
5008     return C1.urem(C2);
5009   case ISD::SDIV:
5010     if (!C2.getBoolValue())
5011       break;
5012     return C1.sdiv(C2);
5013   case ISD::SREM:
5014     if (!C2.getBoolValue())
5015       break;
5016     return C1.srem(C2);
5017   }
5018   return llvm::None;
5019 }
5020 
5021 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5022                                        const GlobalAddressSDNode *GA,
5023                                        const SDNode *N2) {
5024   if (GA->getOpcode() != ISD::GlobalAddress)
5025     return SDValue();
5026   if (!TLI->isOffsetFoldingLegal(GA))
5027     return SDValue();
5028   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5029   if (!C2)
5030     return SDValue();
5031   int64_t Offset = C2->getSExtValue();
5032   switch (Opcode) {
5033   case ISD::ADD: break;
5034   case ISD::SUB: Offset = -uint64_t(Offset); break;
5035   default: return SDValue();
5036   }
5037   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5038                           GA->getOffset() + uint64_t(Offset));
5039 }
5040 
5041 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5042   switch (Opcode) {
5043   case ISD::SDIV:
5044   case ISD::UDIV:
5045   case ISD::SREM:
5046   case ISD::UREM: {
5047     // If a divisor is zero/undef or any element of a divisor vector is
5048     // zero/undef, the whole op is undef.
5049     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5050     SDValue Divisor = Ops[1];
5051     if (Divisor.isUndef() || isNullConstant(Divisor))
5052       return true;
5053 
5054     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5055            llvm::any_of(Divisor->op_values(),
5056                         [](SDValue V) { return V.isUndef() ||
5057                                         isNullConstant(V); });
5058     // TODO: Handle signed overflow.
5059   }
5060   // TODO: Handle oversized shifts.
5061   default:
5062     return false;
5063   }
5064 }
5065 
5066 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5067                                              EVT VT, ArrayRef<SDValue> Ops) {
5068   // If the opcode is a target-specific ISD node, there's nothing we can
5069   // do here and the operand rules may not line up with the below, so
5070   // bail early.
5071   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5072   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5073   // foldCONCAT_VECTORS in getNode before this is called.
5074   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5075     return SDValue();
5076 
5077   // For now, the array Ops should only contain two values.
5078   // This enforcement will be removed once this function is merged with
5079   // FoldConstantVectorArithmetic
5080   if (Ops.size() != 2)
5081     return SDValue();
5082 
5083   if (isUndef(Opcode, Ops))
5084     return getUNDEF(VT);
5085 
5086   SDNode *N1 = Ops[0].getNode();
5087   SDNode *N2 = Ops[1].getNode();
5088 
5089   // Handle the case of two scalars.
5090   if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
5091     if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
5092       if (C1->isOpaque() || C2->isOpaque())
5093         return SDValue();
5094 
5095       Optional<APInt> FoldAttempt =
5096           FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5097       if (!FoldAttempt)
5098         return SDValue();
5099 
5100       SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5101       assert((!Folded || !VT.isVector()) &&
5102              "Can't fold vectors ops with scalar operands");
5103       return Folded;
5104     }
5105   }
5106 
5107   // fold (add Sym, c) -> Sym+c
5108   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
5109     return FoldSymbolOffset(Opcode, VT, GA, N2);
5110   if (TLI->isCommutativeBinOp(Opcode))
5111     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
5112       return FoldSymbolOffset(Opcode, VT, GA, N1);
5113 
5114   // For fixed width vectors, extract each constant element and fold them
5115   // individually. Either input may be an undef value.
5116   bool IsBVOrSV1 = N1->getOpcode() == ISD::BUILD_VECTOR ||
5117                    N1->getOpcode() == ISD::SPLAT_VECTOR;
5118   if (!IsBVOrSV1 && !N1->isUndef())
5119     return SDValue();
5120   bool IsBVOrSV2 = N2->getOpcode() == ISD::BUILD_VECTOR ||
5121                    N2->getOpcode() == ISD::SPLAT_VECTOR;
5122   if (!IsBVOrSV2 && !N2->isUndef())
5123     return SDValue();
5124   // If both operands are undef, that's handled the same way as scalars.
5125   if (!IsBVOrSV1 && !IsBVOrSV2)
5126     return SDValue();
5127 
5128   EVT SVT = VT.getScalarType();
5129   EVT LegalSVT = SVT;
5130   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5131     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5132     if (LegalSVT.bitsLT(SVT))
5133       return SDValue();
5134   }
5135 
5136   SmallVector<SDValue, 4> Outputs;
5137   unsigned NumOps = 0;
5138   if (IsBVOrSV1)
5139     NumOps = std::max(NumOps, N1->getNumOperands());
5140   if (IsBVOrSV2)
5141     NumOps = std::max(NumOps, N2->getNumOperands());
5142   assert(NumOps != 0 && "Expected non-zero operands");
5143   // Scalable vectors should only be SPLAT_VECTOR or UNDEF here. We only need
5144   // one iteration for that.
5145   assert((!VT.isScalableVector() || NumOps == 1) &&
5146          "Scalar vector should only have one scalar");
5147 
5148   for (unsigned I = 0; I != NumOps; ++I) {
5149     // We can have a fixed length SPLAT_VECTOR and a BUILD_VECTOR so we need
5150     // to use operand 0 of the SPLAT_VECTOR for each fixed element.
5151     SDValue V1;
5152     if (N1->getOpcode() == ISD::BUILD_VECTOR)
5153       V1 = N1->getOperand(I);
5154     else if (N1->getOpcode() == ISD::SPLAT_VECTOR)
5155       V1 = N1->getOperand(0);
5156     else
5157       V1 = getUNDEF(SVT);
5158 
5159     SDValue V2;
5160     if (N2->getOpcode() == ISD::BUILD_VECTOR)
5161       V2 = N2->getOperand(I);
5162     else if (N2->getOpcode() == ISD::SPLAT_VECTOR)
5163       V2 = N2->getOperand(0);
5164     else
5165       V2 = getUNDEF(SVT);
5166 
5167     if (SVT.isInteger()) {
5168       if (V1.getValueType().bitsGT(SVT))
5169         V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
5170       if (V2.getValueType().bitsGT(SVT))
5171         V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
5172     }
5173 
5174     if (V1.getValueType() != SVT || V2.getValueType() != SVT)
5175       return SDValue();
5176 
5177     // Fold one vector element.
5178     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
5179     if (LegalSVT != SVT)
5180       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5181 
5182     // Scalar folding only succeeded if the result is a constant or UNDEF.
5183     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5184         ScalarResult.getOpcode() != ISD::ConstantFP)
5185       return SDValue();
5186     Outputs.push_back(ScalarResult);
5187   }
5188 
5189   if (N1->getOpcode() == ISD::BUILD_VECTOR ||
5190       N2->getOpcode() == ISD::BUILD_VECTOR) {
5191     assert(VT.getVectorNumElements() == Outputs.size() &&
5192            "Vector size mismatch!");
5193 
5194     // Build a big vector out of the scalar elements we generated.
5195     return getBuildVector(VT, SDLoc(), Outputs);
5196   }
5197 
5198   assert((N1->getOpcode() == ISD::SPLAT_VECTOR ||
5199           N2->getOpcode() == ISD::SPLAT_VECTOR) &&
5200          "One operand should be a splat vector");
5201 
5202   assert(Outputs.size() == 1 && "Vector size mismatch!");
5203   return getSplatVector(VT, SDLoc(), Outputs[0]);
5204 }
5205 
5206 // TODO: Merge with FoldConstantArithmetic
5207 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
5208                                                    const SDLoc &DL, EVT VT,
5209                                                    ArrayRef<SDValue> Ops,
5210                                                    const SDNodeFlags Flags) {
5211   // If the opcode is a target-specific ISD node, there's nothing we can
5212   // do here and the operand rules may not line up with the below, so
5213   // bail early.
5214   if (Opcode >= ISD::BUILTIN_OP_END)
5215     return SDValue();
5216 
5217   if (isUndef(Opcode, Ops))
5218     return getUNDEF(VT);
5219 
5220   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
5221   if (!VT.isVector())
5222     return SDValue();
5223 
5224   // TODO: All the folds below are performed lane-by-lane and assume a fixed
5225   // vector width, however we should be able to do constant folds involving
5226   // splat vector nodes too.
5227   if (VT.isScalableVector())
5228     return SDValue();
5229 
5230   // From this point onwards all vectors are assumed to be fixed width.
5231   unsigned NumElts = VT.getVectorNumElements();
5232 
5233   auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
5234     return !Op.getValueType().isVector() ||
5235            Op.getValueType().getVectorNumElements() == NumElts;
5236   };
5237 
5238   auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
5239     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
5240     return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
5241            (BV && BV->isConstant());
5242   };
5243 
5244   // All operands must be vector types with the same number of elements as
5245   // the result type and must be either UNDEF or a build vector of constant
5246   // or UNDEF scalars.
5247   if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
5248       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5249     return SDValue();
5250 
5251   // If we are comparing vectors, then the result needs to be a i1 boolean
5252   // that is then sign-extended back to the legal result type.
5253   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5254 
5255   // Find legal integer scalar type for constant promotion and
5256   // ensure that its scalar size is at least as large as source.
5257   EVT LegalSVT = VT.getScalarType();
5258   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5259     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5260     if (LegalSVT.bitsLT(VT.getScalarType()))
5261       return SDValue();
5262   }
5263 
5264   // Constant fold each scalar lane separately.
5265   SmallVector<SDValue, 4> ScalarResults;
5266   for (unsigned i = 0; i != NumElts; i++) {
5267     SmallVector<SDValue, 4> ScalarOps;
5268     for (SDValue Op : Ops) {
5269       EVT InSVT = Op.getValueType().getScalarType();
5270       BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
5271       if (!InBV) {
5272         // We've checked that this is UNDEF or a constant of some kind.
5273         if (Op.isUndef())
5274           ScalarOps.push_back(getUNDEF(InSVT));
5275         else
5276           ScalarOps.push_back(Op);
5277         continue;
5278       }
5279 
5280       SDValue ScalarOp = InBV->getOperand(i);
5281       EVT ScalarVT = ScalarOp.getValueType();
5282 
5283       // Build vector (integer) scalar operands may need implicit
5284       // truncation - do this before constant folding.
5285       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5286         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5287 
5288       ScalarOps.push_back(ScalarOp);
5289     }
5290 
5291     // Constant fold the scalar operands.
5292     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
5293 
5294     // Legalize the (integer) scalar constant if necessary.
5295     if (LegalSVT != SVT)
5296       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5297 
5298     // Scalar folding only succeeded if the result is a constant or UNDEF.
5299     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5300         ScalarResult.getOpcode() != ISD::ConstantFP)
5301       return SDValue();
5302     ScalarResults.push_back(ScalarResult);
5303   }
5304 
5305   SDValue V = getBuildVector(VT, DL, ScalarResults);
5306   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5307   return V;
5308 }
5309 
5310 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5311                                          EVT VT, SDValue N1, SDValue N2) {
5312   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5313   //       should. That will require dealing with a potentially non-default
5314   //       rounding mode, checking the "opStatus" return value from the APFloat
5315   //       math calculations, and possibly other variations.
5316   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5317   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5318   if (N1CFP && N2CFP) {
5319     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5320     switch (Opcode) {
5321     case ISD::FADD:
5322       C1.add(C2, APFloat::rmNearestTiesToEven);
5323       return getConstantFP(C1, DL, VT);
5324     case ISD::FSUB:
5325       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5326       return getConstantFP(C1, DL, VT);
5327     case ISD::FMUL:
5328       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5329       return getConstantFP(C1, DL, VT);
5330     case ISD::FDIV:
5331       C1.divide(C2, APFloat::rmNearestTiesToEven);
5332       return getConstantFP(C1, DL, VT);
5333     case ISD::FREM:
5334       C1.mod(C2);
5335       return getConstantFP(C1, DL, VT);
5336     case ISD::FCOPYSIGN:
5337       C1.copySign(C2);
5338       return getConstantFP(C1, DL, VT);
5339     default: break;
5340     }
5341   }
5342   if (N1CFP && Opcode == ISD::FP_ROUND) {
5343     APFloat C1 = N1CFP->getValueAPF();    // make copy
5344     bool Unused;
5345     // This can return overflow, underflow, or inexact; we don't care.
5346     // FIXME need to be more flexible about rounding mode.
5347     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5348                       &Unused);
5349     return getConstantFP(C1, DL, VT);
5350   }
5351 
5352   switch (Opcode) {
5353   case ISD::FSUB:
5354     // -0.0 - undef --> undef (consistent with "fneg undef")
5355     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5356       return getUNDEF(VT);
5357     LLVM_FALLTHROUGH;
5358 
5359   case ISD::FADD:
5360   case ISD::FMUL:
5361   case ISD::FDIV:
5362   case ISD::FREM:
5363     // If both operands are undef, the result is undef. If 1 operand is undef,
5364     // the result is NaN. This should match the behavior of the IR optimizer.
5365     if (N1.isUndef() && N2.isUndef())
5366       return getUNDEF(VT);
5367     if (N1.isUndef() || N2.isUndef())
5368       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5369   }
5370   return SDValue();
5371 }
5372 
5373 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5374   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5375 
5376   // There's no need to assert on a byte-aligned pointer. All pointers are at
5377   // least byte aligned.
5378   if (A == Align(1))
5379     return Val;
5380 
5381   FoldingSetNodeID ID;
5382   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5383   ID.AddInteger(A.value());
5384 
5385   void *IP = nullptr;
5386   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5387     return SDValue(E, 0);
5388 
5389   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5390                                          Val.getValueType(), A);
5391   createOperands(N, {Val});
5392 
5393   CSEMap.InsertNode(N, IP);
5394   InsertNode(N);
5395 
5396   SDValue V(N, 0);
5397   NewSDValueDbgMsg(V, "Creating new node: ", this);
5398   return V;
5399 }
5400 
5401 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5402                               SDValue N1, SDValue N2) {
5403   SDNodeFlags Flags;
5404   if (Inserter)
5405     Flags = Inserter->getFlags();
5406   return getNode(Opcode, DL, VT, N1, N2, Flags);
5407 }
5408 
5409 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5410                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5411   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5412          N2.getOpcode() != ISD::DELETED_NODE &&
5413          "Operand is DELETED_NODE!");
5414   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5415   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5416   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5417   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5418 
5419   // Canonicalize constant to RHS if commutative.
5420   if (TLI->isCommutativeBinOp(Opcode)) {
5421     if (N1C && !N2C) {
5422       std::swap(N1C, N2C);
5423       std::swap(N1, N2);
5424     } else if (N1CFP && !N2CFP) {
5425       std::swap(N1CFP, N2CFP);
5426       std::swap(N1, N2);
5427     }
5428   }
5429 
5430   switch (Opcode) {
5431   default: break;
5432   case ISD::TokenFactor:
5433     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5434            N2.getValueType() == MVT::Other && "Invalid token factor!");
5435     // Fold trivial token factors.
5436     if (N1.getOpcode() == ISD::EntryToken) return N2;
5437     if (N2.getOpcode() == ISD::EntryToken) return N1;
5438     if (N1 == N2) return N1;
5439     break;
5440   case ISD::BUILD_VECTOR: {
5441     // Attempt to simplify BUILD_VECTOR.
5442     SDValue Ops[] = {N1, N2};
5443     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5444       return V;
5445     break;
5446   }
5447   case ISD::CONCAT_VECTORS: {
5448     SDValue Ops[] = {N1, N2};
5449     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5450       return V;
5451     break;
5452   }
5453   case ISD::AND:
5454     assert(VT.isInteger() && "This operator does not apply to FP types!");
5455     assert(N1.getValueType() == N2.getValueType() &&
5456            N1.getValueType() == VT && "Binary operator types must match!");
5457     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5458     // worth handling here.
5459     if (N2C && N2C->isNullValue())
5460       return N2;
5461     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
5462       return N1;
5463     break;
5464   case ISD::OR:
5465   case ISD::XOR:
5466   case ISD::ADD:
5467   case ISD::SUB:
5468     assert(VT.isInteger() && "This operator does not apply to FP types!");
5469     assert(N1.getValueType() == N2.getValueType() &&
5470            N1.getValueType() == VT && "Binary operator types must match!");
5471     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5472     // it's worth handling here.
5473     if (N2C && N2C->isNullValue())
5474       return N1;
5475     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5476         VT.getVectorElementType() == MVT::i1)
5477       return getNode(ISD::XOR, DL, VT, N1, N2);
5478     break;
5479   case ISD::MUL:
5480     assert(VT.isInteger() && "This operator does not apply to FP types!");
5481     assert(N1.getValueType() == N2.getValueType() &&
5482            N1.getValueType() == VT && "Binary operator types must match!");
5483     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5484       return getNode(ISD::AND, DL, VT, N1, N2);
5485     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5486       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5487       const APInt &N2CImm = N2C->getAPIntValue();
5488       return getVScale(DL, VT, MulImm * N2CImm);
5489     }
5490     break;
5491   case ISD::UDIV:
5492   case ISD::UREM:
5493   case ISD::MULHU:
5494   case ISD::MULHS:
5495   case ISD::SDIV:
5496   case ISD::SREM:
5497   case ISD::SADDSAT:
5498   case ISD::SSUBSAT:
5499   case ISD::UADDSAT:
5500   case ISD::USUBSAT:
5501     assert(VT.isInteger() && "This operator does not apply to FP types!");
5502     assert(N1.getValueType() == N2.getValueType() &&
5503            N1.getValueType() == VT && "Binary operator types must match!");
5504     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5505       // fold (add_sat x, y) -> (or x, y) for bool types.
5506       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5507         return getNode(ISD::OR, DL, VT, N1, N2);
5508       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5509       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5510         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5511     }
5512     break;
5513   case ISD::SMIN:
5514   case ISD::UMAX:
5515     assert(VT.isInteger() && "This operator does not apply to FP types!");
5516     assert(N1.getValueType() == N2.getValueType() &&
5517            N1.getValueType() == VT && "Binary operator types must match!");
5518     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5519       return getNode(ISD::OR, DL, VT, N1, N2);
5520     break;
5521   case ISD::SMAX:
5522   case ISD::UMIN:
5523     assert(VT.isInteger() && "This operator does not apply to FP types!");
5524     assert(N1.getValueType() == N2.getValueType() &&
5525            N1.getValueType() == VT && "Binary operator types must match!");
5526     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5527       return getNode(ISD::AND, DL, VT, N1, N2);
5528     break;
5529   case ISD::FADD:
5530   case ISD::FSUB:
5531   case ISD::FMUL:
5532   case ISD::FDIV:
5533   case ISD::FREM:
5534     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5535     assert(N1.getValueType() == N2.getValueType() &&
5536            N1.getValueType() == VT && "Binary operator types must match!");
5537     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5538       return V;
5539     break;
5540   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5541     assert(N1.getValueType() == VT &&
5542            N1.getValueType().isFloatingPoint() &&
5543            N2.getValueType().isFloatingPoint() &&
5544            "Invalid FCOPYSIGN!");
5545     break;
5546   case ISD::SHL:
5547     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5548       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5549       const APInt &ShiftImm = N2C->getAPIntValue();
5550       return getVScale(DL, VT, MulImm << ShiftImm);
5551     }
5552     LLVM_FALLTHROUGH;
5553   case ISD::SRA:
5554   case ISD::SRL:
5555     if (SDValue V = simplifyShift(N1, N2))
5556       return V;
5557     LLVM_FALLTHROUGH;
5558   case ISD::ROTL:
5559   case ISD::ROTR:
5560     assert(VT == N1.getValueType() &&
5561            "Shift operators return type must be the same as their first arg");
5562     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5563            "Shifts only work on integers");
5564     assert((!VT.isVector() || VT == N2.getValueType()) &&
5565            "Vector shift amounts must be in the same as their first arg");
5566     // Verify that the shift amount VT is big enough to hold valid shift
5567     // amounts.  This catches things like trying to shift an i1024 value by an
5568     // i8, which is easy to fall into in generic code that uses
5569     // TLI.getShiftAmount().
5570     assert(N2.getValueType().getScalarSizeInBits() >=
5571                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5572            "Invalid use of small shift amount with oversized value!");
5573 
5574     // Always fold shifts of i1 values so the code generator doesn't need to
5575     // handle them.  Since we know the size of the shift has to be less than the
5576     // size of the value, the shift/rotate count is guaranteed to be zero.
5577     if (VT == MVT::i1)
5578       return N1;
5579     if (N2C && N2C->isNullValue())
5580       return N1;
5581     break;
5582   case ISD::FP_ROUND:
5583     assert(VT.isFloatingPoint() &&
5584            N1.getValueType().isFloatingPoint() &&
5585            VT.bitsLE(N1.getValueType()) &&
5586            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5587            "Invalid FP_ROUND!");
5588     if (N1.getValueType() == VT) return N1;  // noop conversion.
5589     break;
5590   case ISD::AssertSext:
5591   case ISD::AssertZext: {
5592     EVT EVT = cast<VTSDNode>(N2)->getVT();
5593     assert(VT == N1.getValueType() && "Not an inreg extend!");
5594     assert(VT.isInteger() && EVT.isInteger() &&
5595            "Cannot *_EXTEND_INREG FP types");
5596     assert(!EVT.isVector() &&
5597            "AssertSExt/AssertZExt type should be the vector element type "
5598            "rather than the vector type!");
5599     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5600     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5601     break;
5602   }
5603   case ISD::SIGN_EXTEND_INREG: {
5604     EVT EVT = cast<VTSDNode>(N2)->getVT();
5605     assert(VT == N1.getValueType() && "Not an inreg extend!");
5606     assert(VT.isInteger() && EVT.isInteger() &&
5607            "Cannot *_EXTEND_INREG FP types");
5608     assert(EVT.isVector() == VT.isVector() &&
5609            "SIGN_EXTEND_INREG type should be vector iff the operand "
5610            "type is vector!");
5611     assert((!EVT.isVector() ||
5612             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5613            "Vector element counts must match in SIGN_EXTEND_INREG");
5614     assert(EVT.bitsLE(VT) && "Not extending!");
5615     if (EVT == VT) return N1;  // Not actually extending
5616 
5617     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5618       unsigned FromBits = EVT.getScalarSizeInBits();
5619       Val <<= Val.getBitWidth() - FromBits;
5620       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5621       return getConstant(Val, DL, ConstantVT);
5622     };
5623 
5624     if (N1C) {
5625       const APInt &Val = N1C->getAPIntValue();
5626       return SignExtendInReg(Val, VT);
5627     }
5628     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5629       SmallVector<SDValue, 8> Ops;
5630       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5631       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5632         SDValue Op = N1.getOperand(i);
5633         if (Op.isUndef()) {
5634           Ops.push_back(getUNDEF(OpVT));
5635           continue;
5636         }
5637         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5638         APInt Val = C->getAPIntValue();
5639         Ops.push_back(SignExtendInReg(Val, OpVT));
5640       }
5641       return getBuildVector(VT, DL, Ops);
5642     }
5643     break;
5644   }
5645   case ISD::EXTRACT_VECTOR_ELT:
5646     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5647            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5648              element type of the vector.");
5649 
5650     // Extract from an undefined value or using an undefined index is undefined.
5651     if (N1.isUndef() || N2.isUndef())
5652       return getUNDEF(VT);
5653 
5654     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5655     // vectors. For scalable vectors we will provide appropriate support for
5656     // dealing with arbitrary indices.
5657     if (N2C && N1.getValueType().isFixedLengthVector() &&
5658         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5659       return getUNDEF(VT);
5660 
5661     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5662     // expanding copies of large vectors from registers. This only works for
5663     // fixed length vectors, since we need to know the exact number of
5664     // elements.
5665     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5666         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5667       unsigned Factor =
5668         N1.getOperand(0).getValueType().getVectorNumElements();
5669       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5670                      N1.getOperand(N2C->getZExtValue() / Factor),
5671                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5672     }
5673 
5674     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5675     // lowering is expanding large vector constants.
5676     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5677                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5678       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5679               N1.getValueType().isFixedLengthVector()) &&
5680              "BUILD_VECTOR used for scalable vectors");
5681       unsigned Index =
5682           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5683       SDValue Elt = N1.getOperand(Index);
5684 
5685       if (VT != Elt.getValueType())
5686         // If the vector element type is not legal, the BUILD_VECTOR operands
5687         // are promoted and implicitly truncated, and the result implicitly
5688         // extended. Make that explicit here.
5689         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5690 
5691       return Elt;
5692     }
5693 
5694     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5695     // operations are lowered to scalars.
5696     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5697       // If the indices are the same, return the inserted element else
5698       // if the indices are known different, extract the element from
5699       // the original vector.
5700       SDValue N1Op2 = N1.getOperand(2);
5701       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5702 
5703       if (N1Op2C && N2C) {
5704         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5705           if (VT == N1.getOperand(1).getValueType())
5706             return N1.getOperand(1);
5707           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5708         }
5709         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5710       }
5711     }
5712 
5713     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5714     // when vector types are scalarized and v1iX is legal.
5715     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5716     // Here we are completely ignoring the extract element index (N2),
5717     // which is fine for fixed width vectors, since any index other than 0
5718     // is undefined anyway. However, this cannot be ignored for scalable
5719     // vectors - in theory we could support this, but we don't want to do this
5720     // without a profitability check.
5721     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5722         N1.getValueType().isFixedLengthVector() &&
5723         N1.getValueType().getVectorNumElements() == 1) {
5724       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5725                      N1.getOperand(1));
5726     }
5727     break;
5728   case ISD::EXTRACT_ELEMENT:
5729     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5730     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5731            (N1.getValueType().isInteger() == VT.isInteger()) &&
5732            N1.getValueType() != VT &&
5733            "Wrong types for EXTRACT_ELEMENT!");
5734 
5735     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5736     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5737     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5738     if (N1.getOpcode() == ISD::BUILD_PAIR)
5739       return N1.getOperand(N2C->getZExtValue());
5740 
5741     // EXTRACT_ELEMENT of a constant int is also very common.
5742     if (N1C) {
5743       unsigned ElementSize = VT.getSizeInBits();
5744       unsigned Shift = ElementSize * N2C->getZExtValue();
5745       const APInt &Val = N1C->getAPIntValue();
5746       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5747     }
5748     break;
5749   case ISD::EXTRACT_SUBVECTOR:
5750     EVT N1VT = N1.getValueType();
5751     assert(VT.isVector() && N1VT.isVector() &&
5752            "Extract subvector VTs must be vectors!");
5753     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5754            "Extract subvector VTs must have the same element type!");
5755     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5756            "Cannot extract a scalable vector from a fixed length vector!");
5757     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5758             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5759            "Extract subvector must be from larger vector to smaller vector!");
5760     assert(N2C && "Extract subvector index must be a constant");
5761     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5762             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5763                 N1VT.getVectorMinNumElements()) &&
5764            "Extract subvector overflow!");
5765     assert(N2C->getAPIntValue().getBitWidth() ==
5766                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5767            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5768 
5769     // Trivial extraction.
5770     if (VT == N1VT)
5771       return N1;
5772 
5773     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5774     if (N1.isUndef())
5775       return getUNDEF(VT);
5776 
5777     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5778     // the concat have the same type as the extract.
5779     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5780         VT == N1.getOperand(0).getValueType()) {
5781       unsigned Factor = VT.getVectorMinNumElements();
5782       return N1.getOperand(N2C->getZExtValue() / Factor);
5783     }
5784 
5785     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5786     // during shuffle legalization.
5787     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5788         VT == N1.getOperand(1).getValueType())
5789       return N1.getOperand(1);
5790     break;
5791   }
5792 
5793   // Perform trivial constant folding.
5794   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5795     return SV;
5796 
5797   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5798     return V;
5799 
5800   // Canonicalize an UNDEF to the RHS, even over a constant.
5801   if (N1.isUndef()) {
5802     if (TLI->isCommutativeBinOp(Opcode)) {
5803       std::swap(N1, N2);
5804     } else {
5805       switch (Opcode) {
5806       case ISD::SIGN_EXTEND_INREG:
5807       case ISD::SUB:
5808         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5809       case ISD::UDIV:
5810       case ISD::SDIV:
5811       case ISD::UREM:
5812       case ISD::SREM:
5813       case ISD::SSUBSAT:
5814       case ISD::USUBSAT:
5815         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5816       }
5817     }
5818   }
5819 
5820   // Fold a bunch of operators when the RHS is undef.
5821   if (N2.isUndef()) {
5822     switch (Opcode) {
5823     case ISD::XOR:
5824       if (N1.isUndef())
5825         // Handle undef ^ undef -> 0 special case. This is a common
5826         // idiom (misuse).
5827         return getConstant(0, DL, VT);
5828       LLVM_FALLTHROUGH;
5829     case ISD::ADD:
5830     case ISD::SUB:
5831     case ISD::UDIV:
5832     case ISD::SDIV:
5833     case ISD::UREM:
5834     case ISD::SREM:
5835       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5836     case ISD::MUL:
5837     case ISD::AND:
5838     case ISD::SSUBSAT:
5839     case ISD::USUBSAT:
5840       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5841     case ISD::OR:
5842     case ISD::SADDSAT:
5843     case ISD::UADDSAT:
5844       return getAllOnesConstant(DL, VT);
5845     }
5846   }
5847 
5848   // Memoize this node if possible.
5849   SDNode *N;
5850   SDVTList VTs = getVTList(VT);
5851   SDValue Ops[] = {N1, N2};
5852   if (VT != MVT::Glue) {
5853     FoldingSetNodeID ID;
5854     AddNodeIDNode(ID, Opcode, VTs, Ops);
5855     void *IP = nullptr;
5856     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5857       E->intersectFlagsWith(Flags);
5858       return SDValue(E, 0);
5859     }
5860 
5861     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5862     N->setFlags(Flags);
5863     createOperands(N, Ops);
5864     CSEMap.InsertNode(N, IP);
5865   } else {
5866     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5867     createOperands(N, Ops);
5868   }
5869 
5870   InsertNode(N);
5871   SDValue V = SDValue(N, 0);
5872   NewSDValueDbgMsg(V, "Creating new node: ", this);
5873   return V;
5874 }
5875 
5876 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5877                               SDValue N1, SDValue N2, SDValue N3) {
5878   SDNodeFlags Flags;
5879   if (Inserter)
5880     Flags = Inserter->getFlags();
5881   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
5882 }
5883 
5884 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5885                               SDValue N1, SDValue N2, SDValue N3,
5886                               const SDNodeFlags Flags) {
5887   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5888          N2.getOpcode() != ISD::DELETED_NODE &&
5889          N3.getOpcode() != ISD::DELETED_NODE &&
5890          "Operand is DELETED_NODE!");
5891   // Perform various simplifications.
5892   switch (Opcode) {
5893   case ISD::FMA: {
5894     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5895     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5896            N3.getValueType() == VT && "FMA types must match!");
5897     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5898     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5899     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5900     if (N1CFP && N2CFP && N3CFP) {
5901       APFloat  V1 = N1CFP->getValueAPF();
5902       const APFloat &V2 = N2CFP->getValueAPF();
5903       const APFloat &V3 = N3CFP->getValueAPF();
5904       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
5905       return getConstantFP(V1, DL, VT);
5906     }
5907     break;
5908   }
5909   case ISD::BUILD_VECTOR: {
5910     // Attempt to simplify BUILD_VECTOR.
5911     SDValue Ops[] = {N1, N2, N3};
5912     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5913       return V;
5914     break;
5915   }
5916   case ISD::CONCAT_VECTORS: {
5917     SDValue Ops[] = {N1, N2, N3};
5918     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5919       return V;
5920     break;
5921   }
5922   case ISD::SETCC: {
5923     assert(VT.isInteger() && "SETCC result type must be an integer!");
5924     assert(N1.getValueType() == N2.getValueType() &&
5925            "SETCC operands must have the same type!");
5926     assert(VT.isVector() == N1.getValueType().isVector() &&
5927            "SETCC type should be vector iff the operand type is vector!");
5928     assert((!VT.isVector() || VT.getVectorElementCount() ==
5929                                   N1.getValueType().getVectorElementCount()) &&
5930            "SETCC vector element counts must match!");
5931     // Use FoldSetCC to simplify SETCC's.
5932     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5933       return V;
5934     // Vector constant folding.
5935     SDValue Ops[] = {N1, N2, N3};
5936     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5937       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5938       return V;
5939     }
5940     break;
5941   }
5942   case ISD::SELECT:
5943   case ISD::VSELECT:
5944     if (SDValue V = simplifySelect(N1, N2, N3))
5945       return V;
5946     break;
5947   case ISD::VECTOR_SHUFFLE:
5948     llvm_unreachable("should use getVectorShuffle constructor!");
5949   case ISD::INSERT_VECTOR_ELT: {
5950     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5951     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
5952     // for scalable vectors where we will generate appropriate code to
5953     // deal with out-of-bounds cases correctly.
5954     if (N3C && N1.getValueType().isFixedLengthVector() &&
5955         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5956       return getUNDEF(VT);
5957 
5958     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
5959     if (N3.isUndef())
5960       return getUNDEF(VT);
5961 
5962     // If the inserted element is an UNDEF, just use the input vector.
5963     if (N2.isUndef())
5964       return N1;
5965 
5966     break;
5967   }
5968   case ISD::INSERT_SUBVECTOR: {
5969     // Inserting undef into undef is still undef.
5970     if (N1.isUndef() && N2.isUndef())
5971       return getUNDEF(VT);
5972 
5973     EVT N2VT = N2.getValueType();
5974     assert(VT == N1.getValueType() &&
5975            "Dest and insert subvector source types must match!");
5976     assert(VT.isVector() && N2VT.isVector() &&
5977            "Insert subvector VTs must be vectors!");
5978     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
5979            "Cannot insert a scalable vector into a fixed length vector!");
5980     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5981             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
5982            "Insert subvector must be from smaller vector to larger vector!");
5983     assert(isa<ConstantSDNode>(N3) &&
5984            "Insert subvector index must be constant");
5985     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5986             (N2VT.getVectorMinNumElements() +
5987              cast<ConstantSDNode>(N3)->getZExtValue()) <=
5988                 VT.getVectorMinNumElements()) &&
5989            "Insert subvector overflow!");
5990     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
5991                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5992            "Constant index for INSERT_SUBVECTOR has an invalid size");
5993 
5994     // Trivial insertion.
5995     if (VT == N2VT)
5996       return N2;
5997 
5998     // If this is an insert of an extracted vector into an undef vector, we
5999     // can just use the input to the extract.
6000     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6001         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6002       return N2.getOperand(0);
6003     break;
6004   }
6005   case ISD::BITCAST:
6006     // Fold bit_convert nodes from a type to themselves.
6007     if (N1.getValueType() == VT)
6008       return N1;
6009     break;
6010   }
6011 
6012   // Memoize node if it doesn't produce a flag.
6013   SDNode *N;
6014   SDVTList VTs = getVTList(VT);
6015   SDValue Ops[] = {N1, N2, N3};
6016   if (VT != MVT::Glue) {
6017     FoldingSetNodeID ID;
6018     AddNodeIDNode(ID, Opcode, VTs, Ops);
6019     void *IP = nullptr;
6020     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6021       E->intersectFlagsWith(Flags);
6022       return SDValue(E, 0);
6023     }
6024 
6025     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6026     N->setFlags(Flags);
6027     createOperands(N, Ops);
6028     CSEMap.InsertNode(N, IP);
6029   } else {
6030     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6031     createOperands(N, Ops);
6032   }
6033 
6034   InsertNode(N);
6035   SDValue V = SDValue(N, 0);
6036   NewSDValueDbgMsg(V, "Creating new node: ", this);
6037   return V;
6038 }
6039 
6040 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6041                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6042   SDValue Ops[] = { N1, N2, N3, N4 };
6043   return getNode(Opcode, DL, VT, Ops);
6044 }
6045 
6046 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6047                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6048                               SDValue N5) {
6049   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6050   return getNode(Opcode, DL, VT, Ops);
6051 }
6052 
6053 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6054 /// the incoming stack arguments to be loaded from the stack.
6055 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6056   SmallVector<SDValue, 8> ArgChains;
6057 
6058   // Include the original chain at the beginning of the list. When this is
6059   // used by target LowerCall hooks, this helps legalize find the
6060   // CALLSEQ_BEGIN node.
6061   ArgChains.push_back(Chain);
6062 
6063   // Add a chain value for each stack argument.
6064   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
6065        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
6066     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
6067       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6068         if (FI->getIndex() < 0)
6069           ArgChains.push_back(SDValue(L, 1));
6070 
6071   // Build a tokenfactor for all the chains.
6072   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6073 }
6074 
6075 /// getMemsetValue - Vectorized representation of the memset value
6076 /// operand.
6077 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6078                               const SDLoc &dl) {
6079   assert(!Value.isUndef());
6080 
6081   unsigned NumBits = VT.getScalarSizeInBits();
6082   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6083     assert(C->getAPIntValue().getBitWidth() == 8);
6084     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6085     if (VT.isInteger()) {
6086       bool IsOpaque = VT.getSizeInBits() > 64 ||
6087           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6088       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6089     }
6090     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6091                              VT);
6092   }
6093 
6094   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6095   EVT IntVT = VT.getScalarType();
6096   if (!IntVT.isInteger())
6097     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6098 
6099   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6100   if (NumBits > 8) {
6101     // Use a multiplication with 0x010101... to extend the input to the
6102     // required length.
6103     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6104     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6105                         DAG.getConstant(Magic, dl, IntVT));
6106   }
6107 
6108   if (VT != Value.getValueType() && !VT.isInteger())
6109     Value = DAG.getBitcast(VT.getScalarType(), Value);
6110   if (VT != Value.getValueType())
6111     Value = DAG.getSplatBuildVector(VT, dl, Value);
6112 
6113   return Value;
6114 }
6115 
6116 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6117 /// used when a memcpy is turned into a memset when the source is a constant
6118 /// string ptr.
6119 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6120                                   const TargetLowering &TLI,
6121                                   const ConstantDataArraySlice &Slice) {
6122   // Handle vector with all elements zero.
6123   if (Slice.Array == nullptr) {
6124     if (VT.isInteger())
6125       return DAG.getConstant(0, dl, VT);
6126     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6127       return DAG.getConstantFP(0.0, dl, VT);
6128     if (VT.isVector()) {
6129       unsigned NumElts = VT.getVectorNumElements();
6130       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6131       return DAG.getNode(ISD::BITCAST, dl, VT,
6132                          DAG.getConstant(0, dl,
6133                                          EVT::getVectorVT(*DAG.getContext(),
6134                                                           EltVT, NumElts)));
6135     }
6136     llvm_unreachable("Expected type!");
6137   }
6138 
6139   assert(!VT.isVector() && "Can't handle vector type here!");
6140   unsigned NumVTBits = VT.getSizeInBits();
6141   unsigned NumVTBytes = NumVTBits / 8;
6142   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6143 
6144   APInt Val(NumVTBits, 0);
6145   if (DAG.getDataLayout().isLittleEndian()) {
6146     for (unsigned i = 0; i != NumBytes; ++i)
6147       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6148   } else {
6149     for (unsigned i = 0; i != NumBytes; ++i)
6150       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6151   }
6152 
6153   // If the "cost" of materializing the integer immediate is less than the cost
6154   // of a load, then it is cost effective to turn the load into the immediate.
6155   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6156   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6157     return DAG.getConstant(Val, dl, VT);
6158   return SDValue(nullptr, 0);
6159 }
6160 
6161 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6162                                            const SDLoc &DL,
6163                                            const SDNodeFlags Flags) {
6164   EVT VT = Base.getValueType();
6165   SDValue Index;
6166 
6167   if (Offset.isScalable())
6168     Index = getVScale(DL, Base.getValueType(),
6169                       APInt(Base.getValueSizeInBits().getFixedSize(),
6170                             Offset.getKnownMinSize()));
6171   else
6172     Index = getConstant(Offset.getFixedSize(), DL, VT);
6173 
6174   return getMemBasePlusOffset(Base, Index, DL, Flags);
6175 }
6176 
6177 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6178                                            const SDLoc &DL,
6179                                            const SDNodeFlags Flags) {
6180   assert(Offset.getValueType().isInteger());
6181   EVT BasePtrVT = Ptr.getValueType();
6182   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6183 }
6184 
6185 /// Returns true if memcpy source is constant data.
6186 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6187   uint64_t SrcDelta = 0;
6188   GlobalAddressSDNode *G = nullptr;
6189   if (Src.getOpcode() == ISD::GlobalAddress)
6190     G = cast<GlobalAddressSDNode>(Src);
6191   else if (Src.getOpcode() == ISD::ADD &&
6192            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6193            Src.getOperand(1).getOpcode() == ISD::Constant) {
6194     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6195     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6196   }
6197   if (!G)
6198     return false;
6199 
6200   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6201                                   SrcDelta + G->getOffset());
6202 }
6203 
6204 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6205                                       SelectionDAG &DAG) {
6206   // On Darwin, -Os means optimize for size without hurting performance, so
6207   // only really optimize for size when -Oz (MinSize) is used.
6208   if (MF.getTarget().getTargetTriple().isOSDarwin())
6209     return MF.getFunction().hasMinSize();
6210   return DAG.shouldOptForSize();
6211 }
6212 
6213 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6214                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6215                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6216                           SmallVector<SDValue, 16> &OutStoreChains) {
6217   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6218   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6219   SmallVector<SDValue, 16> GluedLoadChains;
6220   for (unsigned i = From; i < To; ++i) {
6221     OutChains.push_back(OutLoadChains[i]);
6222     GluedLoadChains.push_back(OutLoadChains[i]);
6223   }
6224 
6225   // Chain for all loads.
6226   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6227                                   GluedLoadChains);
6228 
6229   for (unsigned i = From; i < To; ++i) {
6230     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6231     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6232                                   ST->getBasePtr(), ST->getMemoryVT(),
6233                                   ST->getMemOperand());
6234     OutChains.push_back(NewStore);
6235   }
6236 }
6237 
6238 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6239                                        SDValue Chain, SDValue Dst, SDValue Src,
6240                                        uint64_t Size, Align Alignment,
6241                                        bool isVol, bool AlwaysInline,
6242                                        MachinePointerInfo DstPtrInfo,
6243                                        MachinePointerInfo SrcPtrInfo) {
6244   // Turn a memcpy of undef to nop.
6245   // FIXME: We need to honor volatile even is Src is undef.
6246   if (Src.isUndef())
6247     return Chain;
6248 
6249   // Expand memcpy to a series of load and store ops if the size operand falls
6250   // below a certain threshold.
6251   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6252   // rather than maybe a humongous number of loads and stores.
6253   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6254   const DataLayout &DL = DAG.getDataLayout();
6255   LLVMContext &C = *DAG.getContext();
6256   std::vector<EVT> MemOps;
6257   bool DstAlignCanChange = false;
6258   MachineFunction &MF = DAG.getMachineFunction();
6259   MachineFrameInfo &MFI = MF.getFrameInfo();
6260   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6261   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6262   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6263     DstAlignCanChange = true;
6264   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6265   if (!SrcAlign || Alignment > *SrcAlign)
6266     SrcAlign = Alignment;
6267   assert(SrcAlign && "SrcAlign must be set");
6268   ConstantDataArraySlice Slice;
6269   // If marked as volatile, perform a copy even when marked as constant.
6270   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6271   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6272   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6273   const MemOp Op = isZeroConstant
6274                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6275                                     /*IsZeroMemset*/ true, isVol)
6276                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6277                                      *SrcAlign, isVol, CopyFromConstant);
6278   if (!TLI.findOptimalMemOpLowering(
6279           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6280           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6281     return SDValue();
6282 
6283   if (DstAlignCanChange) {
6284     Type *Ty = MemOps[0].getTypeForEVT(C);
6285     Align NewAlign = DL.getABITypeAlign(Ty);
6286 
6287     // Don't promote to an alignment that would require dynamic stack
6288     // realignment.
6289     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6290     if (!TRI->hasStackRealignment(MF))
6291       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6292         NewAlign = NewAlign / 2;
6293 
6294     if (NewAlign > Alignment) {
6295       // Give the stack frame object a larger alignment if needed.
6296       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6297         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6298       Alignment = NewAlign;
6299     }
6300   }
6301 
6302   MachineMemOperand::Flags MMOFlags =
6303       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6304   SmallVector<SDValue, 16> OutLoadChains;
6305   SmallVector<SDValue, 16> OutStoreChains;
6306   SmallVector<SDValue, 32> OutChains;
6307   unsigned NumMemOps = MemOps.size();
6308   uint64_t SrcOff = 0, DstOff = 0;
6309   for (unsigned i = 0; i != NumMemOps; ++i) {
6310     EVT VT = MemOps[i];
6311     unsigned VTSize = VT.getSizeInBits() / 8;
6312     SDValue Value, Store;
6313 
6314     if (VTSize > Size) {
6315       // Issuing an unaligned load / store pair  that overlaps with the previous
6316       // pair. Adjust the offset accordingly.
6317       assert(i == NumMemOps-1 && i != 0);
6318       SrcOff -= VTSize - Size;
6319       DstOff -= VTSize - Size;
6320     }
6321 
6322     if (CopyFromConstant &&
6323         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6324       // It's unlikely a store of a vector immediate can be done in a single
6325       // instruction. It would require a load from a constantpool first.
6326       // We only handle zero vectors here.
6327       // FIXME: Handle other cases where store of vector immediate is done in
6328       // a single instruction.
6329       ConstantDataArraySlice SubSlice;
6330       if (SrcOff < Slice.Length) {
6331         SubSlice = Slice;
6332         SubSlice.move(SrcOff);
6333       } else {
6334         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6335         SubSlice.Array = nullptr;
6336         SubSlice.Offset = 0;
6337         SubSlice.Length = VTSize;
6338       }
6339       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6340       if (Value.getNode()) {
6341         Store = DAG.getStore(
6342             Chain, dl, Value,
6343             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6344             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags);
6345         OutChains.push_back(Store);
6346       }
6347     }
6348 
6349     if (!Store.getNode()) {
6350       // The type might not be legal for the target.  This should only happen
6351       // if the type is smaller than a legal type, as on PPC, so the right
6352       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6353       // to Load/Store if NVT==VT.
6354       // FIXME does the case above also need this?
6355       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6356       assert(NVT.bitsGE(VT));
6357 
6358       bool isDereferenceable =
6359         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6360       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6361       if (isDereferenceable)
6362         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6363 
6364       Value = DAG.getExtLoad(
6365           ISD::EXTLOAD, dl, NVT, Chain,
6366           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6367           SrcPtrInfo.getWithOffset(SrcOff), VT,
6368           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags);
6369       OutLoadChains.push_back(Value.getValue(1));
6370 
6371       Store = DAG.getTruncStore(
6372           Chain, dl, Value,
6373           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6374           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags);
6375       OutStoreChains.push_back(Store);
6376     }
6377     SrcOff += VTSize;
6378     DstOff += VTSize;
6379     Size -= VTSize;
6380   }
6381 
6382   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6383                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6384   unsigned NumLdStInMemcpy = OutStoreChains.size();
6385 
6386   if (NumLdStInMemcpy) {
6387     // It may be that memcpy might be converted to memset if it's memcpy
6388     // of constants. In such a case, we won't have loads and stores, but
6389     // just stores. In the absence of loads, there is nothing to gang up.
6390     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6391       // If target does not care, just leave as it.
6392       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6393         OutChains.push_back(OutLoadChains[i]);
6394         OutChains.push_back(OutStoreChains[i]);
6395       }
6396     } else {
6397       // Ld/St less than/equal limit set by target.
6398       if (NumLdStInMemcpy <= GluedLdStLimit) {
6399           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6400                                         NumLdStInMemcpy, OutLoadChains,
6401                                         OutStoreChains);
6402       } else {
6403         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6404         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6405         unsigned GlueIter = 0;
6406 
6407         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6408           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6409           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6410 
6411           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6412                                        OutLoadChains, OutStoreChains);
6413           GlueIter += GluedLdStLimit;
6414         }
6415 
6416         // Residual ld/st.
6417         if (RemainingLdStInMemcpy) {
6418           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6419                                         RemainingLdStInMemcpy, OutLoadChains,
6420                                         OutStoreChains);
6421         }
6422       }
6423     }
6424   }
6425   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6426 }
6427 
6428 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6429                                         SDValue Chain, SDValue Dst, SDValue Src,
6430                                         uint64_t Size, Align Alignment,
6431                                         bool isVol, bool AlwaysInline,
6432                                         MachinePointerInfo DstPtrInfo,
6433                                         MachinePointerInfo SrcPtrInfo) {
6434   // Turn a memmove of undef to nop.
6435   // FIXME: We need to honor volatile even is Src is undef.
6436   if (Src.isUndef())
6437     return Chain;
6438 
6439   // Expand memmove to a series of load and store ops if the size operand falls
6440   // below a certain threshold.
6441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6442   const DataLayout &DL = DAG.getDataLayout();
6443   LLVMContext &C = *DAG.getContext();
6444   std::vector<EVT> MemOps;
6445   bool DstAlignCanChange = false;
6446   MachineFunction &MF = DAG.getMachineFunction();
6447   MachineFrameInfo &MFI = MF.getFrameInfo();
6448   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6449   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6450   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6451     DstAlignCanChange = true;
6452   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6453   if (!SrcAlign || Alignment > *SrcAlign)
6454     SrcAlign = Alignment;
6455   assert(SrcAlign && "SrcAlign must be set");
6456   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6457   if (!TLI.findOptimalMemOpLowering(
6458           MemOps, Limit,
6459           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6460                       /*IsVolatile*/ true),
6461           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6462           MF.getFunction().getAttributes()))
6463     return SDValue();
6464 
6465   if (DstAlignCanChange) {
6466     Type *Ty = MemOps[0].getTypeForEVT(C);
6467     Align NewAlign = DL.getABITypeAlign(Ty);
6468     if (NewAlign > Alignment) {
6469       // Give the stack frame object a larger alignment if needed.
6470       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6471         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6472       Alignment = NewAlign;
6473     }
6474   }
6475 
6476   MachineMemOperand::Flags MMOFlags =
6477       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6478   uint64_t SrcOff = 0, DstOff = 0;
6479   SmallVector<SDValue, 8> LoadValues;
6480   SmallVector<SDValue, 8> LoadChains;
6481   SmallVector<SDValue, 8> OutChains;
6482   unsigned NumMemOps = MemOps.size();
6483   for (unsigned i = 0; i < NumMemOps; i++) {
6484     EVT VT = MemOps[i];
6485     unsigned VTSize = VT.getSizeInBits() / 8;
6486     SDValue Value;
6487 
6488     bool isDereferenceable =
6489       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6490     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6491     if (isDereferenceable)
6492       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6493 
6494     Value =
6495         DAG.getLoad(VT, dl, Chain,
6496                     DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6497                     SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags);
6498     LoadValues.push_back(Value);
6499     LoadChains.push_back(Value.getValue(1));
6500     SrcOff += VTSize;
6501   }
6502   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6503   OutChains.clear();
6504   for (unsigned i = 0; i < NumMemOps; i++) {
6505     EVT VT = MemOps[i];
6506     unsigned VTSize = VT.getSizeInBits() / 8;
6507     SDValue Store;
6508 
6509     Store =
6510         DAG.getStore(Chain, dl, LoadValues[i],
6511                      DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6512                      DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags);
6513     OutChains.push_back(Store);
6514     DstOff += VTSize;
6515   }
6516 
6517   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6518 }
6519 
6520 /// Lower the call to 'memset' intrinsic function into a series of store
6521 /// operations.
6522 ///
6523 /// \param DAG Selection DAG where lowered code is placed.
6524 /// \param dl Link to corresponding IR location.
6525 /// \param Chain Control flow dependency.
6526 /// \param Dst Pointer to destination memory location.
6527 /// \param Src Value of byte to write into the memory.
6528 /// \param Size Number of bytes to write.
6529 /// \param Alignment Alignment of the destination in bytes.
6530 /// \param isVol True if destination is volatile.
6531 /// \param DstPtrInfo IR information on the memory pointer.
6532 /// \returns New head in the control flow, if lowering was successful, empty
6533 /// SDValue otherwise.
6534 ///
6535 /// The function tries to replace 'llvm.memset' intrinsic with several store
6536 /// operations and value calculation code. This is usually profitable for small
6537 /// memory size.
6538 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6539                                SDValue Chain, SDValue Dst, SDValue Src,
6540                                uint64_t Size, Align Alignment, bool isVol,
6541                                MachinePointerInfo DstPtrInfo) {
6542   // Turn a memset of undef to nop.
6543   // FIXME: We need to honor volatile even is Src is undef.
6544   if (Src.isUndef())
6545     return Chain;
6546 
6547   // Expand memset to a series of load/store ops if the size operand
6548   // falls below a certain threshold.
6549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6550   std::vector<EVT> MemOps;
6551   bool DstAlignCanChange = false;
6552   MachineFunction &MF = DAG.getMachineFunction();
6553   MachineFrameInfo &MFI = MF.getFrameInfo();
6554   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6555   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6556   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6557     DstAlignCanChange = true;
6558   bool IsZeroVal =
6559     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6560   if (!TLI.findOptimalMemOpLowering(
6561           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6562           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6563           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6564     return SDValue();
6565 
6566   if (DstAlignCanChange) {
6567     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6568     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6569     if (NewAlign > Alignment) {
6570       // Give the stack frame object a larger alignment if needed.
6571       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6572         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6573       Alignment = NewAlign;
6574     }
6575   }
6576 
6577   SmallVector<SDValue, 8> OutChains;
6578   uint64_t DstOff = 0;
6579   unsigned NumMemOps = MemOps.size();
6580 
6581   // Find the largest store and generate the bit pattern for it.
6582   EVT LargestVT = MemOps[0];
6583   for (unsigned i = 1; i < NumMemOps; i++)
6584     if (MemOps[i].bitsGT(LargestVT))
6585       LargestVT = MemOps[i];
6586   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6587 
6588   for (unsigned i = 0; i < NumMemOps; i++) {
6589     EVT VT = MemOps[i];
6590     unsigned VTSize = VT.getSizeInBits() / 8;
6591     if (VTSize > Size) {
6592       // Issuing an unaligned load / store pair  that overlaps with the previous
6593       // pair. Adjust the offset accordingly.
6594       assert(i == NumMemOps-1 && i != 0);
6595       DstOff -= VTSize - Size;
6596     }
6597 
6598     // If this store is smaller than the largest store see whether we can get
6599     // the smaller value for free with a truncate.
6600     SDValue Value = MemSetValue;
6601     if (VT.bitsLT(LargestVT)) {
6602       if (!LargestVT.isVector() && !VT.isVector() &&
6603           TLI.isTruncateFree(LargestVT, VT))
6604         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6605       else
6606         Value = getMemsetValue(Src, VT, DAG, dl);
6607     }
6608     assert(Value.getValueType() == VT && "Value with wrong type.");
6609     SDValue Store = DAG.getStore(
6610         Chain, dl, Value,
6611         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6612         DstPtrInfo.getWithOffset(DstOff), Alignment,
6613         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
6614     OutChains.push_back(Store);
6615     DstOff += VT.getSizeInBits() / 8;
6616     Size -= VTSize;
6617   }
6618 
6619   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6620 }
6621 
6622 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6623                                             unsigned AS) {
6624   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6625   // pointer operands can be losslessly bitcasted to pointers of address space 0
6626   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6627     report_fatal_error("cannot lower memory intrinsic in address space " +
6628                        Twine(AS));
6629   }
6630 }
6631 
6632 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6633                                 SDValue Src, SDValue Size, Align Alignment,
6634                                 bool isVol, bool AlwaysInline, bool isTailCall,
6635                                 MachinePointerInfo DstPtrInfo,
6636                                 MachinePointerInfo SrcPtrInfo) {
6637   // Check to see if we should lower the memcpy to loads and stores first.
6638   // For cases within the target-specified limits, this is the best choice.
6639   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6640   if (ConstantSize) {
6641     // Memcpy with size zero? Just return the original chain.
6642     if (ConstantSize->isNullValue())
6643       return Chain;
6644 
6645     SDValue Result = getMemcpyLoadsAndStores(
6646         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6647         isVol, false, DstPtrInfo, SrcPtrInfo);
6648     if (Result.getNode())
6649       return Result;
6650   }
6651 
6652   // Then check to see if we should lower the memcpy with target-specific
6653   // code. If the target chooses to do this, this is the next best.
6654   if (TSI) {
6655     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6656         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6657         DstPtrInfo, SrcPtrInfo);
6658     if (Result.getNode())
6659       return Result;
6660   }
6661 
6662   // If we really need inline code and the target declined to provide it,
6663   // use a (potentially long) sequence of loads and stores.
6664   if (AlwaysInline) {
6665     assert(ConstantSize && "AlwaysInline requires a constant size!");
6666     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6667                                    ConstantSize->getZExtValue(), Alignment,
6668                                    isVol, true, DstPtrInfo, SrcPtrInfo);
6669   }
6670 
6671   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6672   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6673 
6674   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6675   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6676   // respect volatile, so they may do things like read or write memory
6677   // beyond the given memory regions. But fixing this isn't easy, and most
6678   // people don't care.
6679 
6680   // Emit a library call.
6681   TargetLowering::ArgListTy Args;
6682   TargetLowering::ArgListEntry Entry;
6683   Entry.Ty = Type::getInt8PtrTy(*getContext());
6684   Entry.Node = Dst; Args.push_back(Entry);
6685   Entry.Node = Src; Args.push_back(Entry);
6686 
6687   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6688   Entry.Node = Size; Args.push_back(Entry);
6689   // FIXME: pass in SDLoc
6690   TargetLowering::CallLoweringInfo CLI(*this);
6691   CLI.setDebugLoc(dl)
6692       .setChain(Chain)
6693       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6694                     Dst.getValueType().getTypeForEVT(*getContext()),
6695                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6696                                       TLI->getPointerTy(getDataLayout())),
6697                     std::move(Args))
6698       .setDiscardResult()
6699       .setTailCall(isTailCall);
6700 
6701   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6702   return CallResult.second;
6703 }
6704 
6705 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6706                                       SDValue Dst, unsigned DstAlign,
6707                                       SDValue Src, unsigned SrcAlign,
6708                                       SDValue Size, Type *SizeTy,
6709                                       unsigned ElemSz, bool isTailCall,
6710                                       MachinePointerInfo DstPtrInfo,
6711                                       MachinePointerInfo SrcPtrInfo) {
6712   // Emit a library call.
6713   TargetLowering::ArgListTy Args;
6714   TargetLowering::ArgListEntry Entry;
6715   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6716   Entry.Node = Dst;
6717   Args.push_back(Entry);
6718 
6719   Entry.Node = Src;
6720   Args.push_back(Entry);
6721 
6722   Entry.Ty = SizeTy;
6723   Entry.Node = Size;
6724   Args.push_back(Entry);
6725 
6726   RTLIB::Libcall LibraryCall =
6727       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6728   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6729     report_fatal_error("Unsupported element size");
6730 
6731   TargetLowering::CallLoweringInfo CLI(*this);
6732   CLI.setDebugLoc(dl)
6733       .setChain(Chain)
6734       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6735                     Type::getVoidTy(*getContext()),
6736                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6737                                       TLI->getPointerTy(getDataLayout())),
6738                     std::move(Args))
6739       .setDiscardResult()
6740       .setTailCall(isTailCall);
6741 
6742   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6743   return CallResult.second;
6744 }
6745 
6746 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6747                                  SDValue Src, SDValue Size, Align Alignment,
6748                                  bool isVol, bool isTailCall,
6749                                  MachinePointerInfo DstPtrInfo,
6750                                  MachinePointerInfo SrcPtrInfo) {
6751   // Check to see if we should lower the memmove to loads and stores first.
6752   // For cases within the target-specified limits, this is the best choice.
6753   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6754   if (ConstantSize) {
6755     // Memmove with size zero? Just return the original chain.
6756     if (ConstantSize->isNullValue())
6757       return Chain;
6758 
6759     SDValue Result = getMemmoveLoadsAndStores(
6760         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6761         isVol, false, DstPtrInfo, SrcPtrInfo);
6762     if (Result.getNode())
6763       return Result;
6764   }
6765 
6766   // Then check to see if we should lower the memmove with target-specific
6767   // code. If the target chooses to do this, this is the next best.
6768   if (TSI) {
6769     SDValue Result =
6770         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6771                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6772     if (Result.getNode())
6773       return Result;
6774   }
6775 
6776   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6777   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6778 
6779   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6780   // not be safe.  See memcpy above for more details.
6781 
6782   // Emit a library call.
6783   TargetLowering::ArgListTy Args;
6784   TargetLowering::ArgListEntry Entry;
6785   Entry.Ty = Type::getInt8PtrTy(*getContext());
6786   Entry.Node = Dst; Args.push_back(Entry);
6787   Entry.Node = Src; Args.push_back(Entry);
6788 
6789   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6790   Entry.Node = Size; Args.push_back(Entry);
6791   // FIXME:  pass in SDLoc
6792   TargetLowering::CallLoweringInfo CLI(*this);
6793   CLI.setDebugLoc(dl)
6794       .setChain(Chain)
6795       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6796                     Dst.getValueType().getTypeForEVT(*getContext()),
6797                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6798                                       TLI->getPointerTy(getDataLayout())),
6799                     std::move(Args))
6800       .setDiscardResult()
6801       .setTailCall(isTailCall);
6802 
6803   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6804   return CallResult.second;
6805 }
6806 
6807 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6808                                        SDValue Dst, unsigned DstAlign,
6809                                        SDValue Src, unsigned SrcAlign,
6810                                        SDValue Size, Type *SizeTy,
6811                                        unsigned ElemSz, bool isTailCall,
6812                                        MachinePointerInfo DstPtrInfo,
6813                                        MachinePointerInfo SrcPtrInfo) {
6814   // Emit a library call.
6815   TargetLowering::ArgListTy Args;
6816   TargetLowering::ArgListEntry Entry;
6817   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6818   Entry.Node = Dst;
6819   Args.push_back(Entry);
6820 
6821   Entry.Node = Src;
6822   Args.push_back(Entry);
6823 
6824   Entry.Ty = SizeTy;
6825   Entry.Node = Size;
6826   Args.push_back(Entry);
6827 
6828   RTLIB::Libcall LibraryCall =
6829       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6830   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6831     report_fatal_error("Unsupported element size");
6832 
6833   TargetLowering::CallLoweringInfo CLI(*this);
6834   CLI.setDebugLoc(dl)
6835       .setChain(Chain)
6836       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6837                     Type::getVoidTy(*getContext()),
6838                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6839                                       TLI->getPointerTy(getDataLayout())),
6840                     std::move(Args))
6841       .setDiscardResult()
6842       .setTailCall(isTailCall);
6843 
6844   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6845   return CallResult.second;
6846 }
6847 
6848 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6849                                 SDValue Src, SDValue Size, Align Alignment,
6850                                 bool isVol, bool isTailCall,
6851                                 MachinePointerInfo DstPtrInfo) {
6852   // Check to see if we should lower the memset to stores first.
6853   // For cases within the target-specified limits, this is the best choice.
6854   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6855   if (ConstantSize) {
6856     // Memset with size zero? Just return the original chain.
6857     if (ConstantSize->isNullValue())
6858       return Chain;
6859 
6860     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
6861                                      ConstantSize->getZExtValue(), Alignment,
6862                                      isVol, DstPtrInfo);
6863 
6864     if (Result.getNode())
6865       return Result;
6866   }
6867 
6868   // Then check to see if we should lower the memset with target-specific
6869   // code. If the target chooses to do this, this is the next best.
6870   if (TSI) {
6871     SDValue Result = TSI->EmitTargetCodeForMemset(
6872         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
6873     if (Result.getNode())
6874       return Result;
6875   }
6876 
6877   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6878 
6879   // Emit a library call.
6880   TargetLowering::ArgListTy Args;
6881   TargetLowering::ArgListEntry Entry;
6882   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
6883   Args.push_back(Entry);
6884   Entry.Node = Src;
6885   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6886   Args.push_back(Entry);
6887   Entry.Node = Size;
6888   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6889   Args.push_back(Entry);
6890 
6891   // FIXME: pass in SDLoc
6892   TargetLowering::CallLoweringInfo CLI(*this);
6893   CLI.setDebugLoc(dl)
6894       .setChain(Chain)
6895       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
6896                     Dst.getValueType().getTypeForEVT(*getContext()),
6897                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
6898                                       TLI->getPointerTy(getDataLayout())),
6899                     std::move(Args))
6900       .setDiscardResult()
6901       .setTailCall(isTailCall);
6902 
6903   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6904   return CallResult.second;
6905 }
6906 
6907 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6908                                       SDValue Dst, unsigned DstAlign,
6909                                       SDValue Value, SDValue Size, Type *SizeTy,
6910                                       unsigned ElemSz, bool isTailCall,
6911                                       MachinePointerInfo DstPtrInfo) {
6912   // Emit a library call.
6913   TargetLowering::ArgListTy Args;
6914   TargetLowering::ArgListEntry Entry;
6915   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6916   Entry.Node = Dst;
6917   Args.push_back(Entry);
6918 
6919   Entry.Ty = Type::getInt8Ty(*getContext());
6920   Entry.Node = Value;
6921   Args.push_back(Entry);
6922 
6923   Entry.Ty = SizeTy;
6924   Entry.Node = Size;
6925   Args.push_back(Entry);
6926 
6927   RTLIB::Libcall LibraryCall =
6928       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6929   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6930     report_fatal_error("Unsupported element size");
6931 
6932   TargetLowering::CallLoweringInfo CLI(*this);
6933   CLI.setDebugLoc(dl)
6934       .setChain(Chain)
6935       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6936                     Type::getVoidTy(*getContext()),
6937                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6938                                       TLI->getPointerTy(getDataLayout())),
6939                     std::move(Args))
6940       .setDiscardResult()
6941       .setTailCall(isTailCall);
6942 
6943   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6944   return CallResult.second;
6945 }
6946 
6947 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6948                                 SDVTList VTList, ArrayRef<SDValue> Ops,
6949                                 MachineMemOperand *MMO) {
6950   FoldingSetNodeID ID;
6951   ID.AddInteger(MemVT.getRawBits());
6952   AddNodeIDNode(ID, Opcode, VTList, Ops);
6953   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6954   void* IP = nullptr;
6955   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6956     cast<AtomicSDNode>(E)->refineAlignment(MMO);
6957     return SDValue(E, 0);
6958   }
6959 
6960   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6961                                     VTList, MemVT, MMO);
6962   createOperands(N, Ops);
6963 
6964   CSEMap.InsertNode(N, IP);
6965   InsertNode(N);
6966   return SDValue(N, 0);
6967 }
6968 
6969 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6970                                        EVT MemVT, SDVTList VTs, SDValue Chain,
6971                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
6972                                        MachineMemOperand *MMO) {
6973   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6974          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6975   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6976 
6977   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6978   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6979 }
6980 
6981 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6982                                 SDValue Chain, SDValue Ptr, SDValue Val,
6983                                 MachineMemOperand *MMO) {
6984   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6985           Opcode == ISD::ATOMIC_LOAD_SUB ||
6986           Opcode == ISD::ATOMIC_LOAD_AND ||
6987           Opcode == ISD::ATOMIC_LOAD_CLR ||
6988           Opcode == ISD::ATOMIC_LOAD_OR ||
6989           Opcode == ISD::ATOMIC_LOAD_XOR ||
6990           Opcode == ISD::ATOMIC_LOAD_NAND ||
6991           Opcode == ISD::ATOMIC_LOAD_MIN ||
6992           Opcode == ISD::ATOMIC_LOAD_MAX ||
6993           Opcode == ISD::ATOMIC_LOAD_UMIN ||
6994           Opcode == ISD::ATOMIC_LOAD_UMAX ||
6995           Opcode == ISD::ATOMIC_LOAD_FADD ||
6996           Opcode == ISD::ATOMIC_LOAD_FSUB ||
6997           Opcode == ISD::ATOMIC_SWAP ||
6998           Opcode == ISD::ATOMIC_STORE) &&
6999          "Invalid Atomic Op");
7000 
7001   EVT VT = Val.getValueType();
7002 
7003   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7004                                                getVTList(VT, MVT::Other);
7005   SDValue Ops[] = {Chain, Ptr, Val};
7006   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7007 }
7008 
7009 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7010                                 EVT VT, SDValue Chain, SDValue Ptr,
7011                                 MachineMemOperand *MMO) {
7012   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7013 
7014   SDVTList VTs = getVTList(VT, MVT::Other);
7015   SDValue Ops[] = {Chain, Ptr};
7016   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7017 }
7018 
7019 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7020 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7021   if (Ops.size() == 1)
7022     return Ops[0];
7023 
7024   SmallVector<EVT, 4> VTs;
7025   VTs.reserve(Ops.size());
7026   for (const SDValue &Op : Ops)
7027     VTs.push_back(Op.getValueType());
7028   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7029 }
7030 
7031 SDValue SelectionDAG::getMemIntrinsicNode(
7032     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7033     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7034     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7035   if (!Size && MemVT.isScalableVector())
7036     Size = MemoryLocation::UnknownSize;
7037   else if (!Size)
7038     Size = MemVT.getStoreSize();
7039 
7040   MachineFunction &MF = getMachineFunction();
7041   MachineMemOperand *MMO =
7042       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7043 
7044   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7045 }
7046 
7047 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7048                                           SDVTList VTList,
7049                                           ArrayRef<SDValue> Ops, EVT MemVT,
7050                                           MachineMemOperand *MMO) {
7051   assert((Opcode == ISD::INTRINSIC_VOID ||
7052           Opcode == ISD::INTRINSIC_W_CHAIN ||
7053           Opcode == ISD::PREFETCH ||
7054           ((int)Opcode <= std::numeric_limits<int>::max() &&
7055            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7056          "Opcode is not a memory-accessing opcode!");
7057 
7058   // Memoize the node unless it returns a flag.
7059   MemIntrinsicSDNode *N;
7060   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7061     FoldingSetNodeID ID;
7062     AddNodeIDNode(ID, Opcode, VTList, Ops);
7063     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7064         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7065     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7066     void *IP = nullptr;
7067     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7068       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7069       return SDValue(E, 0);
7070     }
7071 
7072     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7073                                       VTList, MemVT, MMO);
7074     createOperands(N, Ops);
7075 
7076   CSEMap.InsertNode(N, IP);
7077   } else {
7078     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7079                                       VTList, MemVT, MMO);
7080     createOperands(N, Ops);
7081   }
7082   InsertNode(N);
7083   SDValue V(N, 0);
7084   NewSDValueDbgMsg(V, "Creating new node: ", this);
7085   return V;
7086 }
7087 
7088 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7089                                       SDValue Chain, int FrameIndex,
7090                                       int64_t Size, int64_t Offset) {
7091   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7092   const auto VTs = getVTList(MVT::Other);
7093   SDValue Ops[2] = {
7094       Chain,
7095       getFrameIndex(FrameIndex,
7096                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7097                     true)};
7098 
7099   FoldingSetNodeID ID;
7100   AddNodeIDNode(ID, Opcode, VTs, Ops);
7101   ID.AddInteger(FrameIndex);
7102   ID.AddInteger(Size);
7103   ID.AddInteger(Offset);
7104   void *IP = nullptr;
7105   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7106     return SDValue(E, 0);
7107 
7108   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7109       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7110   createOperands(N, Ops);
7111   CSEMap.InsertNode(N, IP);
7112   InsertNode(N);
7113   SDValue V(N, 0);
7114   NewSDValueDbgMsg(V, "Creating new node: ", this);
7115   return V;
7116 }
7117 
7118 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7119                                          uint64_t Guid, uint64_t Index,
7120                                          uint32_t Attr) {
7121   const unsigned Opcode = ISD::PSEUDO_PROBE;
7122   const auto VTs = getVTList(MVT::Other);
7123   SDValue Ops[] = {Chain};
7124   FoldingSetNodeID ID;
7125   AddNodeIDNode(ID, Opcode, VTs, Ops);
7126   ID.AddInteger(Guid);
7127   ID.AddInteger(Index);
7128   void *IP = nullptr;
7129   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7130     return SDValue(E, 0);
7131 
7132   auto *N = newSDNode<PseudoProbeSDNode>(
7133       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7134   createOperands(N, Ops);
7135   CSEMap.InsertNode(N, IP);
7136   InsertNode(N);
7137   SDValue V(N, 0);
7138   NewSDValueDbgMsg(V, "Creating new node: ", this);
7139   return V;
7140 }
7141 
7142 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7143 /// MachinePointerInfo record from it.  This is particularly useful because the
7144 /// code generator has many cases where it doesn't bother passing in a
7145 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7146 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7147                                            SelectionDAG &DAG, SDValue Ptr,
7148                                            int64_t Offset = 0) {
7149   // If this is FI+Offset, we can model it.
7150   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7151     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7152                                              FI->getIndex(), Offset);
7153 
7154   // If this is (FI+Offset1)+Offset2, we can model it.
7155   if (Ptr.getOpcode() != ISD::ADD ||
7156       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7157       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7158     return Info;
7159 
7160   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7161   return MachinePointerInfo::getFixedStack(
7162       DAG.getMachineFunction(), FI,
7163       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7164 }
7165 
7166 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7167 /// MachinePointerInfo record from it.  This is particularly useful because the
7168 /// code generator has many cases where it doesn't bother passing in a
7169 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7170 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7171                                            SelectionDAG &DAG, SDValue Ptr,
7172                                            SDValue OffsetOp) {
7173   // If the 'Offset' value isn't a constant, we can't handle this.
7174   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7175     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7176   if (OffsetOp.isUndef())
7177     return InferPointerInfo(Info, DAG, Ptr);
7178   return Info;
7179 }
7180 
7181 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7182                               EVT VT, const SDLoc &dl, SDValue Chain,
7183                               SDValue Ptr, SDValue Offset,
7184                               MachinePointerInfo PtrInfo, EVT MemVT,
7185                               Align Alignment,
7186                               MachineMemOperand::Flags MMOFlags,
7187                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7188   assert(Chain.getValueType() == MVT::Other &&
7189         "Invalid chain type");
7190 
7191   MMOFlags |= MachineMemOperand::MOLoad;
7192   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7193   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7194   // clients.
7195   if (PtrInfo.V.isNull())
7196     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7197 
7198   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7199   MachineFunction &MF = getMachineFunction();
7200   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7201                                                    Alignment, AAInfo, Ranges);
7202   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7203 }
7204 
7205 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7206                               EVT VT, const SDLoc &dl, SDValue Chain,
7207                               SDValue Ptr, SDValue Offset, EVT MemVT,
7208                               MachineMemOperand *MMO) {
7209   if (VT == MemVT) {
7210     ExtType = ISD::NON_EXTLOAD;
7211   } else if (ExtType == ISD::NON_EXTLOAD) {
7212     assert(VT == MemVT && "Non-extending load from different memory type!");
7213   } else {
7214     // Extending load.
7215     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7216            "Should only be an extending load, not truncating!");
7217     assert(VT.isInteger() == MemVT.isInteger() &&
7218            "Cannot convert from FP to Int or Int -> FP!");
7219     assert(VT.isVector() == MemVT.isVector() &&
7220            "Cannot use an ext load to convert to or from a vector!");
7221     assert((!VT.isVector() ||
7222             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7223            "Cannot use an ext load to change the number of vector elements!");
7224   }
7225 
7226   bool Indexed = AM != ISD::UNINDEXED;
7227   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7228 
7229   SDVTList VTs = Indexed ?
7230     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7231   SDValue Ops[] = { Chain, Ptr, Offset };
7232   FoldingSetNodeID ID;
7233   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7234   ID.AddInteger(MemVT.getRawBits());
7235   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7236       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7237   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7238   void *IP = nullptr;
7239   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7240     cast<LoadSDNode>(E)->refineAlignment(MMO);
7241     return SDValue(E, 0);
7242   }
7243   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7244                                   ExtType, MemVT, MMO);
7245   createOperands(N, Ops);
7246 
7247   CSEMap.InsertNode(N, IP);
7248   InsertNode(N);
7249   SDValue V(N, 0);
7250   NewSDValueDbgMsg(V, "Creating new node: ", this);
7251   return V;
7252 }
7253 
7254 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7255                               SDValue Ptr, MachinePointerInfo PtrInfo,
7256                               MaybeAlign Alignment,
7257                               MachineMemOperand::Flags MMOFlags,
7258                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7259   SDValue Undef = getUNDEF(Ptr.getValueType());
7260   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7261                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7262 }
7263 
7264 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7265                               SDValue Ptr, MachineMemOperand *MMO) {
7266   SDValue Undef = getUNDEF(Ptr.getValueType());
7267   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7268                  VT, MMO);
7269 }
7270 
7271 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7272                                  EVT VT, SDValue Chain, SDValue Ptr,
7273                                  MachinePointerInfo PtrInfo, EVT MemVT,
7274                                  MaybeAlign Alignment,
7275                                  MachineMemOperand::Flags MMOFlags,
7276                                  const AAMDNodes &AAInfo) {
7277   SDValue Undef = getUNDEF(Ptr.getValueType());
7278   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7279                  MemVT, Alignment, MMOFlags, AAInfo);
7280 }
7281 
7282 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7283                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7284                                  MachineMemOperand *MMO) {
7285   SDValue Undef = getUNDEF(Ptr.getValueType());
7286   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7287                  MemVT, MMO);
7288 }
7289 
7290 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7291                                      SDValue Base, SDValue Offset,
7292                                      ISD::MemIndexedMode AM) {
7293   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7294   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7295   // Don't propagate the invariant or dereferenceable flags.
7296   auto MMOFlags =
7297       LD->getMemOperand()->getFlags() &
7298       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7299   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7300                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7301                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7302 }
7303 
7304 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7305                                SDValue Ptr, MachinePointerInfo PtrInfo,
7306                                Align Alignment,
7307                                MachineMemOperand::Flags MMOFlags,
7308                                const AAMDNodes &AAInfo) {
7309   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7310 
7311   MMOFlags |= MachineMemOperand::MOStore;
7312   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7313 
7314   if (PtrInfo.V.isNull())
7315     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7316 
7317   MachineFunction &MF = getMachineFunction();
7318   uint64_t Size =
7319       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7320   MachineMemOperand *MMO =
7321       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7322   return getStore(Chain, dl, Val, Ptr, MMO);
7323 }
7324 
7325 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7326                                SDValue Ptr, MachineMemOperand *MMO) {
7327   assert(Chain.getValueType() == MVT::Other &&
7328         "Invalid chain type");
7329   EVT VT = Val.getValueType();
7330   SDVTList VTs = getVTList(MVT::Other);
7331   SDValue Undef = getUNDEF(Ptr.getValueType());
7332   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7333   FoldingSetNodeID ID;
7334   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7335   ID.AddInteger(VT.getRawBits());
7336   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7337       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7338   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7339   void *IP = nullptr;
7340   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7341     cast<StoreSDNode>(E)->refineAlignment(MMO);
7342     return SDValue(E, 0);
7343   }
7344   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7345                                    ISD::UNINDEXED, false, VT, MMO);
7346   createOperands(N, Ops);
7347 
7348   CSEMap.InsertNode(N, IP);
7349   InsertNode(N);
7350   SDValue V(N, 0);
7351   NewSDValueDbgMsg(V, "Creating new node: ", this);
7352   return V;
7353 }
7354 
7355 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7356                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7357                                     EVT SVT, Align Alignment,
7358                                     MachineMemOperand::Flags MMOFlags,
7359                                     const AAMDNodes &AAInfo) {
7360   assert(Chain.getValueType() == MVT::Other &&
7361         "Invalid chain type");
7362 
7363   MMOFlags |= MachineMemOperand::MOStore;
7364   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7365 
7366   if (PtrInfo.V.isNull())
7367     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7368 
7369   MachineFunction &MF = getMachineFunction();
7370   MachineMemOperand *MMO = MF.getMachineMemOperand(
7371       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7372       Alignment, AAInfo);
7373   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7374 }
7375 
7376 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7377                                     SDValue Ptr, EVT SVT,
7378                                     MachineMemOperand *MMO) {
7379   EVT VT = Val.getValueType();
7380 
7381   assert(Chain.getValueType() == MVT::Other &&
7382         "Invalid chain type");
7383   if (VT == SVT)
7384     return getStore(Chain, dl, Val, Ptr, MMO);
7385 
7386   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7387          "Should only be a truncating store, not extending!");
7388   assert(VT.isInteger() == SVT.isInteger() &&
7389          "Can't do FP-INT conversion!");
7390   assert(VT.isVector() == SVT.isVector() &&
7391          "Cannot use trunc store to convert to or from a vector!");
7392   assert((!VT.isVector() ||
7393           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7394          "Cannot use trunc store to change the number of vector elements!");
7395 
7396   SDVTList VTs = getVTList(MVT::Other);
7397   SDValue Undef = getUNDEF(Ptr.getValueType());
7398   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7399   FoldingSetNodeID ID;
7400   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7401   ID.AddInteger(SVT.getRawBits());
7402   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7403       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7404   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7405   void *IP = nullptr;
7406   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7407     cast<StoreSDNode>(E)->refineAlignment(MMO);
7408     return SDValue(E, 0);
7409   }
7410   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7411                                    ISD::UNINDEXED, true, SVT, MMO);
7412   createOperands(N, Ops);
7413 
7414   CSEMap.InsertNode(N, IP);
7415   InsertNode(N);
7416   SDValue V(N, 0);
7417   NewSDValueDbgMsg(V, "Creating new node: ", this);
7418   return V;
7419 }
7420 
7421 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7422                                       SDValue Base, SDValue Offset,
7423                                       ISD::MemIndexedMode AM) {
7424   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7425   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7426   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7427   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7428   FoldingSetNodeID ID;
7429   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7430   ID.AddInteger(ST->getMemoryVT().getRawBits());
7431   ID.AddInteger(ST->getRawSubclassData());
7432   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7433   void *IP = nullptr;
7434   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7435     return SDValue(E, 0);
7436 
7437   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7438                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7439                                    ST->getMemOperand());
7440   createOperands(N, Ops);
7441 
7442   CSEMap.InsertNode(N, IP);
7443   InsertNode(N);
7444   SDValue V(N, 0);
7445   NewSDValueDbgMsg(V, "Creating new node: ", this);
7446   return V;
7447 }
7448 
7449 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7450                                     SDValue Base, SDValue Offset, SDValue Mask,
7451                                     SDValue PassThru, EVT MemVT,
7452                                     MachineMemOperand *MMO,
7453                                     ISD::MemIndexedMode AM,
7454                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7455   bool Indexed = AM != ISD::UNINDEXED;
7456   assert((Indexed || Offset.isUndef()) &&
7457          "Unindexed masked load with an offset!");
7458   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
7459                          : getVTList(VT, MVT::Other);
7460   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
7461   FoldingSetNodeID ID;
7462   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
7463   ID.AddInteger(MemVT.getRawBits());
7464   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
7465       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
7466   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7467   void *IP = nullptr;
7468   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7469     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
7470     return SDValue(E, 0);
7471   }
7472   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7473                                         AM, ExtTy, isExpanding, MemVT, MMO);
7474   createOperands(N, Ops);
7475 
7476   CSEMap.InsertNode(N, IP);
7477   InsertNode(N);
7478   SDValue V(N, 0);
7479   NewSDValueDbgMsg(V, "Creating new node: ", this);
7480   return V;
7481 }
7482 
7483 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
7484                                            SDValue Base, SDValue Offset,
7485                                            ISD::MemIndexedMode AM) {
7486   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
7487   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
7488   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
7489                        Offset, LD->getMask(), LD->getPassThru(),
7490                        LD->getMemoryVT(), LD->getMemOperand(), AM,
7491                        LD->getExtensionType(), LD->isExpandingLoad());
7492 }
7493 
7494 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
7495                                      SDValue Val, SDValue Base, SDValue Offset,
7496                                      SDValue Mask, EVT MemVT,
7497                                      MachineMemOperand *MMO,
7498                                      ISD::MemIndexedMode AM, bool IsTruncating,
7499                                      bool IsCompressing) {
7500   assert(Chain.getValueType() == MVT::Other &&
7501         "Invalid chain type");
7502   bool Indexed = AM != ISD::UNINDEXED;
7503   assert((Indexed || Offset.isUndef()) &&
7504          "Unindexed masked store with an offset!");
7505   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
7506                          : getVTList(MVT::Other);
7507   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
7508   FoldingSetNodeID ID;
7509   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
7510   ID.AddInteger(MemVT.getRawBits());
7511   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
7512       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7513   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7514   void *IP = nullptr;
7515   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7516     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
7517     return SDValue(E, 0);
7518   }
7519   auto *N =
7520       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7521                                    IsTruncating, IsCompressing, MemVT, MMO);
7522   createOperands(N, Ops);
7523 
7524   CSEMap.InsertNode(N, IP);
7525   InsertNode(N);
7526   SDValue V(N, 0);
7527   NewSDValueDbgMsg(V, "Creating new node: ", this);
7528   return V;
7529 }
7530 
7531 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
7532                                             SDValue Base, SDValue Offset,
7533                                             ISD::MemIndexedMode AM) {
7534   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
7535   assert(ST->getOffset().isUndef() &&
7536          "Masked store is already a indexed store!");
7537   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
7538                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
7539                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
7540 }
7541 
7542 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
7543                                       ArrayRef<SDValue> Ops,
7544                                       MachineMemOperand *MMO,
7545                                       ISD::MemIndexType IndexType,
7546                                       ISD::LoadExtType ExtTy) {
7547   assert(Ops.size() == 6 && "Incompatible number of operands");
7548 
7549   FoldingSetNodeID ID;
7550   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7551   ID.AddInteger(VT.getRawBits());
7552   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7553       dl.getIROrder(), VTs, VT, MMO, IndexType, ExtTy));
7554   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7555   void *IP = nullptr;
7556   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7557     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7558     return SDValue(E, 0);
7559   }
7560 
7561   IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]);
7562   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7563                                           VTs, VT, MMO, IndexType, ExtTy);
7564   createOperands(N, Ops);
7565 
7566   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7567          "Incompatible type of the PassThru value in MaskedGatherSDNode");
7568   assert(N->getMask().getValueType().getVectorElementCount() ==
7569              N->getValueType(0).getVectorElementCount() &&
7570          "Vector width mismatch between mask and data");
7571   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7572              N->getValueType(0).getVectorElementCount().isScalable() &&
7573          "Scalable flags of index and data do not match");
7574   assert(ElementCount::isKnownGE(
7575              N->getIndex().getValueType().getVectorElementCount(),
7576              N->getValueType(0).getVectorElementCount()) &&
7577          "Vector width mismatch between index and data");
7578   assert(isa<ConstantSDNode>(N->getScale()) &&
7579          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7580          "Scale should be a constant power of 2");
7581 
7582   CSEMap.InsertNode(N, IP);
7583   InsertNode(N);
7584   SDValue V(N, 0);
7585   NewSDValueDbgMsg(V, "Creating new node: ", this);
7586   return V;
7587 }
7588 
7589 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
7590                                        ArrayRef<SDValue> Ops,
7591                                        MachineMemOperand *MMO,
7592                                        ISD::MemIndexType IndexType,
7593                                        bool IsTrunc) {
7594   assert(Ops.size() == 6 && "Incompatible number of operands");
7595 
7596   FoldingSetNodeID ID;
7597   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7598   ID.AddInteger(VT.getRawBits());
7599   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7600       dl.getIROrder(), VTs, VT, MMO, IndexType, IsTrunc));
7601   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7602   void *IP = nullptr;
7603   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7604     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7605     return SDValue(E, 0);
7606   }
7607 
7608   IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]);
7609   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7610                                            VTs, VT, MMO, IndexType, IsTrunc);
7611   createOperands(N, Ops);
7612 
7613   assert(N->getMask().getValueType().getVectorElementCount() ==
7614              N->getValue().getValueType().getVectorElementCount() &&
7615          "Vector width mismatch between mask and data");
7616   assert(
7617       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7618           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7619       "Scalable flags of index and data do not match");
7620   assert(ElementCount::isKnownGE(
7621              N->getIndex().getValueType().getVectorElementCount(),
7622              N->getValue().getValueType().getVectorElementCount()) &&
7623          "Vector width mismatch between index and data");
7624   assert(isa<ConstantSDNode>(N->getScale()) &&
7625          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7626          "Scale should be a constant power of 2");
7627 
7628   CSEMap.InsertNode(N, IP);
7629   InsertNode(N);
7630   SDValue V(N, 0);
7631   NewSDValueDbgMsg(V, "Creating new node: ", this);
7632   return V;
7633 }
7634 
7635 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7636   // select undef, T, F --> T (if T is a constant), otherwise F
7637   // select, ?, undef, F --> F
7638   // select, ?, T, undef --> T
7639   if (Cond.isUndef())
7640     return isConstantValueOfAnyType(T) ? T : F;
7641   if (T.isUndef())
7642     return F;
7643   if (F.isUndef())
7644     return T;
7645 
7646   // select true, T, F --> T
7647   // select false, T, F --> F
7648   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7649     return CondC->isNullValue() ? F : T;
7650 
7651   // TODO: This should simplify VSELECT with constant condition using something
7652   // like this (but check boolean contents to be complete?):
7653   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7654   //    return T;
7655   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7656   //    return F;
7657 
7658   // select ?, T, T --> T
7659   if (T == F)
7660     return T;
7661 
7662   return SDValue();
7663 }
7664 
7665 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7666   // shift undef, Y --> 0 (can always assume that the undef value is 0)
7667   if (X.isUndef())
7668     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7669   // shift X, undef --> undef (because it may shift by the bitwidth)
7670   if (Y.isUndef())
7671     return getUNDEF(X.getValueType());
7672 
7673   // shift 0, Y --> 0
7674   // shift X, 0 --> X
7675   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7676     return X;
7677 
7678   // shift X, C >= bitwidth(X) --> undef
7679   // All vector elements must be too big (or undef) to avoid partial undefs.
7680   auto isShiftTooBig = [X](ConstantSDNode *Val) {
7681     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7682   };
7683   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7684     return getUNDEF(X.getValueType());
7685 
7686   return SDValue();
7687 }
7688 
7689 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
7690                                       SDNodeFlags Flags) {
7691   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
7692   // (an undef operand can be chosen to be Nan/Inf), then the result of this
7693   // operation is poison. That result can be relaxed to undef.
7694   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
7695   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7696   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
7697                 (YC && YC->getValueAPF().isNaN());
7698   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
7699                 (YC && YC->getValueAPF().isInfinity());
7700 
7701   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
7702     return getUNDEF(X.getValueType());
7703 
7704   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
7705     return getUNDEF(X.getValueType());
7706 
7707   if (!YC)
7708     return SDValue();
7709 
7710   // X + -0.0 --> X
7711   if (Opcode == ISD::FADD)
7712     if (YC->getValueAPF().isNegZero())
7713       return X;
7714 
7715   // X - +0.0 --> X
7716   if (Opcode == ISD::FSUB)
7717     if (YC->getValueAPF().isPosZero())
7718       return X;
7719 
7720   // X * 1.0 --> X
7721   // X / 1.0 --> X
7722   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7723     if (YC->getValueAPF().isExactlyValue(1.0))
7724       return X;
7725 
7726   // X * 0.0 --> 0.0
7727   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
7728     if (YC->getValueAPF().isZero())
7729       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
7730 
7731   return SDValue();
7732 }
7733 
7734 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7735                                SDValue Ptr, SDValue SV, unsigned Align) {
7736   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7737   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7738 }
7739 
7740 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7741                               ArrayRef<SDUse> Ops) {
7742   switch (Ops.size()) {
7743   case 0: return getNode(Opcode, DL, VT);
7744   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7745   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7746   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7747   default: break;
7748   }
7749 
7750   // Copy from an SDUse array into an SDValue array for use with
7751   // the regular getNode logic.
7752   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7753   return getNode(Opcode, DL, VT, NewOps);
7754 }
7755 
7756 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7757                               ArrayRef<SDValue> Ops) {
7758   SDNodeFlags Flags;
7759   if (Inserter)
7760     Flags = Inserter->getFlags();
7761   return getNode(Opcode, DL, VT, Ops, Flags);
7762 }
7763 
7764 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7765                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7766   unsigned NumOps = Ops.size();
7767   switch (NumOps) {
7768   case 0: return getNode(Opcode, DL, VT);
7769   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7770   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7771   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7772   default: break;
7773   }
7774 
7775 #ifndef NDEBUG
7776   for (auto &Op : Ops)
7777     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7778            "Operand is DELETED_NODE!");
7779 #endif
7780 
7781   switch (Opcode) {
7782   default: break;
7783   case ISD::BUILD_VECTOR:
7784     // Attempt to simplify BUILD_VECTOR.
7785     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7786       return V;
7787     break;
7788   case ISD::CONCAT_VECTORS:
7789     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7790       return V;
7791     break;
7792   case ISD::SELECT_CC:
7793     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7794     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7795            "LHS and RHS of condition must have same type!");
7796     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7797            "True and False arms of SelectCC must have same type!");
7798     assert(Ops[2].getValueType() == VT &&
7799            "select_cc node must be of same type as true and false value!");
7800     break;
7801   case ISD::BR_CC:
7802     assert(NumOps == 5 && "BR_CC takes 5 operands!");
7803     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7804            "LHS/RHS of comparison should match types!");
7805     break;
7806   }
7807 
7808   // Memoize nodes.
7809   SDNode *N;
7810   SDVTList VTs = getVTList(VT);
7811 
7812   if (VT != MVT::Glue) {
7813     FoldingSetNodeID ID;
7814     AddNodeIDNode(ID, Opcode, VTs, Ops);
7815     void *IP = nullptr;
7816 
7817     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7818       return SDValue(E, 0);
7819 
7820     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7821     createOperands(N, Ops);
7822 
7823     CSEMap.InsertNode(N, IP);
7824   } else {
7825     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7826     createOperands(N, Ops);
7827   }
7828 
7829   N->setFlags(Flags);
7830   InsertNode(N);
7831   SDValue V(N, 0);
7832   NewSDValueDbgMsg(V, "Creating new node: ", this);
7833   return V;
7834 }
7835 
7836 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7837                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7838   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7839 }
7840 
7841 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7842                               ArrayRef<SDValue> Ops) {
7843   SDNodeFlags Flags;
7844   if (Inserter)
7845     Flags = Inserter->getFlags();
7846   return getNode(Opcode, DL, VTList, Ops, Flags);
7847 }
7848 
7849 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7850                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7851   if (VTList.NumVTs == 1)
7852     return getNode(Opcode, DL, VTList.VTs[0], Ops);
7853 
7854 #ifndef NDEBUG
7855   for (auto &Op : Ops)
7856     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7857            "Operand is DELETED_NODE!");
7858 #endif
7859 
7860   switch (Opcode) {
7861   case ISD::STRICT_FP_EXTEND:
7862     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
7863            "Invalid STRICT_FP_EXTEND!");
7864     assert(VTList.VTs[0].isFloatingPoint() &&
7865            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
7866     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7867            "STRICT_FP_EXTEND result type should be vector iff the operand "
7868            "type is vector!");
7869     assert((!VTList.VTs[0].isVector() ||
7870             VTList.VTs[0].getVectorNumElements() ==
7871             Ops[1].getValueType().getVectorNumElements()) &&
7872            "Vector element count mismatch!");
7873     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
7874            "Invalid fpext node, dst <= src!");
7875     break;
7876   case ISD::STRICT_FP_ROUND:
7877     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
7878     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7879            "STRICT_FP_ROUND result type should be vector iff the operand "
7880            "type is vector!");
7881     assert((!VTList.VTs[0].isVector() ||
7882             VTList.VTs[0].getVectorNumElements() ==
7883             Ops[1].getValueType().getVectorNumElements()) &&
7884            "Vector element count mismatch!");
7885     assert(VTList.VTs[0].isFloatingPoint() &&
7886            Ops[1].getValueType().isFloatingPoint() &&
7887            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
7888            isa<ConstantSDNode>(Ops[2]) &&
7889            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
7890             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
7891            "Invalid STRICT_FP_ROUND!");
7892     break;
7893 #if 0
7894   // FIXME: figure out how to safely handle things like
7895   // int foo(int x) { return 1 << (x & 255); }
7896   // int bar() { return foo(256); }
7897   case ISD::SRA_PARTS:
7898   case ISD::SRL_PARTS:
7899   case ISD::SHL_PARTS:
7900     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7901         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
7902       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7903     else if (N3.getOpcode() == ISD::AND)
7904       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
7905         // If the and is only masking out bits that cannot effect the shift,
7906         // eliminate the and.
7907         unsigned NumBits = VT.getScalarSizeInBits()*2;
7908         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
7909           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7910       }
7911     break;
7912 #endif
7913   }
7914 
7915   // Memoize the node unless it returns a flag.
7916   SDNode *N;
7917   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7918     FoldingSetNodeID ID;
7919     AddNodeIDNode(ID, Opcode, VTList, Ops);
7920     void *IP = nullptr;
7921     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7922       return SDValue(E, 0);
7923 
7924     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7925     createOperands(N, Ops);
7926     CSEMap.InsertNode(N, IP);
7927   } else {
7928     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7929     createOperands(N, Ops);
7930   }
7931 
7932   N->setFlags(Flags);
7933   InsertNode(N);
7934   SDValue V(N, 0);
7935   NewSDValueDbgMsg(V, "Creating new node: ", this);
7936   return V;
7937 }
7938 
7939 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7940                               SDVTList VTList) {
7941   return getNode(Opcode, DL, VTList, None);
7942 }
7943 
7944 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7945                               SDValue N1) {
7946   SDValue Ops[] = { N1 };
7947   return getNode(Opcode, DL, VTList, Ops);
7948 }
7949 
7950 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7951                               SDValue N1, SDValue N2) {
7952   SDValue Ops[] = { N1, N2 };
7953   return getNode(Opcode, DL, VTList, Ops);
7954 }
7955 
7956 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7957                               SDValue N1, SDValue N2, SDValue N3) {
7958   SDValue Ops[] = { N1, N2, N3 };
7959   return getNode(Opcode, DL, VTList, Ops);
7960 }
7961 
7962 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7963                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7964   SDValue Ops[] = { N1, N2, N3, N4 };
7965   return getNode(Opcode, DL, VTList, Ops);
7966 }
7967 
7968 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7969                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7970                               SDValue N5) {
7971   SDValue Ops[] = { N1, N2, N3, N4, N5 };
7972   return getNode(Opcode, DL, VTList, Ops);
7973 }
7974 
7975 SDVTList SelectionDAG::getVTList(EVT VT) {
7976   return makeVTList(SDNode::getValueTypeList(VT), 1);
7977 }
7978 
7979 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
7980   FoldingSetNodeID ID;
7981   ID.AddInteger(2U);
7982   ID.AddInteger(VT1.getRawBits());
7983   ID.AddInteger(VT2.getRawBits());
7984 
7985   void *IP = nullptr;
7986   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7987   if (!Result) {
7988     EVT *Array = Allocator.Allocate<EVT>(2);
7989     Array[0] = VT1;
7990     Array[1] = VT2;
7991     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
7992     VTListMap.InsertNode(Result, IP);
7993   }
7994   return Result->getSDVTList();
7995 }
7996 
7997 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
7998   FoldingSetNodeID ID;
7999   ID.AddInteger(3U);
8000   ID.AddInteger(VT1.getRawBits());
8001   ID.AddInteger(VT2.getRawBits());
8002   ID.AddInteger(VT3.getRawBits());
8003 
8004   void *IP = nullptr;
8005   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8006   if (!Result) {
8007     EVT *Array = Allocator.Allocate<EVT>(3);
8008     Array[0] = VT1;
8009     Array[1] = VT2;
8010     Array[2] = VT3;
8011     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8012     VTListMap.InsertNode(Result, IP);
8013   }
8014   return Result->getSDVTList();
8015 }
8016 
8017 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8018   FoldingSetNodeID ID;
8019   ID.AddInteger(4U);
8020   ID.AddInteger(VT1.getRawBits());
8021   ID.AddInteger(VT2.getRawBits());
8022   ID.AddInteger(VT3.getRawBits());
8023   ID.AddInteger(VT4.getRawBits());
8024 
8025   void *IP = nullptr;
8026   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8027   if (!Result) {
8028     EVT *Array = Allocator.Allocate<EVT>(4);
8029     Array[0] = VT1;
8030     Array[1] = VT2;
8031     Array[2] = VT3;
8032     Array[3] = VT4;
8033     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8034     VTListMap.InsertNode(Result, IP);
8035   }
8036   return Result->getSDVTList();
8037 }
8038 
8039 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8040   unsigned NumVTs = VTs.size();
8041   FoldingSetNodeID ID;
8042   ID.AddInteger(NumVTs);
8043   for (unsigned index = 0; index < NumVTs; index++) {
8044     ID.AddInteger(VTs[index].getRawBits());
8045   }
8046 
8047   void *IP = nullptr;
8048   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8049   if (!Result) {
8050     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8051     llvm::copy(VTs, Array);
8052     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8053     VTListMap.InsertNode(Result, IP);
8054   }
8055   return Result->getSDVTList();
8056 }
8057 
8058 
8059 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8060 /// specified operands.  If the resultant node already exists in the DAG,
8061 /// this does not modify the specified node, instead it returns the node that
8062 /// already exists.  If the resultant node does not exist in the DAG, the
8063 /// input node is returned.  As a degenerate case, if you specify the same
8064 /// input operands as the node already has, the input node is returned.
8065 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8066   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8067 
8068   // Check to see if there is no change.
8069   if (Op == N->getOperand(0)) return N;
8070 
8071   // See if the modified node already exists.
8072   void *InsertPos = nullptr;
8073   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8074     return Existing;
8075 
8076   // Nope it doesn't.  Remove the node from its current place in the maps.
8077   if (InsertPos)
8078     if (!RemoveNodeFromCSEMaps(N))
8079       InsertPos = nullptr;
8080 
8081   // Now we update the operands.
8082   N->OperandList[0].set(Op);
8083 
8084   updateDivergence(N);
8085   // If this gets put into a CSE map, add it.
8086   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8087   return N;
8088 }
8089 
8090 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8091   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8092 
8093   // Check to see if there is no change.
8094   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8095     return N;   // No operands changed, just return the input node.
8096 
8097   // See if the modified node already exists.
8098   void *InsertPos = nullptr;
8099   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8100     return Existing;
8101 
8102   // Nope it doesn't.  Remove the node from its current place in the maps.
8103   if (InsertPos)
8104     if (!RemoveNodeFromCSEMaps(N))
8105       InsertPos = nullptr;
8106 
8107   // Now we update the operands.
8108   if (N->OperandList[0] != Op1)
8109     N->OperandList[0].set(Op1);
8110   if (N->OperandList[1] != Op2)
8111     N->OperandList[1].set(Op2);
8112 
8113   updateDivergence(N);
8114   // If this gets put into a CSE map, add it.
8115   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8116   return N;
8117 }
8118 
8119 SDNode *SelectionDAG::
8120 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8121   SDValue Ops[] = { Op1, Op2, Op3 };
8122   return UpdateNodeOperands(N, Ops);
8123 }
8124 
8125 SDNode *SelectionDAG::
8126 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8127                    SDValue Op3, SDValue Op4) {
8128   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8129   return UpdateNodeOperands(N, Ops);
8130 }
8131 
8132 SDNode *SelectionDAG::
8133 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8134                    SDValue Op3, SDValue Op4, SDValue Op5) {
8135   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8136   return UpdateNodeOperands(N, Ops);
8137 }
8138 
8139 SDNode *SelectionDAG::
8140 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8141   unsigned NumOps = Ops.size();
8142   assert(N->getNumOperands() == NumOps &&
8143          "Update with wrong number of operands");
8144 
8145   // If no operands changed just return the input node.
8146   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8147     return N;
8148 
8149   // See if the modified node already exists.
8150   void *InsertPos = nullptr;
8151   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8152     return Existing;
8153 
8154   // Nope it doesn't.  Remove the node from its current place in the maps.
8155   if (InsertPos)
8156     if (!RemoveNodeFromCSEMaps(N))
8157       InsertPos = nullptr;
8158 
8159   // Now we update the operands.
8160   for (unsigned i = 0; i != NumOps; ++i)
8161     if (N->OperandList[i] != Ops[i])
8162       N->OperandList[i].set(Ops[i]);
8163 
8164   updateDivergence(N);
8165   // If this gets put into a CSE map, add it.
8166   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8167   return N;
8168 }
8169 
8170 /// DropOperands - Release the operands and set this node to have
8171 /// zero operands.
8172 void SDNode::DropOperands() {
8173   // Unlike the code in MorphNodeTo that does this, we don't need to
8174   // watch for dead nodes here.
8175   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8176     SDUse &Use = *I++;
8177     Use.set(SDValue());
8178   }
8179 }
8180 
8181 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8182                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8183   if (NewMemRefs.empty()) {
8184     N->clearMemRefs();
8185     return;
8186   }
8187 
8188   // Check if we can avoid allocating by storing a single reference directly.
8189   if (NewMemRefs.size() == 1) {
8190     N->MemRefs = NewMemRefs[0];
8191     N->NumMemRefs = 1;
8192     return;
8193   }
8194 
8195   MachineMemOperand **MemRefsBuffer =
8196       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8197   llvm::copy(NewMemRefs, MemRefsBuffer);
8198   N->MemRefs = MemRefsBuffer;
8199   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8200 }
8201 
8202 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8203 /// machine opcode.
8204 ///
8205 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8206                                    EVT VT) {
8207   SDVTList VTs = getVTList(VT);
8208   return SelectNodeTo(N, MachineOpc, VTs, None);
8209 }
8210 
8211 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8212                                    EVT VT, SDValue Op1) {
8213   SDVTList VTs = getVTList(VT);
8214   SDValue Ops[] = { Op1 };
8215   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8216 }
8217 
8218 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8219                                    EVT VT, SDValue Op1,
8220                                    SDValue Op2) {
8221   SDVTList VTs = getVTList(VT);
8222   SDValue Ops[] = { Op1, Op2 };
8223   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8224 }
8225 
8226 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8227                                    EVT VT, SDValue Op1,
8228                                    SDValue Op2, SDValue Op3) {
8229   SDVTList VTs = getVTList(VT);
8230   SDValue Ops[] = { Op1, Op2, Op3 };
8231   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8232 }
8233 
8234 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8235                                    EVT VT, ArrayRef<SDValue> Ops) {
8236   SDVTList VTs = getVTList(VT);
8237   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8238 }
8239 
8240 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8241                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8242   SDVTList VTs = getVTList(VT1, VT2);
8243   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8244 }
8245 
8246 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8247                                    EVT VT1, EVT VT2) {
8248   SDVTList VTs = getVTList(VT1, VT2);
8249   return SelectNodeTo(N, MachineOpc, VTs, None);
8250 }
8251 
8252 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8253                                    EVT VT1, EVT VT2, EVT VT3,
8254                                    ArrayRef<SDValue> Ops) {
8255   SDVTList VTs = getVTList(VT1, VT2, VT3);
8256   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8257 }
8258 
8259 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8260                                    EVT VT1, EVT VT2,
8261                                    SDValue Op1, SDValue Op2) {
8262   SDVTList VTs = getVTList(VT1, VT2);
8263   SDValue Ops[] = { Op1, Op2 };
8264   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8265 }
8266 
8267 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8268                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8269   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8270   // Reset the NodeID to -1.
8271   New->setNodeId(-1);
8272   if (New != N) {
8273     ReplaceAllUsesWith(N, New);
8274     RemoveDeadNode(N);
8275   }
8276   return New;
8277 }
8278 
8279 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8280 /// the line number information on the merged node since it is not possible to
8281 /// preserve the information that operation is associated with multiple lines.
8282 /// This will make the debugger working better at -O0, were there is a higher
8283 /// probability having other instructions associated with that line.
8284 ///
8285 /// For IROrder, we keep the smaller of the two
8286 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8287   DebugLoc NLoc = N->getDebugLoc();
8288   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8289     N->setDebugLoc(DebugLoc());
8290   }
8291   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8292   N->setIROrder(Order);
8293   return N;
8294 }
8295 
8296 /// MorphNodeTo - This *mutates* the specified node to have the specified
8297 /// return type, opcode, and operands.
8298 ///
8299 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8300 /// node of the specified opcode and operands, it returns that node instead of
8301 /// the current one.  Note that the SDLoc need not be the same.
8302 ///
8303 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8304 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8305 /// node, and because it doesn't require CSE recalculation for any of
8306 /// the node's users.
8307 ///
8308 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8309 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8310 /// the legalizer which maintain worklists that would need to be updated when
8311 /// deleting things.
8312 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8313                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8314   // If an identical node already exists, use it.
8315   void *IP = nullptr;
8316   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8317     FoldingSetNodeID ID;
8318     AddNodeIDNode(ID, Opc, VTs, Ops);
8319     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8320       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8321   }
8322 
8323   if (!RemoveNodeFromCSEMaps(N))
8324     IP = nullptr;
8325 
8326   // Start the morphing.
8327   N->NodeType = Opc;
8328   N->ValueList = VTs.VTs;
8329   N->NumValues = VTs.NumVTs;
8330 
8331   // Clear the operands list, updating used nodes to remove this from their
8332   // use list.  Keep track of any operands that become dead as a result.
8333   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8334   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8335     SDUse &Use = *I++;
8336     SDNode *Used = Use.getNode();
8337     Use.set(SDValue());
8338     if (Used->use_empty())
8339       DeadNodeSet.insert(Used);
8340   }
8341 
8342   // For MachineNode, initialize the memory references information.
8343   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8344     MN->clearMemRefs();
8345 
8346   // Swap for an appropriately sized array from the recycler.
8347   removeOperands(N);
8348   createOperands(N, Ops);
8349 
8350   // Delete any nodes that are still dead after adding the uses for the
8351   // new operands.
8352   if (!DeadNodeSet.empty()) {
8353     SmallVector<SDNode *, 16> DeadNodes;
8354     for (SDNode *N : DeadNodeSet)
8355       if (N->use_empty())
8356         DeadNodes.push_back(N);
8357     RemoveDeadNodes(DeadNodes);
8358   }
8359 
8360   if (IP)
8361     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8362   return N;
8363 }
8364 
8365 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8366   unsigned OrigOpc = Node->getOpcode();
8367   unsigned NewOpc;
8368   switch (OrigOpc) {
8369   default:
8370     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8371 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8372   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8373 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8374   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8375 #include "llvm/IR/ConstrainedOps.def"
8376   }
8377 
8378   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8379 
8380   // We're taking this node out of the chain, so we need to re-link things.
8381   SDValue InputChain = Node->getOperand(0);
8382   SDValue OutputChain = SDValue(Node, 1);
8383   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8384 
8385   SmallVector<SDValue, 3> Ops;
8386   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8387     Ops.push_back(Node->getOperand(i));
8388 
8389   SDVTList VTs = getVTList(Node->getValueType(0));
8390   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8391 
8392   // MorphNodeTo can operate in two ways: if an existing node with the
8393   // specified operands exists, it can just return it.  Otherwise, it
8394   // updates the node in place to have the requested operands.
8395   if (Res == Node) {
8396     // If we updated the node in place, reset the node ID.  To the isel,
8397     // this should be just like a newly allocated machine node.
8398     Res->setNodeId(-1);
8399   } else {
8400     ReplaceAllUsesWith(Node, Res);
8401     RemoveDeadNode(Node);
8402   }
8403 
8404   return Res;
8405 }
8406 
8407 /// getMachineNode - These are used for target selectors to create a new node
8408 /// with specified return type(s), MachineInstr opcode, and operands.
8409 ///
8410 /// Note that getMachineNode returns the resultant node.  If there is already a
8411 /// node of the specified opcode and operands, it returns that node instead of
8412 /// the current one.
8413 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8414                                             EVT VT) {
8415   SDVTList VTs = getVTList(VT);
8416   return getMachineNode(Opcode, dl, VTs, None);
8417 }
8418 
8419 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8420                                             EVT VT, SDValue Op1) {
8421   SDVTList VTs = getVTList(VT);
8422   SDValue Ops[] = { Op1 };
8423   return getMachineNode(Opcode, dl, VTs, Ops);
8424 }
8425 
8426 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8427                                             EVT VT, SDValue Op1, SDValue Op2) {
8428   SDVTList VTs = getVTList(VT);
8429   SDValue Ops[] = { Op1, Op2 };
8430   return getMachineNode(Opcode, dl, VTs, Ops);
8431 }
8432 
8433 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8434                                             EVT VT, SDValue Op1, SDValue Op2,
8435                                             SDValue Op3) {
8436   SDVTList VTs = getVTList(VT);
8437   SDValue Ops[] = { Op1, Op2, Op3 };
8438   return getMachineNode(Opcode, dl, VTs, Ops);
8439 }
8440 
8441 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8442                                             EVT VT, ArrayRef<SDValue> Ops) {
8443   SDVTList VTs = getVTList(VT);
8444   return getMachineNode(Opcode, dl, VTs, Ops);
8445 }
8446 
8447 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8448                                             EVT VT1, EVT VT2, SDValue Op1,
8449                                             SDValue Op2) {
8450   SDVTList VTs = getVTList(VT1, VT2);
8451   SDValue Ops[] = { Op1, Op2 };
8452   return getMachineNode(Opcode, dl, VTs, Ops);
8453 }
8454 
8455 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8456                                             EVT VT1, EVT VT2, SDValue Op1,
8457                                             SDValue Op2, SDValue Op3) {
8458   SDVTList VTs = getVTList(VT1, VT2);
8459   SDValue Ops[] = { Op1, Op2, Op3 };
8460   return getMachineNode(Opcode, dl, VTs, Ops);
8461 }
8462 
8463 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8464                                             EVT VT1, EVT VT2,
8465                                             ArrayRef<SDValue> Ops) {
8466   SDVTList VTs = getVTList(VT1, VT2);
8467   return getMachineNode(Opcode, dl, VTs, Ops);
8468 }
8469 
8470 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8471                                             EVT VT1, EVT VT2, EVT VT3,
8472                                             SDValue Op1, SDValue Op2) {
8473   SDVTList VTs = getVTList(VT1, VT2, VT3);
8474   SDValue Ops[] = { Op1, Op2 };
8475   return getMachineNode(Opcode, dl, VTs, Ops);
8476 }
8477 
8478 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8479                                             EVT VT1, EVT VT2, EVT VT3,
8480                                             SDValue Op1, SDValue Op2,
8481                                             SDValue Op3) {
8482   SDVTList VTs = getVTList(VT1, VT2, VT3);
8483   SDValue Ops[] = { Op1, Op2, Op3 };
8484   return getMachineNode(Opcode, dl, VTs, Ops);
8485 }
8486 
8487 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8488                                             EVT VT1, EVT VT2, EVT VT3,
8489                                             ArrayRef<SDValue> Ops) {
8490   SDVTList VTs = getVTList(VT1, VT2, VT3);
8491   return getMachineNode(Opcode, dl, VTs, Ops);
8492 }
8493 
8494 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8495                                             ArrayRef<EVT> ResultTys,
8496                                             ArrayRef<SDValue> Ops) {
8497   SDVTList VTs = getVTList(ResultTys);
8498   return getMachineNode(Opcode, dl, VTs, Ops);
8499 }
8500 
8501 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
8502                                             SDVTList VTs,
8503                                             ArrayRef<SDValue> Ops) {
8504   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
8505   MachineSDNode *N;
8506   void *IP = nullptr;
8507 
8508   if (DoCSE) {
8509     FoldingSetNodeID ID;
8510     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
8511     IP = nullptr;
8512     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8513       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
8514     }
8515   }
8516 
8517   // Allocate a new MachineSDNode.
8518   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8519   createOperands(N, Ops);
8520 
8521   if (DoCSE)
8522     CSEMap.InsertNode(N, IP);
8523 
8524   InsertNode(N);
8525   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
8526   return N;
8527 }
8528 
8529 /// getTargetExtractSubreg - A convenience function for creating
8530 /// TargetOpcode::EXTRACT_SUBREG nodes.
8531 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8532                                              SDValue Operand) {
8533   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8534   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
8535                                   VT, Operand, SRIdxVal);
8536   return SDValue(Subreg, 0);
8537 }
8538 
8539 /// getTargetInsertSubreg - A convenience function for creating
8540 /// TargetOpcode::INSERT_SUBREG nodes.
8541 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8542                                             SDValue Operand, SDValue Subreg) {
8543   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8544   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
8545                                   VT, Operand, Subreg, SRIdxVal);
8546   return SDValue(Result, 0);
8547 }
8548 
8549 /// getNodeIfExists - Get the specified node if it's already available, or
8550 /// else return NULL.
8551 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8552                                       ArrayRef<SDValue> Ops) {
8553   SDNodeFlags Flags;
8554   if (Inserter)
8555     Flags = Inserter->getFlags();
8556   return getNodeIfExists(Opcode, VTList, Ops, Flags);
8557 }
8558 
8559 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8560                                       ArrayRef<SDValue> Ops,
8561                                       const SDNodeFlags Flags) {
8562   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8563     FoldingSetNodeID ID;
8564     AddNodeIDNode(ID, Opcode, VTList, Ops);
8565     void *IP = nullptr;
8566     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
8567       E->intersectFlagsWith(Flags);
8568       return E;
8569     }
8570   }
8571   return nullptr;
8572 }
8573 
8574 /// doesNodeExist - Check if a node exists without modifying its flags.
8575 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
8576                                  ArrayRef<SDValue> Ops) {
8577   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8578     FoldingSetNodeID ID;
8579     AddNodeIDNode(ID, Opcode, VTList, Ops);
8580     void *IP = nullptr;
8581     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
8582       return true;
8583   }
8584   return false;
8585 }
8586 
8587 /// getDbgValue - Creates a SDDbgValue node.
8588 ///
8589 /// SDNode
8590 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
8591                                       SDNode *N, unsigned R, bool IsIndirect,
8592                                       const DebugLoc &DL, unsigned O) {
8593   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8594          "Expected inlined-at fields to agree");
8595   return new (DbgInfo->getAlloc())
8596       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
8597                  {}, IsIndirect, DL, O,
8598                  /*IsVariadic=*/false);
8599 }
8600 
8601 /// Constant
8602 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
8603                                               DIExpression *Expr,
8604                                               const Value *C,
8605                                               const DebugLoc &DL, unsigned O) {
8606   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8607          "Expected inlined-at fields to agree");
8608   return new (DbgInfo->getAlloc())
8609       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
8610                  /*IsIndirect=*/false, DL, O,
8611                  /*IsVariadic=*/false);
8612 }
8613 
8614 /// FrameIndex
8615 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8616                                                 DIExpression *Expr, unsigned FI,
8617                                                 bool IsIndirect,
8618                                                 const DebugLoc &DL,
8619                                                 unsigned O) {
8620   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8621          "Expected inlined-at fields to agree");
8622   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
8623 }
8624 
8625 /// FrameIndex with dependencies
8626 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8627                                                 DIExpression *Expr, unsigned FI,
8628                                                 ArrayRef<SDNode *> Dependencies,
8629                                                 bool IsIndirect,
8630                                                 const DebugLoc &DL,
8631                                                 unsigned O) {
8632   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8633          "Expected inlined-at fields to agree");
8634   return new (DbgInfo->getAlloc())
8635       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
8636                  Dependencies, IsIndirect, DL, O,
8637                  /*IsVariadic=*/false);
8638 }
8639 
8640 /// VReg
8641 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
8642                                           unsigned VReg, bool IsIndirect,
8643                                           const DebugLoc &DL, unsigned O) {
8644   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8645          "Expected inlined-at fields to agree");
8646   return new (DbgInfo->getAlloc())
8647       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
8648                  {}, IsIndirect, DL, O,
8649                  /*IsVariadic=*/false);
8650 }
8651 
8652 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
8653                                           ArrayRef<SDDbgOperand> Locs,
8654                                           ArrayRef<SDNode *> Dependencies,
8655                                           bool IsIndirect, const DebugLoc &DL,
8656                                           unsigned O, bool IsVariadic) {
8657   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8658          "Expected inlined-at fields to agree");
8659   return new (DbgInfo->getAlloc())
8660       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
8661                  DL, O, IsVariadic);
8662 }
8663 
8664 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8665                                      unsigned OffsetInBits, unsigned SizeInBits,
8666                                      bool InvalidateDbg) {
8667   SDNode *FromNode = From.getNode();
8668   SDNode *ToNode = To.getNode();
8669   assert(FromNode && ToNode && "Can't modify dbg values");
8670 
8671   // PR35338
8672   // TODO: assert(From != To && "Redundant dbg value transfer");
8673   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8674   if (From == To || FromNode == ToNode)
8675     return;
8676 
8677   if (!FromNode->getHasDebugValue())
8678     return;
8679 
8680   SDDbgOperand FromLocOp =
8681       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
8682   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
8683 
8684   SmallVector<SDDbgValue *, 2> ClonedDVs;
8685   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8686     if (Dbg->isInvalidated())
8687       continue;
8688 
8689     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8690 
8691     // Create a new location ops vector that is equal to the old vector, but
8692     // with each instance of FromLocOp replaced with ToLocOp.
8693     bool Changed = false;
8694     auto NewLocOps = Dbg->copyLocationOps();
8695     std::replace_if(
8696         NewLocOps.begin(), NewLocOps.end(),
8697         [&Changed, FromLocOp](const SDDbgOperand &Op) {
8698           bool Match = Op == FromLocOp;
8699           Changed |= Match;
8700           return Match;
8701         },
8702         ToLocOp);
8703     // Ignore this SDDbgValue if we didn't find a matching location.
8704     if (!Changed)
8705       continue;
8706 
8707     DIVariable *Var = Dbg->getVariable();
8708     auto *Expr = Dbg->getExpression();
8709     // If a fragment is requested, update the expression.
8710     if (SizeInBits) {
8711       // When splitting a larger (e.g., sign-extended) value whose
8712       // lower bits are described with an SDDbgValue, do not attempt
8713       // to transfer the SDDbgValue to the upper bits.
8714       if (auto FI = Expr->getFragmentInfo())
8715         if (OffsetInBits + SizeInBits > FI->SizeInBits)
8716           continue;
8717       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8718                                                              SizeInBits);
8719       if (!Fragment)
8720         continue;
8721       Expr = *Fragment;
8722     }
8723 
8724     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
8725     // Clone the SDDbgValue and move it to To.
8726     SDDbgValue *Clone = getDbgValueList(
8727         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
8728         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
8729         Dbg->isVariadic());
8730     ClonedDVs.push_back(Clone);
8731 
8732     if (InvalidateDbg) {
8733       // Invalidate value and indicate the SDDbgValue should not be emitted.
8734       Dbg->setIsInvalidated();
8735       Dbg->setIsEmitted();
8736     }
8737   }
8738 
8739   for (SDDbgValue *Dbg : ClonedDVs) {
8740     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
8741            "Transferred DbgValues should depend on the new SDNode");
8742     AddDbgValue(Dbg, false);
8743   }
8744 }
8745 
8746 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8747   if (!N.getHasDebugValue())
8748     return;
8749 
8750   SmallVector<SDDbgValue *, 2> ClonedDVs;
8751   for (auto DV : GetDbgValues(&N)) {
8752     if (DV->isInvalidated())
8753       continue;
8754     switch (N.getOpcode()) {
8755     default:
8756       break;
8757     case ISD::ADD:
8758       SDValue N0 = N.getOperand(0);
8759       SDValue N1 = N.getOperand(1);
8760       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8761           isConstantIntBuildVectorOrConstantInt(N1)) {
8762         uint64_t Offset = N.getConstantOperandVal(1);
8763 
8764         // Rewrite an ADD constant node into a DIExpression. Since we are
8765         // performing arithmetic to compute the variable's *value* in the
8766         // DIExpression, we need to mark the expression with a
8767         // DW_OP_stack_value.
8768         auto *DIExpr = DV->getExpression();
8769         auto NewLocOps = DV->copyLocationOps();
8770         bool Changed = false;
8771         for (size_t i = 0; i < NewLocOps.size(); ++i) {
8772           // We're not given a ResNo to compare against because the whole
8773           // node is going away. We know that any ISD::ADD only has one
8774           // result, so we can assume any node match is using the result.
8775           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
8776               NewLocOps[i].getSDNode() != &N)
8777             continue;
8778           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
8779           SmallVector<uint64_t, 3> ExprOps;
8780           DIExpression::appendOffset(ExprOps, Offset);
8781           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
8782           Changed = true;
8783         }
8784         (void)Changed;
8785         assert(Changed && "Salvage target doesn't use N");
8786 
8787         auto AdditionalDependencies = DV->getAdditionalDependencies();
8788         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
8789                                             NewLocOps, AdditionalDependencies,
8790                                             DV->isIndirect(), DV->getDebugLoc(),
8791                                             DV->getOrder(), DV->isVariadic());
8792         ClonedDVs.push_back(Clone);
8793         DV->setIsInvalidated();
8794         DV->setIsEmitted();
8795         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8796                    N0.getNode()->dumprFull(this);
8797                    dbgs() << " into " << *DIExpr << '\n');
8798       }
8799     }
8800   }
8801 
8802   for (SDDbgValue *Dbg : ClonedDVs) {
8803     assert(!Dbg->getSDNodes().empty() &&
8804            "Salvaged DbgValue should depend on a new SDNode");
8805     AddDbgValue(Dbg, false);
8806   }
8807 }
8808 
8809 /// Creates a SDDbgLabel node.
8810 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8811                                       const DebugLoc &DL, unsigned O) {
8812   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8813          "Expected inlined-at fields to agree");
8814   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8815 }
8816 
8817 namespace {
8818 
8819 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8820 /// pointed to by a use iterator is deleted, increment the use iterator
8821 /// so that it doesn't dangle.
8822 ///
8823 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8824   SDNode::use_iterator &UI;
8825   SDNode::use_iterator &UE;
8826 
8827   void NodeDeleted(SDNode *N, SDNode *E) override {
8828     // Increment the iterator as needed.
8829     while (UI != UE && N == *UI)
8830       ++UI;
8831   }
8832 
8833 public:
8834   RAUWUpdateListener(SelectionDAG &d,
8835                      SDNode::use_iterator &ui,
8836                      SDNode::use_iterator &ue)
8837     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8838 };
8839 
8840 } // end anonymous namespace
8841 
8842 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8843 /// This can cause recursive merging of nodes in the DAG.
8844 ///
8845 /// This version assumes From has a single result value.
8846 ///
8847 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8848   SDNode *From = FromN.getNode();
8849   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8850          "Cannot replace with this method!");
8851   assert(From != To.getNode() && "Cannot replace uses of with self");
8852 
8853   // Preserve Debug Values
8854   transferDbgValues(FromN, To);
8855 
8856   // Iterate over all the existing uses of From. New uses will be added
8857   // to the beginning of the use list, which we avoid visiting.
8858   // This specifically avoids visiting uses of From that arise while the
8859   // replacement is happening, because any such uses would be the result
8860   // of CSE: If an existing node looks like From after one of its operands
8861   // is replaced by To, we don't want to replace of all its users with To
8862   // too. See PR3018 for more info.
8863   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8864   RAUWUpdateListener Listener(*this, UI, UE);
8865   while (UI != UE) {
8866     SDNode *User = *UI;
8867 
8868     // This node is about to morph, remove its old self from the CSE maps.
8869     RemoveNodeFromCSEMaps(User);
8870 
8871     // A user can appear in a use list multiple times, and when this
8872     // happens the uses are usually next to each other in the list.
8873     // To help reduce the number of CSE recomputations, process all
8874     // the uses of this user that we can find this way.
8875     do {
8876       SDUse &Use = UI.getUse();
8877       ++UI;
8878       Use.set(To);
8879       if (To->isDivergent() != From->isDivergent())
8880         updateDivergence(User);
8881     } while (UI != UE && *UI == User);
8882     // Now that we have modified User, add it back to the CSE maps.  If it
8883     // already exists there, recursively merge the results together.
8884     AddModifiedNodeToCSEMaps(User);
8885   }
8886 
8887   // If we just RAUW'd the root, take note.
8888   if (FromN == getRoot())
8889     setRoot(To);
8890 }
8891 
8892 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8893 /// This can cause recursive merging of nodes in the DAG.
8894 ///
8895 /// This version assumes that for each value of From, there is a
8896 /// corresponding value in To in the same position with the same type.
8897 ///
8898 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
8899 #ifndef NDEBUG
8900   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8901     assert((!From->hasAnyUseOfValue(i) ||
8902             From->getValueType(i) == To->getValueType(i)) &&
8903            "Cannot use this version of ReplaceAllUsesWith!");
8904 #endif
8905 
8906   // Handle the trivial case.
8907   if (From == To)
8908     return;
8909 
8910   // Preserve Debug Info. Only do this if there's a use.
8911   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8912     if (From->hasAnyUseOfValue(i)) {
8913       assert((i < To->getNumValues()) && "Invalid To location");
8914       transferDbgValues(SDValue(From, i), SDValue(To, i));
8915     }
8916 
8917   // Iterate over just the existing users of From. See the comments in
8918   // the ReplaceAllUsesWith above.
8919   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8920   RAUWUpdateListener Listener(*this, UI, UE);
8921   while (UI != UE) {
8922     SDNode *User = *UI;
8923 
8924     // This node is about to morph, remove its old self from the CSE maps.
8925     RemoveNodeFromCSEMaps(User);
8926 
8927     // A user can appear in a use list multiple times, and when this
8928     // happens the uses are usually next to each other in the list.
8929     // To help reduce the number of CSE recomputations, process all
8930     // the uses of this user that we can find this way.
8931     do {
8932       SDUse &Use = UI.getUse();
8933       ++UI;
8934       Use.setNode(To);
8935       if (To->isDivergent() != From->isDivergent())
8936         updateDivergence(User);
8937     } while (UI != UE && *UI == User);
8938 
8939     // Now that we have modified User, add it back to the CSE maps.  If it
8940     // already exists there, recursively merge the results together.
8941     AddModifiedNodeToCSEMaps(User);
8942   }
8943 
8944   // If we just RAUW'd the root, take note.
8945   if (From == getRoot().getNode())
8946     setRoot(SDValue(To, getRoot().getResNo()));
8947 }
8948 
8949 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8950 /// This can cause recursive merging of nodes in the DAG.
8951 ///
8952 /// This version can replace From with any result values.  To must match the
8953 /// number and types of values returned by From.
8954 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
8955   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
8956     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
8957 
8958   // Preserve Debug Info.
8959   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8960     transferDbgValues(SDValue(From, i), To[i]);
8961 
8962   // Iterate over just the existing users of From. See the comments in
8963   // the ReplaceAllUsesWith above.
8964   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8965   RAUWUpdateListener Listener(*this, UI, UE);
8966   while (UI != UE) {
8967     SDNode *User = *UI;
8968 
8969     // This node is about to morph, remove its old self from the CSE maps.
8970     RemoveNodeFromCSEMaps(User);
8971 
8972     // A user can appear in a use list multiple times, and when this happens the
8973     // uses are usually next to each other in the list.  To help reduce the
8974     // number of CSE and divergence recomputations, process all the uses of this
8975     // user that we can find this way.
8976     bool To_IsDivergent = false;
8977     do {
8978       SDUse &Use = UI.getUse();
8979       const SDValue &ToOp = To[Use.getResNo()];
8980       ++UI;
8981       Use.set(ToOp);
8982       To_IsDivergent |= ToOp->isDivergent();
8983     } while (UI != UE && *UI == User);
8984 
8985     if (To_IsDivergent != From->isDivergent())
8986       updateDivergence(User);
8987 
8988     // Now that we have modified User, add it back to the CSE maps.  If it
8989     // already exists there, recursively merge the results together.
8990     AddModifiedNodeToCSEMaps(User);
8991   }
8992 
8993   // If we just RAUW'd the root, take note.
8994   if (From == getRoot().getNode())
8995     setRoot(SDValue(To[getRoot().getResNo()]));
8996 }
8997 
8998 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8999 /// uses of other values produced by From.getNode() alone.  The Deleted
9000 /// vector is handled the same way as for ReplaceAllUsesWith.
9001 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9002   // Handle the really simple, really trivial case efficiently.
9003   if (From == To) return;
9004 
9005   // Handle the simple, trivial, case efficiently.
9006   if (From.getNode()->getNumValues() == 1) {
9007     ReplaceAllUsesWith(From, To);
9008     return;
9009   }
9010 
9011   // Preserve Debug Info.
9012   transferDbgValues(From, To);
9013 
9014   // Iterate over just the existing users of From. See the comments in
9015   // the ReplaceAllUsesWith above.
9016   SDNode::use_iterator UI = From.getNode()->use_begin(),
9017                        UE = From.getNode()->use_end();
9018   RAUWUpdateListener Listener(*this, UI, UE);
9019   while (UI != UE) {
9020     SDNode *User = *UI;
9021     bool UserRemovedFromCSEMaps = false;
9022 
9023     // A user can appear in a use list multiple times, and when this
9024     // happens the uses are usually next to each other in the list.
9025     // To help reduce the number of CSE recomputations, process all
9026     // the uses of this user that we can find this way.
9027     do {
9028       SDUse &Use = UI.getUse();
9029 
9030       // Skip uses of different values from the same node.
9031       if (Use.getResNo() != From.getResNo()) {
9032         ++UI;
9033         continue;
9034       }
9035 
9036       // If this node hasn't been modified yet, it's still in the CSE maps,
9037       // so remove its old self from the CSE maps.
9038       if (!UserRemovedFromCSEMaps) {
9039         RemoveNodeFromCSEMaps(User);
9040         UserRemovedFromCSEMaps = true;
9041       }
9042 
9043       ++UI;
9044       Use.set(To);
9045       if (To->isDivergent() != From->isDivergent())
9046         updateDivergence(User);
9047     } while (UI != UE && *UI == User);
9048     // We are iterating over all uses of the From node, so if a use
9049     // doesn't use the specific value, no changes are made.
9050     if (!UserRemovedFromCSEMaps)
9051       continue;
9052 
9053     // Now that we have modified User, add it back to the CSE maps.  If it
9054     // already exists there, recursively merge the results together.
9055     AddModifiedNodeToCSEMaps(User);
9056   }
9057 
9058   // If we just RAUW'd the root, take note.
9059   if (From == getRoot())
9060     setRoot(To);
9061 }
9062 
9063 namespace {
9064 
9065   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9066   /// to record information about a use.
9067   struct UseMemo {
9068     SDNode *User;
9069     unsigned Index;
9070     SDUse *Use;
9071   };
9072 
9073   /// operator< - Sort Memos by User.
9074   bool operator<(const UseMemo &L, const UseMemo &R) {
9075     return (intptr_t)L.User < (intptr_t)R.User;
9076   }
9077 
9078 } // end anonymous namespace
9079 
9080 bool SelectionDAG::calculateDivergence(SDNode *N) {
9081   if (TLI->isSDNodeAlwaysUniform(N)) {
9082     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9083            "Conflicting divergence information!");
9084     return false;
9085   }
9086   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9087     return true;
9088   for (auto &Op : N->ops()) {
9089     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9090       return true;
9091   }
9092   return false;
9093 }
9094 
9095 void SelectionDAG::updateDivergence(SDNode *N) {
9096   SmallVector<SDNode *, 16> Worklist(1, N);
9097   do {
9098     N = Worklist.pop_back_val();
9099     bool IsDivergent = calculateDivergence(N);
9100     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9101       N->SDNodeBits.IsDivergent = IsDivergent;
9102       llvm::append_range(Worklist, N->uses());
9103     }
9104   } while (!Worklist.empty());
9105 }
9106 
9107 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9108   DenseMap<SDNode *, unsigned> Degree;
9109   Order.reserve(AllNodes.size());
9110   for (auto &N : allnodes()) {
9111     unsigned NOps = N.getNumOperands();
9112     Degree[&N] = NOps;
9113     if (0 == NOps)
9114       Order.push_back(&N);
9115   }
9116   for (size_t I = 0; I != Order.size(); ++I) {
9117     SDNode *N = Order[I];
9118     for (auto U : N->uses()) {
9119       unsigned &UnsortedOps = Degree[U];
9120       if (0 == --UnsortedOps)
9121         Order.push_back(U);
9122     }
9123   }
9124 }
9125 
9126 #ifndef NDEBUG
9127 void SelectionDAG::VerifyDAGDiverence() {
9128   std::vector<SDNode *> TopoOrder;
9129   CreateTopologicalOrder(TopoOrder);
9130   for (auto *N : TopoOrder) {
9131     assert(calculateDivergence(N) == N->isDivergent() &&
9132            "Divergence bit inconsistency detected");
9133   }
9134 }
9135 #endif
9136 
9137 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9138 /// uses of other values produced by From.getNode() alone.  The same value
9139 /// may appear in both the From and To list.  The Deleted vector is
9140 /// handled the same way as for ReplaceAllUsesWith.
9141 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9142                                               const SDValue *To,
9143                                               unsigned Num){
9144   // Handle the simple, trivial case efficiently.
9145   if (Num == 1)
9146     return ReplaceAllUsesOfValueWith(*From, *To);
9147 
9148   transferDbgValues(*From, *To);
9149 
9150   // Read up all the uses and make records of them. This helps
9151   // processing new uses that are introduced during the
9152   // replacement process.
9153   SmallVector<UseMemo, 4> Uses;
9154   for (unsigned i = 0; i != Num; ++i) {
9155     unsigned FromResNo = From[i].getResNo();
9156     SDNode *FromNode = From[i].getNode();
9157     for (SDNode::use_iterator UI = FromNode->use_begin(),
9158          E = FromNode->use_end(); UI != E; ++UI) {
9159       SDUse &Use = UI.getUse();
9160       if (Use.getResNo() == FromResNo) {
9161         UseMemo Memo = { *UI, i, &Use };
9162         Uses.push_back(Memo);
9163       }
9164     }
9165   }
9166 
9167   // Sort the uses, so that all the uses from a given User are together.
9168   llvm::sort(Uses);
9169 
9170   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9171        UseIndex != UseIndexEnd; ) {
9172     // We know that this user uses some value of From.  If it is the right
9173     // value, update it.
9174     SDNode *User = Uses[UseIndex].User;
9175 
9176     // This node is about to morph, remove its old self from the CSE maps.
9177     RemoveNodeFromCSEMaps(User);
9178 
9179     // The Uses array is sorted, so all the uses for a given User
9180     // are next to each other in the list.
9181     // To help reduce the number of CSE recomputations, process all
9182     // the uses of this user that we can find this way.
9183     do {
9184       unsigned i = Uses[UseIndex].Index;
9185       SDUse &Use = *Uses[UseIndex].Use;
9186       ++UseIndex;
9187 
9188       Use.set(To[i]);
9189     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9190 
9191     // Now that we have modified User, add it back to the CSE maps.  If it
9192     // already exists there, recursively merge the results together.
9193     AddModifiedNodeToCSEMaps(User);
9194   }
9195 }
9196 
9197 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9198 /// based on their topological order. It returns the maximum id and a vector
9199 /// of the SDNodes* in assigned order by reference.
9200 unsigned SelectionDAG::AssignTopologicalOrder() {
9201   unsigned DAGSize = 0;
9202 
9203   // SortedPos tracks the progress of the algorithm. Nodes before it are
9204   // sorted, nodes after it are unsorted. When the algorithm completes
9205   // it is at the end of the list.
9206   allnodes_iterator SortedPos = allnodes_begin();
9207 
9208   // Visit all the nodes. Move nodes with no operands to the front of
9209   // the list immediately. Annotate nodes that do have operands with their
9210   // operand count. Before we do this, the Node Id fields of the nodes
9211   // may contain arbitrary values. After, the Node Id fields for nodes
9212   // before SortedPos will contain the topological sort index, and the
9213   // Node Id fields for nodes At SortedPos and after will contain the
9214   // count of outstanding operands.
9215   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
9216     SDNode *N = &*I++;
9217     checkForCycles(N, this);
9218     unsigned Degree = N->getNumOperands();
9219     if (Degree == 0) {
9220       // A node with no uses, add it to the result array immediately.
9221       N->setNodeId(DAGSize++);
9222       allnodes_iterator Q(N);
9223       if (Q != SortedPos)
9224         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9225       assert(SortedPos != AllNodes.end() && "Overran node list");
9226       ++SortedPos;
9227     } else {
9228       // Temporarily use the Node Id as scratch space for the degree count.
9229       N->setNodeId(Degree);
9230     }
9231   }
9232 
9233   // Visit all the nodes. As we iterate, move nodes into sorted order,
9234   // such that by the time the end is reached all nodes will be sorted.
9235   for (SDNode &Node : allnodes()) {
9236     SDNode *N = &Node;
9237     checkForCycles(N, this);
9238     // N is in sorted position, so all its uses have one less operand
9239     // that needs to be sorted.
9240     for (SDNode *P : N->uses()) {
9241       unsigned Degree = P->getNodeId();
9242       assert(Degree != 0 && "Invalid node degree");
9243       --Degree;
9244       if (Degree == 0) {
9245         // All of P's operands are sorted, so P may sorted now.
9246         P->setNodeId(DAGSize++);
9247         if (P->getIterator() != SortedPos)
9248           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9249         assert(SortedPos != AllNodes.end() && "Overran node list");
9250         ++SortedPos;
9251       } else {
9252         // Update P's outstanding operand count.
9253         P->setNodeId(Degree);
9254       }
9255     }
9256     if (Node.getIterator() == SortedPos) {
9257 #ifndef NDEBUG
9258       allnodes_iterator I(N);
9259       SDNode *S = &*++I;
9260       dbgs() << "Overran sorted position:\n";
9261       S->dumprFull(this); dbgs() << "\n";
9262       dbgs() << "Checking if this is due to cycles\n";
9263       checkForCycles(this, true);
9264 #endif
9265       llvm_unreachable(nullptr);
9266     }
9267   }
9268 
9269   assert(SortedPos == AllNodes.end() &&
9270          "Topological sort incomplete!");
9271   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9272          "First node in topological sort is not the entry token!");
9273   assert(AllNodes.front().getNodeId() == 0 &&
9274          "First node in topological sort has non-zero id!");
9275   assert(AllNodes.front().getNumOperands() == 0 &&
9276          "First node in topological sort has operands!");
9277   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9278          "Last node in topologic sort has unexpected id!");
9279   assert(AllNodes.back().use_empty() &&
9280          "Last node in topologic sort has users!");
9281   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9282   return DAGSize;
9283 }
9284 
9285 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9286 /// value is produced by SD.
9287 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9288   for (SDNode *SD : DB->getSDNodes()) {
9289     if (!SD)
9290       continue;
9291     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9292     SD->setHasDebugValue(true);
9293   }
9294   DbgInfo->add(DB, isParameter);
9295 }
9296 
9297 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9298 
9299 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9300                                                    SDValue NewMemOpChain) {
9301   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9302   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9303   // The new memory operation must have the same position as the old load in
9304   // terms of memory dependency. Create a TokenFactor for the old load and new
9305   // memory operation and update uses of the old load's output chain to use that
9306   // TokenFactor.
9307   if (OldChain == NewMemOpChain || OldChain.use_empty())
9308     return NewMemOpChain;
9309 
9310   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9311                                 OldChain, NewMemOpChain);
9312   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9313   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9314   return TokenFactor;
9315 }
9316 
9317 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9318                                                    SDValue NewMemOp) {
9319   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9320   SDValue OldChain = SDValue(OldLoad, 1);
9321   SDValue NewMemOpChain = NewMemOp.getValue(1);
9322   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9323 }
9324 
9325 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9326                                                      Function **OutFunction) {
9327   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9328 
9329   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9330   auto *Module = MF->getFunction().getParent();
9331   auto *Function = Module->getFunction(Symbol);
9332 
9333   if (OutFunction != nullptr)
9334       *OutFunction = Function;
9335 
9336   if (Function != nullptr) {
9337     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9338     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9339   }
9340 
9341   std::string ErrorStr;
9342   raw_string_ostream ErrorFormatter(ErrorStr);
9343 
9344   ErrorFormatter << "Undefined external symbol ";
9345   ErrorFormatter << '"' << Symbol << '"';
9346   ErrorFormatter.flush();
9347 
9348   report_fatal_error(ErrorStr);
9349 }
9350 
9351 //===----------------------------------------------------------------------===//
9352 //                              SDNode Class
9353 //===----------------------------------------------------------------------===//
9354 
9355 bool llvm::isNullConstant(SDValue V) {
9356   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9357   return Const != nullptr && Const->isNullValue();
9358 }
9359 
9360 bool llvm::isNullFPConstant(SDValue V) {
9361   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9362   return Const != nullptr && Const->isZero() && !Const->isNegative();
9363 }
9364 
9365 bool llvm::isAllOnesConstant(SDValue V) {
9366   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9367   return Const != nullptr && Const->isAllOnesValue();
9368 }
9369 
9370 bool llvm::isOneConstant(SDValue V) {
9371   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9372   return Const != nullptr && Const->isOne();
9373 }
9374 
9375 SDValue llvm::peekThroughBitcasts(SDValue V) {
9376   while (V.getOpcode() == ISD::BITCAST)
9377     V = V.getOperand(0);
9378   return V;
9379 }
9380 
9381 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9382   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9383     V = V.getOperand(0);
9384   return V;
9385 }
9386 
9387 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9388   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9389     V = V.getOperand(0);
9390   return V;
9391 }
9392 
9393 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9394   if (V.getOpcode() != ISD::XOR)
9395     return false;
9396   V = peekThroughBitcasts(V.getOperand(1));
9397   unsigned NumBits = V.getScalarValueSizeInBits();
9398   ConstantSDNode *C =
9399       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9400   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9401 }
9402 
9403 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9404                                           bool AllowTruncation) {
9405   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9406     return CN;
9407 
9408   // SplatVectors can truncate their operands. Ignore that case here unless
9409   // AllowTruncation is set.
9410   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9411     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9412     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9413       EVT CVT = CN->getValueType(0);
9414       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9415       if (AllowTruncation || CVT == VecEltVT)
9416         return CN;
9417     }
9418   }
9419 
9420   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9421     BitVector UndefElements;
9422     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9423 
9424     // BuildVectors can truncate their operands. Ignore that case here unless
9425     // AllowTruncation is set.
9426     if (CN && (UndefElements.none() || AllowUndefs)) {
9427       EVT CVT = CN->getValueType(0);
9428       EVT NSVT = N.getValueType().getScalarType();
9429       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9430       if (AllowTruncation || (CVT == NSVT))
9431         return CN;
9432     }
9433   }
9434 
9435   return nullptr;
9436 }
9437 
9438 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9439                                           bool AllowUndefs,
9440                                           bool AllowTruncation) {
9441   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9442     return CN;
9443 
9444   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9445     BitVector UndefElements;
9446     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9447 
9448     // BuildVectors can truncate their operands. Ignore that case here unless
9449     // AllowTruncation is set.
9450     if (CN && (UndefElements.none() || AllowUndefs)) {
9451       EVT CVT = CN->getValueType(0);
9452       EVT NSVT = N.getValueType().getScalarType();
9453       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9454       if (AllowTruncation || (CVT == NSVT))
9455         return CN;
9456     }
9457   }
9458 
9459   return nullptr;
9460 }
9461 
9462 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
9463   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9464     return CN;
9465 
9466   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9467     BitVector UndefElements;
9468     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
9469     if (CN && (UndefElements.none() || AllowUndefs))
9470       return CN;
9471   }
9472 
9473   if (N.getOpcode() == ISD::SPLAT_VECTOR)
9474     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
9475       return CN;
9476 
9477   return nullptr;
9478 }
9479 
9480 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
9481                                               const APInt &DemandedElts,
9482                                               bool AllowUndefs) {
9483   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9484     return CN;
9485 
9486   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9487     BitVector UndefElements;
9488     ConstantFPSDNode *CN =
9489         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
9490     if (CN && (UndefElements.none() || AllowUndefs))
9491       return CN;
9492   }
9493 
9494   return nullptr;
9495 }
9496 
9497 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
9498   // TODO: may want to use peekThroughBitcast() here.
9499   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9500   return C && C->isNullValue();
9501 }
9502 
9503 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
9504   // TODO: may want to use peekThroughBitcast() here.
9505   unsigned BitWidth = N.getScalarValueSizeInBits();
9506   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9507   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
9508 }
9509 
9510 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
9511   N = peekThroughBitcasts(N);
9512   unsigned BitWidth = N.getScalarValueSizeInBits();
9513   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9514   return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
9515 }
9516 
9517 HandleSDNode::~HandleSDNode() {
9518   DropOperands();
9519 }
9520 
9521 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
9522                                          const DebugLoc &DL,
9523                                          const GlobalValue *GA, EVT VT,
9524                                          int64_t o, unsigned TF)
9525     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
9526   TheGlobal = GA;
9527 }
9528 
9529 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
9530                                          EVT VT, unsigned SrcAS,
9531                                          unsigned DestAS)
9532     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
9533       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
9534 
9535 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
9536                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
9537     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
9538   MemSDNodeBits.IsVolatile = MMO->isVolatile();
9539   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
9540   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
9541   MemSDNodeBits.IsInvariant = MMO->isInvariant();
9542 
9543   // We check here that the size of the memory operand fits within the size of
9544   // the MMO. This is because the MMO might indicate only a possible address
9545   // range instead of specifying the affected memory addresses precisely.
9546   // TODO: Make MachineMemOperands aware of scalable vectors.
9547   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
9548          "Size mismatch!");
9549 }
9550 
9551 /// Profile - Gather unique data for the node.
9552 ///
9553 void SDNode::Profile(FoldingSetNodeID &ID) const {
9554   AddNodeIDNode(ID, this);
9555 }
9556 
9557 namespace {
9558 
9559   struct EVTArray {
9560     std::vector<EVT> VTs;
9561 
9562     EVTArray() {
9563       VTs.reserve(MVT::LAST_VALUETYPE);
9564       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
9565         VTs.push_back(MVT((MVT::SimpleValueType)i));
9566     }
9567   };
9568 
9569 } // end anonymous namespace
9570 
9571 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
9572 static ManagedStatic<EVTArray> SimpleVTArray;
9573 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
9574 
9575 /// getValueTypeList - Return a pointer to the specified value type.
9576 ///
9577 const EVT *SDNode::getValueTypeList(EVT VT) {
9578   if (VT.isExtended()) {
9579     sys::SmartScopedLock<true> Lock(*VTMutex);
9580     return &(*EVTs->insert(VT).first);
9581   }
9582   assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && "Value type out of range!");
9583   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
9584 }
9585 
9586 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
9587 /// indicated value.  This method ignores uses of other values defined by this
9588 /// operation.
9589 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
9590   assert(Value < getNumValues() && "Bad value!");
9591 
9592   // TODO: Only iterate over uses of a given value of the node
9593   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
9594     if (UI.getUse().getResNo() == Value) {
9595       if (NUses == 0)
9596         return false;
9597       --NUses;
9598     }
9599   }
9600 
9601   // Found exactly the right number of uses?
9602   return NUses == 0;
9603 }
9604 
9605 /// hasAnyUseOfValue - Return true if there are any use of the indicated
9606 /// value. This method ignores uses of other values defined by this operation.
9607 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
9608   assert(Value < getNumValues() && "Bad value!");
9609 
9610   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
9611     if (UI.getUse().getResNo() == Value)
9612       return true;
9613 
9614   return false;
9615 }
9616 
9617 /// isOnlyUserOf - Return true if this node is the only use of N.
9618 bool SDNode::isOnlyUserOf(const SDNode *N) const {
9619   bool Seen = false;
9620   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9621     SDNode *User = *I;
9622     if (User == this)
9623       Seen = true;
9624     else
9625       return false;
9626   }
9627 
9628   return Seen;
9629 }
9630 
9631 /// Return true if the only users of N are contained in Nodes.
9632 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
9633   bool Seen = false;
9634   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9635     SDNode *User = *I;
9636     if (llvm::is_contained(Nodes, User))
9637       Seen = true;
9638     else
9639       return false;
9640   }
9641 
9642   return Seen;
9643 }
9644 
9645 /// isOperand - Return true if this node is an operand of N.
9646 bool SDValue::isOperandOf(const SDNode *N) const {
9647   return is_contained(N->op_values(), *this);
9648 }
9649 
9650 bool SDNode::isOperandOf(const SDNode *N) const {
9651   return any_of(N->op_values(),
9652                 [this](SDValue Op) { return this == Op.getNode(); });
9653 }
9654 
9655 /// reachesChainWithoutSideEffects - Return true if this operand (which must
9656 /// be a chain) reaches the specified operand without crossing any
9657 /// side-effecting instructions on any chain path.  In practice, this looks
9658 /// through token factors and non-volatile loads.  In order to remain efficient,
9659 /// this only looks a couple of nodes in, it does not do an exhaustive search.
9660 ///
9661 /// Note that we only need to examine chains when we're searching for
9662 /// side-effects; SelectionDAG requires that all side-effects are represented
9663 /// by chains, even if another operand would force a specific ordering. This
9664 /// constraint is necessary to allow transformations like splitting loads.
9665 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
9666                                              unsigned Depth) const {
9667   if (*this == Dest) return true;
9668 
9669   // Don't search too deeply, we just want to be able to see through
9670   // TokenFactor's etc.
9671   if (Depth == 0) return false;
9672 
9673   // If this is a token factor, all inputs to the TF happen in parallel.
9674   if (getOpcode() == ISD::TokenFactor) {
9675     // First, try a shallow search.
9676     if (is_contained((*this)->ops(), Dest)) {
9677       // We found the chain we want as an operand of this TokenFactor.
9678       // Essentially, we reach the chain without side-effects if we could
9679       // serialize the TokenFactor into a simple chain of operations with
9680       // Dest as the last operation. This is automatically true if the
9681       // chain has one use: there are no other ordering constraints.
9682       // If the chain has more than one use, we give up: some other
9683       // use of Dest might force a side-effect between Dest and the current
9684       // node.
9685       if (Dest.hasOneUse())
9686         return true;
9687     }
9688     // Next, try a deep search: check whether every operand of the TokenFactor
9689     // reaches Dest.
9690     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
9691       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
9692     });
9693   }
9694 
9695   // Loads don't have side effects, look through them.
9696   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
9697     if (Ld->isUnordered())
9698       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
9699   }
9700   return false;
9701 }
9702 
9703 bool SDNode::hasPredecessor(const SDNode *N) const {
9704   SmallPtrSet<const SDNode *, 32> Visited;
9705   SmallVector<const SDNode *, 16> Worklist;
9706   Worklist.push_back(this);
9707   return hasPredecessorHelper(N, Visited, Worklist);
9708 }
9709 
9710 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
9711   this->Flags.intersectWith(Flags);
9712 }
9713 
9714 SDValue
9715 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
9716                                   ArrayRef<ISD::NodeType> CandidateBinOps,
9717                                   bool AllowPartials) {
9718   // The pattern must end in an extract from index 0.
9719   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9720       !isNullConstant(Extract->getOperand(1)))
9721     return SDValue();
9722 
9723   // Match against one of the candidate binary ops.
9724   SDValue Op = Extract->getOperand(0);
9725   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9726         return Op.getOpcode() == unsigned(BinOp);
9727       }))
9728     return SDValue();
9729 
9730   // Floating-point reductions may require relaxed constraints on the final step
9731   // of the reduction because they may reorder intermediate operations.
9732   unsigned CandidateBinOp = Op.getOpcode();
9733   if (Op.getValueType().isFloatingPoint()) {
9734     SDNodeFlags Flags = Op->getFlags();
9735     switch (CandidateBinOp) {
9736     case ISD::FADD:
9737       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
9738         return SDValue();
9739       break;
9740     default:
9741       llvm_unreachable("Unhandled FP opcode for binop reduction");
9742     }
9743   }
9744 
9745   // Matching failed - attempt to see if we did enough stages that a partial
9746   // reduction from a subvector is possible.
9747   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
9748     if (!AllowPartials || !Op)
9749       return SDValue();
9750     EVT OpVT = Op.getValueType();
9751     EVT OpSVT = OpVT.getScalarType();
9752     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
9753     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
9754       return SDValue();
9755     BinOp = (ISD::NodeType)CandidateBinOp;
9756     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
9757                    getVectorIdxConstant(0, SDLoc(Op)));
9758   };
9759 
9760   // At each stage, we're looking for something that looks like:
9761   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9762   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9763   //                               i32 undef, i32 undef, i32 undef, i32 undef>
9764   // %a = binop <8 x i32> %op, %s
9765   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9766   // we expect something like:
9767   // <4,5,6,7,u,u,u,u>
9768   // <2,3,u,u,u,u,u,u>
9769   // <1,u,u,u,u,u,u,u>
9770   // While a partial reduction match would be:
9771   // <2,3,u,u,u,u,u,u>
9772   // <1,u,u,u,u,u,u,u>
9773   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9774   SDValue PrevOp;
9775   for (unsigned i = 0; i < Stages; ++i) {
9776     unsigned MaskEnd = (1 << i);
9777 
9778     if (Op.getOpcode() != CandidateBinOp)
9779       return PartialReduction(PrevOp, MaskEnd);
9780 
9781     SDValue Op0 = Op.getOperand(0);
9782     SDValue Op1 = Op.getOperand(1);
9783 
9784     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9785     if (Shuffle) {
9786       Op = Op1;
9787     } else {
9788       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9789       Op = Op0;
9790     }
9791 
9792     // The first operand of the shuffle should be the same as the other operand
9793     // of the binop.
9794     if (!Shuffle || Shuffle->getOperand(0) != Op)
9795       return PartialReduction(PrevOp, MaskEnd);
9796 
9797     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9798     for (int Index = 0; Index < (int)MaskEnd; ++Index)
9799       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
9800         return PartialReduction(PrevOp, MaskEnd);
9801 
9802     PrevOp = Op;
9803   }
9804 
9805   // Handle subvector reductions, which tend to appear after the shuffle
9806   // reduction stages.
9807   while (Op.getOpcode() == CandidateBinOp) {
9808     unsigned NumElts = Op.getValueType().getVectorNumElements();
9809     SDValue Op0 = Op.getOperand(0);
9810     SDValue Op1 = Op.getOperand(1);
9811     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9812         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9813         Op0.getOperand(0) != Op1.getOperand(0))
9814       break;
9815     SDValue Src = Op0.getOperand(0);
9816     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
9817     if (NumSrcElts != (2 * NumElts))
9818       break;
9819     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
9820           Op1.getConstantOperandAPInt(1) == NumElts) &&
9821         !(Op1.getConstantOperandAPInt(1) == 0 &&
9822           Op0.getConstantOperandAPInt(1) == NumElts))
9823       break;
9824     Op = Src;
9825   }
9826 
9827   BinOp = (ISD::NodeType)CandidateBinOp;
9828   return Op;
9829 }
9830 
9831 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9832   assert(N->getNumValues() == 1 &&
9833          "Can't unroll a vector with multiple results!");
9834 
9835   EVT VT = N->getValueType(0);
9836   unsigned NE = VT.getVectorNumElements();
9837   EVT EltVT = VT.getVectorElementType();
9838   SDLoc dl(N);
9839 
9840   SmallVector<SDValue, 8> Scalars;
9841   SmallVector<SDValue, 4> Operands(N->getNumOperands());
9842 
9843   // If ResNE is 0, fully unroll the vector op.
9844   if (ResNE == 0)
9845     ResNE = NE;
9846   else if (NE > ResNE)
9847     NE = ResNE;
9848 
9849   unsigned i;
9850   for (i= 0; i != NE; ++i) {
9851     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9852       SDValue Operand = N->getOperand(j);
9853       EVT OperandVT = Operand.getValueType();
9854       if (OperandVT.isVector()) {
9855         // A vector operand; extract a single element.
9856         EVT OperandEltVT = OperandVT.getVectorElementType();
9857         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
9858                               Operand, getVectorIdxConstant(i, dl));
9859       } else {
9860         // A scalar operand; just use it as is.
9861         Operands[j] = Operand;
9862       }
9863     }
9864 
9865     switch (N->getOpcode()) {
9866     default: {
9867       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9868                                 N->getFlags()));
9869       break;
9870     }
9871     case ISD::VSELECT:
9872       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
9873       break;
9874     case ISD::SHL:
9875     case ISD::SRA:
9876     case ISD::SRL:
9877     case ISD::ROTL:
9878     case ISD::ROTR:
9879       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
9880                                getShiftAmountOperand(Operands[0].getValueType(),
9881                                                      Operands[1])));
9882       break;
9883     case ISD::SIGN_EXTEND_INREG: {
9884       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
9885       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
9886                                 Operands[0],
9887                                 getValueType(ExtVT)));
9888     }
9889     }
9890   }
9891 
9892   for (; i < ResNE; ++i)
9893     Scalars.push_back(getUNDEF(EltVT));
9894 
9895   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
9896   return getBuildVector(VecVT, dl, Scalars);
9897 }
9898 
9899 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
9900     SDNode *N, unsigned ResNE) {
9901   unsigned Opcode = N->getOpcode();
9902   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
9903           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
9904           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
9905          "Expected an overflow opcode");
9906 
9907   EVT ResVT = N->getValueType(0);
9908   EVT OvVT = N->getValueType(1);
9909   EVT ResEltVT = ResVT.getVectorElementType();
9910   EVT OvEltVT = OvVT.getVectorElementType();
9911   SDLoc dl(N);
9912 
9913   // If ResNE is 0, fully unroll the vector op.
9914   unsigned NE = ResVT.getVectorNumElements();
9915   if (ResNE == 0)
9916     ResNE = NE;
9917   else if (NE > ResNE)
9918     NE = ResNE;
9919 
9920   SmallVector<SDValue, 8> LHSScalars;
9921   SmallVector<SDValue, 8> RHSScalars;
9922   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
9923   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
9924 
9925   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
9926   SDVTList VTs = getVTList(ResEltVT, SVT);
9927   SmallVector<SDValue, 8> ResScalars;
9928   SmallVector<SDValue, 8> OvScalars;
9929   for (unsigned i = 0; i < NE; ++i) {
9930     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
9931     SDValue Ov =
9932         getSelect(dl, OvEltVT, Res.getValue(1),
9933                   getBoolConstant(true, dl, OvEltVT, ResVT),
9934                   getConstant(0, dl, OvEltVT));
9935 
9936     ResScalars.push_back(Res);
9937     OvScalars.push_back(Ov);
9938   }
9939 
9940   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
9941   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
9942 
9943   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
9944   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
9945   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
9946                         getBuildVector(NewOvVT, dl, OvScalars));
9947 }
9948 
9949 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
9950                                                   LoadSDNode *Base,
9951                                                   unsigned Bytes,
9952                                                   int Dist) const {
9953   if (LD->isVolatile() || Base->isVolatile())
9954     return false;
9955   // TODO: probably too restrictive for atomics, revisit
9956   if (!LD->isSimple())
9957     return false;
9958   if (LD->isIndexed() || Base->isIndexed())
9959     return false;
9960   if (LD->getChain() != Base->getChain())
9961     return false;
9962   EVT VT = LD->getValueType(0);
9963   if (VT.getSizeInBits() / 8 != Bytes)
9964     return false;
9965 
9966   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
9967   auto LocDecomp = BaseIndexOffset::match(LD, *this);
9968 
9969   int64_t Offset = 0;
9970   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
9971     return (Dist * Bytes == Offset);
9972   return false;
9973 }
9974 
9975 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
9976 /// if it cannot be inferred.
9977 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
9978   // If this is a GlobalAddress + cst, return the alignment.
9979   const GlobalValue *GV = nullptr;
9980   int64_t GVOffset = 0;
9981   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
9982     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
9983     KnownBits Known(PtrWidth);
9984     llvm::computeKnownBits(GV, Known, getDataLayout());
9985     unsigned AlignBits = Known.countMinTrailingZeros();
9986     if (AlignBits)
9987       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
9988   }
9989 
9990   // If this is a direct reference to a stack slot, use information about the
9991   // stack slot's alignment.
9992   int FrameIdx = INT_MIN;
9993   int64_t FrameOffset = 0;
9994   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
9995     FrameIdx = FI->getIndex();
9996   } else if (isBaseWithConstantOffset(Ptr) &&
9997              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
9998     // Handle FI+Cst
9999     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10000     FrameOffset = Ptr.getConstantOperandVal(1);
10001   }
10002 
10003   if (FrameIdx != INT_MIN) {
10004     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10005     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10006   }
10007 
10008   return None;
10009 }
10010 
10011 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10012 /// which is split (or expanded) into two not necessarily identical pieces.
10013 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10014   // Currently all types are split in half.
10015   EVT LoVT, HiVT;
10016   if (!VT.isVector())
10017     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10018   else
10019     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10020 
10021   return std::make_pair(LoVT, HiVT);
10022 }
10023 
10024 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10025 /// type, dependent on an enveloping VT that has been split into two identical
10026 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10027 std::pair<EVT, EVT>
10028 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10029                                        bool *HiIsEmpty) const {
10030   EVT EltTp = VT.getVectorElementType();
10031   // Examples:
10032   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10033   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10034   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10035   //   etc.
10036   ElementCount VTNumElts = VT.getVectorElementCount();
10037   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10038   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10039          "Mixing fixed width and scalable vectors when enveloping a type");
10040   EVT LoVT, HiVT;
10041   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10042     LoVT = EnvVT;
10043     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10044     *HiIsEmpty = false;
10045   } else {
10046     // Flag that hi type has zero storage size, but return split envelop type
10047     // (this would be easier if vector types with zero elements were allowed).
10048     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10049     HiVT = EnvVT;
10050     *HiIsEmpty = true;
10051   }
10052   return std::make_pair(LoVT, HiVT);
10053 }
10054 
10055 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10056 /// low/high part.
10057 std::pair<SDValue, SDValue>
10058 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10059                           const EVT &HiVT) {
10060   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10061          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10062          "Splitting vector with an invalid mixture of fixed and scalable "
10063          "vector types");
10064   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10065              N.getValueType().getVectorMinNumElements() &&
10066          "More vector elements requested than available!");
10067   SDValue Lo, Hi;
10068   Lo =
10069       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10070   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10071   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10072   // IDX with the runtime scaling factor of the result vector type. For
10073   // fixed-width result vectors, that runtime scaling factor is 1.
10074   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10075                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10076   return std::make_pair(Lo, Hi);
10077 }
10078 
10079 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10080 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10081   EVT VT = N.getValueType();
10082   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10083                                 NextPowerOf2(VT.getVectorNumElements()));
10084   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10085                  getVectorIdxConstant(0, DL));
10086 }
10087 
10088 void SelectionDAG::ExtractVectorElements(SDValue Op,
10089                                          SmallVectorImpl<SDValue> &Args,
10090                                          unsigned Start, unsigned Count,
10091                                          EVT EltVT) {
10092   EVT VT = Op.getValueType();
10093   if (Count == 0)
10094     Count = VT.getVectorNumElements();
10095   if (EltVT == EVT())
10096     EltVT = VT.getVectorElementType();
10097   SDLoc SL(Op);
10098   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10099     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10100                            getVectorIdxConstant(i, SL)));
10101   }
10102 }
10103 
10104 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10105 unsigned GlobalAddressSDNode::getAddressSpace() const {
10106   return getGlobal()->getType()->getAddressSpace();
10107 }
10108 
10109 Type *ConstantPoolSDNode::getType() const {
10110   if (isMachineConstantPoolEntry())
10111     return Val.MachineCPVal->getType();
10112   return Val.ConstVal->getType();
10113 }
10114 
10115 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10116                                         unsigned &SplatBitSize,
10117                                         bool &HasAnyUndefs,
10118                                         unsigned MinSplatBits,
10119                                         bool IsBigEndian) const {
10120   EVT VT = getValueType(0);
10121   assert(VT.isVector() && "Expected a vector type");
10122   unsigned VecWidth = VT.getSizeInBits();
10123   if (MinSplatBits > VecWidth)
10124     return false;
10125 
10126   // FIXME: The widths are based on this node's type, but build vectors can
10127   // truncate their operands.
10128   SplatValue = APInt(VecWidth, 0);
10129   SplatUndef = APInt(VecWidth, 0);
10130 
10131   // Get the bits. Bits with undefined values (when the corresponding element
10132   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10133   // in SplatValue. If any of the values are not constant, give up and return
10134   // false.
10135   unsigned int NumOps = getNumOperands();
10136   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10137   unsigned EltWidth = VT.getScalarSizeInBits();
10138 
10139   for (unsigned j = 0; j < NumOps; ++j) {
10140     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10141     SDValue OpVal = getOperand(i);
10142     unsigned BitPos = j * EltWidth;
10143 
10144     if (OpVal.isUndef())
10145       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10146     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10147       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10148     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10149       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10150     else
10151       return false;
10152   }
10153 
10154   // The build_vector is all constants or undefs. Find the smallest element
10155   // size that splats the vector.
10156   HasAnyUndefs = (SplatUndef != 0);
10157 
10158   // FIXME: This does not work for vectors with elements less than 8 bits.
10159   while (VecWidth > 8) {
10160     unsigned HalfSize = VecWidth / 2;
10161     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
10162     APInt LowValue = SplatValue.trunc(HalfSize);
10163     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
10164     APInt LowUndef = SplatUndef.trunc(HalfSize);
10165 
10166     // If the two halves do not match (ignoring undef bits), stop here.
10167     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10168         MinSplatBits > HalfSize)
10169       break;
10170 
10171     SplatValue = HighValue | LowValue;
10172     SplatUndef = HighUndef & LowUndef;
10173 
10174     VecWidth = HalfSize;
10175   }
10176 
10177   SplatBitSize = VecWidth;
10178   return true;
10179 }
10180 
10181 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10182                                          BitVector *UndefElements) const {
10183   unsigned NumOps = getNumOperands();
10184   if (UndefElements) {
10185     UndefElements->clear();
10186     UndefElements->resize(NumOps);
10187   }
10188   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10189   if (!DemandedElts)
10190     return SDValue();
10191   SDValue Splatted;
10192   for (unsigned i = 0; i != NumOps; ++i) {
10193     if (!DemandedElts[i])
10194       continue;
10195     SDValue Op = getOperand(i);
10196     if (Op.isUndef()) {
10197       if (UndefElements)
10198         (*UndefElements)[i] = true;
10199     } else if (!Splatted) {
10200       Splatted = Op;
10201     } else if (Splatted != Op) {
10202       return SDValue();
10203     }
10204   }
10205 
10206   if (!Splatted) {
10207     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10208     assert(getOperand(FirstDemandedIdx).isUndef() &&
10209            "Can only have a splat without a constant for all undefs.");
10210     return getOperand(FirstDemandedIdx);
10211   }
10212 
10213   return Splatted;
10214 }
10215 
10216 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10217   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10218   return getSplatValue(DemandedElts, UndefElements);
10219 }
10220 
10221 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10222                                             SmallVectorImpl<SDValue> &Sequence,
10223                                             BitVector *UndefElements) const {
10224   unsigned NumOps = getNumOperands();
10225   Sequence.clear();
10226   if (UndefElements) {
10227     UndefElements->clear();
10228     UndefElements->resize(NumOps);
10229   }
10230   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10231   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10232     return false;
10233 
10234   // Set the undefs even if we don't find a sequence (like getSplatValue).
10235   if (UndefElements)
10236     for (unsigned I = 0; I != NumOps; ++I)
10237       if (DemandedElts[I] && getOperand(I).isUndef())
10238         (*UndefElements)[I] = true;
10239 
10240   // Iteratively widen the sequence length looking for repetitions.
10241   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10242     Sequence.append(SeqLen, SDValue());
10243     for (unsigned I = 0; I != NumOps; ++I) {
10244       if (!DemandedElts[I])
10245         continue;
10246       SDValue &SeqOp = Sequence[I % SeqLen];
10247       SDValue Op = getOperand(I);
10248       if (Op.isUndef()) {
10249         if (!SeqOp)
10250           SeqOp = Op;
10251         continue;
10252       }
10253       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10254         Sequence.clear();
10255         break;
10256       }
10257       SeqOp = Op;
10258     }
10259     if (!Sequence.empty())
10260       return true;
10261   }
10262 
10263   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10264   return false;
10265 }
10266 
10267 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10268                                             BitVector *UndefElements) const {
10269   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10270   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10271 }
10272 
10273 ConstantSDNode *
10274 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10275                                         BitVector *UndefElements) const {
10276   return dyn_cast_or_null<ConstantSDNode>(
10277       getSplatValue(DemandedElts, UndefElements));
10278 }
10279 
10280 ConstantSDNode *
10281 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10282   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10283 }
10284 
10285 ConstantFPSDNode *
10286 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10287                                           BitVector *UndefElements) const {
10288   return dyn_cast_or_null<ConstantFPSDNode>(
10289       getSplatValue(DemandedElts, UndefElements));
10290 }
10291 
10292 ConstantFPSDNode *
10293 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10294   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10295 }
10296 
10297 int32_t
10298 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10299                                                    uint32_t BitWidth) const {
10300   if (ConstantFPSDNode *CN =
10301           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10302     bool IsExact;
10303     APSInt IntVal(BitWidth);
10304     const APFloat &APF = CN->getValueAPF();
10305     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10306             APFloat::opOK ||
10307         !IsExact)
10308       return -1;
10309 
10310     return IntVal.exactLogBase2();
10311   }
10312   return -1;
10313 }
10314 
10315 bool BuildVectorSDNode::isConstant() const {
10316   for (const SDValue &Op : op_values()) {
10317     unsigned Opc = Op.getOpcode();
10318     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10319       return false;
10320   }
10321   return true;
10322 }
10323 
10324 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10325   // Find the first non-undef value in the shuffle mask.
10326   unsigned i, e;
10327   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10328     /* search */;
10329 
10330   // If all elements are undefined, this shuffle can be considered a splat
10331   // (although it should eventually get simplified away completely).
10332   if (i == e)
10333     return true;
10334 
10335   // Make sure all remaining elements are either undef or the same as the first
10336   // non-undef value.
10337   for (int Idx = Mask[i]; i != e; ++i)
10338     if (Mask[i] >= 0 && Mask[i] != Idx)
10339       return false;
10340   return true;
10341 }
10342 
10343 // Returns the SDNode if it is a constant integer BuildVector
10344 // or constant integer.
10345 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10346   if (isa<ConstantSDNode>(N))
10347     return N.getNode();
10348   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10349     return N.getNode();
10350   // Treat a GlobalAddress supporting constant offset folding as a
10351   // constant integer.
10352   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10353     if (GA->getOpcode() == ISD::GlobalAddress &&
10354         TLI->isOffsetFoldingLegal(GA))
10355       return GA;
10356   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10357       isa<ConstantSDNode>(N.getOperand(0)))
10358     return N.getNode();
10359   return nullptr;
10360 }
10361 
10362 // Returns the SDNode if it is a constant float BuildVector
10363 // or constant float.
10364 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10365   if (isa<ConstantFPSDNode>(N))
10366     return N.getNode();
10367 
10368   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10369     return N.getNode();
10370 
10371   return nullptr;
10372 }
10373 
10374 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10375   assert(!Node->OperandList && "Node already has operands");
10376   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
10377          "too many operands to fit into SDNode");
10378   SDUse *Ops = OperandRecycler.allocate(
10379       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10380 
10381   bool IsDivergent = false;
10382   for (unsigned I = 0; I != Vals.size(); ++I) {
10383     Ops[I].setUser(Node);
10384     Ops[I].setInitial(Vals[I]);
10385     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10386       IsDivergent |= Ops[I].getNode()->isDivergent();
10387   }
10388   Node->NumOperands = Vals.size();
10389   Node->OperandList = Ops;
10390   if (!TLI->isSDNodeAlwaysUniform(Node)) {
10391     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10392     Node->SDNodeBits.IsDivergent = IsDivergent;
10393   }
10394   checkForCycles(Node);
10395 }
10396 
10397 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10398                                      SmallVectorImpl<SDValue> &Vals) {
10399   size_t Limit = SDNode::getMaxNumOperands();
10400   while (Vals.size() > Limit) {
10401     unsigned SliceIdx = Vals.size() - Limit;
10402     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
10403     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
10404     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
10405     Vals.emplace_back(NewTF);
10406   }
10407   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
10408 }
10409 
10410 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
10411                                         EVT VT, SDNodeFlags Flags) {
10412   switch (Opcode) {
10413   default:
10414     return SDValue();
10415   case ISD::ADD:
10416   case ISD::OR:
10417   case ISD::XOR:
10418   case ISD::UMAX:
10419     return getConstant(0, DL, VT);
10420   case ISD::MUL:
10421     return getConstant(1, DL, VT);
10422   case ISD::AND:
10423   case ISD::UMIN:
10424     return getAllOnesConstant(DL, VT);
10425   case ISD::SMAX:
10426     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
10427   case ISD::SMIN:
10428     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
10429   case ISD::FADD:
10430     return getConstantFP(-0.0, DL, VT);
10431   case ISD::FMUL:
10432     return getConstantFP(1.0, DL, VT);
10433   case ISD::FMINNUM:
10434   case ISD::FMAXNUM: {
10435     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
10436     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
10437     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
10438                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
10439                         APFloat::getLargest(Semantics);
10440     if (Opcode == ISD::FMAXNUM)
10441       NeutralAF.changeSign();
10442 
10443     return getConstantFP(NeutralAF, DL, VT);
10444   }
10445   }
10446 }
10447 
10448 #ifndef NDEBUG
10449 static void checkForCyclesHelper(const SDNode *N,
10450                                  SmallPtrSetImpl<const SDNode*> &Visited,
10451                                  SmallPtrSetImpl<const SDNode*> &Checked,
10452                                  const llvm::SelectionDAG *DAG) {
10453   // If this node has already been checked, don't check it again.
10454   if (Checked.count(N))
10455     return;
10456 
10457   // If a node has already been visited on this depth-first walk, reject it as
10458   // a cycle.
10459   if (!Visited.insert(N).second) {
10460     errs() << "Detected cycle in SelectionDAG\n";
10461     dbgs() << "Offending node:\n";
10462     N->dumprFull(DAG); dbgs() << "\n";
10463     abort();
10464   }
10465 
10466   for (const SDValue &Op : N->op_values())
10467     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
10468 
10469   Checked.insert(N);
10470   Visited.erase(N);
10471 }
10472 #endif
10473 
10474 void llvm::checkForCycles(const llvm::SDNode *N,
10475                           const llvm::SelectionDAG *DAG,
10476                           bool force) {
10477 #ifndef NDEBUG
10478   bool check = force;
10479 #ifdef EXPENSIVE_CHECKS
10480   check = true;
10481 #endif  // EXPENSIVE_CHECKS
10482   if (check) {
10483     assert(N && "Checking nonexistent SDNode");
10484     SmallPtrSet<const SDNode*, 32> visited;
10485     SmallPtrSet<const SDNode*, 32> checked;
10486     checkForCyclesHelper(N, visited, checked, DAG);
10487   }
10488 #endif  // !NDEBUG
10489 }
10490 
10491 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
10492   checkForCycles(DAG->getRoot().getNode(), DAG, force);
10493 }
10494