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     } else if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
149       SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
150       return true;
151     }
152   }
153 
154   auto *BV = dyn_cast<BuildVectorSDNode>(N);
155   if (!BV)
156     return false;
157 
158   APInt SplatUndef;
159   unsigned SplatBitSize;
160   bool HasUndefs;
161   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
162   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
163                              EltSize) &&
164          EltSize == SplatBitSize;
165 }
166 
167 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
168 // specializations of the more general isConstantSplatVector()?
169 
170 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
171   // Look through a bit convert.
172   while (N->getOpcode() == ISD::BITCAST)
173     N = N->getOperand(0).getNode();
174 
175   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
176     APInt SplatVal;
177     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnesValue();
178   }
179 
180   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
181 
182   unsigned i = 0, e = N->getNumOperands();
183 
184   // Skip over all of the undef values.
185   while (i != e && N->getOperand(i).isUndef())
186     ++i;
187 
188   // Do not accept an all-undef vector.
189   if (i == e) return false;
190 
191   // Do not accept build_vectors that aren't all constants or which have non-~0
192   // elements. We have to be a bit careful here, as the type of the constant
193   // may not be the same as the type of the vector elements due to type
194   // legalization (the elements are promoted to a legal type for the target and
195   // a vector of a type may be legal when the base element type is not).
196   // We only want to check enough bits to cover the vector elements, because
197   // we care if the resultant vector is all ones, not whether the individual
198   // constants are.
199   SDValue NotZero = N->getOperand(i);
200   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
201   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
202     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
203       return false;
204   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
205     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
206       return false;
207   } else
208     return false;
209 
210   // Okay, we have at least one ~0 value, check to see if the rest match or are
211   // undefs. Even with the above element type twiddling, this should be OK, as
212   // the same type legalization should have applied to all the elements.
213   for (++i; i != e; ++i)
214     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
215       return false;
216   return true;
217 }
218 
219 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
220   // Look through a bit convert.
221   while (N->getOpcode() == ISD::BITCAST)
222     N = N->getOperand(0).getNode();
223 
224   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
225     APInt SplatVal;
226     return isConstantSplatVector(N, SplatVal) && SplatVal.isNullValue();
227   }
228 
229   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
230 
231   bool IsAllUndef = true;
232   for (const SDValue &Op : N->op_values()) {
233     if (Op.isUndef())
234       continue;
235     IsAllUndef = false;
236     // Do not accept build_vectors that aren't all constants or which have non-0
237     // elements. We have to be a bit careful here, as the type of the constant
238     // may not be the same as the type of the vector elements due to type
239     // legalization (the elements are promoted to a legal type for the target
240     // and a vector of a type may be legal when the base element type is not).
241     // We only want to check enough bits to cover the vector elements, because
242     // we care if the resultant vector is all zeros, not whether the individual
243     // constants are.
244     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
245     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
246       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
247         return false;
248     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
249       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
250         return false;
251     } else
252       return false;
253   }
254 
255   // Do not accept an all-undef vector.
256   if (IsAllUndef)
257     return false;
258   return true;
259 }
260 
261 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
262   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
263 }
264 
265 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
266   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
267 }
268 
269 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
270   if (N->getOpcode() != ISD::BUILD_VECTOR)
271     return false;
272 
273   for (const SDValue &Op : N->op_values()) {
274     if (Op.isUndef())
275       continue;
276     if (!isa<ConstantSDNode>(Op))
277       return false;
278   }
279   return true;
280 }
281 
282 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
283   if (N->getOpcode() != ISD::BUILD_VECTOR)
284     return false;
285 
286   for (const SDValue &Op : N->op_values()) {
287     if (Op.isUndef())
288       continue;
289     if (!isa<ConstantFPSDNode>(Op))
290       return false;
291   }
292   return true;
293 }
294 
295 bool ISD::allOperandsUndef(const SDNode *N) {
296   // Return false if the node has no operands.
297   // This is "logically inconsistent" with the definition of "all" but
298   // is probably the desired behavior.
299   if (N->getNumOperands() == 0)
300     return false;
301   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
302 }
303 
304 bool ISD::matchUnaryPredicate(SDValue Op,
305                               std::function<bool(ConstantSDNode *)> Match,
306                               bool AllowUndefs) {
307   // FIXME: Add support for scalar UNDEF cases?
308   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
309     return Match(Cst);
310 
311   // FIXME: Add support for vector UNDEF cases?
312   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
313       ISD::SPLAT_VECTOR != Op.getOpcode())
314     return false;
315 
316   EVT SVT = Op.getValueType().getScalarType();
317   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
318     if (AllowUndefs && Op.getOperand(i).isUndef()) {
319       if (!Match(nullptr))
320         return false;
321       continue;
322     }
323 
324     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
325     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
326       return false;
327   }
328   return true;
329 }
330 
331 bool ISD::matchBinaryPredicate(
332     SDValue LHS, SDValue RHS,
333     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
334     bool AllowUndefs, bool AllowTypeMismatch) {
335   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
336     return false;
337 
338   // TODO: Add support for scalar UNDEF cases?
339   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
340     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
341       return Match(LHSCst, RHSCst);
342 
343   // TODO: Add support for vector UNDEF cases?
344   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
345       ISD::BUILD_VECTOR != RHS.getOpcode())
346     return false;
347 
348   EVT SVT = LHS.getValueType().getScalarType();
349   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
350     SDValue LHSOp = LHS.getOperand(i);
351     SDValue RHSOp = RHS.getOperand(i);
352     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
353     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
354     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
355     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
356     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
357       return false;
358     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
359                                LHSOp.getValueType() != RHSOp.getValueType()))
360       return false;
361     if (!Match(LHSCst, RHSCst))
362       return false;
363   }
364   return true;
365 }
366 
367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
368   switch (VecReduceOpcode) {
369   default:
370     llvm_unreachable("Expected VECREDUCE opcode");
371   case ISD::VECREDUCE_FADD:
372   case ISD::VECREDUCE_SEQ_FADD:
373     return ISD::FADD;
374   case ISD::VECREDUCE_FMUL:
375   case ISD::VECREDUCE_SEQ_FMUL:
376     return ISD::FMUL;
377   case ISD::VECREDUCE_ADD:
378     return ISD::ADD;
379   case ISD::VECREDUCE_MUL:
380     return ISD::MUL;
381   case ISD::VECREDUCE_AND:
382     return ISD::AND;
383   case ISD::VECREDUCE_OR:
384     return ISD::OR;
385   case ISD::VECREDUCE_XOR:
386     return ISD::XOR;
387   case ISD::VECREDUCE_SMAX:
388     return ISD::SMAX;
389   case ISD::VECREDUCE_SMIN:
390     return ISD::SMIN;
391   case ISD::VECREDUCE_UMAX:
392     return ISD::UMAX;
393   case ISD::VECREDUCE_UMIN:
394     return ISD::UMIN;
395   case ISD::VECREDUCE_FMAX:
396     return ISD::FMAXNUM;
397   case ISD::VECREDUCE_FMIN:
398     return ISD::FMINNUM;
399   }
400 }
401 
402 bool ISD::isVPOpcode(unsigned Opcode) {
403   switch (Opcode) {
404   default:
405     return false;
406 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
407   case ISD::SDOPC:                                                             \
408     return true;
409 #include "llvm/IR/VPIntrinsics.def"
410   }
411 }
412 
413 /// The operand position of the vector mask.
414 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
415   switch (Opcode) {
416   default:
417     return None;
418 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...)        \
419   case ISD::SDOPC:                                                             \
420     return MASKPOS;
421 #include "llvm/IR/VPIntrinsics.def"
422   }
423 }
424 
425 /// The operand position of the explicit vector length parameter.
426 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
427   switch (Opcode) {
428   default:
429     return None;
430 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS)     \
431   case ISD::SDOPC:                                                             \
432     return EVLPOS;
433 #include "llvm/IR/VPIntrinsics.def"
434   }
435 }
436 
437 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
438   switch (ExtType) {
439   case ISD::EXTLOAD:
440     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
441   case ISD::SEXTLOAD:
442     return ISD::SIGN_EXTEND;
443   case ISD::ZEXTLOAD:
444     return ISD::ZERO_EXTEND;
445   default:
446     break;
447   }
448 
449   llvm_unreachable("Invalid LoadExtType");
450 }
451 
452 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
453   // To perform this operation, we just need to swap the L and G bits of the
454   // operation.
455   unsigned OldL = (Operation >> 2) & 1;
456   unsigned OldG = (Operation >> 1) & 1;
457   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
458                        (OldL << 1) |       // New G bit
459                        (OldG << 2));       // New L bit.
460 }
461 
462 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
463   unsigned Operation = Op;
464   if (isIntegerLike)
465     Operation ^= 7;   // Flip L, G, E bits, but not U.
466   else
467     Operation ^= 15;  // Flip all of the condition bits.
468 
469   if (Operation > ISD::SETTRUE2)
470     Operation &= ~8;  // Don't let N and U bits get set.
471 
472   return ISD::CondCode(Operation);
473 }
474 
475 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
476   return getSetCCInverseImpl(Op, Type.isInteger());
477 }
478 
479 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
480                                                bool isIntegerLike) {
481   return getSetCCInverseImpl(Op, isIntegerLike);
482 }
483 
484 /// For an integer comparison, return 1 if the comparison is a signed operation
485 /// and 2 if the result is an unsigned comparison. Return zero if the operation
486 /// does not depend on the sign of the input (setne and seteq).
487 static int isSignedOp(ISD::CondCode Opcode) {
488   switch (Opcode) {
489   default: llvm_unreachable("Illegal integer setcc operation!");
490   case ISD::SETEQ:
491   case ISD::SETNE: return 0;
492   case ISD::SETLT:
493   case ISD::SETLE:
494   case ISD::SETGT:
495   case ISD::SETGE: return 1;
496   case ISD::SETULT:
497   case ISD::SETULE:
498   case ISD::SETUGT:
499   case ISD::SETUGE: return 2;
500   }
501 }
502 
503 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
504                                        EVT Type) {
505   bool IsInteger = Type.isInteger();
506   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
507     // Cannot fold a signed integer setcc with an unsigned integer setcc.
508     return ISD::SETCC_INVALID;
509 
510   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
511 
512   // If the N and U bits get set, then the resultant comparison DOES suddenly
513   // care about orderedness, and it is true when ordered.
514   if (Op > ISD::SETTRUE2)
515     Op &= ~16;     // Clear the U bit if the N bit is set.
516 
517   // Canonicalize illegal integer setcc's.
518   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
519     Op = ISD::SETNE;
520 
521   return ISD::CondCode(Op);
522 }
523 
524 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
525                                         EVT Type) {
526   bool IsInteger = Type.isInteger();
527   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
528     // Cannot fold a signed setcc with an unsigned setcc.
529     return ISD::SETCC_INVALID;
530 
531   // Combine all of the condition bits.
532   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
533 
534   // Canonicalize illegal integer setcc's.
535   if (IsInteger) {
536     switch (Result) {
537     default: break;
538     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
539     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
540     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
541     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
542     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
543     }
544   }
545 
546   return Result;
547 }
548 
549 //===----------------------------------------------------------------------===//
550 //                           SDNode Profile Support
551 //===----------------------------------------------------------------------===//
552 
553 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
554 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
555   ID.AddInteger(OpC);
556 }
557 
558 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
559 /// solely with their pointer.
560 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
561   ID.AddPointer(VTList.VTs);
562 }
563 
564 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
565 static void AddNodeIDOperands(FoldingSetNodeID &ID,
566                               ArrayRef<SDValue> Ops) {
567   for (auto& Op : Ops) {
568     ID.AddPointer(Op.getNode());
569     ID.AddInteger(Op.getResNo());
570   }
571 }
572 
573 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
574 static void AddNodeIDOperands(FoldingSetNodeID &ID,
575                               ArrayRef<SDUse> Ops) {
576   for (auto& Op : Ops) {
577     ID.AddPointer(Op.getNode());
578     ID.AddInteger(Op.getResNo());
579   }
580 }
581 
582 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
583                           SDVTList VTList, ArrayRef<SDValue> OpList) {
584   AddNodeIDOpcode(ID, OpC);
585   AddNodeIDValueTypes(ID, VTList);
586   AddNodeIDOperands(ID, OpList);
587 }
588 
589 /// If this is an SDNode with special info, add this info to the NodeID data.
590 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
591   switch (N->getOpcode()) {
592   case ISD::TargetExternalSymbol:
593   case ISD::ExternalSymbol:
594   case ISD::MCSymbol:
595     llvm_unreachable("Should only be used on nodes with operands");
596   default: break;  // Normal nodes don't need extra info.
597   case ISD::TargetConstant:
598   case ISD::Constant: {
599     const ConstantSDNode *C = cast<ConstantSDNode>(N);
600     ID.AddPointer(C->getConstantIntValue());
601     ID.AddBoolean(C->isOpaque());
602     break;
603   }
604   case ISD::TargetConstantFP:
605   case ISD::ConstantFP:
606     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
607     break;
608   case ISD::TargetGlobalAddress:
609   case ISD::GlobalAddress:
610   case ISD::TargetGlobalTLSAddress:
611   case ISD::GlobalTLSAddress: {
612     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
613     ID.AddPointer(GA->getGlobal());
614     ID.AddInteger(GA->getOffset());
615     ID.AddInteger(GA->getTargetFlags());
616     break;
617   }
618   case ISD::BasicBlock:
619     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
620     break;
621   case ISD::Register:
622     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
623     break;
624   case ISD::RegisterMask:
625     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
626     break;
627   case ISD::SRCVALUE:
628     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
629     break;
630   case ISD::FrameIndex:
631   case ISD::TargetFrameIndex:
632     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
633     break;
634   case ISD::LIFETIME_START:
635   case ISD::LIFETIME_END:
636     if (cast<LifetimeSDNode>(N)->hasOffset()) {
637       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
638       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
639     }
640     break;
641   case ISD::PSEUDO_PROBE:
642     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
643     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
644     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
645     break;
646   case ISD::JumpTable:
647   case ISD::TargetJumpTable:
648     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
649     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
650     break;
651   case ISD::ConstantPool:
652   case ISD::TargetConstantPool: {
653     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
654     ID.AddInteger(CP->getAlign().value());
655     ID.AddInteger(CP->getOffset());
656     if (CP->isMachineConstantPoolEntry())
657       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
658     else
659       ID.AddPointer(CP->getConstVal());
660     ID.AddInteger(CP->getTargetFlags());
661     break;
662   }
663   case ISD::TargetIndex: {
664     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
665     ID.AddInteger(TI->getIndex());
666     ID.AddInteger(TI->getOffset());
667     ID.AddInteger(TI->getTargetFlags());
668     break;
669   }
670   case ISD::LOAD: {
671     const LoadSDNode *LD = cast<LoadSDNode>(N);
672     ID.AddInteger(LD->getMemoryVT().getRawBits());
673     ID.AddInteger(LD->getRawSubclassData());
674     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
675     break;
676   }
677   case ISD::STORE: {
678     const StoreSDNode *ST = cast<StoreSDNode>(N);
679     ID.AddInteger(ST->getMemoryVT().getRawBits());
680     ID.AddInteger(ST->getRawSubclassData());
681     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
682     break;
683   }
684   case ISD::MLOAD: {
685     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
686     ID.AddInteger(MLD->getMemoryVT().getRawBits());
687     ID.AddInteger(MLD->getRawSubclassData());
688     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
689     break;
690   }
691   case ISD::MSTORE: {
692     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
693     ID.AddInteger(MST->getMemoryVT().getRawBits());
694     ID.AddInteger(MST->getRawSubclassData());
695     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
696     break;
697   }
698   case ISD::MGATHER: {
699     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
700     ID.AddInteger(MG->getMemoryVT().getRawBits());
701     ID.AddInteger(MG->getRawSubclassData());
702     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
703     break;
704   }
705   case ISD::MSCATTER: {
706     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
707     ID.AddInteger(MS->getMemoryVT().getRawBits());
708     ID.AddInteger(MS->getRawSubclassData());
709     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
710     break;
711   }
712   case ISD::ATOMIC_CMP_SWAP:
713   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
714   case ISD::ATOMIC_SWAP:
715   case ISD::ATOMIC_LOAD_ADD:
716   case ISD::ATOMIC_LOAD_SUB:
717   case ISD::ATOMIC_LOAD_AND:
718   case ISD::ATOMIC_LOAD_CLR:
719   case ISD::ATOMIC_LOAD_OR:
720   case ISD::ATOMIC_LOAD_XOR:
721   case ISD::ATOMIC_LOAD_NAND:
722   case ISD::ATOMIC_LOAD_MIN:
723   case ISD::ATOMIC_LOAD_MAX:
724   case ISD::ATOMIC_LOAD_UMIN:
725   case ISD::ATOMIC_LOAD_UMAX:
726   case ISD::ATOMIC_LOAD:
727   case ISD::ATOMIC_STORE: {
728     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
729     ID.AddInteger(AT->getMemoryVT().getRawBits());
730     ID.AddInteger(AT->getRawSubclassData());
731     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
732     break;
733   }
734   case ISD::PREFETCH: {
735     const MemSDNode *PF = cast<MemSDNode>(N);
736     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
737     break;
738   }
739   case ISD::VECTOR_SHUFFLE: {
740     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
741     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
742          i != e; ++i)
743       ID.AddInteger(SVN->getMaskElt(i));
744     break;
745   }
746   case ISD::TargetBlockAddress:
747   case ISD::BlockAddress: {
748     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
749     ID.AddPointer(BA->getBlockAddress());
750     ID.AddInteger(BA->getOffset());
751     ID.AddInteger(BA->getTargetFlags());
752     break;
753   }
754   } // end switch (N->getOpcode())
755 
756   // Target specific memory nodes could also have address spaces to check.
757   if (N->isTargetMemoryOpcode())
758     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
759 }
760 
761 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
762 /// data.
763 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
764   AddNodeIDOpcode(ID, N->getOpcode());
765   // Add the return value info.
766   AddNodeIDValueTypes(ID, N->getVTList());
767   // Add the operand info.
768   AddNodeIDOperands(ID, N->ops());
769 
770   // Handle SDNode leafs with special info.
771   AddNodeIDCustom(ID, N);
772 }
773 
774 //===----------------------------------------------------------------------===//
775 //                              SelectionDAG Class
776 //===----------------------------------------------------------------------===//
777 
778 /// doNotCSE - Return true if CSE should not be performed for this node.
779 static bool doNotCSE(SDNode *N) {
780   if (N->getValueType(0) == MVT::Glue)
781     return true; // Never CSE anything that produces a flag.
782 
783   switch (N->getOpcode()) {
784   default: break;
785   case ISD::HANDLENODE:
786   case ISD::EH_LABEL:
787     return true;   // Never CSE these nodes.
788   }
789 
790   // Check that remaining values produced are not flags.
791   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
792     if (N->getValueType(i) == MVT::Glue)
793       return true; // Never CSE anything that produces a flag.
794 
795   return false;
796 }
797 
798 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
799 /// SelectionDAG.
800 void SelectionDAG::RemoveDeadNodes() {
801   // Create a dummy node (which is not added to allnodes), that adds a reference
802   // to the root node, preventing it from being deleted.
803   HandleSDNode Dummy(getRoot());
804 
805   SmallVector<SDNode*, 128> DeadNodes;
806 
807   // Add all obviously-dead nodes to the DeadNodes worklist.
808   for (SDNode &Node : allnodes())
809     if (Node.use_empty())
810       DeadNodes.push_back(&Node);
811 
812   RemoveDeadNodes(DeadNodes);
813 
814   // If the root changed (e.g. it was a dead load, update the root).
815   setRoot(Dummy.getValue());
816 }
817 
818 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
819 /// given list, and any nodes that become unreachable as a result.
820 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
821 
822   // Process the worklist, deleting the nodes and adding their uses to the
823   // worklist.
824   while (!DeadNodes.empty()) {
825     SDNode *N = DeadNodes.pop_back_val();
826     // Skip to next node if we've already managed to delete the node. This could
827     // happen if replacing a node causes a node previously added to the node to
828     // be deleted.
829     if (N->getOpcode() == ISD::DELETED_NODE)
830       continue;
831 
832     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
833       DUL->NodeDeleted(N, nullptr);
834 
835     // Take the node out of the appropriate CSE map.
836     RemoveNodeFromCSEMaps(N);
837 
838     // Next, brutally remove the operand list.  This is safe to do, as there are
839     // no cycles in the graph.
840     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
841       SDUse &Use = *I++;
842       SDNode *Operand = Use.getNode();
843       Use.set(SDValue());
844 
845       // Now that we removed this operand, see if there are no uses of it left.
846       if (Operand->use_empty())
847         DeadNodes.push_back(Operand);
848     }
849 
850     DeallocateNode(N);
851   }
852 }
853 
854 void SelectionDAG::RemoveDeadNode(SDNode *N){
855   SmallVector<SDNode*, 16> DeadNodes(1, N);
856 
857   // Create a dummy node that adds a reference to the root node, preventing
858   // it from being deleted.  (This matters if the root is an operand of the
859   // dead node.)
860   HandleSDNode Dummy(getRoot());
861 
862   RemoveDeadNodes(DeadNodes);
863 }
864 
865 void SelectionDAG::DeleteNode(SDNode *N) {
866   // First take this out of the appropriate CSE map.
867   RemoveNodeFromCSEMaps(N);
868 
869   // Finally, remove uses due to operands of this node, remove from the
870   // AllNodes list, and delete the node.
871   DeleteNodeNotInCSEMaps(N);
872 }
873 
874 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
875   assert(N->getIterator() != AllNodes.begin() &&
876          "Cannot delete the entry node!");
877   assert(N->use_empty() && "Cannot delete a node that is not dead!");
878 
879   // Drop all of the operands and decrement used node's use counts.
880   N->DropOperands();
881 
882   DeallocateNode(N);
883 }
884 
885 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
886   assert(!(V->isVariadic() && isParameter));
887   if (isParameter)
888     ByvalParmDbgValues.push_back(V);
889   else
890     DbgValues.push_back(V);
891   for (const SDNode *Node : V->getSDNodes())
892     if (Node)
893       DbgValMap[Node].push_back(V);
894 }
895 
896 void SDDbgInfo::erase(const SDNode *Node) {
897   DbgValMapType::iterator I = DbgValMap.find(Node);
898   if (I == DbgValMap.end())
899     return;
900   for (auto &Val: I->second)
901     Val->setIsInvalidated();
902   DbgValMap.erase(I);
903 }
904 
905 void SelectionDAG::DeallocateNode(SDNode *N) {
906   // If we have operands, deallocate them.
907   removeOperands(N);
908 
909   NodeAllocator.Deallocate(AllNodes.remove(N));
910 
911   // Set the opcode to DELETED_NODE to help catch bugs when node
912   // memory is reallocated.
913   // FIXME: There are places in SDag that have grown a dependency on the opcode
914   // value in the released node.
915   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
916   N->NodeType = ISD::DELETED_NODE;
917 
918   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
919   // them and forget about that node.
920   DbgInfo->erase(N);
921 }
922 
923 #ifndef NDEBUG
924 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
925 static void VerifySDNode(SDNode *N) {
926   switch (N->getOpcode()) {
927   default:
928     break;
929   case ISD::BUILD_PAIR: {
930     EVT VT = N->getValueType(0);
931     assert(N->getNumValues() == 1 && "Too many results!");
932     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
933            "Wrong return type!");
934     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
935     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
936            "Mismatched operand types!");
937     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
938            "Wrong operand type!");
939     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
940            "Wrong return type size");
941     break;
942   }
943   case ISD::BUILD_VECTOR: {
944     assert(N->getNumValues() == 1 && "Too many results!");
945     assert(N->getValueType(0).isVector() && "Wrong return type!");
946     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
947            "Wrong number of operands!");
948     EVT EltVT = N->getValueType(0).getVectorElementType();
949     for (const SDUse &Op : N->ops()) {
950       assert((Op.getValueType() == EltVT ||
951               (EltVT.isInteger() && Op.getValueType().isInteger() &&
952                EltVT.bitsLE(Op.getValueType()))) &&
953              "Wrong operand type!");
954       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
955              "Operands must all have the same type");
956     }
957     break;
958   }
959   }
960 }
961 #endif // NDEBUG
962 
963 /// Insert a newly allocated node into the DAG.
964 ///
965 /// Handles insertion into the all nodes list and CSE map, as well as
966 /// verification and other common operations when a new node is allocated.
967 void SelectionDAG::InsertNode(SDNode *N) {
968   AllNodes.push_back(N);
969 #ifndef NDEBUG
970   N->PersistentId = NextPersistentId++;
971   VerifySDNode(N);
972 #endif
973   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
974     DUL->NodeInserted(N);
975 }
976 
977 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
978 /// correspond to it.  This is useful when we're about to delete or repurpose
979 /// the node.  We don't want future request for structurally identical nodes
980 /// to return N anymore.
981 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
982   bool Erased = false;
983   switch (N->getOpcode()) {
984   case ISD::HANDLENODE: return false;  // noop.
985   case ISD::CONDCODE:
986     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
987            "Cond code doesn't exist!");
988     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
989     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
990     break;
991   case ISD::ExternalSymbol:
992     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
993     break;
994   case ISD::TargetExternalSymbol: {
995     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
996     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
997         ESN->getSymbol(), ESN->getTargetFlags()));
998     break;
999   }
1000   case ISD::MCSymbol: {
1001     auto *MCSN = cast<MCSymbolSDNode>(N);
1002     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1003     break;
1004   }
1005   case ISD::VALUETYPE: {
1006     EVT VT = cast<VTSDNode>(N)->getVT();
1007     if (VT.isExtended()) {
1008       Erased = ExtendedValueTypeNodes.erase(VT);
1009     } else {
1010       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1011       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1012     }
1013     break;
1014   }
1015   default:
1016     // Remove it from the CSE Map.
1017     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1018     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1019     Erased = CSEMap.RemoveNode(N);
1020     break;
1021   }
1022 #ifndef NDEBUG
1023   // Verify that the node was actually in one of the CSE maps, unless it has a
1024   // flag result (which cannot be CSE'd) or is one of the special cases that are
1025   // not subject to CSE.
1026   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1027       !N->isMachineOpcode() && !doNotCSE(N)) {
1028     N->dump(this);
1029     dbgs() << "\n";
1030     llvm_unreachable("Node is not in map!");
1031   }
1032 #endif
1033   return Erased;
1034 }
1035 
1036 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1037 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1038 /// node already exists, in which case transfer all its users to the existing
1039 /// node. This transfer can potentially trigger recursive merging.
1040 void
1041 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1042   // For node types that aren't CSE'd, just act as if no identical node
1043   // already exists.
1044   if (!doNotCSE(N)) {
1045     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1046     if (Existing != N) {
1047       // If there was already an existing matching node, use ReplaceAllUsesWith
1048       // to replace the dead one with the existing one.  This can cause
1049       // recursive merging of other unrelated nodes down the line.
1050       ReplaceAllUsesWith(N, Existing);
1051 
1052       // N is now dead. Inform the listeners and delete it.
1053       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1054         DUL->NodeDeleted(N, Existing);
1055       DeleteNodeNotInCSEMaps(N);
1056       return;
1057     }
1058   }
1059 
1060   // If the node doesn't already exist, we updated it.  Inform listeners.
1061   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1062     DUL->NodeUpdated(N);
1063 }
1064 
1065 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1066 /// were replaced with those specified.  If this node is never memoized,
1067 /// return null, otherwise return a pointer to the slot it would take.  If a
1068 /// node already exists with these operands, the slot will be non-null.
1069 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1070                                            void *&InsertPos) {
1071   if (doNotCSE(N))
1072     return nullptr;
1073 
1074   SDValue Ops[] = { Op };
1075   FoldingSetNodeID ID;
1076   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1077   AddNodeIDCustom(ID, N);
1078   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1079   if (Node)
1080     Node->intersectFlagsWith(N->getFlags());
1081   return Node;
1082 }
1083 
1084 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1085 /// were replaced with those specified.  If this node is never memoized,
1086 /// return null, otherwise return a pointer to the slot it would take.  If a
1087 /// node already exists with these operands, the slot will be non-null.
1088 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1089                                            SDValue Op1, SDValue Op2,
1090                                            void *&InsertPos) {
1091   if (doNotCSE(N))
1092     return nullptr;
1093 
1094   SDValue Ops[] = { Op1, Op2 };
1095   FoldingSetNodeID ID;
1096   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1097   AddNodeIDCustom(ID, N);
1098   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1099   if (Node)
1100     Node->intersectFlagsWith(N->getFlags());
1101   return Node;
1102 }
1103 
1104 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1105 /// were replaced with those specified.  If this node is never memoized,
1106 /// return null, otherwise return a pointer to the slot it would take.  If a
1107 /// node already exists with these operands, the slot will be non-null.
1108 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1109                                            void *&InsertPos) {
1110   if (doNotCSE(N))
1111     return nullptr;
1112 
1113   FoldingSetNodeID ID;
1114   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1115   AddNodeIDCustom(ID, N);
1116   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1117   if (Node)
1118     Node->intersectFlagsWith(N->getFlags());
1119   return Node;
1120 }
1121 
1122 Align SelectionDAG::getEVTAlign(EVT VT) const {
1123   Type *Ty = VT == MVT::iPTR ?
1124                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1125                    VT.getTypeForEVT(*getContext());
1126 
1127   return getDataLayout().getABITypeAlign(Ty);
1128 }
1129 
1130 // EntryNode could meaningfully have debug info if we can find it...
1131 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1132     : TM(tm), OptLevel(OL),
1133       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1134       Root(getEntryNode()) {
1135   InsertNode(&EntryNode);
1136   DbgInfo = new SDDbgInfo();
1137 }
1138 
1139 void SelectionDAG::init(MachineFunction &NewMF,
1140                         OptimizationRemarkEmitter &NewORE,
1141                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1142                         LegacyDivergenceAnalysis * Divergence,
1143                         ProfileSummaryInfo *PSIin,
1144                         BlockFrequencyInfo *BFIin) {
1145   MF = &NewMF;
1146   SDAGISelPass = PassPtr;
1147   ORE = &NewORE;
1148   TLI = getSubtarget().getTargetLowering();
1149   TSI = getSubtarget().getSelectionDAGInfo();
1150   LibInfo = LibraryInfo;
1151   Context = &MF->getFunction().getContext();
1152   DA = Divergence;
1153   PSI = PSIin;
1154   BFI = BFIin;
1155 }
1156 
1157 SelectionDAG::~SelectionDAG() {
1158   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1159   allnodes_clear();
1160   OperandRecycler.clear(OperandAllocator);
1161   delete DbgInfo;
1162 }
1163 
1164 bool SelectionDAG::shouldOptForSize() const {
1165   return MF->getFunction().hasOptSize() ||
1166       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1167 }
1168 
1169 void SelectionDAG::allnodes_clear() {
1170   assert(&*AllNodes.begin() == &EntryNode);
1171   AllNodes.remove(AllNodes.begin());
1172   while (!AllNodes.empty())
1173     DeallocateNode(&AllNodes.front());
1174 #ifndef NDEBUG
1175   NextPersistentId = 0;
1176 #endif
1177 }
1178 
1179 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1180                                           void *&InsertPos) {
1181   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1182   if (N) {
1183     switch (N->getOpcode()) {
1184     default: break;
1185     case ISD::Constant:
1186     case ISD::ConstantFP:
1187       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1188                        "debug location.  Use another overload.");
1189     }
1190   }
1191   return N;
1192 }
1193 
1194 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1195                                           const SDLoc &DL, void *&InsertPos) {
1196   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1197   if (N) {
1198     switch (N->getOpcode()) {
1199     case ISD::Constant:
1200     case ISD::ConstantFP:
1201       // Erase debug location from the node if the node is used at several
1202       // different places. Do not propagate one location to all uses as it
1203       // will cause a worse single stepping debugging experience.
1204       if (N->getDebugLoc() != DL.getDebugLoc())
1205         N->setDebugLoc(DebugLoc());
1206       break;
1207     default:
1208       // When the node's point of use is located earlier in the instruction
1209       // sequence than its prior point of use, update its debug info to the
1210       // earlier location.
1211       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1212         N->setDebugLoc(DL.getDebugLoc());
1213       break;
1214     }
1215   }
1216   return N;
1217 }
1218 
1219 void SelectionDAG::clear() {
1220   allnodes_clear();
1221   OperandRecycler.clear(OperandAllocator);
1222   OperandAllocator.Reset();
1223   CSEMap.clear();
1224 
1225   ExtendedValueTypeNodes.clear();
1226   ExternalSymbols.clear();
1227   TargetExternalSymbols.clear();
1228   MCSymbols.clear();
1229   SDCallSiteDbgInfo.clear();
1230   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1231             static_cast<CondCodeSDNode*>(nullptr));
1232   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1233             static_cast<SDNode*>(nullptr));
1234 
1235   EntryNode.UseList = nullptr;
1236   InsertNode(&EntryNode);
1237   Root = getEntryNode();
1238   DbgInfo->clear();
1239 }
1240 
1241 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1242   return VT.bitsGT(Op.getValueType())
1243              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1244              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1245 }
1246 
1247 std::pair<SDValue, SDValue>
1248 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1249                                        const SDLoc &DL, EVT VT) {
1250   assert(!VT.bitsEq(Op.getValueType()) &&
1251          "Strict no-op FP extend/round not allowed.");
1252   SDValue Res =
1253       VT.bitsGT(Op.getValueType())
1254           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1255           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1256                     {Chain, Op, getIntPtrConstant(0, DL)});
1257 
1258   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1259 }
1260 
1261 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1262   return VT.bitsGT(Op.getValueType()) ?
1263     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1264     getNode(ISD::TRUNCATE, DL, VT, Op);
1265 }
1266 
1267 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1268   return VT.bitsGT(Op.getValueType()) ?
1269     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1270     getNode(ISD::TRUNCATE, DL, VT, Op);
1271 }
1272 
1273 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1274   return VT.bitsGT(Op.getValueType()) ?
1275     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1276     getNode(ISD::TRUNCATE, DL, VT, Op);
1277 }
1278 
1279 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1280                                         EVT OpVT) {
1281   if (VT.bitsLE(Op.getValueType()))
1282     return getNode(ISD::TRUNCATE, SL, VT, Op);
1283 
1284   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1285   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1286 }
1287 
1288 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1289   EVT OpVT = Op.getValueType();
1290   assert(VT.isInteger() && OpVT.isInteger() &&
1291          "Cannot getZeroExtendInReg FP types");
1292   assert(VT.isVector() == OpVT.isVector() &&
1293          "getZeroExtendInReg type should be vector iff the operand "
1294          "type is vector!");
1295   assert((!VT.isVector() ||
1296           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1297          "Vector element counts must match in getZeroExtendInReg");
1298   assert(VT.bitsLE(OpVT) && "Not extending!");
1299   if (OpVT == VT)
1300     return Op;
1301   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1302                                    VT.getScalarSizeInBits());
1303   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1304 }
1305 
1306 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1307   // Only unsigned pointer semantics are supported right now. In the future this
1308   // might delegate to TLI to check pointer signedness.
1309   return getZExtOrTrunc(Op, DL, VT);
1310 }
1311 
1312 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1313   // Only unsigned pointer semantics are supported right now. In the future this
1314   // might delegate to TLI to check pointer signedness.
1315   return getZeroExtendInReg(Op, DL, VT);
1316 }
1317 
1318 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1319 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1320   EVT EltVT = VT.getScalarType();
1321   SDValue NegOne =
1322     getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1323   return getNode(ISD::XOR, DL, VT, Val, NegOne);
1324 }
1325 
1326 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1327   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1328   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1329 }
1330 
1331 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1332                                       EVT OpVT) {
1333   if (!V)
1334     return getConstant(0, DL, VT);
1335 
1336   switch (TLI->getBooleanContents(OpVT)) {
1337   case TargetLowering::ZeroOrOneBooleanContent:
1338   case TargetLowering::UndefinedBooleanContent:
1339     return getConstant(1, DL, VT);
1340   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1341     return getAllOnesConstant(DL, VT);
1342   }
1343   llvm_unreachable("Unexpected boolean content enum!");
1344 }
1345 
1346 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1347                                   bool isT, bool isO) {
1348   EVT EltVT = VT.getScalarType();
1349   assert((EltVT.getSizeInBits() >= 64 ||
1350           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1351          "getConstant with a uint64_t value that doesn't fit in the type!");
1352   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1353 }
1354 
1355 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1356                                   bool isT, bool isO) {
1357   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1358 }
1359 
1360 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1361                                   EVT VT, bool isT, bool isO) {
1362   assert(VT.isInteger() && "Cannot create FP integer constant!");
1363 
1364   EVT EltVT = VT.getScalarType();
1365   const ConstantInt *Elt = &Val;
1366 
1367   // In some cases the vector type is legal but the element type is illegal and
1368   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1369   // inserted value (the type does not need to match the vector element type).
1370   // Any extra bits introduced will be truncated away.
1371   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1372                            TargetLowering::TypePromoteInteger) {
1373     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1374     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1375     Elt = ConstantInt::get(*getContext(), NewVal);
1376   }
1377   // In other cases the element type is illegal and needs to be expanded, for
1378   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1379   // the value into n parts and use a vector type with n-times the elements.
1380   // Then bitcast to the type requested.
1381   // Legalizing constants too early makes the DAGCombiner's job harder so we
1382   // only legalize if the DAG tells us we must produce legal types.
1383   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1384            TLI->getTypeAction(*getContext(), EltVT) ==
1385                TargetLowering::TypeExpandInteger) {
1386     const APInt &NewVal = Elt->getValue();
1387     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1388     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1389 
1390     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1391     if (VT.isScalableVector()) {
1392       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1393              "Can only handle an even split!");
1394       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1395 
1396       SmallVector<SDValue, 2> ScalarParts;
1397       for (unsigned i = 0; i != Parts; ++i)
1398         ScalarParts.push_back(getConstant(
1399             NewVal.lshr(i * ViaEltSizeInBits).trunc(ViaEltSizeInBits), DL,
1400             ViaEltVT, isT, isO));
1401 
1402       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1403     }
1404 
1405     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1406     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1407 
1408     // Check the temporary vector is the correct size. If this fails then
1409     // getTypeToTransformTo() probably returned a type whose size (in bits)
1410     // isn't a power-of-2 factor of the requested type size.
1411     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1412 
1413     SmallVector<SDValue, 2> EltParts;
1414     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1415       EltParts.push_back(getConstant(
1416           NewVal.lshr(i * ViaEltSizeInBits).zextOrTrunc(ViaEltSizeInBits), DL,
1417           ViaEltVT, isT, isO));
1418     }
1419 
1420     // EltParts is currently in little endian order. If we actually want
1421     // big-endian order then reverse it now.
1422     if (getDataLayout().isBigEndian())
1423       std::reverse(EltParts.begin(), EltParts.end());
1424 
1425     // The elements must be reversed when the element order is different
1426     // to the endianness of the elements (because the BITCAST is itself a
1427     // vector shuffle in this situation). However, we do not need any code to
1428     // perform this reversal because getConstant() is producing a vector
1429     // splat.
1430     // This situation occurs in MIPS MSA.
1431 
1432     SmallVector<SDValue, 8> Ops;
1433     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1434       llvm::append_range(Ops, EltParts);
1435 
1436     SDValue V =
1437         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1438     return V;
1439   }
1440 
1441   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1442          "APInt size does not match type size!");
1443   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1444   FoldingSetNodeID ID;
1445   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1446   ID.AddPointer(Elt);
1447   ID.AddBoolean(isO);
1448   void *IP = nullptr;
1449   SDNode *N = nullptr;
1450   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1451     if (!VT.isVector())
1452       return SDValue(N, 0);
1453 
1454   if (!N) {
1455     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1456     CSEMap.InsertNode(N, IP);
1457     InsertNode(N);
1458     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1459   }
1460 
1461   SDValue Result(N, 0);
1462   if (VT.isScalableVector())
1463     Result = getSplatVector(VT, DL, Result);
1464   else if (VT.isVector())
1465     Result = getSplatBuildVector(VT, DL, Result);
1466 
1467   return Result;
1468 }
1469 
1470 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1471                                         bool isTarget) {
1472   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1473 }
1474 
1475 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1476                                              const SDLoc &DL, bool LegalTypes) {
1477   assert(VT.isInteger() && "Shift amount is not an integer type!");
1478   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1479   return getConstant(Val, DL, ShiftVT);
1480 }
1481 
1482 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1483                                            bool isTarget) {
1484   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1485 }
1486 
1487 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1488                                     bool isTarget) {
1489   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1490 }
1491 
1492 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1493                                     EVT VT, bool isTarget) {
1494   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1495 
1496   EVT EltVT = VT.getScalarType();
1497 
1498   // Do the map lookup using the actual bit pattern for the floating point
1499   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1500   // we don't have issues with SNANs.
1501   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1502   FoldingSetNodeID ID;
1503   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1504   ID.AddPointer(&V);
1505   void *IP = nullptr;
1506   SDNode *N = nullptr;
1507   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1508     if (!VT.isVector())
1509       return SDValue(N, 0);
1510 
1511   if (!N) {
1512     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1513     CSEMap.InsertNode(N, IP);
1514     InsertNode(N);
1515   }
1516 
1517   SDValue Result(N, 0);
1518   if (VT.isScalableVector())
1519     Result = getSplatVector(VT, DL, Result);
1520   else if (VT.isVector())
1521     Result = getSplatBuildVector(VT, DL, Result);
1522   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1523   return Result;
1524 }
1525 
1526 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1527                                     bool isTarget) {
1528   EVT EltVT = VT.getScalarType();
1529   if (EltVT == MVT::f32)
1530     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1531   else if (EltVT == MVT::f64)
1532     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1533   else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1534            EltVT == MVT::f16 || EltVT == MVT::bf16) {
1535     bool Ignored;
1536     APFloat APF = APFloat(Val);
1537     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1538                 &Ignored);
1539     return getConstantFP(APF, DL, VT, isTarget);
1540   } else
1541     llvm_unreachable("Unsupported type in getConstantFP");
1542 }
1543 
1544 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1545                                        EVT VT, int64_t Offset, bool isTargetGA,
1546                                        unsigned TargetFlags) {
1547   assert((TargetFlags == 0 || isTargetGA) &&
1548          "Cannot set target flags on target-independent globals");
1549 
1550   // Truncate (with sign-extension) the offset value to the pointer size.
1551   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1552   if (BitWidth < 64)
1553     Offset = SignExtend64(Offset, BitWidth);
1554 
1555   unsigned Opc;
1556   if (GV->isThreadLocal())
1557     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1558   else
1559     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1560 
1561   FoldingSetNodeID ID;
1562   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1563   ID.AddPointer(GV);
1564   ID.AddInteger(Offset);
1565   ID.AddInteger(TargetFlags);
1566   void *IP = nullptr;
1567   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1568     return SDValue(E, 0);
1569 
1570   auto *N = newSDNode<GlobalAddressSDNode>(
1571       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1572   CSEMap.InsertNode(N, IP);
1573     InsertNode(N);
1574   return SDValue(N, 0);
1575 }
1576 
1577 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1578   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1579   FoldingSetNodeID ID;
1580   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1581   ID.AddInteger(FI);
1582   void *IP = nullptr;
1583   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1584     return SDValue(E, 0);
1585 
1586   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1587   CSEMap.InsertNode(N, IP);
1588   InsertNode(N);
1589   return SDValue(N, 0);
1590 }
1591 
1592 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1593                                    unsigned TargetFlags) {
1594   assert((TargetFlags == 0 || isTarget) &&
1595          "Cannot set target flags on target-independent jump tables");
1596   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1597   FoldingSetNodeID ID;
1598   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1599   ID.AddInteger(JTI);
1600   ID.AddInteger(TargetFlags);
1601   void *IP = nullptr;
1602   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1603     return SDValue(E, 0);
1604 
1605   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1606   CSEMap.InsertNode(N, IP);
1607   InsertNode(N);
1608   return SDValue(N, 0);
1609 }
1610 
1611 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1612                                       MaybeAlign Alignment, int Offset,
1613                                       bool isTarget, unsigned TargetFlags) {
1614   assert((TargetFlags == 0 || isTarget) &&
1615          "Cannot set target flags on target-independent globals");
1616   if (!Alignment)
1617     Alignment = shouldOptForSize()
1618                     ? getDataLayout().getABITypeAlign(C->getType())
1619                     : getDataLayout().getPrefTypeAlign(C->getType());
1620   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1621   FoldingSetNodeID ID;
1622   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1623   ID.AddInteger(Alignment->value());
1624   ID.AddInteger(Offset);
1625   ID.AddPointer(C);
1626   ID.AddInteger(TargetFlags);
1627   void *IP = nullptr;
1628   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1629     return SDValue(E, 0);
1630 
1631   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1632                                           TargetFlags);
1633   CSEMap.InsertNode(N, IP);
1634   InsertNode(N);
1635   SDValue V = SDValue(N, 0);
1636   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1637   return V;
1638 }
1639 
1640 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1641                                       MaybeAlign Alignment, int Offset,
1642                                       bool isTarget, unsigned TargetFlags) {
1643   assert((TargetFlags == 0 || isTarget) &&
1644          "Cannot set target flags on target-independent globals");
1645   if (!Alignment)
1646     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1647   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1648   FoldingSetNodeID ID;
1649   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1650   ID.AddInteger(Alignment->value());
1651   ID.AddInteger(Offset);
1652   C->addSelectionDAGCSEId(ID);
1653   ID.AddInteger(TargetFlags);
1654   void *IP = nullptr;
1655   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1656     return SDValue(E, 0);
1657 
1658   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1659                                           TargetFlags);
1660   CSEMap.InsertNode(N, IP);
1661   InsertNode(N);
1662   return SDValue(N, 0);
1663 }
1664 
1665 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1666                                      unsigned TargetFlags) {
1667   FoldingSetNodeID ID;
1668   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1669   ID.AddInteger(Index);
1670   ID.AddInteger(Offset);
1671   ID.AddInteger(TargetFlags);
1672   void *IP = nullptr;
1673   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1674     return SDValue(E, 0);
1675 
1676   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1677   CSEMap.InsertNode(N, IP);
1678   InsertNode(N);
1679   return SDValue(N, 0);
1680 }
1681 
1682 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1683   FoldingSetNodeID ID;
1684   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1685   ID.AddPointer(MBB);
1686   void *IP = nullptr;
1687   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1688     return SDValue(E, 0);
1689 
1690   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1691   CSEMap.InsertNode(N, IP);
1692   InsertNode(N);
1693   return SDValue(N, 0);
1694 }
1695 
1696 SDValue SelectionDAG::getValueType(EVT VT) {
1697   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1698       ValueTypeNodes.size())
1699     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1700 
1701   SDNode *&N = VT.isExtended() ?
1702     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1703 
1704   if (N) return SDValue(N, 0);
1705   N = newSDNode<VTSDNode>(VT);
1706   InsertNode(N);
1707   return SDValue(N, 0);
1708 }
1709 
1710 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1711   SDNode *&N = ExternalSymbols[Sym];
1712   if (N) return SDValue(N, 0);
1713   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1714   InsertNode(N);
1715   return SDValue(N, 0);
1716 }
1717 
1718 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1719   SDNode *&N = MCSymbols[Sym];
1720   if (N)
1721     return SDValue(N, 0);
1722   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1723   InsertNode(N);
1724   return SDValue(N, 0);
1725 }
1726 
1727 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1728                                               unsigned TargetFlags) {
1729   SDNode *&N =
1730       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1731   if (N) return SDValue(N, 0);
1732   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1733   InsertNode(N);
1734   return SDValue(N, 0);
1735 }
1736 
1737 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1738   if ((unsigned)Cond >= CondCodeNodes.size())
1739     CondCodeNodes.resize(Cond+1);
1740 
1741   if (!CondCodeNodes[Cond]) {
1742     auto *N = newSDNode<CondCodeSDNode>(Cond);
1743     CondCodeNodes[Cond] = N;
1744     InsertNode(N);
1745   }
1746 
1747   return SDValue(CondCodeNodes[Cond], 0);
1748 }
1749 
1750 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, SDValue Step) {
1751   if (ResVT.isScalableVector())
1752     return getNode(ISD::STEP_VECTOR, DL, ResVT, Step);
1753 
1754   EVT OpVT = Step.getValueType();
1755   APInt StepVal = cast<ConstantSDNode>(Step)->getAPIntValue();
1756   SmallVector<SDValue, 16> OpsStepConstants;
1757   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1758     OpsStepConstants.push_back(getConstant(StepVal * i, DL, OpVT));
1759   return getBuildVector(ResVT, DL, OpsStepConstants);
1760 }
1761 
1762 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1763 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1764 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1765   std::swap(N1, N2);
1766   ShuffleVectorSDNode::commuteMask(M);
1767 }
1768 
1769 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1770                                        SDValue N2, ArrayRef<int> Mask) {
1771   assert(VT.getVectorNumElements() == Mask.size() &&
1772            "Must have the same number of vector elements as mask elements!");
1773   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1774          "Invalid VECTOR_SHUFFLE");
1775 
1776   // Canonicalize shuffle undef, undef -> undef
1777   if (N1.isUndef() && N2.isUndef())
1778     return getUNDEF(VT);
1779 
1780   // Validate that all indices in Mask are within the range of the elements
1781   // input to the shuffle.
1782   int NElts = Mask.size();
1783   assert(llvm::all_of(Mask,
1784                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1785          "Index out of range");
1786 
1787   // Copy the mask so we can do any needed cleanup.
1788   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1789 
1790   // Canonicalize shuffle v, v -> v, undef
1791   if (N1 == N2) {
1792     N2 = getUNDEF(VT);
1793     for (int i = 0; i != NElts; ++i)
1794       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1795   }
1796 
1797   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1798   if (N1.isUndef())
1799     commuteShuffle(N1, N2, MaskVec);
1800 
1801   if (TLI->hasVectorBlend()) {
1802     // If shuffling a splat, try to blend the splat instead. We do this here so
1803     // that even when this arises during lowering we don't have to re-handle it.
1804     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1805       BitVector UndefElements;
1806       SDValue Splat = BV->getSplatValue(&UndefElements);
1807       if (!Splat)
1808         return;
1809 
1810       for (int i = 0; i < NElts; ++i) {
1811         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1812           continue;
1813 
1814         // If this input comes from undef, mark it as such.
1815         if (UndefElements[MaskVec[i] - Offset]) {
1816           MaskVec[i] = -1;
1817           continue;
1818         }
1819 
1820         // If we can blend a non-undef lane, use that instead.
1821         if (!UndefElements[i])
1822           MaskVec[i] = i + Offset;
1823       }
1824     };
1825     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1826       BlendSplat(N1BV, 0);
1827     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1828       BlendSplat(N2BV, NElts);
1829   }
1830 
1831   // Canonicalize all index into lhs, -> shuffle lhs, undef
1832   // Canonicalize all index into rhs, -> shuffle rhs, undef
1833   bool AllLHS = true, AllRHS = true;
1834   bool N2Undef = N2.isUndef();
1835   for (int i = 0; i != NElts; ++i) {
1836     if (MaskVec[i] >= NElts) {
1837       if (N2Undef)
1838         MaskVec[i] = -1;
1839       else
1840         AllLHS = false;
1841     } else if (MaskVec[i] >= 0) {
1842       AllRHS = false;
1843     }
1844   }
1845   if (AllLHS && AllRHS)
1846     return getUNDEF(VT);
1847   if (AllLHS && !N2Undef)
1848     N2 = getUNDEF(VT);
1849   if (AllRHS) {
1850     N1 = getUNDEF(VT);
1851     commuteShuffle(N1, N2, MaskVec);
1852   }
1853   // Reset our undef status after accounting for the mask.
1854   N2Undef = N2.isUndef();
1855   // Re-check whether both sides ended up undef.
1856   if (N1.isUndef() && N2Undef)
1857     return getUNDEF(VT);
1858 
1859   // If Identity shuffle return that node.
1860   bool Identity = true, AllSame = true;
1861   for (int i = 0; i != NElts; ++i) {
1862     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1863     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1864   }
1865   if (Identity && NElts)
1866     return N1;
1867 
1868   // Shuffling a constant splat doesn't change the result.
1869   if (N2Undef) {
1870     SDValue V = N1;
1871 
1872     // Look through any bitcasts. We check that these don't change the number
1873     // (and size) of elements and just changes their types.
1874     while (V.getOpcode() == ISD::BITCAST)
1875       V = V->getOperand(0);
1876 
1877     // A splat should always show up as a build vector node.
1878     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1879       BitVector UndefElements;
1880       SDValue Splat = BV->getSplatValue(&UndefElements);
1881       // If this is a splat of an undef, shuffling it is also undef.
1882       if (Splat && Splat.isUndef())
1883         return getUNDEF(VT);
1884 
1885       bool SameNumElts =
1886           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1887 
1888       // We only have a splat which can skip shuffles if there is a splatted
1889       // value and no undef lanes rearranged by the shuffle.
1890       if (Splat && UndefElements.none()) {
1891         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1892         // number of elements match or the value splatted is a zero constant.
1893         if (SameNumElts)
1894           return N1;
1895         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1896           if (C->isNullValue())
1897             return N1;
1898       }
1899 
1900       // If the shuffle itself creates a splat, build the vector directly.
1901       if (AllSame && SameNumElts) {
1902         EVT BuildVT = BV->getValueType(0);
1903         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1904         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1905 
1906         // We may have jumped through bitcasts, so the type of the
1907         // BUILD_VECTOR may not match the type of the shuffle.
1908         if (BuildVT != VT)
1909           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1910         return NewBV;
1911       }
1912     }
1913   }
1914 
1915   FoldingSetNodeID ID;
1916   SDValue Ops[2] = { N1, N2 };
1917   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1918   for (int i = 0; i != NElts; ++i)
1919     ID.AddInteger(MaskVec[i]);
1920 
1921   void* IP = nullptr;
1922   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1923     return SDValue(E, 0);
1924 
1925   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1926   // SDNode doesn't have access to it.  This memory will be "leaked" when
1927   // the node is deallocated, but recovered when the NodeAllocator is released.
1928   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1929   llvm::copy(MaskVec, MaskAlloc);
1930 
1931   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1932                                            dl.getDebugLoc(), MaskAlloc);
1933   createOperands(N, Ops);
1934 
1935   CSEMap.InsertNode(N, IP);
1936   InsertNode(N);
1937   SDValue V = SDValue(N, 0);
1938   NewSDValueDbgMsg(V, "Creating new node: ", this);
1939   return V;
1940 }
1941 
1942 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1943   EVT VT = SV.getValueType(0);
1944   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1945   ShuffleVectorSDNode::commuteMask(MaskVec);
1946 
1947   SDValue Op0 = SV.getOperand(0);
1948   SDValue Op1 = SV.getOperand(1);
1949   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1950 }
1951 
1952 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1953   FoldingSetNodeID ID;
1954   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1955   ID.AddInteger(RegNo);
1956   void *IP = nullptr;
1957   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1958     return SDValue(E, 0);
1959 
1960   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1961   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1962   CSEMap.InsertNode(N, IP);
1963   InsertNode(N);
1964   return SDValue(N, 0);
1965 }
1966 
1967 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1968   FoldingSetNodeID ID;
1969   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1970   ID.AddPointer(RegMask);
1971   void *IP = nullptr;
1972   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1973     return SDValue(E, 0);
1974 
1975   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1976   CSEMap.InsertNode(N, IP);
1977   InsertNode(N);
1978   return SDValue(N, 0);
1979 }
1980 
1981 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1982                                  MCSymbol *Label) {
1983   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1984 }
1985 
1986 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1987                                    SDValue Root, MCSymbol *Label) {
1988   FoldingSetNodeID ID;
1989   SDValue Ops[] = { Root };
1990   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1991   ID.AddPointer(Label);
1992   void *IP = nullptr;
1993   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1994     return SDValue(E, 0);
1995 
1996   auto *N =
1997       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
1998   createOperands(N, Ops);
1999 
2000   CSEMap.InsertNode(N, IP);
2001   InsertNode(N);
2002   return SDValue(N, 0);
2003 }
2004 
2005 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2006                                       int64_t Offset, bool isTarget,
2007                                       unsigned TargetFlags) {
2008   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2009 
2010   FoldingSetNodeID ID;
2011   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2012   ID.AddPointer(BA);
2013   ID.AddInteger(Offset);
2014   ID.AddInteger(TargetFlags);
2015   void *IP = nullptr;
2016   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2017     return SDValue(E, 0);
2018 
2019   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2020   CSEMap.InsertNode(N, IP);
2021   InsertNode(N);
2022   return SDValue(N, 0);
2023 }
2024 
2025 SDValue SelectionDAG::getSrcValue(const Value *V) {
2026   FoldingSetNodeID ID;
2027   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2028   ID.AddPointer(V);
2029 
2030   void *IP = nullptr;
2031   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2032     return SDValue(E, 0);
2033 
2034   auto *N = newSDNode<SrcValueSDNode>(V);
2035   CSEMap.InsertNode(N, IP);
2036   InsertNode(N);
2037   return SDValue(N, 0);
2038 }
2039 
2040 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2041   FoldingSetNodeID ID;
2042   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2043   ID.AddPointer(MD);
2044 
2045   void *IP = nullptr;
2046   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2047     return SDValue(E, 0);
2048 
2049   auto *N = newSDNode<MDNodeSDNode>(MD);
2050   CSEMap.InsertNode(N, IP);
2051   InsertNode(N);
2052   return SDValue(N, 0);
2053 }
2054 
2055 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2056   if (VT == V.getValueType())
2057     return V;
2058 
2059   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2060 }
2061 
2062 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2063                                        unsigned SrcAS, unsigned DestAS) {
2064   SDValue Ops[] = {Ptr};
2065   FoldingSetNodeID ID;
2066   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2067   ID.AddInteger(SrcAS);
2068   ID.AddInteger(DestAS);
2069 
2070   void *IP = nullptr;
2071   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2072     return SDValue(E, 0);
2073 
2074   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2075                                            VT, SrcAS, DestAS);
2076   createOperands(N, Ops);
2077 
2078   CSEMap.InsertNode(N, IP);
2079   InsertNode(N);
2080   return SDValue(N, 0);
2081 }
2082 
2083 SDValue SelectionDAG::getFreeze(SDValue V) {
2084   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2085 }
2086 
2087 /// getShiftAmountOperand - Return the specified value casted to
2088 /// the target's desired shift amount type.
2089 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2090   EVT OpTy = Op.getValueType();
2091   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2092   if (OpTy == ShTy || OpTy.isVector()) return Op;
2093 
2094   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2095 }
2096 
2097 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2098   SDLoc dl(Node);
2099   const TargetLowering &TLI = getTargetLoweringInfo();
2100   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2101   EVT VT = Node->getValueType(0);
2102   SDValue Tmp1 = Node->getOperand(0);
2103   SDValue Tmp2 = Node->getOperand(1);
2104   const MaybeAlign MA(Node->getConstantOperandVal(3));
2105 
2106   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2107                                Tmp2, MachinePointerInfo(V));
2108   SDValue VAList = VAListLoad;
2109 
2110   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2111     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2112                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2113 
2114     VAList =
2115         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2116                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2117   }
2118 
2119   // Increment the pointer, VAList, to the next vaarg
2120   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2121                  getConstant(getDataLayout().getTypeAllocSize(
2122                                                VT.getTypeForEVT(*getContext())),
2123                              dl, VAList.getValueType()));
2124   // Store the incremented VAList to the legalized pointer
2125   Tmp1 =
2126       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2127   // Load the actual argument out of the pointer VAList
2128   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2129 }
2130 
2131 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2132   SDLoc dl(Node);
2133   const TargetLowering &TLI = getTargetLoweringInfo();
2134   // This defaults to loading a pointer from the input and storing it to the
2135   // output, returning the chain.
2136   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2137   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2138   SDValue Tmp1 =
2139       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2140               Node->getOperand(2), MachinePointerInfo(VS));
2141   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2142                   MachinePointerInfo(VD));
2143 }
2144 
2145 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2146   const DataLayout &DL = getDataLayout();
2147   Type *Ty = VT.getTypeForEVT(*getContext());
2148   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2149 
2150   if (TLI->isTypeLegal(VT) || !VT.isVector())
2151     return RedAlign;
2152 
2153   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2154   const Align StackAlign = TFI->getStackAlign();
2155 
2156   // See if we can choose a smaller ABI alignment in cases where it's an
2157   // illegal vector type that will get broken down.
2158   if (RedAlign > StackAlign) {
2159     EVT IntermediateVT;
2160     MVT RegisterVT;
2161     unsigned NumIntermediates;
2162     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2163                                 NumIntermediates, RegisterVT);
2164     Ty = IntermediateVT.getTypeForEVT(*getContext());
2165     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2166     if (RedAlign2 < RedAlign)
2167       RedAlign = RedAlign2;
2168   }
2169 
2170   return RedAlign;
2171 }
2172 
2173 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2174   MachineFrameInfo &MFI = MF->getFrameInfo();
2175   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2176   int StackID = 0;
2177   if (Bytes.isScalable())
2178     StackID = TFI->getStackIDForScalableVectors();
2179   // The stack id gives an indication of whether the object is scalable or
2180   // not, so it's safe to pass in the minimum size here.
2181   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2182                                        false, nullptr, StackID);
2183   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2184 }
2185 
2186 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2187   Type *Ty = VT.getTypeForEVT(*getContext());
2188   Align StackAlign =
2189       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2190   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2191 }
2192 
2193 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2194   TypeSize VT1Size = VT1.getStoreSize();
2195   TypeSize VT2Size = VT2.getStoreSize();
2196   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2197          "Don't know how to choose the maximum size when creating a stack "
2198          "temporary");
2199   TypeSize Bytes =
2200       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2201 
2202   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2203   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2204   const DataLayout &DL = getDataLayout();
2205   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2206   return CreateStackTemporary(Bytes, Align);
2207 }
2208 
2209 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2210                                 ISD::CondCode Cond, const SDLoc &dl) {
2211   EVT OpVT = N1.getValueType();
2212 
2213   // These setcc operations always fold.
2214   switch (Cond) {
2215   default: break;
2216   case ISD::SETFALSE:
2217   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2218   case ISD::SETTRUE:
2219   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2220 
2221   case ISD::SETOEQ:
2222   case ISD::SETOGT:
2223   case ISD::SETOGE:
2224   case ISD::SETOLT:
2225   case ISD::SETOLE:
2226   case ISD::SETONE:
2227   case ISD::SETO:
2228   case ISD::SETUO:
2229   case ISD::SETUEQ:
2230   case ISD::SETUNE:
2231     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2232     break;
2233   }
2234 
2235   if (OpVT.isInteger()) {
2236     // For EQ and NE, we can always pick a value for the undef to make the
2237     // predicate pass or fail, so we can return undef.
2238     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2239     // icmp eq/ne X, undef -> undef.
2240     if ((N1.isUndef() || N2.isUndef()) &&
2241         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2242       return getUNDEF(VT);
2243 
2244     // If both operands are undef, we can return undef for int comparison.
2245     // icmp undef, undef -> undef.
2246     if (N1.isUndef() && N2.isUndef())
2247       return getUNDEF(VT);
2248 
2249     // icmp X, X -> true/false
2250     // icmp X, undef -> true/false because undef could be X.
2251     if (N1 == N2)
2252       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2253   }
2254 
2255   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2256     const APInt &C2 = N2C->getAPIntValue();
2257     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2258       const APInt &C1 = N1C->getAPIntValue();
2259 
2260       switch (Cond) {
2261       default: llvm_unreachable("Unknown integer setcc!");
2262       case ISD::SETEQ:  return getBoolConstant(C1 == C2, dl, VT, OpVT);
2263       case ISD::SETNE:  return getBoolConstant(C1 != C2, dl, VT, OpVT);
2264       case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2265       case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2266       case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2267       case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2268       case ISD::SETLT:  return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2269       case ISD::SETGT:  return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2270       case ISD::SETLE:  return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2271       case ISD::SETGE:  return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2272       }
2273     }
2274   }
2275 
2276   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2277   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2278 
2279   if (N1CFP && N2CFP) {
2280     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2281     switch (Cond) {
2282     default: break;
2283     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2284                         return getUNDEF(VT);
2285                       LLVM_FALLTHROUGH;
2286     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2287                                              OpVT);
2288     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2289                         return getUNDEF(VT);
2290                       LLVM_FALLTHROUGH;
2291     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2292                                              R==APFloat::cmpLessThan, dl, VT,
2293                                              OpVT);
2294     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2295                         return getUNDEF(VT);
2296                       LLVM_FALLTHROUGH;
2297     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2298                                              OpVT);
2299     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2300                         return getUNDEF(VT);
2301                       LLVM_FALLTHROUGH;
2302     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2303                                              VT, OpVT);
2304     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2305                         return getUNDEF(VT);
2306                       LLVM_FALLTHROUGH;
2307     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2308                                              R==APFloat::cmpEqual, dl, VT,
2309                                              OpVT);
2310     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2311                         return getUNDEF(VT);
2312                       LLVM_FALLTHROUGH;
2313     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2314                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2315     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2316                                              OpVT);
2317     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2318                                              OpVT);
2319     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2320                                              R==APFloat::cmpEqual, dl, VT,
2321                                              OpVT);
2322     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2323                                              OpVT);
2324     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2325                                              R==APFloat::cmpLessThan, dl, VT,
2326                                              OpVT);
2327     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2328                                              R==APFloat::cmpUnordered, dl, VT,
2329                                              OpVT);
2330     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2331                                              VT, OpVT);
2332     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2333                                              OpVT);
2334     }
2335   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2336     // Ensure that the constant occurs on the RHS.
2337     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2338     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2339       return SDValue();
2340     return getSetCC(dl, VT, N2, N1, SwappedCond);
2341   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2342              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2343     // If an operand is known to be a nan (or undef that could be a nan), we can
2344     // fold it.
2345     // Choosing NaN for the undef will always make unordered comparison succeed
2346     // and ordered comparison fails.
2347     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2348     switch (ISD::getUnorderedFlavor(Cond)) {
2349     default:
2350       llvm_unreachable("Unknown flavor!");
2351     case 0: // Known false.
2352       return getBoolConstant(false, dl, VT, OpVT);
2353     case 1: // Known true.
2354       return getBoolConstant(true, dl, VT, OpVT);
2355     case 2: // Undefined.
2356       return getUNDEF(VT);
2357     }
2358   }
2359 
2360   // Could not fold it.
2361   return SDValue();
2362 }
2363 
2364 /// See if the specified operand can be simplified with the knowledge that only
2365 /// the bits specified by DemandedBits are used.
2366 /// TODO: really we should be making this into the DAG equivalent of
2367 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2368 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2369   EVT VT = V.getValueType();
2370 
2371   if (VT.isScalableVector())
2372     return SDValue();
2373 
2374   APInt DemandedElts = VT.isVector()
2375                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2376                            : APInt(1, 1);
2377   return GetDemandedBits(V, DemandedBits, DemandedElts);
2378 }
2379 
2380 /// See if the specified operand can be simplified with the knowledge that only
2381 /// the bits specified by DemandedBits are used in the elements specified by
2382 /// DemandedElts.
2383 /// TODO: really we should be making this into the DAG equivalent of
2384 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2385 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2386                                       const APInt &DemandedElts) {
2387   switch (V.getOpcode()) {
2388   default:
2389     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2390                                                 *this, 0);
2391   case ISD::Constant: {
2392     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2393     APInt NewVal = CVal & DemandedBits;
2394     if (NewVal != CVal)
2395       return getConstant(NewVal, SDLoc(V), V.getValueType());
2396     break;
2397   }
2398   case ISD::SRL:
2399     // Only look at single-use SRLs.
2400     if (!V.getNode()->hasOneUse())
2401       break;
2402     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2403       // See if we can recursively simplify the LHS.
2404       unsigned Amt = RHSC->getZExtValue();
2405 
2406       // Watch out for shift count overflow though.
2407       if (Amt >= DemandedBits.getBitWidth())
2408         break;
2409       APInt SrcDemandedBits = DemandedBits << Amt;
2410       if (SDValue SimplifyLHS =
2411               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2412         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2413                        V.getOperand(1));
2414     }
2415     break;
2416   }
2417   return SDValue();
2418 }
2419 
2420 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2421 /// use this predicate to simplify operations downstream.
2422 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2423   unsigned BitWidth = Op.getScalarValueSizeInBits();
2424   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2425 }
2426 
2427 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2428 /// this predicate to simplify operations downstream.  Mask is known to be zero
2429 /// for bits that V cannot have.
2430 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2431                                      unsigned Depth) const {
2432   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2433 }
2434 
2435 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2436 /// DemandedElts.  We use this predicate to simplify operations downstream.
2437 /// Mask is known to be zero for bits that V cannot have.
2438 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2439                                      const APInt &DemandedElts,
2440                                      unsigned Depth) const {
2441   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2442 }
2443 
2444 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2445 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2446                                         unsigned Depth) const {
2447   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2448 }
2449 
2450 /// isSplatValue - Return true if the vector V has the same value
2451 /// across all DemandedElts. For scalable vectors it does not make
2452 /// sense to specify which elements are demanded or undefined, therefore
2453 /// they are simply ignored.
2454 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2455                                 APInt &UndefElts, unsigned Depth) {
2456   EVT VT = V.getValueType();
2457   assert(VT.isVector() && "Vector type expected");
2458 
2459   if (!VT.isScalableVector() && !DemandedElts)
2460     return false; // No demanded elts, better to assume we don't know anything.
2461 
2462   if (Depth >= MaxRecursionDepth)
2463     return false; // Limit search depth.
2464 
2465   // Deal with some common cases here that work for both fixed and scalable
2466   // vector types.
2467   switch (V.getOpcode()) {
2468   case ISD::SPLAT_VECTOR:
2469     UndefElts = V.getOperand(0).isUndef()
2470                     ? APInt::getAllOnesValue(DemandedElts.getBitWidth())
2471                     : APInt(DemandedElts.getBitWidth(), 0);
2472     return true;
2473   case ISD::ADD:
2474   case ISD::SUB:
2475   case ISD::AND:
2476   case ISD::XOR:
2477   case ISD::OR: {
2478     APInt UndefLHS, UndefRHS;
2479     SDValue LHS = V.getOperand(0);
2480     SDValue RHS = V.getOperand(1);
2481     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2482         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2483       UndefElts = UndefLHS | UndefRHS;
2484       return true;
2485     }
2486     return false;
2487   }
2488   case ISD::ABS:
2489   case ISD::TRUNCATE:
2490   case ISD::SIGN_EXTEND:
2491   case ISD::ZERO_EXTEND:
2492     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2493   }
2494 
2495   // We don't support other cases than those above for scalable vectors at
2496   // the moment.
2497   if (VT.isScalableVector())
2498     return false;
2499 
2500   unsigned NumElts = VT.getVectorNumElements();
2501   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2502   UndefElts = APInt::getNullValue(NumElts);
2503 
2504   switch (V.getOpcode()) {
2505   case ISD::BUILD_VECTOR: {
2506     SDValue Scl;
2507     for (unsigned i = 0; i != NumElts; ++i) {
2508       SDValue Op = V.getOperand(i);
2509       if (Op.isUndef()) {
2510         UndefElts.setBit(i);
2511         continue;
2512       }
2513       if (!DemandedElts[i])
2514         continue;
2515       if (Scl && Scl != Op)
2516         return false;
2517       Scl = Op;
2518     }
2519     return true;
2520   }
2521   case ISD::VECTOR_SHUFFLE: {
2522     // Check if this is a shuffle node doing a splat.
2523     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2524     int SplatIndex = -1;
2525     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2526     for (int i = 0; i != (int)NumElts; ++i) {
2527       int M = Mask[i];
2528       if (M < 0) {
2529         UndefElts.setBit(i);
2530         continue;
2531       }
2532       if (!DemandedElts[i])
2533         continue;
2534       if (0 <= SplatIndex && SplatIndex != M)
2535         return false;
2536       SplatIndex = M;
2537     }
2538     return true;
2539   }
2540   case ISD::EXTRACT_SUBVECTOR: {
2541     // Offset the demanded elts by the subvector index.
2542     SDValue Src = V.getOperand(0);
2543     // We don't support scalable vectors at the moment.
2544     if (Src.getValueType().isScalableVector())
2545       return false;
2546     uint64_t Idx = V.getConstantOperandVal(1);
2547     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2548     APInt UndefSrcElts;
2549     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2550     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2551       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2552       return true;
2553     }
2554     break;
2555   }
2556   }
2557 
2558   return false;
2559 }
2560 
2561 /// Helper wrapper to main isSplatValue function.
2562 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2563   EVT VT = V.getValueType();
2564   assert(VT.isVector() && "Vector type expected");
2565 
2566   APInt UndefElts;
2567   APInt DemandedElts;
2568 
2569   // For now we don't support this with scalable vectors.
2570   if (!VT.isScalableVector())
2571     DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2572   return isSplatValue(V, DemandedElts, UndefElts) &&
2573          (AllowUndefs || !UndefElts);
2574 }
2575 
2576 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2577   V = peekThroughExtractSubvectors(V);
2578 
2579   EVT VT = V.getValueType();
2580   unsigned Opcode = V.getOpcode();
2581   switch (Opcode) {
2582   default: {
2583     APInt UndefElts;
2584     APInt DemandedElts;
2585 
2586     if (!VT.isScalableVector())
2587       DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2588 
2589     if (isSplatValue(V, DemandedElts, UndefElts)) {
2590       if (VT.isScalableVector()) {
2591         // DemandedElts and UndefElts are ignored for scalable vectors, since
2592         // the only supported cases are SPLAT_VECTOR nodes.
2593         SplatIdx = 0;
2594       } else {
2595         // Handle case where all demanded elements are UNDEF.
2596         if (DemandedElts.isSubsetOf(UndefElts)) {
2597           SplatIdx = 0;
2598           return getUNDEF(VT);
2599         }
2600         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2601       }
2602       return V;
2603     }
2604     break;
2605   }
2606   case ISD::SPLAT_VECTOR:
2607     SplatIdx = 0;
2608     return V;
2609   case ISD::VECTOR_SHUFFLE: {
2610     if (VT.isScalableVector())
2611       return SDValue();
2612 
2613     // Check if this is a shuffle node doing a splat.
2614     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2615     // getTargetVShiftNode currently struggles without the splat source.
2616     auto *SVN = cast<ShuffleVectorSDNode>(V);
2617     if (!SVN->isSplat())
2618       break;
2619     int Idx = SVN->getSplatIndex();
2620     int NumElts = V.getValueType().getVectorNumElements();
2621     SplatIdx = Idx % NumElts;
2622     return V.getOperand(Idx / NumElts);
2623   }
2624   }
2625 
2626   return SDValue();
2627 }
2628 
2629 SDValue SelectionDAG::getSplatValue(SDValue V) {
2630   int SplatIdx;
2631   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
2632     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V),
2633                    SrcVector.getValueType().getScalarType(), SrcVector,
2634                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2635   return SDValue();
2636 }
2637 
2638 const APInt *
2639 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2640                                           const APInt &DemandedElts) const {
2641   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2642           V.getOpcode() == ISD::SRA) &&
2643          "Unknown shift node");
2644   unsigned BitWidth = V.getScalarValueSizeInBits();
2645   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2646     // Shifting more than the bitwidth is not valid.
2647     const APInt &ShAmt = SA->getAPIntValue();
2648     if (ShAmt.ult(BitWidth))
2649       return &ShAmt;
2650   }
2651   return nullptr;
2652 }
2653 
2654 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2655     SDValue V, const APInt &DemandedElts) const {
2656   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2657           V.getOpcode() == ISD::SRA) &&
2658          "Unknown shift node");
2659   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2660     return ValidAmt;
2661   unsigned BitWidth = V.getScalarValueSizeInBits();
2662   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2663   if (!BV)
2664     return nullptr;
2665   const APInt *MinShAmt = nullptr;
2666   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2667     if (!DemandedElts[i])
2668       continue;
2669     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2670     if (!SA)
2671       return nullptr;
2672     // Shifting more than the bitwidth is not valid.
2673     const APInt &ShAmt = SA->getAPIntValue();
2674     if (ShAmt.uge(BitWidth))
2675       return nullptr;
2676     if (MinShAmt && MinShAmt->ule(ShAmt))
2677       continue;
2678     MinShAmt = &ShAmt;
2679   }
2680   return MinShAmt;
2681 }
2682 
2683 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2684     SDValue V, const APInt &DemandedElts) const {
2685   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2686           V.getOpcode() == ISD::SRA) &&
2687          "Unknown shift node");
2688   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2689     return ValidAmt;
2690   unsigned BitWidth = V.getScalarValueSizeInBits();
2691   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2692   if (!BV)
2693     return nullptr;
2694   const APInt *MaxShAmt = nullptr;
2695   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2696     if (!DemandedElts[i])
2697       continue;
2698     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2699     if (!SA)
2700       return nullptr;
2701     // Shifting more than the bitwidth is not valid.
2702     const APInt &ShAmt = SA->getAPIntValue();
2703     if (ShAmt.uge(BitWidth))
2704       return nullptr;
2705     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2706       continue;
2707     MaxShAmt = &ShAmt;
2708   }
2709   return MaxShAmt;
2710 }
2711 
2712 /// Determine which bits of Op are known to be either zero or one and return
2713 /// them in Known. For vectors, the known bits are those that are shared by
2714 /// every vector element.
2715 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2716   EVT VT = Op.getValueType();
2717 
2718   // TOOD: Until we have a plan for how to represent demanded elements for
2719   // scalable vectors, we can just bail out for now.
2720   if (Op.getValueType().isScalableVector()) {
2721     unsigned BitWidth = Op.getScalarValueSizeInBits();
2722     return KnownBits(BitWidth);
2723   }
2724 
2725   APInt DemandedElts = VT.isVector()
2726                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2727                            : APInt(1, 1);
2728   return computeKnownBits(Op, DemandedElts, Depth);
2729 }
2730 
2731 /// Determine which bits of Op are known to be either zero or one and return
2732 /// them in Known. The DemandedElts argument allows us to only collect the known
2733 /// bits that are shared by the requested vector elements.
2734 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2735                                          unsigned Depth) const {
2736   unsigned BitWidth = Op.getScalarValueSizeInBits();
2737 
2738   KnownBits Known(BitWidth);   // Don't know anything.
2739 
2740   // TOOD: Until we have a plan for how to represent demanded elements for
2741   // scalable vectors, we can just bail out for now.
2742   if (Op.getValueType().isScalableVector())
2743     return Known;
2744 
2745   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2746     // We know all of the bits for a constant!
2747     return KnownBits::makeConstant(C->getAPIntValue());
2748   }
2749   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2750     // We know all of the bits for a constant fp!
2751     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2752   }
2753 
2754   if (Depth >= MaxRecursionDepth)
2755     return Known;  // Limit search depth.
2756 
2757   KnownBits Known2;
2758   unsigned NumElts = DemandedElts.getBitWidth();
2759   assert((!Op.getValueType().isVector() ||
2760           NumElts == Op.getValueType().getVectorNumElements()) &&
2761          "Unexpected vector size");
2762 
2763   if (!DemandedElts)
2764     return Known;  // No demanded elts, better to assume we don't know anything.
2765 
2766   unsigned Opcode = Op.getOpcode();
2767   switch (Opcode) {
2768   case ISD::BUILD_VECTOR:
2769     // Collect the known bits that are shared by every demanded vector element.
2770     Known.Zero.setAllBits(); Known.One.setAllBits();
2771     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2772       if (!DemandedElts[i])
2773         continue;
2774 
2775       SDValue SrcOp = Op.getOperand(i);
2776       Known2 = computeKnownBits(SrcOp, Depth + 1);
2777 
2778       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2779       if (SrcOp.getValueSizeInBits() != BitWidth) {
2780         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2781                "Expected BUILD_VECTOR implicit truncation");
2782         Known2 = Known2.trunc(BitWidth);
2783       }
2784 
2785       // Known bits are the values that are shared by every demanded element.
2786       Known = KnownBits::commonBits(Known, Known2);
2787 
2788       // If we don't know any bits, early out.
2789       if (Known.isUnknown())
2790         break;
2791     }
2792     break;
2793   case ISD::VECTOR_SHUFFLE: {
2794     // Collect the known bits that are shared by every vector element referenced
2795     // by the shuffle.
2796     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2797     Known.Zero.setAllBits(); Known.One.setAllBits();
2798     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2799     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2800     for (unsigned i = 0; i != NumElts; ++i) {
2801       if (!DemandedElts[i])
2802         continue;
2803 
2804       int M = SVN->getMaskElt(i);
2805       if (M < 0) {
2806         // For UNDEF elements, we don't know anything about the common state of
2807         // the shuffle result.
2808         Known.resetAll();
2809         DemandedLHS.clearAllBits();
2810         DemandedRHS.clearAllBits();
2811         break;
2812       }
2813 
2814       if ((unsigned)M < NumElts)
2815         DemandedLHS.setBit((unsigned)M % NumElts);
2816       else
2817         DemandedRHS.setBit((unsigned)M % NumElts);
2818     }
2819     // Known bits are the values that are shared by every demanded element.
2820     if (!!DemandedLHS) {
2821       SDValue LHS = Op.getOperand(0);
2822       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2823       Known = KnownBits::commonBits(Known, Known2);
2824     }
2825     // If we don't know any bits, early out.
2826     if (Known.isUnknown())
2827       break;
2828     if (!!DemandedRHS) {
2829       SDValue RHS = Op.getOperand(1);
2830       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2831       Known = KnownBits::commonBits(Known, Known2);
2832     }
2833     break;
2834   }
2835   case ISD::CONCAT_VECTORS: {
2836     // Split DemandedElts and test each of the demanded subvectors.
2837     Known.Zero.setAllBits(); Known.One.setAllBits();
2838     EVT SubVectorVT = Op.getOperand(0).getValueType();
2839     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2840     unsigned NumSubVectors = Op.getNumOperands();
2841     for (unsigned i = 0; i != NumSubVectors; ++i) {
2842       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2843       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2844       if (!!DemandedSub) {
2845         SDValue Sub = Op.getOperand(i);
2846         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2847         Known = KnownBits::commonBits(Known, Known2);
2848       }
2849       // If we don't know any bits, early out.
2850       if (Known.isUnknown())
2851         break;
2852     }
2853     break;
2854   }
2855   case ISD::INSERT_SUBVECTOR: {
2856     // Demand any elements from the subvector and the remainder from the src its
2857     // inserted into.
2858     SDValue Src = Op.getOperand(0);
2859     SDValue Sub = Op.getOperand(1);
2860     uint64_t Idx = Op.getConstantOperandVal(2);
2861     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2862     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2863     APInt DemandedSrcElts = DemandedElts;
2864     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2865 
2866     Known.One.setAllBits();
2867     Known.Zero.setAllBits();
2868     if (!!DemandedSubElts) {
2869       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2870       if (Known.isUnknown())
2871         break; // early-out.
2872     }
2873     if (!!DemandedSrcElts) {
2874       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2875       Known = KnownBits::commonBits(Known, Known2);
2876     }
2877     break;
2878   }
2879   case ISD::EXTRACT_SUBVECTOR: {
2880     // Offset the demanded elts by the subvector index.
2881     SDValue Src = Op.getOperand(0);
2882     // Bail until we can represent demanded elements for scalable vectors.
2883     if (Src.getValueType().isScalableVector())
2884       break;
2885     uint64_t Idx = Op.getConstantOperandVal(1);
2886     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2887     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2888     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2889     break;
2890   }
2891   case ISD::SCALAR_TO_VECTOR: {
2892     // We know about scalar_to_vector as much as we know about it source,
2893     // which becomes the first element of otherwise unknown vector.
2894     if (DemandedElts != 1)
2895       break;
2896 
2897     SDValue N0 = Op.getOperand(0);
2898     Known = computeKnownBits(N0, Depth + 1);
2899     if (N0.getValueSizeInBits() != BitWidth)
2900       Known = Known.trunc(BitWidth);
2901 
2902     break;
2903   }
2904   case ISD::BITCAST: {
2905     SDValue N0 = Op.getOperand(0);
2906     EVT SubVT = N0.getValueType();
2907     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2908 
2909     // Ignore bitcasts from unsupported types.
2910     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2911       break;
2912 
2913     // Fast handling of 'identity' bitcasts.
2914     if (BitWidth == SubBitWidth) {
2915       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2916       break;
2917     }
2918 
2919     bool IsLE = getDataLayout().isLittleEndian();
2920 
2921     // Bitcast 'small element' vector to 'large element' scalar/vector.
2922     if ((BitWidth % SubBitWidth) == 0) {
2923       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2924 
2925       // Collect known bits for the (larger) output by collecting the known
2926       // bits from each set of sub elements and shift these into place.
2927       // We need to separately call computeKnownBits for each set of
2928       // sub elements as the knownbits for each is likely to be different.
2929       unsigned SubScale = BitWidth / SubBitWidth;
2930       APInt SubDemandedElts(NumElts * SubScale, 0);
2931       for (unsigned i = 0; i != NumElts; ++i)
2932         if (DemandedElts[i])
2933           SubDemandedElts.setBit(i * SubScale);
2934 
2935       for (unsigned i = 0; i != SubScale; ++i) {
2936         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2937                          Depth + 1);
2938         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2939         Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2940         Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2941       }
2942     }
2943 
2944     // Bitcast 'large element' scalar/vector to 'small element' vector.
2945     if ((SubBitWidth % BitWidth) == 0) {
2946       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2947 
2948       // Collect known bits for the (smaller) output by collecting the known
2949       // bits from the overlapping larger input elements and extracting the
2950       // sub sections we actually care about.
2951       unsigned SubScale = SubBitWidth / BitWidth;
2952       APInt SubDemandedElts(NumElts / SubScale, 0);
2953       for (unsigned i = 0; i != NumElts; ++i)
2954         if (DemandedElts[i])
2955           SubDemandedElts.setBit(i / SubScale);
2956 
2957       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2958 
2959       Known.Zero.setAllBits(); Known.One.setAllBits();
2960       for (unsigned i = 0; i != NumElts; ++i)
2961         if (DemandedElts[i]) {
2962           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2963           unsigned Offset = (Shifts % SubScale) * BitWidth;
2964           Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2965           Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2966           // If we don't know any bits, early out.
2967           if (Known.isUnknown())
2968             break;
2969         }
2970     }
2971     break;
2972   }
2973   case ISD::AND:
2974     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2975     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2976 
2977     Known &= Known2;
2978     break;
2979   case ISD::OR:
2980     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2981     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2982 
2983     Known |= Known2;
2984     break;
2985   case ISD::XOR:
2986     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2987     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2988 
2989     Known ^= Known2;
2990     break;
2991   case ISD::MUL: {
2992     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2993     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2994     Known = KnownBits::mul(Known, Known2);
2995     break;
2996   }
2997   case ISD::MULHU: {
2998     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2999     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3000     Known = KnownBits::mulhu(Known, Known2);
3001     break;
3002   }
3003   case ISD::MULHS: {
3004     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3005     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3006     Known = KnownBits::mulhs(Known, Known2);
3007     break;
3008   }
3009   case ISD::UMUL_LOHI: {
3010     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3011     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3012     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3013     if (Op.getResNo() == 0)
3014       Known = KnownBits::mul(Known, Known2);
3015     else
3016       Known = KnownBits::mulhu(Known, Known2);
3017     break;
3018   }
3019   case ISD::SMUL_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::mulhs(Known, Known2);
3027     break;
3028   }
3029   case ISD::UDIV: {
3030     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3031     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3032     Known = KnownBits::udiv(Known, Known2);
3033     break;
3034   }
3035   case ISD::SELECT:
3036   case ISD::VSELECT:
3037     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3038     // If we don't know any bits, early out.
3039     if (Known.isUnknown())
3040       break;
3041     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3042 
3043     // Only known if known in both the LHS and RHS.
3044     Known = KnownBits::commonBits(Known, Known2);
3045     break;
3046   case ISD::SELECT_CC:
3047     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3048     // If we don't know any bits, early out.
3049     if (Known.isUnknown())
3050       break;
3051     Known2 = computeKnownBits(Op.getOperand(2), 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::SMULO:
3057   case ISD::UMULO:
3058   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3059     if (Op.getResNo() != 1)
3060       break;
3061     // The boolean result conforms to getBooleanContents.
3062     // If we know the result of a setcc has the top bits zero, use this info.
3063     // We know that we have an integer-based boolean since these operations
3064     // are only available for integer.
3065     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3066             TargetLowering::ZeroOrOneBooleanContent &&
3067         BitWidth > 1)
3068       Known.Zero.setBitsFrom(1);
3069     break;
3070   case ISD::SETCC:
3071   case ISD::STRICT_FSETCC:
3072   case ISD::STRICT_FSETCCS: {
3073     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3074     // If we know the result of a setcc has the top bits zero, use this info.
3075     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3076             TargetLowering::ZeroOrOneBooleanContent &&
3077         BitWidth > 1)
3078       Known.Zero.setBitsFrom(1);
3079     break;
3080   }
3081   case ISD::SHL:
3082     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3083     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3084     Known = KnownBits::shl(Known, Known2);
3085 
3086     // Minimum shift low bits are known zero.
3087     if (const APInt *ShMinAmt =
3088             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3089       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3090     break;
3091   case ISD::SRL:
3092     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3093     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3094     Known = KnownBits::lshr(Known, Known2);
3095 
3096     // Minimum shift high bits are known zero.
3097     if (const APInt *ShMinAmt =
3098             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3099       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3100     break;
3101   case ISD::SRA:
3102     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3103     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3104     Known = KnownBits::ashr(Known, Known2);
3105     // TODO: Add minimum shift high known sign bits.
3106     break;
3107   case ISD::FSHL:
3108   case ISD::FSHR:
3109     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3110       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3111 
3112       // For fshl, 0-shift returns the 1st arg.
3113       // For fshr, 0-shift returns the 2nd arg.
3114       if (Amt == 0) {
3115         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3116                                  DemandedElts, Depth + 1);
3117         break;
3118       }
3119 
3120       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3121       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3122       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3123       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3124       if (Opcode == ISD::FSHL) {
3125         Known.One <<= Amt;
3126         Known.Zero <<= Amt;
3127         Known2.One.lshrInPlace(BitWidth - Amt);
3128         Known2.Zero.lshrInPlace(BitWidth - Amt);
3129       } else {
3130         Known.One <<= BitWidth - Amt;
3131         Known.Zero <<= BitWidth - Amt;
3132         Known2.One.lshrInPlace(Amt);
3133         Known2.Zero.lshrInPlace(Amt);
3134       }
3135       Known.One |= Known2.One;
3136       Known.Zero |= Known2.Zero;
3137     }
3138     break;
3139   case ISD::SIGN_EXTEND_INREG: {
3140     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3141     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3142     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3143     break;
3144   }
3145   case ISD::CTTZ:
3146   case ISD::CTTZ_ZERO_UNDEF: {
3147     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3148     // If we have a known 1, its position is our upper bound.
3149     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3150     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3151     Known.Zero.setBitsFrom(LowBits);
3152     break;
3153   }
3154   case ISD::CTLZ:
3155   case ISD::CTLZ_ZERO_UNDEF: {
3156     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3157     // If we have a known 1, its position is our upper bound.
3158     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3159     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3160     Known.Zero.setBitsFrom(LowBits);
3161     break;
3162   }
3163   case ISD::CTPOP: {
3164     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3165     // If we know some of the bits are zero, they can't be one.
3166     unsigned PossibleOnes = Known2.countMaxPopulation();
3167     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3168     break;
3169   }
3170   case ISD::PARITY: {
3171     // Parity returns 0 everywhere but the LSB.
3172     Known.Zero.setBitsFrom(1);
3173     break;
3174   }
3175   case ISD::LOAD: {
3176     LoadSDNode *LD = cast<LoadSDNode>(Op);
3177     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3178     if (ISD::isNON_EXTLoad(LD) && Cst) {
3179       // Determine any common known bits from the loaded constant pool value.
3180       Type *CstTy = Cst->getType();
3181       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3182         // If its a vector splat, then we can (quickly) reuse the scalar path.
3183         // NOTE: We assume all elements match and none are UNDEF.
3184         if (CstTy->isVectorTy()) {
3185           if (const Constant *Splat = Cst->getSplatValue()) {
3186             Cst = Splat;
3187             CstTy = Cst->getType();
3188           }
3189         }
3190         // TODO - do we need to handle different bitwidths?
3191         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3192           // Iterate across all vector elements finding common known bits.
3193           Known.One.setAllBits();
3194           Known.Zero.setAllBits();
3195           for (unsigned i = 0; i != NumElts; ++i) {
3196             if (!DemandedElts[i])
3197               continue;
3198             if (Constant *Elt = Cst->getAggregateElement(i)) {
3199               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3200                 const APInt &Value = CInt->getValue();
3201                 Known.One &= Value;
3202                 Known.Zero &= ~Value;
3203                 continue;
3204               }
3205               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3206                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3207                 Known.One &= Value;
3208                 Known.Zero &= ~Value;
3209                 continue;
3210               }
3211             }
3212             Known.One.clearAllBits();
3213             Known.Zero.clearAllBits();
3214             break;
3215           }
3216         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3217           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3218             Known = KnownBits::makeConstant(CInt->getValue());
3219           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3220             Known =
3221                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3222           }
3223         }
3224       }
3225     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3226       // If this is a ZEXTLoad and we are looking at the loaded value.
3227       EVT VT = LD->getMemoryVT();
3228       unsigned MemBits = VT.getScalarSizeInBits();
3229       Known.Zero.setBitsFrom(MemBits);
3230     } else if (const MDNode *Ranges = LD->getRanges()) {
3231       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3232         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3233     }
3234     break;
3235   }
3236   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3237     EVT InVT = Op.getOperand(0).getValueType();
3238     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3239     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3240     Known = Known.zext(BitWidth);
3241     break;
3242   }
3243   case ISD::ZERO_EXTEND: {
3244     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3245     Known = Known.zext(BitWidth);
3246     break;
3247   }
3248   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3249     EVT InVT = Op.getOperand(0).getValueType();
3250     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3251     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3252     // If the sign bit is known to be zero or one, then sext will extend
3253     // it to the top bits, else it will just zext.
3254     Known = Known.sext(BitWidth);
3255     break;
3256   }
3257   case ISD::SIGN_EXTEND: {
3258     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3259     // If the sign bit is known to be zero or one, then sext will extend
3260     // it to the top bits, else it will just zext.
3261     Known = Known.sext(BitWidth);
3262     break;
3263   }
3264   case ISD::ANY_EXTEND_VECTOR_INREG: {
3265     EVT InVT = Op.getOperand(0).getValueType();
3266     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3267     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3268     Known = Known.anyext(BitWidth);
3269     break;
3270   }
3271   case ISD::ANY_EXTEND: {
3272     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3273     Known = Known.anyext(BitWidth);
3274     break;
3275   }
3276   case ISD::TRUNCATE: {
3277     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3278     Known = Known.trunc(BitWidth);
3279     break;
3280   }
3281   case ISD::AssertZext: {
3282     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3283     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3284     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3285     Known.Zero |= (~InMask);
3286     Known.One  &= (~Known.Zero);
3287     break;
3288   }
3289   case ISD::AssertAlign: {
3290     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3291     assert(LogOfAlign != 0);
3292     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3293     // well as clearing one bits.
3294     Known.Zero.setLowBits(LogOfAlign);
3295     Known.One.clearLowBits(LogOfAlign);
3296     break;
3297   }
3298   case ISD::FGETSIGN:
3299     // All bits are zero except the low bit.
3300     Known.Zero.setBitsFrom(1);
3301     break;
3302   case ISD::USUBO:
3303   case ISD::SSUBO:
3304     if (Op.getResNo() == 1) {
3305       // If we know the result of a setcc has the top bits zero, use this info.
3306       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3307               TargetLowering::ZeroOrOneBooleanContent &&
3308           BitWidth > 1)
3309         Known.Zero.setBitsFrom(1);
3310       break;
3311     }
3312     LLVM_FALLTHROUGH;
3313   case ISD::SUB:
3314   case ISD::SUBC: {
3315     assert(Op.getResNo() == 0 &&
3316            "We only compute knownbits for the difference here.");
3317 
3318     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3319     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3320     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3321                                         Known, Known2);
3322     break;
3323   }
3324   case ISD::UADDO:
3325   case ISD::SADDO:
3326   case ISD::ADDCARRY:
3327     if (Op.getResNo() == 1) {
3328       // If we know the result of a setcc has the top bits zero, use this info.
3329       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3330               TargetLowering::ZeroOrOneBooleanContent &&
3331           BitWidth > 1)
3332         Known.Zero.setBitsFrom(1);
3333       break;
3334     }
3335     LLVM_FALLTHROUGH;
3336   case ISD::ADD:
3337   case ISD::ADDC:
3338   case ISD::ADDE: {
3339     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3340 
3341     // With ADDE and ADDCARRY, a carry bit may be added in.
3342     KnownBits Carry(1);
3343     if (Opcode == ISD::ADDE)
3344       // Can't track carry from glue, set carry to unknown.
3345       Carry.resetAll();
3346     else if (Opcode == ISD::ADDCARRY)
3347       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3348       // the trouble (how often will we find a known carry bit). And I haven't
3349       // tested this very much yet, but something like this might work:
3350       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3351       //   Carry = Carry.zextOrTrunc(1, false);
3352       Carry.resetAll();
3353     else
3354       Carry.setAllZero();
3355 
3356     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3357     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3358     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3359     break;
3360   }
3361   case ISD::SREM: {
3362     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3363     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3364     Known = KnownBits::srem(Known, Known2);
3365     break;
3366   }
3367   case ISD::UREM: {
3368     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3369     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3370     Known = KnownBits::urem(Known, Known2);
3371     break;
3372   }
3373   case ISD::EXTRACT_ELEMENT: {
3374     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3375     const unsigned Index = Op.getConstantOperandVal(1);
3376     const unsigned EltBitWidth = Op.getValueSizeInBits();
3377 
3378     // Remove low part of known bits mask
3379     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3380     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3381 
3382     // Remove high part of known bit mask
3383     Known = Known.trunc(EltBitWidth);
3384     break;
3385   }
3386   case ISD::EXTRACT_VECTOR_ELT: {
3387     SDValue InVec = Op.getOperand(0);
3388     SDValue EltNo = Op.getOperand(1);
3389     EVT VecVT = InVec.getValueType();
3390     // computeKnownBits not yet implemented for scalable vectors.
3391     if (VecVT.isScalableVector())
3392       break;
3393     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3394     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3395 
3396     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3397     // anything about the extended bits.
3398     if (BitWidth > EltBitWidth)
3399       Known = Known.trunc(EltBitWidth);
3400 
3401     // If we know the element index, just demand that vector element, else for
3402     // an unknown element index, ignore DemandedElts and demand them all.
3403     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3404     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3405     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3406       DemandedSrcElts =
3407           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3408 
3409     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3410     if (BitWidth > EltBitWidth)
3411       Known = Known.anyext(BitWidth);
3412     break;
3413   }
3414   case ISD::INSERT_VECTOR_ELT: {
3415     // If we know the element index, split the demand between the
3416     // source vector and the inserted element, otherwise assume we need
3417     // the original demanded vector elements and the value.
3418     SDValue InVec = Op.getOperand(0);
3419     SDValue InVal = Op.getOperand(1);
3420     SDValue EltNo = Op.getOperand(2);
3421     bool DemandedVal = true;
3422     APInt DemandedVecElts = DemandedElts;
3423     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3424     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3425       unsigned EltIdx = CEltNo->getZExtValue();
3426       DemandedVal = !!DemandedElts[EltIdx];
3427       DemandedVecElts.clearBit(EltIdx);
3428     }
3429     Known.One.setAllBits();
3430     Known.Zero.setAllBits();
3431     if (DemandedVal) {
3432       Known2 = computeKnownBits(InVal, Depth + 1);
3433       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3434     }
3435     if (!!DemandedVecElts) {
3436       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3437       Known = KnownBits::commonBits(Known, Known2);
3438     }
3439     break;
3440   }
3441   case ISD::BITREVERSE: {
3442     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3443     Known = Known2.reverseBits();
3444     break;
3445   }
3446   case ISD::BSWAP: {
3447     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3448     Known = Known2.byteSwap();
3449     break;
3450   }
3451   case ISD::ABS: {
3452     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3453     Known = Known2.abs();
3454     break;
3455   }
3456   case ISD::USUBSAT: {
3457     // The result of usubsat will never be larger than the LHS.
3458     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3459     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3460     break;
3461   }
3462   case ISD::UMIN: {
3463     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3464     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3465     Known = KnownBits::umin(Known, Known2);
3466     break;
3467   }
3468   case ISD::UMAX: {
3469     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3470     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3471     Known = KnownBits::umax(Known, Known2);
3472     break;
3473   }
3474   case ISD::SMIN:
3475   case ISD::SMAX: {
3476     // If we have a clamp pattern, we know that the number of sign bits will be
3477     // the minimum of the clamp min/max range.
3478     bool IsMax = (Opcode == ISD::SMAX);
3479     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3480     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3481       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3482         CstHigh =
3483             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3484     if (CstLow && CstHigh) {
3485       if (!IsMax)
3486         std::swap(CstLow, CstHigh);
3487 
3488       const APInt &ValueLow = CstLow->getAPIntValue();
3489       const APInt &ValueHigh = CstHigh->getAPIntValue();
3490       if (ValueLow.sle(ValueHigh)) {
3491         unsigned LowSignBits = ValueLow.getNumSignBits();
3492         unsigned HighSignBits = ValueHigh.getNumSignBits();
3493         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3494         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3495           Known.One.setHighBits(MinSignBits);
3496           break;
3497         }
3498         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3499           Known.Zero.setHighBits(MinSignBits);
3500           break;
3501         }
3502       }
3503     }
3504 
3505     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3506     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3507     if (IsMax)
3508       Known = KnownBits::smax(Known, Known2);
3509     else
3510       Known = KnownBits::smin(Known, Known2);
3511     break;
3512   }
3513   case ISD::FrameIndex:
3514   case ISD::TargetFrameIndex:
3515     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3516                                        Known, getMachineFunction());
3517     break;
3518 
3519   default:
3520     if (Opcode < ISD::BUILTIN_OP_END)
3521       break;
3522     LLVM_FALLTHROUGH;
3523   case ISD::INTRINSIC_WO_CHAIN:
3524   case ISD::INTRINSIC_W_CHAIN:
3525   case ISD::INTRINSIC_VOID:
3526     // Allow the target to implement this method for its nodes.
3527     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3528     break;
3529   }
3530 
3531   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3532   return Known;
3533 }
3534 
3535 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3536                                                              SDValue N1) const {
3537   // X + 0 never overflow
3538   if (isNullConstant(N1))
3539     return OFK_Never;
3540 
3541   KnownBits N1Known = computeKnownBits(N1);
3542   if (N1Known.Zero.getBoolValue()) {
3543     KnownBits N0Known = computeKnownBits(N0);
3544 
3545     bool overflow;
3546     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3547     if (!overflow)
3548       return OFK_Never;
3549   }
3550 
3551   // mulhi + 1 never overflow
3552   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3553       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3554     return OFK_Never;
3555 
3556   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3557     KnownBits N0Known = computeKnownBits(N0);
3558 
3559     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3560       return OFK_Never;
3561   }
3562 
3563   return OFK_Sometime;
3564 }
3565 
3566 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3567   EVT OpVT = Val.getValueType();
3568   unsigned BitWidth = OpVT.getScalarSizeInBits();
3569 
3570   // Is the constant a known power of 2?
3571   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3572     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3573 
3574   // A left-shift of a constant one will have exactly one bit set because
3575   // shifting the bit off the end is undefined.
3576   if (Val.getOpcode() == ISD::SHL) {
3577     auto *C = isConstOrConstSplat(Val.getOperand(0));
3578     if (C && C->getAPIntValue() == 1)
3579       return true;
3580   }
3581 
3582   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3583   // one bit set.
3584   if (Val.getOpcode() == ISD::SRL) {
3585     auto *C = isConstOrConstSplat(Val.getOperand(0));
3586     if (C && C->getAPIntValue().isSignMask())
3587       return true;
3588   }
3589 
3590   // Are all operands of a build vector constant powers of two?
3591   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3592     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3593           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3594             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3595           return false;
3596         }))
3597       return true;
3598 
3599   // More could be done here, though the above checks are enough
3600   // to handle some common cases.
3601 
3602   // Fall back to computeKnownBits to catch other known cases.
3603   KnownBits Known = computeKnownBits(Val);
3604   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3605 }
3606 
3607 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3608   EVT VT = Op.getValueType();
3609 
3610   // TODO: Assume we don't know anything for now.
3611   if (VT.isScalableVector())
3612     return 1;
3613 
3614   APInt DemandedElts = VT.isVector()
3615                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
3616                            : APInt(1, 1);
3617   return ComputeNumSignBits(Op, DemandedElts, Depth);
3618 }
3619 
3620 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3621                                           unsigned Depth) const {
3622   EVT VT = Op.getValueType();
3623   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3624   unsigned VTBits = VT.getScalarSizeInBits();
3625   unsigned NumElts = DemandedElts.getBitWidth();
3626   unsigned Tmp, Tmp2;
3627   unsigned FirstAnswer = 1;
3628 
3629   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3630     const APInt &Val = C->getAPIntValue();
3631     return Val.getNumSignBits();
3632   }
3633 
3634   if (Depth >= MaxRecursionDepth)
3635     return 1;  // Limit search depth.
3636 
3637   if (!DemandedElts || VT.isScalableVector())
3638     return 1;  // No demanded elts, better to assume we don't know anything.
3639 
3640   unsigned Opcode = Op.getOpcode();
3641   switch (Opcode) {
3642   default: break;
3643   case ISD::AssertSext:
3644     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3645     return VTBits-Tmp+1;
3646   case ISD::AssertZext:
3647     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3648     return VTBits-Tmp;
3649 
3650   case ISD::BUILD_VECTOR:
3651     Tmp = VTBits;
3652     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3653       if (!DemandedElts[i])
3654         continue;
3655 
3656       SDValue SrcOp = Op.getOperand(i);
3657       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3658 
3659       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3660       if (SrcOp.getValueSizeInBits() != VTBits) {
3661         assert(SrcOp.getValueSizeInBits() > VTBits &&
3662                "Expected BUILD_VECTOR implicit truncation");
3663         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3664         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3665       }
3666       Tmp = std::min(Tmp, Tmp2);
3667     }
3668     return Tmp;
3669 
3670   case ISD::VECTOR_SHUFFLE: {
3671     // Collect the minimum number of sign bits that are shared by every vector
3672     // element referenced by the shuffle.
3673     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3674     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3675     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3676     for (unsigned i = 0; i != NumElts; ++i) {
3677       int M = SVN->getMaskElt(i);
3678       if (!DemandedElts[i])
3679         continue;
3680       // For UNDEF elements, we don't know anything about the common state of
3681       // the shuffle result.
3682       if (M < 0)
3683         return 1;
3684       if ((unsigned)M < NumElts)
3685         DemandedLHS.setBit((unsigned)M % NumElts);
3686       else
3687         DemandedRHS.setBit((unsigned)M % NumElts);
3688     }
3689     Tmp = std::numeric_limits<unsigned>::max();
3690     if (!!DemandedLHS)
3691       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3692     if (!!DemandedRHS) {
3693       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3694       Tmp = std::min(Tmp, Tmp2);
3695     }
3696     // If we don't know anything, early out and try computeKnownBits fall-back.
3697     if (Tmp == 1)
3698       break;
3699     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3700     return Tmp;
3701   }
3702 
3703   case ISD::BITCAST: {
3704     SDValue N0 = Op.getOperand(0);
3705     EVT SrcVT = N0.getValueType();
3706     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3707 
3708     // Ignore bitcasts from unsupported types..
3709     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3710       break;
3711 
3712     // Fast handling of 'identity' bitcasts.
3713     if (VTBits == SrcBits)
3714       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3715 
3716     bool IsLE = getDataLayout().isLittleEndian();
3717 
3718     // Bitcast 'large element' scalar/vector to 'small element' vector.
3719     if ((SrcBits % VTBits) == 0) {
3720       assert(VT.isVector() && "Expected bitcast to vector");
3721 
3722       unsigned Scale = SrcBits / VTBits;
3723       APInt SrcDemandedElts(NumElts / Scale, 0);
3724       for (unsigned i = 0; i != NumElts; ++i)
3725         if (DemandedElts[i])
3726           SrcDemandedElts.setBit(i / Scale);
3727 
3728       // Fast case - sign splat can be simply split across the small elements.
3729       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3730       if (Tmp == SrcBits)
3731         return VTBits;
3732 
3733       // Slow case - determine how far the sign extends into each sub-element.
3734       Tmp2 = VTBits;
3735       for (unsigned i = 0; i != NumElts; ++i)
3736         if (DemandedElts[i]) {
3737           unsigned SubOffset = i % Scale;
3738           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3739           SubOffset = SubOffset * VTBits;
3740           if (Tmp <= SubOffset)
3741             return 1;
3742           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3743         }
3744       return Tmp2;
3745     }
3746     break;
3747   }
3748 
3749   case ISD::SIGN_EXTEND:
3750     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3751     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3752   case ISD::SIGN_EXTEND_INREG:
3753     // Max of the input and what this extends.
3754     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3755     Tmp = VTBits-Tmp+1;
3756     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3757     return std::max(Tmp, Tmp2);
3758   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3759     SDValue Src = Op.getOperand(0);
3760     EVT SrcVT = Src.getValueType();
3761     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3762     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3763     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3764   }
3765   case ISD::SRA:
3766     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3767     // SRA X, C -> adds C sign bits.
3768     if (const APInt *ShAmt =
3769             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3770       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3771     return Tmp;
3772   case ISD::SHL:
3773     if (const APInt *ShAmt =
3774             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3775       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3776       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3777       if (ShAmt->ult(Tmp))
3778         return Tmp - ShAmt->getZExtValue();
3779     }
3780     break;
3781   case ISD::AND:
3782   case ISD::OR:
3783   case ISD::XOR:    // NOT is handled here.
3784     // Logical binary ops preserve the number of sign bits at the worst.
3785     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3786     if (Tmp != 1) {
3787       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3788       FirstAnswer = std::min(Tmp, Tmp2);
3789       // We computed what we know about the sign bits as our first
3790       // answer. Now proceed to the generic code that uses
3791       // computeKnownBits, and pick whichever answer is better.
3792     }
3793     break;
3794 
3795   case ISD::SELECT:
3796   case ISD::VSELECT:
3797     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3798     if (Tmp == 1) return 1;  // Early out.
3799     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3800     return std::min(Tmp, Tmp2);
3801   case ISD::SELECT_CC:
3802     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3803     if (Tmp == 1) return 1;  // Early out.
3804     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3805     return std::min(Tmp, Tmp2);
3806 
3807   case ISD::SMIN:
3808   case ISD::SMAX: {
3809     // If we have a clamp pattern, we know that the number of sign bits will be
3810     // the minimum of the clamp min/max range.
3811     bool IsMax = (Opcode == ISD::SMAX);
3812     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3813     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3814       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3815         CstHigh =
3816             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3817     if (CstLow && CstHigh) {
3818       if (!IsMax)
3819         std::swap(CstLow, CstHigh);
3820       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3821         Tmp = CstLow->getAPIntValue().getNumSignBits();
3822         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3823         return std::min(Tmp, Tmp2);
3824       }
3825     }
3826 
3827     // Fallback - just get the minimum number of sign bits of the operands.
3828     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3829     if (Tmp == 1)
3830       return 1;  // Early out.
3831     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3832     return std::min(Tmp, Tmp2);
3833   }
3834   case ISD::UMIN:
3835   case ISD::UMAX:
3836     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3837     if (Tmp == 1)
3838       return 1;  // Early out.
3839     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3840     return std::min(Tmp, Tmp2);
3841   case ISD::SADDO:
3842   case ISD::UADDO:
3843   case ISD::SSUBO:
3844   case ISD::USUBO:
3845   case ISD::SMULO:
3846   case ISD::UMULO:
3847     if (Op.getResNo() != 1)
3848       break;
3849     // The boolean result conforms to getBooleanContents.  Fall through.
3850     // If setcc returns 0/-1, all bits are sign bits.
3851     // We know that we have an integer-based boolean since these operations
3852     // are only available for integer.
3853     if (TLI->getBooleanContents(VT.isVector(), false) ==
3854         TargetLowering::ZeroOrNegativeOneBooleanContent)
3855       return VTBits;
3856     break;
3857   case ISD::SETCC:
3858   case ISD::STRICT_FSETCC:
3859   case ISD::STRICT_FSETCCS: {
3860     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3861     // If setcc returns 0/-1, all bits are sign bits.
3862     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3863         TargetLowering::ZeroOrNegativeOneBooleanContent)
3864       return VTBits;
3865     break;
3866   }
3867   case ISD::ROTL:
3868   case ISD::ROTR:
3869     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3870 
3871     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3872     if (Tmp == VTBits)
3873       return VTBits;
3874 
3875     if (ConstantSDNode *C =
3876             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3877       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3878 
3879       // Handle rotate right by N like a rotate left by 32-N.
3880       if (Opcode == ISD::ROTR)
3881         RotAmt = (VTBits - RotAmt) % VTBits;
3882 
3883       // If we aren't rotating out all of the known-in sign bits, return the
3884       // number that are left.  This handles rotl(sext(x), 1) for example.
3885       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3886     }
3887     break;
3888   case ISD::ADD:
3889   case ISD::ADDC:
3890     // Add can have at most one carry bit.  Thus we know that the output
3891     // is, at worst, one more bit than the inputs.
3892     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3893     if (Tmp == 1) return 1; // Early out.
3894 
3895     // Special case decrementing a value (ADD X, -1):
3896     if (ConstantSDNode *CRHS =
3897             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3898       if (CRHS->isAllOnesValue()) {
3899         KnownBits Known =
3900             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3901 
3902         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3903         // sign bits set.
3904         if ((Known.Zero | 1).isAllOnesValue())
3905           return VTBits;
3906 
3907         // If we are subtracting one from a positive number, there is no carry
3908         // out of the result.
3909         if (Known.isNonNegative())
3910           return Tmp;
3911       }
3912 
3913     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3914     if (Tmp2 == 1) return 1; // Early out.
3915     return std::min(Tmp, Tmp2) - 1;
3916   case ISD::SUB:
3917     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3918     if (Tmp2 == 1) return 1; // Early out.
3919 
3920     // Handle NEG.
3921     if (ConstantSDNode *CLHS =
3922             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
3923       if (CLHS->isNullValue()) {
3924         KnownBits Known =
3925             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3926         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3927         // sign bits set.
3928         if ((Known.Zero | 1).isAllOnesValue())
3929           return VTBits;
3930 
3931         // If the input is known to be positive (the sign bit is known clear),
3932         // the output of the NEG has the same number of sign bits as the input.
3933         if (Known.isNonNegative())
3934           return Tmp2;
3935 
3936         // Otherwise, we treat this like a SUB.
3937       }
3938 
3939     // Sub can have at most one carry bit.  Thus we know that the output
3940     // is, at worst, one more bit than the inputs.
3941     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3942     if (Tmp == 1) return 1; // Early out.
3943     return std::min(Tmp, Tmp2) - 1;
3944   case ISD::MUL: {
3945     // The output of the Mul can be at most twice the valid bits in the inputs.
3946     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3947     if (SignBitsOp0 == 1)
3948       break;
3949     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3950     if (SignBitsOp1 == 1)
3951       break;
3952     unsigned OutValidBits =
3953         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
3954     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
3955   }
3956   case ISD::SREM:
3957     // The sign bit is the LHS's sign bit, except when the result of the
3958     // remainder is zero. The magnitude of the result should be less than or
3959     // equal to the magnitude of the LHS. Therefore, the result should have
3960     // at least as many sign bits as the left hand side.
3961     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3962   case ISD::TRUNCATE: {
3963     // Check if the sign bits of source go down as far as the truncated value.
3964     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3965     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3966     if (NumSrcSignBits > (NumSrcBits - VTBits))
3967       return NumSrcSignBits - (NumSrcBits - VTBits);
3968     break;
3969   }
3970   case ISD::EXTRACT_ELEMENT: {
3971     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3972     const int BitWidth = Op.getValueSizeInBits();
3973     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3974 
3975     // Get reverse index (starting from 1), Op1 value indexes elements from
3976     // little end. Sign starts at big end.
3977     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3978 
3979     // If the sign portion ends in our element the subtraction gives correct
3980     // result. Otherwise it gives either negative or > bitwidth result
3981     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3982   }
3983   case ISD::INSERT_VECTOR_ELT: {
3984     // If we know the element index, split the demand between the
3985     // source vector and the inserted element, otherwise assume we need
3986     // the original demanded vector elements and the value.
3987     SDValue InVec = Op.getOperand(0);
3988     SDValue InVal = Op.getOperand(1);
3989     SDValue EltNo = Op.getOperand(2);
3990     bool DemandedVal = true;
3991     APInt DemandedVecElts = DemandedElts;
3992     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3993     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3994       unsigned EltIdx = CEltNo->getZExtValue();
3995       DemandedVal = !!DemandedElts[EltIdx];
3996       DemandedVecElts.clearBit(EltIdx);
3997     }
3998     Tmp = std::numeric_limits<unsigned>::max();
3999     if (DemandedVal) {
4000       // TODO - handle implicit truncation of inserted elements.
4001       if (InVal.getScalarValueSizeInBits() != VTBits)
4002         break;
4003       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4004       Tmp = std::min(Tmp, Tmp2);
4005     }
4006     if (!!DemandedVecElts) {
4007       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4008       Tmp = std::min(Tmp, Tmp2);
4009     }
4010     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4011     return Tmp;
4012   }
4013   case ISD::EXTRACT_VECTOR_ELT: {
4014     SDValue InVec = Op.getOperand(0);
4015     SDValue EltNo = Op.getOperand(1);
4016     EVT VecVT = InVec.getValueType();
4017     // ComputeNumSignBits not yet implemented for scalable vectors.
4018     if (VecVT.isScalableVector())
4019       break;
4020     const unsigned BitWidth = Op.getValueSizeInBits();
4021     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4022     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4023 
4024     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4025     // anything about sign bits. But if the sizes match we can derive knowledge
4026     // about sign bits from the vector operand.
4027     if (BitWidth != EltBitWidth)
4028       break;
4029 
4030     // If we know the element index, just demand that vector element, else for
4031     // an unknown element index, ignore DemandedElts and demand them all.
4032     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
4033     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4034     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4035       DemandedSrcElts =
4036           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4037 
4038     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4039   }
4040   case ISD::EXTRACT_SUBVECTOR: {
4041     // Offset the demanded elts by the subvector index.
4042     SDValue Src = Op.getOperand(0);
4043     // Bail until we can represent demanded elements for scalable vectors.
4044     if (Src.getValueType().isScalableVector())
4045       break;
4046     uint64_t Idx = Op.getConstantOperandVal(1);
4047     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4048     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4049     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4050   }
4051   case ISD::CONCAT_VECTORS: {
4052     // Determine the minimum number of sign bits across all demanded
4053     // elts of the input vectors. Early out if the result is already 1.
4054     Tmp = std::numeric_limits<unsigned>::max();
4055     EVT SubVectorVT = Op.getOperand(0).getValueType();
4056     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4057     unsigned NumSubVectors = Op.getNumOperands();
4058     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4059       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
4060       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
4061       if (!DemandedSub)
4062         continue;
4063       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4064       Tmp = std::min(Tmp, Tmp2);
4065     }
4066     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4067     return Tmp;
4068   }
4069   case ISD::INSERT_SUBVECTOR: {
4070     // Demand any elements from the subvector and the remainder from the src its
4071     // inserted into.
4072     SDValue Src = Op.getOperand(0);
4073     SDValue Sub = Op.getOperand(1);
4074     uint64_t Idx = Op.getConstantOperandVal(2);
4075     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4076     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4077     APInt DemandedSrcElts = DemandedElts;
4078     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
4079 
4080     Tmp = std::numeric_limits<unsigned>::max();
4081     if (!!DemandedSubElts) {
4082       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4083       if (Tmp == 1)
4084         return 1; // early-out
4085     }
4086     if (!!DemandedSrcElts) {
4087       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4088       Tmp = std::min(Tmp, Tmp2);
4089     }
4090     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4091     return Tmp;
4092   }
4093   }
4094 
4095   // If we are looking at the loaded value of the SDNode.
4096   if (Op.getResNo() == 0) {
4097     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4098     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4099       unsigned ExtType = LD->getExtensionType();
4100       switch (ExtType) {
4101       default: break;
4102       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4103         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4104         return VTBits - Tmp + 1;
4105       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4106         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4107         return VTBits - Tmp;
4108       case ISD::NON_EXTLOAD:
4109         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4110           // We only need to handle vectors - computeKnownBits should handle
4111           // scalar cases.
4112           Type *CstTy = Cst->getType();
4113           if (CstTy->isVectorTy() &&
4114               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4115             Tmp = VTBits;
4116             for (unsigned i = 0; i != NumElts; ++i) {
4117               if (!DemandedElts[i])
4118                 continue;
4119               if (Constant *Elt = Cst->getAggregateElement(i)) {
4120                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4121                   const APInt &Value = CInt->getValue();
4122                   Tmp = std::min(Tmp, Value.getNumSignBits());
4123                   continue;
4124                 }
4125                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4126                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4127                   Tmp = std::min(Tmp, Value.getNumSignBits());
4128                   continue;
4129                 }
4130               }
4131               // Unknown type. Conservatively assume no bits match sign bit.
4132               return 1;
4133             }
4134             return Tmp;
4135           }
4136         }
4137         break;
4138       }
4139     }
4140   }
4141 
4142   // Allow the target to implement this method for its nodes.
4143   if (Opcode >= ISD::BUILTIN_OP_END ||
4144       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4145       Opcode == ISD::INTRINSIC_W_CHAIN ||
4146       Opcode == ISD::INTRINSIC_VOID) {
4147     unsigned NumBits =
4148         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4149     if (NumBits > 1)
4150       FirstAnswer = std::max(FirstAnswer, NumBits);
4151   }
4152 
4153   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4154   // use this information.
4155   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4156 
4157   APInt Mask;
4158   if (Known.isNonNegative()) {        // sign bit is 0
4159     Mask = Known.Zero;
4160   } else if (Known.isNegative()) {  // sign bit is 1;
4161     Mask = Known.One;
4162   } else {
4163     // Nothing known.
4164     return FirstAnswer;
4165   }
4166 
4167   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4168   // the number of identical bits in the top of the input value.
4169   Mask <<= Mask.getBitWidth()-VTBits;
4170   return std::max(FirstAnswer, Mask.countLeadingOnes());
4171 }
4172 
4173 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4174   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4175       !isa<ConstantSDNode>(Op.getOperand(1)))
4176     return false;
4177 
4178   if (Op.getOpcode() == ISD::OR &&
4179       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4180     return false;
4181 
4182   return true;
4183 }
4184 
4185 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4186   // If we're told that NaNs won't happen, assume they won't.
4187   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4188     return true;
4189 
4190   if (Depth >= MaxRecursionDepth)
4191     return false; // Limit search depth.
4192 
4193   // TODO: Handle vectors.
4194   // If the value is a constant, we can obviously see if it is a NaN or not.
4195   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4196     return !C->getValueAPF().isNaN() ||
4197            (SNaN && !C->getValueAPF().isSignaling());
4198   }
4199 
4200   unsigned Opcode = Op.getOpcode();
4201   switch (Opcode) {
4202   case ISD::FADD:
4203   case ISD::FSUB:
4204   case ISD::FMUL:
4205   case ISD::FDIV:
4206   case ISD::FREM:
4207   case ISD::FSIN:
4208   case ISD::FCOS: {
4209     if (SNaN)
4210       return true;
4211     // TODO: Need isKnownNeverInfinity
4212     return false;
4213   }
4214   case ISD::FCANONICALIZE:
4215   case ISD::FEXP:
4216   case ISD::FEXP2:
4217   case ISD::FTRUNC:
4218   case ISD::FFLOOR:
4219   case ISD::FCEIL:
4220   case ISD::FROUND:
4221   case ISD::FROUNDEVEN:
4222   case ISD::FRINT:
4223   case ISD::FNEARBYINT: {
4224     if (SNaN)
4225       return true;
4226     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4227   }
4228   case ISD::FABS:
4229   case ISD::FNEG:
4230   case ISD::FCOPYSIGN: {
4231     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4232   }
4233   case ISD::SELECT:
4234     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4235            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4236   case ISD::FP_EXTEND:
4237   case ISD::FP_ROUND: {
4238     if (SNaN)
4239       return true;
4240     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4241   }
4242   case ISD::SINT_TO_FP:
4243   case ISD::UINT_TO_FP:
4244     return true;
4245   case ISD::FMA:
4246   case ISD::FMAD: {
4247     if (SNaN)
4248       return true;
4249     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4250            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4251            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4252   }
4253   case ISD::FSQRT: // Need is known positive
4254   case ISD::FLOG:
4255   case ISD::FLOG2:
4256   case ISD::FLOG10:
4257   case ISD::FPOWI:
4258   case ISD::FPOW: {
4259     if (SNaN)
4260       return true;
4261     // TODO: Refine on operand
4262     return false;
4263   }
4264   case ISD::FMINNUM:
4265   case ISD::FMAXNUM: {
4266     // Only one needs to be known not-nan, since it will be returned if the
4267     // other ends up being one.
4268     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4269            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4270   }
4271   case ISD::FMINNUM_IEEE:
4272   case ISD::FMAXNUM_IEEE: {
4273     if (SNaN)
4274       return true;
4275     // This can return a NaN if either operand is an sNaN, or if both operands
4276     // are NaN.
4277     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4278             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4279            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4280             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4281   }
4282   case ISD::FMINIMUM:
4283   case ISD::FMAXIMUM: {
4284     // TODO: Does this quiet or return the origina NaN as-is?
4285     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4286            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4287   }
4288   case ISD::EXTRACT_VECTOR_ELT: {
4289     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4290   }
4291   default:
4292     if (Opcode >= ISD::BUILTIN_OP_END ||
4293         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4294         Opcode == ISD::INTRINSIC_W_CHAIN ||
4295         Opcode == ISD::INTRINSIC_VOID) {
4296       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4297     }
4298 
4299     return false;
4300   }
4301 }
4302 
4303 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4304   assert(Op.getValueType().isFloatingPoint() &&
4305          "Floating point type expected");
4306 
4307   // If the value is a constant, we can obviously see if it is a zero or not.
4308   // TODO: Add BuildVector support.
4309   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4310     return !C->isZero();
4311   return false;
4312 }
4313 
4314 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4315   assert(!Op.getValueType().isFloatingPoint() &&
4316          "Floating point types unsupported - use isKnownNeverZeroFloat");
4317 
4318   // If the value is a constant, we can obviously see if it is a zero or not.
4319   if (ISD::matchUnaryPredicate(
4320           Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4321     return true;
4322 
4323   // TODO: Recognize more cases here.
4324   switch (Op.getOpcode()) {
4325   default: break;
4326   case ISD::OR:
4327     if (isKnownNeverZero(Op.getOperand(1)) ||
4328         isKnownNeverZero(Op.getOperand(0)))
4329       return true;
4330     break;
4331   }
4332 
4333   return false;
4334 }
4335 
4336 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4337   // Check the obvious case.
4338   if (A == B) return true;
4339 
4340   // For for negative and positive zero.
4341   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4342     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4343       if (CA->isZero() && CB->isZero()) return true;
4344 
4345   // Otherwise they may not be equal.
4346   return false;
4347 }
4348 
4349 // FIXME: unify with llvm::haveNoCommonBitsSet.
4350 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4351 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4352   assert(A.getValueType() == B.getValueType() &&
4353          "Values must have the same type");
4354   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4355                                         computeKnownBits(B));
4356 }
4357 
4358 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4359                                SelectionDAG &DAG) {
4360   if (cast<ConstantSDNode>(Step)->isNullValue())
4361     return DAG.getConstant(0, DL, VT);
4362 
4363   return SDValue();
4364 }
4365 
4366 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4367                                 ArrayRef<SDValue> Ops,
4368                                 SelectionDAG &DAG) {
4369   int NumOps = Ops.size();
4370   assert(NumOps != 0 && "Can't build an empty vector!");
4371   assert(!VT.isScalableVector() &&
4372          "BUILD_VECTOR cannot be used with scalable types");
4373   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4374          "Incorrect element count in BUILD_VECTOR!");
4375 
4376   // BUILD_VECTOR of UNDEFs is UNDEF.
4377   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4378     return DAG.getUNDEF(VT);
4379 
4380   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4381   SDValue IdentitySrc;
4382   bool IsIdentity = true;
4383   for (int i = 0; i != NumOps; ++i) {
4384     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4385         Ops[i].getOperand(0).getValueType() != VT ||
4386         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4387         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4388         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4389       IsIdentity = false;
4390       break;
4391     }
4392     IdentitySrc = Ops[i].getOperand(0);
4393   }
4394   if (IsIdentity)
4395     return IdentitySrc;
4396 
4397   return SDValue();
4398 }
4399 
4400 /// Try to simplify vector concatenation to an input value, undef, or build
4401 /// vector.
4402 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4403                                   ArrayRef<SDValue> Ops,
4404                                   SelectionDAG &DAG) {
4405   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4406   assert(llvm::all_of(Ops,
4407                       [Ops](SDValue Op) {
4408                         return Ops[0].getValueType() == Op.getValueType();
4409                       }) &&
4410          "Concatenation of vectors with inconsistent value types!");
4411   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4412              VT.getVectorElementCount() &&
4413          "Incorrect element count in vector concatenation!");
4414 
4415   if (Ops.size() == 1)
4416     return Ops[0];
4417 
4418   // Concat of UNDEFs is UNDEF.
4419   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4420     return DAG.getUNDEF(VT);
4421 
4422   // Scan the operands and look for extract operations from a single source
4423   // that correspond to insertion at the same location via this concatenation:
4424   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4425   SDValue IdentitySrc;
4426   bool IsIdentity = true;
4427   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4428     SDValue Op = Ops[i];
4429     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4430     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4431         Op.getOperand(0).getValueType() != VT ||
4432         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4433         Op.getConstantOperandVal(1) != IdentityIndex) {
4434       IsIdentity = false;
4435       break;
4436     }
4437     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4438            "Unexpected identity source vector for concat of extracts");
4439     IdentitySrc = Op.getOperand(0);
4440   }
4441   if (IsIdentity) {
4442     assert(IdentitySrc && "Failed to set source vector of extracts");
4443     return IdentitySrc;
4444   }
4445 
4446   // The code below this point is only designed to work for fixed width
4447   // vectors, so we bail out for now.
4448   if (VT.isScalableVector())
4449     return SDValue();
4450 
4451   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4452   // simplified to one big BUILD_VECTOR.
4453   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4454   EVT SVT = VT.getScalarType();
4455   SmallVector<SDValue, 16> Elts;
4456   for (SDValue Op : Ops) {
4457     EVT OpVT = Op.getValueType();
4458     if (Op.isUndef())
4459       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4460     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4461       Elts.append(Op->op_begin(), Op->op_end());
4462     else
4463       return SDValue();
4464   }
4465 
4466   // BUILD_VECTOR requires all inputs to be of the same type, find the
4467   // maximum type and extend them all.
4468   for (SDValue Op : Elts)
4469     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4470 
4471   if (SVT.bitsGT(VT.getScalarType())) {
4472     for (SDValue &Op : Elts) {
4473       if (Op.isUndef())
4474         Op = DAG.getUNDEF(SVT);
4475       else
4476         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4477                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4478                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4479     }
4480   }
4481 
4482   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4483   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4484   return V;
4485 }
4486 
4487 /// Gets or creates the specified node.
4488 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4489   FoldingSetNodeID ID;
4490   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4491   void *IP = nullptr;
4492   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4493     return SDValue(E, 0);
4494 
4495   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4496                               getVTList(VT));
4497   CSEMap.InsertNode(N, IP);
4498 
4499   InsertNode(N);
4500   SDValue V = SDValue(N, 0);
4501   NewSDValueDbgMsg(V, "Creating new node: ", this);
4502   return V;
4503 }
4504 
4505 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4506                               SDValue Operand) {
4507   SDNodeFlags Flags;
4508   if (Inserter)
4509     Flags = Inserter->getFlags();
4510   return getNode(Opcode, DL, VT, Operand, Flags);
4511 }
4512 
4513 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4514                               SDValue Operand, const SDNodeFlags Flags) {
4515   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4516          "Operand is DELETED_NODE!");
4517   // Constant fold unary operations with an integer constant operand. Even
4518   // opaque constant will be folded, because the folding of unary operations
4519   // doesn't create new constants with different values. Nevertheless, the
4520   // opaque flag is preserved during folding to prevent future folding with
4521   // other constants.
4522   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4523     const APInt &Val = C->getAPIntValue();
4524     switch (Opcode) {
4525     default: break;
4526     case ISD::SIGN_EXTEND:
4527       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4528                          C->isTargetOpcode(), C->isOpaque());
4529     case ISD::TRUNCATE:
4530       if (C->isOpaque())
4531         break;
4532       LLVM_FALLTHROUGH;
4533     case ISD::ANY_EXTEND:
4534     case ISD::ZERO_EXTEND:
4535       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4536                          C->isTargetOpcode(), C->isOpaque());
4537     case ISD::UINT_TO_FP:
4538     case ISD::SINT_TO_FP: {
4539       APFloat apf(EVTToAPFloatSemantics(VT),
4540                   APInt::getNullValue(VT.getSizeInBits()));
4541       (void)apf.convertFromAPInt(Val,
4542                                  Opcode==ISD::SINT_TO_FP,
4543                                  APFloat::rmNearestTiesToEven);
4544       return getConstantFP(apf, DL, VT);
4545     }
4546     case ISD::BITCAST:
4547       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4548         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4549       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4550         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4551       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4552         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4553       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4554         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4555       break;
4556     case ISD::ABS:
4557       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4558                          C->isOpaque());
4559     case ISD::BITREVERSE:
4560       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4561                          C->isOpaque());
4562     case ISD::BSWAP:
4563       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4564                          C->isOpaque());
4565     case ISD::CTPOP:
4566       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4567                          C->isOpaque());
4568     case ISD::CTLZ:
4569     case ISD::CTLZ_ZERO_UNDEF:
4570       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4571                          C->isOpaque());
4572     case ISD::CTTZ:
4573     case ISD::CTTZ_ZERO_UNDEF:
4574       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4575                          C->isOpaque());
4576     case ISD::FP16_TO_FP: {
4577       bool Ignored;
4578       APFloat FPV(APFloat::IEEEhalf(),
4579                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4580 
4581       // This can return overflow, underflow, or inexact; we don't care.
4582       // FIXME need to be more flexible about rounding mode.
4583       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4584                         APFloat::rmNearestTiesToEven, &Ignored);
4585       return getConstantFP(FPV, DL, VT);
4586     }
4587     case ISD::STEP_VECTOR: {
4588       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4589         return V;
4590       break;
4591     }
4592     }
4593   }
4594 
4595   // Constant fold unary operations with a floating point constant operand.
4596   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4597     APFloat V = C->getValueAPF();    // make copy
4598     switch (Opcode) {
4599     case ISD::FNEG:
4600       V.changeSign();
4601       return getConstantFP(V, DL, VT);
4602     case ISD::FABS:
4603       V.clearSign();
4604       return getConstantFP(V, DL, VT);
4605     case ISD::FCEIL: {
4606       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4607       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4608         return getConstantFP(V, DL, VT);
4609       break;
4610     }
4611     case ISD::FTRUNC: {
4612       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4613       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4614         return getConstantFP(V, DL, VT);
4615       break;
4616     }
4617     case ISD::FFLOOR: {
4618       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4619       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4620         return getConstantFP(V, DL, VT);
4621       break;
4622     }
4623     case ISD::FP_EXTEND: {
4624       bool ignored;
4625       // This can return overflow, underflow, or inexact; we don't care.
4626       // FIXME need to be more flexible about rounding mode.
4627       (void)V.convert(EVTToAPFloatSemantics(VT),
4628                       APFloat::rmNearestTiesToEven, &ignored);
4629       return getConstantFP(V, DL, VT);
4630     }
4631     case ISD::FP_TO_SINT:
4632     case ISD::FP_TO_UINT: {
4633       bool ignored;
4634       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4635       // FIXME need to be more flexible about rounding mode.
4636       APFloat::opStatus s =
4637           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4638       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4639         break;
4640       return getConstant(IntVal, DL, VT);
4641     }
4642     case ISD::BITCAST:
4643       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4644         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4645       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4646         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4647       else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4648         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4649       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4650         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4651       break;
4652     case ISD::FP_TO_FP16: {
4653       bool Ignored;
4654       // This can return overflow, underflow, or inexact; we don't care.
4655       // FIXME need to be more flexible about rounding mode.
4656       (void)V.convert(APFloat::IEEEhalf(),
4657                       APFloat::rmNearestTiesToEven, &Ignored);
4658       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4659     }
4660     }
4661   }
4662 
4663   // Constant fold unary operations with a vector integer or float operand.
4664   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4665     if (BV->isConstant()) {
4666       switch (Opcode) {
4667       default:
4668         // FIXME: Entirely reasonable to perform folding of other unary
4669         // operations here as the need arises.
4670         break;
4671       case ISD::FNEG:
4672       case ISD::FABS:
4673       case ISD::FCEIL:
4674       case ISD::FTRUNC:
4675       case ISD::FFLOOR:
4676       case ISD::FP_EXTEND:
4677       case ISD::FP_TO_SINT:
4678       case ISD::FP_TO_UINT:
4679       case ISD::TRUNCATE:
4680       case ISD::ANY_EXTEND:
4681       case ISD::ZERO_EXTEND:
4682       case ISD::SIGN_EXTEND:
4683       case ISD::UINT_TO_FP:
4684       case ISD::SINT_TO_FP:
4685       case ISD::ABS:
4686       case ISD::BITREVERSE:
4687       case ISD::BSWAP:
4688       case ISD::CTLZ:
4689       case ISD::CTLZ_ZERO_UNDEF:
4690       case ISD::CTTZ:
4691       case ISD::CTTZ_ZERO_UNDEF:
4692       case ISD::CTPOP: {
4693         SDValue Ops = { Operand };
4694         if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4695           return Fold;
4696       }
4697       }
4698     }
4699   }
4700 
4701   unsigned OpOpcode = Operand.getNode()->getOpcode();
4702   switch (Opcode) {
4703   case ISD::STEP_VECTOR:
4704     assert(VT.isScalableVector() &&
4705            "STEP_VECTOR can only be used with scalable types");
4706     assert(VT.getScalarSizeInBits() >= 8 &&
4707            "STEP_VECTOR can only be used with vectors of integers that are at "
4708            "least 8 bits wide");
4709     assert(isa<ConstantSDNode>(Operand) &&
4710            cast<ConstantSDNode>(Operand)->getAPIntValue().isNonNegative() &&
4711            cast<ConstantSDNode>(Operand)->getAPIntValue().isSignedIntN(
4712                VT.getScalarSizeInBits()) &&
4713            "Expected STEP_VECTOR integer constant to be positive and fit in "
4714            "the vector element type");
4715     break;
4716   case ISD::FREEZE:
4717     assert(VT == Operand.getValueType() && "Unexpected VT!");
4718     break;
4719   case ISD::TokenFactor:
4720   case ISD::MERGE_VALUES:
4721   case ISD::CONCAT_VECTORS:
4722     return Operand;         // Factor, merge or concat of one node?  No need.
4723   case ISD::BUILD_VECTOR: {
4724     // Attempt to simplify BUILD_VECTOR.
4725     SDValue Ops[] = {Operand};
4726     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4727       return V;
4728     break;
4729   }
4730   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4731   case ISD::FP_EXTEND:
4732     assert(VT.isFloatingPoint() &&
4733            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4734     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4735     assert((!VT.isVector() ||
4736             VT.getVectorElementCount() ==
4737             Operand.getValueType().getVectorElementCount()) &&
4738            "Vector element count mismatch!");
4739     assert(Operand.getValueType().bitsLT(VT) &&
4740            "Invalid fpext node, dst < src!");
4741     if (Operand.isUndef())
4742       return getUNDEF(VT);
4743     break;
4744   case ISD::FP_TO_SINT:
4745   case ISD::FP_TO_UINT:
4746     if (Operand.isUndef())
4747       return getUNDEF(VT);
4748     break;
4749   case ISD::SINT_TO_FP:
4750   case ISD::UINT_TO_FP:
4751     // [us]itofp(undef) = 0, because the result value is bounded.
4752     if (Operand.isUndef())
4753       return getConstantFP(0.0, DL, VT);
4754     break;
4755   case ISD::SIGN_EXTEND:
4756     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4757            "Invalid SIGN_EXTEND!");
4758     assert(VT.isVector() == Operand.getValueType().isVector() &&
4759            "SIGN_EXTEND result type type should be vector iff the operand "
4760            "type is vector!");
4761     if (Operand.getValueType() == VT) return Operand;   // noop extension
4762     assert((!VT.isVector() ||
4763             VT.getVectorElementCount() ==
4764                 Operand.getValueType().getVectorElementCount()) &&
4765            "Vector element count mismatch!");
4766     assert(Operand.getValueType().bitsLT(VT) &&
4767            "Invalid sext node, dst < src!");
4768     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4769       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4770     else if (OpOpcode == ISD::UNDEF)
4771       // sext(undef) = 0, because the top bits will all be the same.
4772       return getConstant(0, DL, VT);
4773     break;
4774   case ISD::ZERO_EXTEND:
4775     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4776            "Invalid ZERO_EXTEND!");
4777     assert(VT.isVector() == Operand.getValueType().isVector() &&
4778            "ZERO_EXTEND result type type should be vector iff the operand "
4779            "type is vector!");
4780     if (Operand.getValueType() == VT) return Operand;   // noop extension
4781     assert((!VT.isVector() ||
4782             VT.getVectorElementCount() ==
4783                 Operand.getValueType().getVectorElementCount()) &&
4784            "Vector element count mismatch!");
4785     assert(Operand.getValueType().bitsLT(VT) &&
4786            "Invalid zext node, dst < src!");
4787     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4788       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4789     else if (OpOpcode == ISD::UNDEF)
4790       // zext(undef) = 0, because the top bits will be zero.
4791       return getConstant(0, DL, VT);
4792     break;
4793   case ISD::ANY_EXTEND:
4794     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4795            "Invalid ANY_EXTEND!");
4796     assert(VT.isVector() == Operand.getValueType().isVector() &&
4797            "ANY_EXTEND result type type should be vector iff the operand "
4798            "type is vector!");
4799     if (Operand.getValueType() == VT) return Operand;   // noop extension
4800     assert((!VT.isVector() ||
4801             VT.getVectorElementCount() ==
4802                 Operand.getValueType().getVectorElementCount()) &&
4803            "Vector element count mismatch!");
4804     assert(Operand.getValueType().bitsLT(VT) &&
4805            "Invalid anyext node, dst < src!");
4806 
4807     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4808         OpOpcode == ISD::ANY_EXTEND)
4809       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4810       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4811     else if (OpOpcode == ISD::UNDEF)
4812       return getUNDEF(VT);
4813 
4814     // (ext (trunc x)) -> x
4815     if (OpOpcode == ISD::TRUNCATE) {
4816       SDValue OpOp = Operand.getOperand(0);
4817       if (OpOp.getValueType() == VT) {
4818         transferDbgValues(Operand, OpOp);
4819         return OpOp;
4820       }
4821     }
4822     break;
4823   case ISD::TRUNCATE:
4824     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4825            "Invalid TRUNCATE!");
4826     assert(VT.isVector() == Operand.getValueType().isVector() &&
4827            "TRUNCATE result type type should be vector iff the operand "
4828            "type is vector!");
4829     if (Operand.getValueType() == VT) return Operand;   // noop truncate
4830     assert((!VT.isVector() ||
4831             VT.getVectorElementCount() ==
4832                 Operand.getValueType().getVectorElementCount()) &&
4833            "Vector element count mismatch!");
4834     assert(Operand.getValueType().bitsGT(VT) &&
4835            "Invalid truncate node, src < dst!");
4836     if (OpOpcode == ISD::TRUNCATE)
4837       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4838     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4839         OpOpcode == ISD::ANY_EXTEND) {
4840       // If the source is smaller than the dest, we still need an extend.
4841       if (Operand.getOperand(0).getValueType().getScalarType()
4842             .bitsLT(VT.getScalarType()))
4843         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4844       if (Operand.getOperand(0).getValueType().bitsGT(VT))
4845         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4846       return Operand.getOperand(0);
4847     }
4848     if (OpOpcode == ISD::UNDEF)
4849       return getUNDEF(VT);
4850     break;
4851   case ISD::ANY_EXTEND_VECTOR_INREG:
4852   case ISD::ZERO_EXTEND_VECTOR_INREG:
4853   case ISD::SIGN_EXTEND_VECTOR_INREG:
4854     assert(VT.isVector() && "This DAG node is restricted to vector types.");
4855     assert(Operand.getValueType().bitsLE(VT) &&
4856            "The input must be the same size or smaller than the result.");
4857     assert(VT.getVectorMinNumElements() <
4858                Operand.getValueType().getVectorMinNumElements() &&
4859            "The destination vector type must have fewer lanes than the input.");
4860     break;
4861   case ISD::ABS:
4862     assert(VT.isInteger() && VT == Operand.getValueType() &&
4863            "Invalid ABS!");
4864     if (OpOpcode == ISD::UNDEF)
4865       return getUNDEF(VT);
4866     break;
4867   case ISD::BSWAP:
4868     assert(VT.isInteger() && VT == Operand.getValueType() &&
4869            "Invalid BSWAP!");
4870     assert((VT.getScalarSizeInBits() % 16 == 0) &&
4871            "BSWAP types must be a multiple of 16 bits!");
4872     if (OpOpcode == ISD::UNDEF)
4873       return getUNDEF(VT);
4874     break;
4875   case ISD::BITREVERSE:
4876     assert(VT.isInteger() && VT == Operand.getValueType() &&
4877            "Invalid BITREVERSE!");
4878     if (OpOpcode == ISD::UNDEF)
4879       return getUNDEF(VT);
4880     break;
4881   case ISD::BITCAST:
4882     // Basic sanity checking.
4883     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4884            "Cannot BITCAST between types of different sizes!");
4885     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
4886     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
4887       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4888     if (OpOpcode == ISD::UNDEF)
4889       return getUNDEF(VT);
4890     break;
4891   case ISD::SCALAR_TO_VECTOR:
4892     assert(VT.isVector() && !Operand.getValueType().isVector() &&
4893            (VT.getVectorElementType() == Operand.getValueType() ||
4894             (VT.getVectorElementType().isInteger() &&
4895              Operand.getValueType().isInteger() &&
4896              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4897            "Illegal SCALAR_TO_VECTOR node!");
4898     if (OpOpcode == ISD::UNDEF)
4899       return getUNDEF(VT);
4900     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4901     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4902         isa<ConstantSDNode>(Operand.getOperand(1)) &&
4903         Operand.getConstantOperandVal(1) == 0 &&
4904         Operand.getOperand(0).getValueType() == VT)
4905       return Operand.getOperand(0);
4906     break;
4907   case ISD::FNEG:
4908     // Negation of an unknown bag of bits is still completely undefined.
4909     if (OpOpcode == ISD::UNDEF)
4910       return getUNDEF(VT);
4911 
4912     if (OpOpcode == ISD::FNEG)  // --X -> X
4913       return Operand.getOperand(0);
4914     break;
4915   case ISD::FABS:
4916     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
4917       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4918     break;
4919   case ISD::VSCALE:
4920     assert(VT == Operand.getValueType() && "Unexpected VT!");
4921     break;
4922   case ISD::CTPOP:
4923     if (Operand.getValueType().getScalarType() == MVT::i1)
4924       return Operand;
4925     break;
4926   case ISD::CTLZ:
4927   case ISD::CTTZ:
4928     if (Operand.getValueType().getScalarType() == MVT::i1)
4929       return getNOT(DL, Operand, Operand.getValueType());
4930     break;
4931   case ISD::VECREDUCE_SMIN:
4932   case ISD::VECREDUCE_UMAX:
4933     if (Operand.getValueType().getScalarType() == MVT::i1)
4934       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
4935     break;
4936   case ISD::VECREDUCE_SMAX:
4937   case ISD::VECREDUCE_UMIN:
4938     if (Operand.getValueType().getScalarType() == MVT::i1)
4939       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
4940     break;
4941   }
4942 
4943   SDNode *N;
4944   SDVTList VTs = getVTList(VT);
4945   SDValue Ops[] = {Operand};
4946   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4947     FoldingSetNodeID ID;
4948     AddNodeIDNode(ID, Opcode, VTs, Ops);
4949     void *IP = nullptr;
4950     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4951       E->intersectFlagsWith(Flags);
4952       return SDValue(E, 0);
4953     }
4954 
4955     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4956     N->setFlags(Flags);
4957     createOperands(N, Ops);
4958     CSEMap.InsertNode(N, IP);
4959   } else {
4960     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4961     createOperands(N, Ops);
4962   }
4963 
4964   InsertNode(N);
4965   SDValue V = SDValue(N, 0);
4966   NewSDValueDbgMsg(V, "Creating new node: ", this);
4967   return V;
4968 }
4969 
4970 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
4971                                        const APInt &C2) {
4972   switch (Opcode) {
4973   case ISD::ADD:  return C1 + C2;
4974   case ISD::SUB:  return C1 - C2;
4975   case ISD::MUL:  return C1 * C2;
4976   case ISD::AND:  return C1 & C2;
4977   case ISD::OR:   return C1 | C2;
4978   case ISD::XOR:  return C1 ^ C2;
4979   case ISD::SHL:  return C1 << C2;
4980   case ISD::SRL:  return C1.lshr(C2);
4981   case ISD::SRA:  return C1.ashr(C2);
4982   case ISD::ROTL: return C1.rotl(C2);
4983   case ISD::ROTR: return C1.rotr(C2);
4984   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
4985   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
4986   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
4987   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
4988   case ISD::SADDSAT: return C1.sadd_sat(C2);
4989   case ISD::UADDSAT: return C1.uadd_sat(C2);
4990   case ISD::SSUBSAT: return C1.ssub_sat(C2);
4991   case ISD::USUBSAT: return C1.usub_sat(C2);
4992   case ISD::UDIV:
4993     if (!C2.getBoolValue())
4994       break;
4995     return C1.udiv(C2);
4996   case ISD::UREM:
4997     if (!C2.getBoolValue())
4998       break;
4999     return C1.urem(C2);
5000   case ISD::SDIV:
5001     if (!C2.getBoolValue())
5002       break;
5003     return C1.sdiv(C2);
5004   case ISD::SREM:
5005     if (!C2.getBoolValue())
5006       break;
5007     return C1.srem(C2);
5008   }
5009   return llvm::None;
5010 }
5011 
5012 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5013                                        const GlobalAddressSDNode *GA,
5014                                        const SDNode *N2) {
5015   if (GA->getOpcode() != ISD::GlobalAddress)
5016     return SDValue();
5017   if (!TLI->isOffsetFoldingLegal(GA))
5018     return SDValue();
5019   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5020   if (!C2)
5021     return SDValue();
5022   int64_t Offset = C2->getSExtValue();
5023   switch (Opcode) {
5024   case ISD::ADD: break;
5025   case ISD::SUB: Offset = -uint64_t(Offset); break;
5026   default: return SDValue();
5027   }
5028   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5029                           GA->getOffset() + uint64_t(Offset));
5030 }
5031 
5032 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5033   switch (Opcode) {
5034   case ISD::SDIV:
5035   case ISD::UDIV:
5036   case ISD::SREM:
5037   case ISD::UREM: {
5038     // If a divisor is zero/undef or any element of a divisor vector is
5039     // zero/undef, the whole op is undef.
5040     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5041     SDValue Divisor = Ops[1];
5042     if (Divisor.isUndef() || isNullConstant(Divisor))
5043       return true;
5044 
5045     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5046            llvm::any_of(Divisor->op_values(),
5047                         [](SDValue V) { return V.isUndef() ||
5048                                         isNullConstant(V); });
5049     // TODO: Handle signed overflow.
5050   }
5051   // TODO: Handle oversized shifts.
5052   default:
5053     return false;
5054   }
5055 }
5056 
5057 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5058                                              EVT VT, ArrayRef<SDValue> Ops) {
5059   // If the opcode is a target-specific ISD node, there's nothing we can
5060   // do here and the operand rules may not line up with the below, so
5061   // bail early.
5062   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5063   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5064   // foldCONCAT_VECTORS in getNode before this is called.
5065   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5066     return SDValue();
5067 
5068   // For now, the array Ops should only contain two values.
5069   // This enforcement will be removed once this function is merged with
5070   // FoldConstantVectorArithmetic
5071   if (Ops.size() != 2)
5072     return SDValue();
5073 
5074   if (isUndef(Opcode, Ops))
5075     return getUNDEF(VT);
5076 
5077   SDNode *N1 = Ops[0].getNode();
5078   SDNode *N2 = Ops[1].getNode();
5079 
5080   // Handle the case of two scalars.
5081   if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
5082     if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
5083       if (C1->isOpaque() || C2->isOpaque())
5084         return SDValue();
5085 
5086       Optional<APInt> FoldAttempt =
5087           FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5088       if (!FoldAttempt)
5089         return SDValue();
5090 
5091       SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5092       assert((!Folded || !VT.isVector()) &&
5093              "Can't fold vectors ops with scalar operands");
5094       return Folded;
5095     }
5096   }
5097 
5098   // fold (add Sym, c) -> Sym+c
5099   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
5100     return FoldSymbolOffset(Opcode, VT, GA, N2);
5101   if (TLI->isCommutativeBinOp(Opcode))
5102     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
5103       return FoldSymbolOffset(Opcode, VT, GA, N1);
5104 
5105   // For fixed width vectors, extract each constant element and fold them
5106   // individually. Either input may be an undef value.
5107   bool IsBVOrSV1 = N1->getOpcode() == ISD::BUILD_VECTOR ||
5108                    N1->getOpcode() == ISD::SPLAT_VECTOR;
5109   if (!IsBVOrSV1 && !N1->isUndef())
5110     return SDValue();
5111   bool IsBVOrSV2 = N2->getOpcode() == ISD::BUILD_VECTOR ||
5112                    N2->getOpcode() == ISD::SPLAT_VECTOR;
5113   if (!IsBVOrSV2 && !N2->isUndef())
5114     return SDValue();
5115   // If both operands are undef, that's handled the same way as scalars.
5116   if (!IsBVOrSV1 && !IsBVOrSV2)
5117     return SDValue();
5118 
5119   EVT SVT = VT.getScalarType();
5120   EVT LegalSVT = SVT;
5121   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5122     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5123     if (LegalSVT.bitsLT(SVT))
5124       return SDValue();
5125   }
5126 
5127   SmallVector<SDValue, 4> Outputs;
5128   unsigned NumOps = 0;
5129   if (IsBVOrSV1)
5130     NumOps = std::max(NumOps, N1->getNumOperands());
5131   if (IsBVOrSV2)
5132     NumOps = std::max(NumOps, N2->getNumOperands());
5133   assert(NumOps != 0 && "Expected non-zero operands");
5134   // Scalable vectors should only be SPLAT_VECTOR or UNDEF here. We only need
5135   // one iteration for that.
5136   assert((!VT.isScalableVector() || NumOps == 1) &&
5137          "Scalar vector should only have one scalar");
5138 
5139   for (unsigned I = 0; I != NumOps; ++I) {
5140     // We can have a fixed length SPLAT_VECTOR and a BUILD_VECTOR so we need
5141     // to use operand 0 of the SPLAT_VECTOR for each fixed element.
5142     SDValue V1;
5143     if (N1->getOpcode() == ISD::BUILD_VECTOR)
5144       V1 = N1->getOperand(I);
5145     else if (N1->getOpcode() == ISD::SPLAT_VECTOR)
5146       V1 = N1->getOperand(0);
5147     else
5148       V1 = getUNDEF(SVT);
5149 
5150     SDValue V2;
5151     if (N2->getOpcode() == ISD::BUILD_VECTOR)
5152       V2 = N2->getOperand(I);
5153     else if (N2->getOpcode() == ISD::SPLAT_VECTOR)
5154       V2 = N2->getOperand(0);
5155     else
5156       V2 = getUNDEF(SVT);
5157 
5158     if (SVT.isInteger()) {
5159       if (V1.getValueType().bitsGT(SVT))
5160         V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
5161       if (V2.getValueType().bitsGT(SVT))
5162         V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
5163     }
5164 
5165     if (V1.getValueType() != SVT || V2.getValueType() != SVT)
5166       return SDValue();
5167 
5168     // Fold one vector element.
5169     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
5170     if (LegalSVT != SVT)
5171       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5172 
5173     // Scalar folding only succeeded if the result is a constant or UNDEF.
5174     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5175         ScalarResult.getOpcode() != ISD::ConstantFP)
5176       return SDValue();
5177     Outputs.push_back(ScalarResult);
5178   }
5179 
5180   if (N1->getOpcode() == ISD::BUILD_VECTOR ||
5181       N2->getOpcode() == ISD::BUILD_VECTOR) {
5182     assert(VT.getVectorNumElements() == Outputs.size() &&
5183            "Vector size mismatch!");
5184 
5185     // Build a big vector out of the scalar elements we generated.
5186     return getBuildVector(VT, SDLoc(), Outputs);
5187   }
5188 
5189   assert((N1->getOpcode() == ISD::SPLAT_VECTOR ||
5190           N2->getOpcode() == ISD::SPLAT_VECTOR) &&
5191          "One operand should be a splat vector");
5192 
5193   assert(Outputs.size() == 1 && "Vector size mismatch!");
5194   return getSplatVector(VT, SDLoc(), Outputs[0]);
5195 }
5196 
5197 // TODO: Merge with FoldConstantArithmetic
5198 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
5199                                                    const SDLoc &DL, EVT VT,
5200                                                    ArrayRef<SDValue> Ops,
5201                                                    const SDNodeFlags Flags) {
5202   // If the opcode is a target-specific ISD node, there's nothing we can
5203   // do here and the operand rules may not line up with the below, so
5204   // bail early.
5205   if (Opcode >= ISD::BUILTIN_OP_END)
5206     return SDValue();
5207 
5208   if (isUndef(Opcode, Ops))
5209     return getUNDEF(VT);
5210 
5211   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
5212   if (!VT.isVector())
5213     return SDValue();
5214 
5215   // TODO: All the folds below are performed lane-by-lane and assume a fixed
5216   // vector width, however we should be able to do constant folds involving
5217   // splat vector nodes too.
5218   if (VT.isScalableVector())
5219     return SDValue();
5220 
5221   // From this point onwards all vectors are assumed to be fixed width.
5222   unsigned NumElts = VT.getVectorNumElements();
5223 
5224   auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
5225     return !Op.getValueType().isVector() ||
5226            Op.getValueType().getVectorNumElements() == NumElts;
5227   };
5228 
5229   auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
5230     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
5231     return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
5232            (BV && BV->isConstant());
5233   };
5234 
5235   // All operands must be vector types with the same number of elements as
5236   // the result type and must be either UNDEF or a build vector of constant
5237   // or UNDEF scalars.
5238   if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
5239       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5240     return SDValue();
5241 
5242   // If we are comparing vectors, then the result needs to be a i1 boolean
5243   // that is then sign-extended back to the legal result type.
5244   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5245 
5246   // Find legal integer scalar type for constant promotion and
5247   // ensure that its scalar size is at least as large as source.
5248   EVT LegalSVT = VT.getScalarType();
5249   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5250     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5251     if (LegalSVT.bitsLT(VT.getScalarType()))
5252       return SDValue();
5253   }
5254 
5255   // Constant fold each scalar lane separately.
5256   SmallVector<SDValue, 4> ScalarResults;
5257   for (unsigned i = 0; i != NumElts; i++) {
5258     SmallVector<SDValue, 4> ScalarOps;
5259     for (SDValue Op : Ops) {
5260       EVT InSVT = Op.getValueType().getScalarType();
5261       BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
5262       if (!InBV) {
5263         // We've checked that this is UNDEF or a constant of some kind.
5264         if (Op.isUndef())
5265           ScalarOps.push_back(getUNDEF(InSVT));
5266         else
5267           ScalarOps.push_back(Op);
5268         continue;
5269       }
5270 
5271       SDValue ScalarOp = InBV->getOperand(i);
5272       EVT ScalarVT = ScalarOp.getValueType();
5273 
5274       // Build vector (integer) scalar operands may need implicit
5275       // truncation - do this before constant folding.
5276       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5277         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5278 
5279       ScalarOps.push_back(ScalarOp);
5280     }
5281 
5282     // Constant fold the scalar operands.
5283     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
5284 
5285     // Legalize the (integer) scalar constant if necessary.
5286     if (LegalSVT != SVT)
5287       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5288 
5289     // Scalar folding only succeeded if the result is a constant or UNDEF.
5290     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5291         ScalarResult.getOpcode() != ISD::ConstantFP)
5292       return SDValue();
5293     ScalarResults.push_back(ScalarResult);
5294   }
5295 
5296   SDValue V = getBuildVector(VT, DL, ScalarResults);
5297   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5298   return V;
5299 }
5300 
5301 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5302                                          EVT VT, SDValue N1, SDValue N2) {
5303   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5304   //       should. That will require dealing with a potentially non-default
5305   //       rounding mode, checking the "opStatus" return value from the APFloat
5306   //       math calculations, and possibly other variations.
5307   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5308   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5309   if (N1CFP && N2CFP) {
5310     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5311     switch (Opcode) {
5312     case ISD::FADD:
5313       C1.add(C2, APFloat::rmNearestTiesToEven);
5314       return getConstantFP(C1, DL, VT);
5315     case ISD::FSUB:
5316       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5317       return getConstantFP(C1, DL, VT);
5318     case ISD::FMUL:
5319       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5320       return getConstantFP(C1, DL, VT);
5321     case ISD::FDIV:
5322       C1.divide(C2, APFloat::rmNearestTiesToEven);
5323       return getConstantFP(C1, DL, VT);
5324     case ISD::FREM:
5325       C1.mod(C2);
5326       return getConstantFP(C1, DL, VT);
5327     case ISD::FCOPYSIGN:
5328       C1.copySign(C2);
5329       return getConstantFP(C1, DL, VT);
5330     default: break;
5331     }
5332   }
5333   if (N1CFP && Opcode == ISD::FP_ROUND) {
5334     APFloat C1 = N1CFP->getValueAPF();    // make copy
5335     bool Unused;
5336     // This can return overflow, underflow, or inexact; we don't care.
5337     // FIXME need to be more flexible about rounding mode.
5338     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5339                       &Unused);
5340     return getConstantFP(C1, DL, VT);
5341   }
5342 
5343   switch (Opcode) {
5344   case ISD::FSUB:
5345     // -0.0 - undef --> undef (consistent with "fneg undef")
5346     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5347       return getUNDEF(VT);
5348     LLVM_FALLTHROUGH;
5349 
5350   case ISD::FADD:
5351   case ISD::FMUL:
5352   case ISD::FDIV:
5353   case ISD::FREM:
5354     // If both operands are undef, the result is undef. If 1 operand is undef,
5355     // the result is NaN. This should match the behavior of the IR optimizer.
5356     if (N1.isUndef() && N2.isUndef())
5357       return getUNDEF(VT);
5358     if (N1.isUndef() || N2.isUndef())
5359       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5360   }
5361   return SDValue();
5362 }
5363 
5364 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5365   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5366 
5367   // There's no need to assert on a byte-aligned pointer. All pointers are at
5368   // least byte aligned.
5369   if (A == Align(1))
5370     return Val;
5371 
5372   FoldingSetNodeID ID;
5373   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5374   ID.AddInteger(A.value());
5375 
5376   void *IP = nullptr;
5377   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5378     return SDValue(E, 0);
5379 
5380   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5381                                          Val.getValueType(), A);
5382   createOperands(N, {Val});
5383 
5384   CSEMap.InsertNode(N, IP);
5385   InsertNode(N);
5386 
5387   SDValue V(N, 0);
5388   NewSDValueDbgMsg(V, "Creating new node: ", this);
5389   return V;
5390 }
5391 
5392 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5393                               SDValue N1, SDValue N2) {
5394   SDNodeFlags Flags;
5395   if (Inserter)
5396     Flags = Inserter->getFlags();
5397   return getNode(Opcode, DL, VT, N1, N2, Flags);
5398 }
5399 
5400 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5401                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5402   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5403          N2.getOpcode() != ISD::DELETED_NODE &&
5404          "Operand is DELETED_NODE!");
5405   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5406   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5407   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5408   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5409 
5410   // Canonicalize constant to RHS if commutative.
5411   if (TLI->isCommutativeBinOp(Opcode)) {
5412     if (N1C && !N2C) {
5413       std::swap(N1C, N2C);
5414       std::swap(N1, N2);
5415     } else if (N1CFP && !N2CFP) {
5416       std::swap(N1CFP, N2CFP);
5417       std::swap(N1, N2);
5418     }
5419   }
5420 
5421   switch (Opcode) {
5422   default: break;
5423   case ISD::TokenFactor:
5424     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5425            N2.getValueType() == MVT::Other && "Invalid token factor!");
5426     // Fold trivial token factors.
5427     if (N1.getOpcode() == ISD::EntryToken) return N2;
5428     if (N2.getOpcode() == ISD::EntryToken) return N1;
5429     if (N1 == N2) return N1;
5430     break;
5431   case ISD::BUILD_VECTOR: {
5432     // Attempt to simplify BUILD_VECTOR.
5433     SDValue Ops[] = {N1, N2};
5434     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5435       return V;
5436     break;
5437   }
5438   case ISD::CONCAT_VECTORS: {
5439     SDValue Ops[] = {N1, N2};
5440     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5441       return V;
5442     break;
5443   }
5444   case ISD::AND:
5445     assert(VT.isInteger() && "This operator does not apply to FP types!");
5446     assert(N1.getValueType() == N2.getValueType() &&
5447            N1.getValueType() == VT && "Binary operator types must match!");
5448     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5449     // worth handling here.
5450     if (N2C && N2C->isNullValue())
5451       return N2;
5452     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
5453       return N1;
5454     break;
5455   case ISD::OR:
5456   case ISD::XOR:
5457   case ISD::ADD:
5458   case ISD::SUB:
5459     assert(VT.isInteger() && "This operator does not apply to FP types!");
5460     assert(N1.getValueType() == N2.getValueType() &&
5461            N1.getValueType() == VT && "Binary operator types must match!");
5462     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5463     // it's worth handling here.
5464     if (N2C && N2C->isNullValue())
5465       return N1;
5466     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5467         VT.getVectorElementType() == MVT::i1)
5468       return getNode(ISD::XOR, DL, VT, N1, N2);
5469     break;
5470   case ISD::MUL:
5471     assert(VT.isInteger() && "This operator does not apply to FP types!");
5472     assert(N1.getValueType() == N2.getValueType() &&
5473            N1.getValueType() == VT && "Binary operator types must match!");
5474     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5475       return getNode(ISD::AND, DL, VT, N1, N2);
5476     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5477       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5478       const APInt &N2CImm = N2C->getAPIntValue();
5479       return getVScale(DL, VT, MulImm * N2CImm);
5480     }
5481     break;
5482   case ISD::UDIV:
5483   case ISD::UREM:
5484   case ISD::MULHU:
5485   case ISD::MULHS:
5486   case ISD::SDIV:
5487   case ISD::SREM:
5488   case ISD::SADDSAT:
5489   case ISD::SSUBSAT:
5490   case ISD::UADDSAT:
5491   case ISD::USUBSAT:
5492     assert(VT.isInteger() && "This operator does not apply to FP types!");
5493     assert(N1.getValueType() == N2.getValueType() &&
5494            N1.getValueType() == VT && "Binary operator types must match!");
5495     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5496       // fold (add_sat x, y) -> (or x, y) for bool types.
5497       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5498         return getNode(ISD::OR, DL, VT, N1, N2);
5499       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5500       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5501         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5502     }
5503     break;
5504   case ISD::SMIN:
5505   case ISD::UMAX:
5506     assert(VT.isInteger() && "This operator does not apply to FP types!");
5507     assert(N1.getValueType() == N2.getValueType() &&
5508            N1.getValueType() == VT && "Binary operator types must match!");
5509     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5510       return getNode(ISD::OR, DL, VT, N1, N2);
5511     break;
5512   case ISD::SMAX:
5513   case ISD::UMIN:
5514     assert(VT.isInteger() && "This operator does not apply to FP types!");
5515     assert(N1.getValueType() == N2.getValueType() &&
5516            N1.getValueType() == VT && "Binary operator types must match!");
5517     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5518       return getNode(ISD::AND, DL, VT, N1, N2);
5519     break;
5520   case ISD::FADD:
5521   case ISD::FSUB:
5522   case ISD::FMUL:
5523   case ISD::FDIV:
5524   case ISD::FREM:
5525     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5526     assert(N1.getValueType() == N2.getValueType() &&
5527            N1.getValueType() == VT && "Binary operator types must match!");
5528     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5529       return V;
5530     break;
5531   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5532     assert(N1.getValueType() == VT &&
5533            N1.getValueType().isFloatingPoint() &&
5534            N2.getValueType().isFloatingPoint() &&
5535            "Invalid FCOPYSIGN!");
5536     break;
5537   case ISD::SHL:
5538     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5539       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5540       const APInt &ShiftImm = N2C->getAPIntValue();
5541       return getVScale(DL, VT, MulImm << ShiftImm);
5542     }
5543     LLVM_FALLTHROUGH;
5544   case ISD::SRA:
5545   case ISD::SRL:
5546     if (SDValue V = simplifyShift(N1, N2))
5547       return V;
5548     LLVM_FALLTHROUGH;
5549   case ISD::ROTL:
5550   case ISD::ROTR:
5551     assert(VT == N1.getValueType() &&
5552            "Shift operators return type must be the same as their first arg");
5553     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5554            "Shifts only work on integers");
5555     assert((!VT.isVector() || VT == N2.getValueType()) &&
5556            "Vector shift amounts must be in the same as their first arg");
5557     // Verify that the shift amount VT is big enough to hold valid shift
5558     // amounts.  This catches things like trying to shift an i1024 value by an
5559     // i8, which is easy to fall into in generic code that uses
5560     // TLI.getShiftAmount().
5561     assert(N2.getValueType().getScalarSizeInBits() >=
5562                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5563            "Invalid use of small shift amount with oversized value!");
5564 
5565     // Always fold shifts of i1 values so the code generator doesn't need to
5566     // handle them.  Since we know the size of the shift has to be less than the
5567     // size of the value, the shift/rotate count is guaranteed to be zero.
5568     if (VT == MVT::i1)
5569       return N1;
5570     if (N2C && N2C->isNullValue())
5571       return N1;
5572     break;
5573   case ISD::FP_ROUND:
5574     assert(VT.isFloatingPoint() &&
5575            N1.getValueType().isFloatingPoint() &&
5576            VT.bitsLE(N1.getValueType()) &&
5577            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5578            "Invalid FP_ROUND!");
5579     if (N1.getValueType() == VT) return N1;  // noop conversion.
5580     break;
5581   case ISD::AssertSext:
5582   case ISD::AssertZext: {
5583     EVT EVT = cast<VTSDNode>(N2)->getVT();
5584     assert(VT == N1.getValueType() && "Not an inreg extend!");
5585     assert(VT.isInteger() && EVT.isInteger() &&
5586            "Cannot *_EXTEND_INREG FP types");
5587     assert(!EVT.isVector() &&
5588            "AssertSExt/AssertZExt type should be the vector element type "
5589            "rather than the vector type!");
5590     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5591     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5592     break;
5593   }
5594   case ISD::SIGN_EXTEND_INREG: {
5595     EVT EVT = cast<VTSDNode>(N2)->getVT();
5596     assert(VT == N1.getValueType() && "Not an inreg extend!");
5597     assert(VT.isInteger() && EVT.isInteger() &&
5598            "Cannot *_EXTEND_INREG FP types");
5599     assert(EVT.isVector() == VT.isVector() &&
5600            "SIGN_EXTEND_INREG type should be vector iff the operand "
5601            "type is vector!");
5602     assert((!EVT.isVector() ||
5603             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5604            "Vector element counts must match in SIGN_EXTEND_INREG");
5605     assert(EVT.bitsLE(VT) && "Not extending!");
5606     if (EVT == VT) return N1;  // Not actually extending
5607 
5608     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5609       unsigned FromBits = EVT.getScalarSizeInBits();
5610       Val <<= Val.getBitWidth() - FromBits;
5611       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5612       return getConstant(Val, DL, ConstantVT);
5613     };
5614 
5615     if (N1C) {
5616       const APInt &Val = N1C->getAPIntValue();
5617       return SignExtendInReg(Val, VT);
5618     }
5619     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5620       SmallVector<SDValue, 8> Ops;
5621       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5622       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5623         SDValue Op = N1.getOperand(i);
5624         if (Op.isUndef()) {
5625           Ops.push_back(getUNDEF(OpVT));
5626           continue;
5627         }
5628         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5629         APInt Val = C->getAPIntValue();
5630         Ops.push_back(SignExtendInReg(Val, OpVT));
5631       }
5632       return getBuildVector(VT, DL, Ops);
5633     }
5634     break;
5635   }
5636   case ISD::EXTRACT_VECTOR_ELT:
5637     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5638            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5639              element type of the vector.");
5640 
5641     // Extract from an undefined value or using an undefined index is undefined.
5642     if (N1.isUndef() || N2.isUndef())
5643       return getUNDEF(VT);
5644 
5645     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5646     // vectors. For scalable vectors we will provide appropriate support for
5647     // dealing with arbitrary indices.
5648     if (N2C && N1.getValueType().isFixedLengthVector() &&
5649         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5650       return getUNDEF(VT);
5651 
5652     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5653     // expanding copies of large vectors from registers. This only works for
5654     // fixed length vectors, since we need to know the exact number of
5655     // elements.
5656     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5657         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5658       unsigned Factor =
5659         N1.getOperand(0).getValueType().getVectorNumElements();
5660       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5661                      N1.getOperand(N2C->getZExtValue() / Factor),
5662                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5663     }
5664 
5665     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5666     // lowering is expanding large vector constants.
5667     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5668                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5669       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5670               N1.getValueType().isFixedLengthVector()) &&
5671              "BUILD_VECTOR used for scalable vectors");
5672       unsigned Index =
5673           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5674       SDValue Elt = N1.getOperand(Index);
5675 
5676       if (VT != Elt.getValueType())
5677         // If the vector element type is not legal, the BUILD_VECTOR operands
5678         // are promoted and implicitly truncated, and the result implicitly
5679         // extended. Make that explicit here.
5680         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5681 
5682       return Elt;
5683     }
5684 
5685     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5686     // operations are lowered to scalars.
5687     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5688       // If the indices are the same, return the inserted element else
5689       // if the indices are known different, extract the element from
5690       // the original vector.
5691       SDValue N1Op2 = N1.getOperand(2);
5692       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5693 
5694       if (N1Op2C && N2C) {
5695         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5696           if (VT == N1.getOperand(1).getValueType())
5697             return N1.getOperand(1);
5698           else
5699             return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5700         }
5701 
5702         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5703       }
5704     }
5705 
5706     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5707     // when vector types are scalarized and v1iX is legal.
5708     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5709     // Here we are completely ignoring the extract element index (N2),
5710     // which is fine for fixed width vectors, since any index other than 0
5711     // is undefined anyway. However, this cannot be ignored for scalable
5712     // vectors - in theory we could support this, but we don't want to do this
5713     // without a profitability check.
5714     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5715         N1.getValueType().isFixedLengthVector() &&
5716         N1.getValueType().getVectorNumElements() == 1) {
5717       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5718                      N1.getOperand(1));
5719     }
5720     break;
5721   case ISD::EXTRACT_ELEMENT:
5722     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5723     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5724            (N1.getValueType().isInteger() == VT.isInteger()) &&
5725            N1.getValueType() != VT &&
5726            "Wrong types for EXTRACT_ELEMENT!");
5727 
5728     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5729     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5730     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5731     if (N1.getOpcode() == ISD::BUILD_PAIR)
5732       return N1.getOperand(N2C->getZExtValue());
5733 
5734     // EXTRACT_ELEMENT of a constant int is also very common.
5735     if (N1C) {
5736       unsigned ElementSize = VT.getSizeInBits();
5737       unsigned Shift = ElementSize * N2C->getZExtValue();
5738       const APInt &Val = N1C->getAPIntValue();
5739       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5740     }
5741     break;
5742   case ISD::EXTRACT_SUBVECTOR:
5743     EVT N1VT = N1.getValueType();
5744     assert(VT.isVector() && N1VT.isVector() &&
5745            "Extract subvector VTs must be vectors!");
5746     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5747            "Extract subvector VTs must have the same element type!");
5748     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5749            "Cannot extract a scalable vector from a fixed length vector!");
5750     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5751             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5752            "Extract subvector must be from larger vector to smaller vector!");
5753     assert(N2C && "Extract subvector index must be a constant");
5754     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5755             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5756                 N1VT.getVectorMinNumElements()) &&
5757            "Extract subvector overflow!");
5758     assert(N2C->getAPIntValue().getBitWidth() ==
5759                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5760            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5761 
5762     // Trivial extraction.
5763     if (VT == N1VT)
5764       return N1;
5765 
5766     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5767     if (N1.isUndef())
5768       return getUNDEF(VT);
5769 
5770     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5771     // the concat have the same type as the extract.
5772     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5773         VT == N1.getOperand(0).getValueType()) {
5774       unsigned Factor = VT.getVectorMinNumElements();
5775       return N1.getOperand(N2C->getZExtValue() / Factor);
5776     }
5777 
5778     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5779     // during shuffle legalization.
5780     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5781         VT == N1.getOperand(1).getValueType())
5782       return N1.getOperand(1);
5783     break;
5784   }
5785 
5786   // Perform trivial constant folding.
5787   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5788     return SV;
5789 
5790   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5791     return V;
5792 
5793   // Canonicalize an UNDEF to the RHS, even over a constant.
5794   if (N1.isUndef()) {
5795     if (TLI->isCommutativeBinOp(Opcode)) {
5796       std::swap(N1, N2);
5797     } else {
5798       switch (Opcode) {
5799       case ISD::SIGN_EXTEND_INREG:
5800       case ISD::SUB:
5801         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5802       case ISD::UDIV:
5803       case ISD::SDIV:
5804       case ISD::UREM:
5805       case ISD::SREM:
5806       case ISD::SSUBSAT:
5807       case ISD::USUBSAT:
5808         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5809       }
5810     }
5811   }
5812 
5813   // Fold a bunch of operators when the RHS is undef.
5814   if (N2.isUndef()) {
5815     switch (Opcode) {
5816     case ISD::XOR:
5817       if (N1.isUndef())
5818         // Handle undef ^ undef -> 0 special case. This is a common
5819         // idiom (misuse).
5820         return getConstant(0, DL, VT);
5821       LLVM_FALLTHROUGH;
5822     case ISD::ADD:
5823     case ISD::SUB:
5824     case ISD::UDIV:
5825     case ISD::SDIV:
5826     case ISD::UREM:
5827     case ISD::SREM:
5828       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5829     case ISD::MUL:
5830     case ISD::AND:
5831     case ISD::SSUBSAT:
5832     case ISD::USUBSAT:
5833       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5834     case ISD::OR:
5835     case ISD::SADDSAT:
5836     case ISD::UADDSAT:
5837       return getAllOnesConstant(DL, VT);
5838     }
5839   }
5840 
5841   // Memoize this node if possible.
5842   SDNode *N;
5843   SDVTList VTs = getVTList(VT);
5844   SDValue Ops[] = {N1, N2};
5845   if (VT != MVT::Glue) {
5846     FoldingSetNodeID ID;
5847     AddNodeIDNode(ID, Opcode, VTs, Ops);
5848     void *IP = nullptr;
5849     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5850       E->intersectFlagsWith(Flags);
5851       return SDValue(E, 0);
5852     }
5853 
5854     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5855     N->setFlags(Flags);
5856     createOperands(N, Ops);
5857     CSEMap.InsertNode(N, IP);
5858   } else {
5859     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5860     createOperands(N, Ops);
5861   }
5862 
5863   InsertNode(N);
5864   SDValue V = SDValue(N, 0);
5865   NewSDValueDbgMsg(V, "Creating new node: ", this);
5866   return V;
5867 }
5868 
5869 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5870                               SDValue N1, SDValue N2, SDValue N3) {
5871   SDNodeFlags Flags;
5872   if (Inserter)
5873     Flags = Inserter->getFlags();
5874   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
5875 }
5876 
5877 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5878                               SDValue N1, SDValue N2, SDValue N3,
5879                               const SDNodeFlags Flags) {
5880   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5881          N2.getOpcode() != ISD::DELETED_NODE &&
5882          N3.getOpcode() != ISD::DELETED_NODE &&
5883          "Operand is DELETED_NODE!");
5884   // Perform various simplifications.
5885   switch (Opcode) {
5886   case ISD::FMA: {
5887     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5888     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5889            N3.getValueType() == VT && "FMA types must match!");
5890     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5891     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5892     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5893     if (N1CFP && N2CFP && N3CFP) {
5894       APFloat  V1 = N1CFP->getValueAPF();
5895       const APFloat &V2 = N2CFP->getValueAPF();
5896       const APFloat &V3 = N3CFP->getValueAPF();
5897       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
5898       return getConstantFP(V1, DL, VT);
5899     }
5900     break;
5901   }
5902   case ISD::BUILD_VECTOR: {
5903     // Attempt to simplify BUILD_VECTOR.
5904     SDValue Ops[] = {N1, N2, N3};
5905     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5906       return V;
5907     break;
5908   }
5909   case ISD::CONCAT_VECTORS: {
5910     SDValue Ops[] = {N1, N2, N3};
5911     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5912       return V;
5913     break;
5914   }
5915   case ISD::SETCC: {
5916     assert(VT.isInteger() && "SETCC result type must be an integer!");
5917     assert(N1.getValueType() == N2.getValueType() &&
5918            "SETCC operands must have the same type!");
5919     assert(VT.isVector() == N1.getValueType().isVector() &&
5920            "SETCC type should be vector iff the operand type is vector!");
5921     assert((!VT.isVector() || VT.getVectorElementCount() ==
5922                                   N1.getValueType().getVectorElementCount()) &&
5923            "SETCC vector element counts must match!");
5924     // Use FoldSetCC to simplify SETCC's.
5925     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5926       return V;
5927     // Vector constant folding.
5928     SDValue Ops[] = {N1, N2, N3};
5929     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5930       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5931       return V;
5932     }
5933     break;
5934   }
5935   case ISD::SELECT:
5936   case ISD::VSELECT:
5937     if (SDValue V = simplifySelect(N1, N2, N3))
5938       return V;
5939     break;
5940   case ISD::VECTOR_SHUFFLE:
5941     llvm_unreachable("should use getVectorShuffle constructor!");
5942   case ISD::INSERT_VECTOR_ELT: {
5943     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5944     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
5945     // for scalable vectors where we will generate appropriate code to
5946     // deal with out-of-bounds cases correctly.
5947     if (N3C && N1.getValueType().isFixedLengthVector() &&
5948         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5949       return getUNDEF(VT);
5950 
5951     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
5952     if (N3.isUndef())
5953       return getUNDEF(VT);
5954 
5955     // If the inserted element is an UNDEF, just use the input vector.
5956     if (N2.isUndef())
5957       return N1;
5958 
5959     break;
5960   }
5961   case ISD::INSERT_SUBVECTOR: {
5962     // Inserting undef into undef is still undef.
5963     if (N1.isUndef() && N2.isUndef())
5964       return getUNDEF(VT);
5965 
5966     EVT N2VT = N2.getValueType();
5967     assert(VT == N1.getValueType() &&
5968            "Dest and insert subvector source types must match!");
5969     assert(VT.isVector() && N2VT.isVector() &&
5970            "Insert subvector VTs must be vectors!");
5971     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
5972            "Cannot insert a scalable vector into a fixed length vector!");
5973     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5974             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
5975            "Insert subvector must be from smaller vector to larger vector!");
5976     assert(isa<ConstantSDNode>(N3) &&
5977            "Insert subvector index must be constant");
5978     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5979             (N2VT.getVectorMinNumElements() +
5980              cast<ConstantSDNode>(N3)->getZExtValue()) <=
5981                 VT.getVectorMinNumElements()) &&
5982            "Insert subvector overflow!");
5983     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
5984                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5985            "Constant index for INSERT_SUBVECTOR has an invalid size");
5986 
5987     // Trivial insertion.
5988     if (VT == N2VT)
5989       return N2;
5990 
5991     // If this is an insert of an extracted vector into an undef vector, we
5992     // can just use the input to the extract.
5993     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5994         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
5995       return N2.getOperand(0);
5996     break;
5997   }
5998   case ISD::BITCAST:
5999     // Fold bit_convert nodes from a type to themselves.
6000     if (N1.getValueType() == VT)
6001       return N1;
6002     break;
6003   }
6004 
6005   // Memoize node if it doesn't produce a flag.
6006   SDNode *N;
6007   SDVTList VTs = getVTList(VT);
6008   SDValue Ops[] = {N1, N2, N3};
6009   if (VT != MVT::Glue) {
6010     FoldingSetNodeID ID;
6011     AddNodeIDNode(ID, Opcode, VTs, Ops);
6012     void *IP = nullptr;
6013     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6014       E->intersectFlagsWith(Flags);
6015       return SDValue(E, 0);
6016     }
6017 
6018     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6019     N->setFlags(Flags);
6020     createOperands(N, Ops);
6021     CSEMap.InsertNode(N, IP);
6022   } else {
6023     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6024     createOperands(N, Ops);
6025   }
6026 
6027   InsertNode(N);
6028   SDValue V = SDValue(N, 0);
6029   NewSDValueDbgMsg(V, "Creating new node: ", this);
6030   return V;
6031 }
6032 
6033 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6034                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6035   SDValue Ops[] = { N1, N2, N3, N4 };
6036   return getNode(Opcode, DL, VT, Ops);
6037 }
6038 
6039 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6040                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6041                               SDValue N5) {
6042   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6043   return getNode(Opcode, DL, VT, Ops);
6044 }
6045 
6046 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6047 /// the incoming stack arguments to be loaded from the stack.
6048 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6049   SmallVector<SDValue, 8> ArgChains;
6050 
6051   // Include the original chain at the beginning of the list. When this is
6052   // used by target LowerCall hooks, this helps legalize find the
6053   // CALLSEQ_BEGIN node.
6054   ArgChains.push_back(Chain);
6055 
6056   // Add a chain value for each stack argument.
6057   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
6058        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
6059     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
6060       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6061         if (FI->getIndex() < 0)
6062           ArgChains.push_back(SDValue(L, 1));
6063 
6064   // Build a tokenfactor for all the chains.
6065   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6066 }
6067 
6068 /// getMemsetValue - Vectorized representation of the memset value
6069 /// operand.
6070 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6071                               const SDLoc &dl) {
6072   assert(!Value.isUndef());
6073 
6074   unsigned NumBits = VT.getScalarSizeInBits();
6075   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6076     assert(C->getAPIntValue().getBitWidth() == 8);
6077     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6078     if (VT.isInteger()) {
6079       bool IsOpaque = VT.getSizeInBits() > 64 ||
6080           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6081       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6082     }
6083     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6084                              VT);
6085   }
6086 
6087   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6088   EVT IntVT = VT.getScalarType();
6089   if (!IntVT.isInteger())
6090     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6091 
6092   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6093   if (NumBits > 8) {
6094     // Use a multiplication with 0x010101... to extend the input to the
6095     // required length.
6096     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6097     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6098                         DAG.getConstant(Magic, dl, IntVT));
6099   }
6100 
6101   if (VT != Value.getValueType() && !VT.isInteger())
6102     Value = DAG.getBitcast(VT.getScalarType(), Value);
6103   if (VT != Value.getValueType())
6104     Value = DAG.getSplatBuildVector(VT, dl, Value);
6105 
6106   return Value;
6107 }
6108 
6109 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6110 /// used when a memcpy is turned into a memset when the source is a constant
6111 /// string ptr.
6112 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6113                                   const TargetLowering &TLI,
6114                                   const ConstantDataArraySlice &Slice) {
6115   // Handle vector with all elements zero.
6116   if (Slice.Array == nullptr) {
6117     if (VT.isInteger())
6118       return DAG.getConstant(0, dl, VT);
6119     else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6120       return DAG.getConstantFP(0.0, dl, VT);
6121     else if (VT.isVector()) {
6122       unsigned NumElts = VT.getVectorNumElements();
6123       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6124       return DAG.getNode(ISD::BITCAST, dl, VT,
6125                          DAG.getConstant(0, dl,
6126                                          EVT::getVectorVT(*DAG.getContext(),
6127                                                           EltVT, NumElts)));
6128     } else
6129       llvm_unreachable("Expected type!");
6130   }
6131 
6132   assert(!VT.isVector() && "Can't handle vector type here!");
6133   unsigned NumVTBits = VT.getSizeInBits();
6134   unsigned NumVTBytes = NumVTBits / 8;
6135   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6136 
6137   APInt Val(NumVTBits, 0);
6138   if (DAG.getDataLayout().isLittleEndian()) {
6139     for (unsigned i = 0; i != NumBytes; ++i)
6140       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6141   } else {
6142     for (unsigned i = 0; i != NumBytes; ++i)
6143       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6144   }
6145 
6146   // If the "cost" of materializing the integer immediate is less than the cost
6147   // of a load, then it is cost effective to turn the load into the immediate.
6148   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6149   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6150     return DAG.getConstant(Val, dl, VT);
6151   return SDValue(nullptr, 0);
6152 }
6153 
6154 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6155                                            const SDLoc &DL,
6156                                            const SDNodeFlags Flags) {
6157   EVT VT = Base.getValueType();
6158   SDValue Index;
6159 
6160   if (Offset.isScalable())
6161     Index = getVScale(DL, Base.getValueType(),
6162                       APInt(Base.getValueSizeInBits().getFixedSize(),
6163                             Offset.getKnownMinSize()));
6164   else
6165     Index = getConstant(Offset.getFixedSize(), DL, VT);
6166 
6167   return getMemBasePlusOffset(Base, Index, DL, Flags);
6168 }
6169 
6170 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6171                                            const SDLoc &DL,
6172                                            const SDNodeFlags Flags) {
6173   assert(Offset.getValueType().isInteger());
6174   EVT BasePtrVT = Ptr.getValueType();
6175   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6176 }
6177 
6178 /// Returns true if memcpy source is constant data.
6179 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6180   uint64_t SrcDelta = 0;
6181   GlobalAddressSDNode *G = nullptr;
6182   if (Src.getOpcode() == ISD::GlobalAddress)
6183     G = cast<GlobalAddressSDNode>(Src);
6184   else if (Src.getOpcode() == ISD::ADD &&
6185            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6186            Src.getOperand(1).getOpcode() == ISD::Constant) {
6187     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6188     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6189   }
6190   if (!G)
6191     return false;
6192 
6193   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6194                                   SrcDelta + G->getOffset());
6195 }
6196 
6197 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6198                                       SelectionDAG &DAG) {
6199   // On Darwin, -Os means optimize for size without hurting performance, so
6200   // only really optimize for size when -Oz (MinSize) is used.
6201   if (MF.getTarget().getTargetTriple().isOSDarwin())
6202     return MF.getFunction().hasMinSize();
6203   return DAG.shouldOptForSize();
6204 }
6205 
6206 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6207                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6208                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6209                           SmallVector<SDValue, 16> &OutStoreChains) {
6210   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6211   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6212   SmallVector<SDValue, 16> GluedLoadChains;
6213   for (unsigned i = From; i < To; ++i) {
6214     OutChains.push_back(OutLoadChains[i]);
6215     GluedLoadChains.push_back(OutLoadChains[i]);
6216   }
6217 
6218   // Chain for all loads.
6219   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6220                                   GluedLoadChains);
6221 
6222   for (unsigned i = From; i < To; ++i) {
6223     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6224     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6225                                   ST->getBasePtr(), ST->getMemoryVT(),
6226                                   ST->getMemOperand());
6227     OutChains.push_back(NewStore);
6228   }
6229 }
6230 
6231 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6232                                        SDValue Chain, SDValue Dst, SDValue Src,
6233                                        uint64_t Size, Align Alignment,
6234                                        bool isVol, bool AlwaysInline,
6235                                        MachinePointerInfo DstPtrInfo,
6236                                        MachinePointerInfo SrcPtrInfo) {
6237   // Turn a memcpy of undef to nop.
6238   // FIXME: We need to honor volatile even is Src is undef.
6239   if (Src.isUndef())
6240     return Chain;
6241 
6242   // Expand memcpy to a series of load and store ops if the size operand falls
6243   // below a certain threshold.
6244   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6245   // rather than maybe a humongous number of loads and stores.
6246   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6247   const DataLayout &DL = DAG.getDataLayout();
6248   LLVMContext &C = *DAG.getContext();
6249   std::vector<EVT> MemOps;
6250   bool DstAlignCanChange = false;
6251   MachineFunction &MF = DAG.getMachineFunction();
6252   MachineFrameInfo &MFI = MF.getFrameInfo();
6253   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6254   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6255   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6256     DstAlignCanChange = true;
6257   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6258   if (!SrcAlign || Alignment > *SrcAlign)
6259     SrcAlign = Alignment;
6260   assert(SrcAlign && "SrcAlign must be set");
6261   ConstantDataArraySlice Slice;
6262   // If marked as volatile, perform a copy even when marked as constant.
6263   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6264   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6265   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6266   const MemOp Op = isZeroConstant
6267                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6268                                     /*IsZeroMemset*/ true, isVol)
6269                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6270                                      *SrcAlign, isVol, CopyFromConstant);
6271   if (!TLI.findOptimalMemOpLowering(
6272           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6273           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6274     return SDValue();
6275 
6276   if (DstAlignCanChange) {
6277     Type *Ty = MemOps[0].getTypeForEVT(C);
6278     Align NewAlign = DL.getABITypeAlign(Ty);
6279 
6280     // Don't promote to an alignment that would require dynamic stack
6281     // realignment.
6282     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6283     if (!TRI->hasStackRealignment(MF))
6284       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6285         NewAlign = NewAlign / 2;
6286 
6287     if (NewAlign > Alignment) {
6288       // Give the stack frame object a larger alignment if needed.
6289       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6290         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6291       Alignment = NewAlign;
6292     }
6293   }
6294 
6295   MachineMemOperand::Flags MMOFlags =
6296       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6297   SmallVector<SDValue, 16> OutLoadChains;
6298   SmallVector<SDValue, 16> OutStoreChains;
6299   SmallVector<SDValue, 32> OutChains;
6300   unsigned NumMemOps = MemOps.size();
6301   uint64_t SrcOff = 0, DstOff = 0;
6302   for (unsigned i = 0; i != NumMemOps; ++i) {
6303     EVT VT = MemOps[i];
6304     unsigned VTSize = VT.getSizeInBits() / 8;
6305     SDValue Value, Store;
6306 
6307     if (VTSize > Size) {
6308       // Issuing an unaligned load / store pair  that overlaps with the previous
6309       // pair. Adjust the offset accordingly.
6310       assert(i == NumMemOps-1 && i != 0);
6311       SrcOff -= VTSize - Size;
6312       DstOff -= VTSize - Size;
6313     }
6314 
6315     if (CopyFromConstant &&
6316         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6317       // It's unlikely a store of a vector immediate can be done in a single
6318       // instruction. It would require a load from a constantpool first.
6319       // We only handle zero vectors here.
6320       // FIXME: Handle other cases where store of vector immediate is done in
6321       // a single instruction.
6322       ConstantDataArraySlice SubSlice;
6323       if (SrcOff < Slice.Length) {
6324         SubSlice = Slice;
6325         SubSlice.move(SrcOff);
6326       } else {
6327         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6328         SubSlice.Array = nullptr;
6329         SubSlice.Offset = 0;
6330         SubSlice.Length = VTSize;
6331       }
6332       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6333       if (Value.getNode()) {
6334         Store = DAG.getStore(
6335             Chain, dl, Value,
6336             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6337             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags);
6338         OutChains.push_back(Store);
6339       }
6340     }
6341 
6342     if (!Store.getNode()) {
6343       // The type might not be legal for the target.  This should only happen
6344       // if the type is smaller than a legal type, as on PPC, so the right
6345       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6346       // to Load/Store if NVT==VT.
6347       // FIXME does the case above also need this?
6348       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6349       assert(NVT.bitsGE(VT));
6350 
6351       bool isDereferenceable =
6352         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6353       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6354       if (isDereferenceable)
6355         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6356 
6357       Value = DAG.getExtLoad(
6358           ISD::EXTLOAD, dl, NVT, Chain,
6359           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6360           SrcPtrInfo.getWithOffset(SrcOff), VT,
6361           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags);
6362       OutLoadChains.push_back(Value.getValue(1));
6363 
6364       Store = DAG.getTruncStore(
6365           Chain, dl, Value,
6366           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6367           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags);
6368       OutStoreChains.push_back(Store);
6369     }
6370     SrcOff += VTSize;
6371     DstOff += VTSize;
6372     Size -= VTSize;
6373   }
6374 
6375   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6376                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6377   unsigned NumLdStInMemcpy = OutStoreChains.size();
6378 
6379   if (NumLdStInMemcpy) {
6380     // It may be that memcpy might be converted to memset if it's memcpy
6381     // of constants. In such a case, we won't have loads and stores, but
6382     // just stores. In the absence of loads, there is nothing to gang up.
6383     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6384       // If target does not care, just leave as it.
6385       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6386         OutChains.push_back(OutLoadChains[i]);
6387         OutChains.push_back(OutStoreChains[i]);
6388       }
6389     } else {
6390       // Ld/St less than/equal limit set by target.
6391       if (NumLdStInMemcpy <= GluedLdStLimit) {
6392           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6393                                         NumLdStInMemcpy, OutLoadChains,
6394                                         OutStoreChains);
6395       } else {
6396         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6397         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6398         unsigned GlueIter = 0;
6399 
6400         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6401           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6402           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6403 
6404           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6405                                        OutLoadChains, OutStoreChains);
6406           GlueIter += GluedLdStLimit;
6407         }
6408 
6409         // Residual ld/st.
6410         if (RemainingLdStInMemcpy) {
6411           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6412                                         RemainingLdStInMemcpy, OutLoadChains,
6413                                         OutStoreChains);
6414         }
6415       }
6416     }
6417   }
6418   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6419 }
6420 
6421 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6422                                         SDValue Chain, SDValue Dst, SDValue Src,
6423                                         uint64_t Size, Align Alignment,
6424                                         bool isVol, bool AlwaysInline,
6425                                         MachinePointerInfo DstPtrInfo,
6426                                         MachinePointerInfo SrcPtrInfo) {
6427   // Turn a memmove of undef to nop.
6428   // FIXME: We need to honor volatile even is Src is undef.
6429   if (Src.isUndef())
6430     return Chain;
6431 
6432   // Expand memmove to a series of load and store ops if the size operand falls
6433   // below a certain threshold.
6434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6435   const DataLayout &DL = DAG.getDataLayout();
6436   LLVMContext &C = *DAG.getContext();
6437   std::vector<EVT> MemOps;
6438   bool DstAlignCanChange = false;
6439   MachineFunction &MF = DAG.getMachineFunction();
6440   MachineFrameInfo &MFI = MF.getFrameInfo();
6441   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6442   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6443   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6444     DstAlignCanChange = true;
6445   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6446   if (!SrcAlign || Alignment > *SrcAlign)
6447     SrcAlign = Alignment;
6448   assert(SrcAlign && "SrcAlign must be set");
6449   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6450   if (!TLI.findOptimalMemOpLowering(
6451           MemOps, Limit,
6452           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6453                       /*IsVolatile*/ true),
6454           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6455           MF.getFunction().getAttributes()))
6456     return SDValue();
6457 
6458   if (DstAlignCanChange) {
6459     Type *Ty = MemOps[0].getTypeForEVT(C);
6460     Align NewAlign = DL.getABITypeAlign(Ty);
6461     if (NewAlign > Alignment) {
6462       // Give the stack frame object a larger alignment if needed.
6463       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6464         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6465       Alignment = NewAlign;
6466     }
6467   }
6468 
6469   MachineMemOperand::Flags MMOFlags =
6470       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6471   uint64_t SrcOff = 0, DstOff = 0;
6472   SmallVector<SDValue, 8> LoadValues;
6473   SmallVector<SDValue, 8> LoadChains;
6474   SmallVector<SDValue, 8> OutChains;
6475   unsigned NumMemOps = MemOps.size();
6476   for (unsigned i = 0; i < NumMemOps; i++) {
6477     EVT VT = MemOps[i];
6478     unsigned VTSize = VT.getSizeInBits() / 8;
6479     SDValue Value;
6480 
6481     bool isDereferenceable =
6482       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6483     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6484     if (isDereferenceable)
6485       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6486 
6487     Value =
6488         DAG.getLoad(VT, dl, Chain,
6489                     DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6490                     SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags);
6491     LoadValues.push_back(Value);
6492     LoadChains.push_back(Value.getValue(1));
6493     SrcOff += VTSize;
6494   }
6495   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6496   OutChains.clear();
6497   for (unsigned i = 0; i < NumMemOps; i++) {
6498     EVT VT = MemOps[i];
6499     unsigned VTSize = VT.getSizeInBits() / 8;
6500     SDValue Store;
6501 
6502     Store =
6503         DAG.getStore(Chain, dl, LoadValues[i],
6504                      DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6505                      DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags);
6506     OutChains.push_back(Store);
6507     DstOff += VTSize;
6508   }
6509 
6510   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6511 }
6512 
6513 /// Lower the call to 'memset' intrinsic function into a series of store
6514 /// operations.
6515 ///
6516 /// \param DAG Selection DAG where lowered code is placed.
6517 /// \param dl Link to corresponding IR location.
6518 /// \param Chain Control flow dependency.
6519 /// \param Dst Pointer to destination memory location.
6520 /// \param Src Value of byte to write into the memory.
6521 /// \param Size Number of bytes to write.
6522 /// \param Alignment Alignment of the destination in bytes.
6523 /// \param isVol True if destination is volatile.
6524 /// \param DstPtrInfo IR information on the memory pointer.
6525 /// \returns New head in the control flow, if lowering was successful, empty
6526 /// SDValue otherwise.
6527 ///
6528 /// The function tries to replace 'llvm.memset' intrinsic with several store
6529 /// operations and value calculation code. This is usually profitable for small
6530 /// memory size.
6531 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6532                                SDValue Chain, SDValue Dst, SDValue Src,
6533                                uint64_t Size, Align Alignment, bool isVol,
6534                                MachinePointerInfo DstPtrInfo) {
6535   // Turn a memset of undef to nop.
6536   // FIXME: We need to honor volatile even is Src is undef.
6537   if (Src.isUndef())
6538     return Chain;
6539 
6540   // Expand memset to a series of load/store ops if the size operand
6541   // falls below a certain threshold.
6542   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6543   std::vector<EVT> MemOps;
6544   bool DstAlignCanChange = false;
6545   MachineFunction &MF = DAG.getMachineFunction();
6546   MachineFrameInfo &MFI = MF.getFrameInfo();
6547   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6548   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6549   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6550     DstAlignCanChange = true;
6551   bool IsZeroVal =
6552     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6553   if (!TLI.findOptimalMemOpLowering(
6554           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6555           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6556           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6557     return SDValue();
6558 
6559   if (DstAlignCanChange) {
6560     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6561     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6562     if (NewAlign > Alignment) {
6563       // Give the stack frame object a larger alignment if needed.
6564       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6565         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6566       Alignment = NewAlign;
6567     }
6568   }
6569 
6570   SmallVector<SDValue, 8> OutChains;
6571   uint64_t DstOff = 0;
6572   unsigned NumMemOps = MemOps.size();
6573 
6574   // Find the largest store and generate the bit pattern for it.
6575   EVT LargestVT = MemOps[0];
6576   for (unsigned i = 1; i < NumMemOps; i++)
6577     if (MemOps[i].bitsGT(LargestVT))
6578       LargestVT = MemOps[i];
6579   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6580 
6581   for (unsigned i = 0; i < NumMemOps; i++) {
6582     EVT VT = MemOps[i];
6583     unsigned VTSize = VT.getSizeInBits() / 8;
6584     if (VTSize > Size) {
6585       // Issuing an unaligned load / store pair  that overlaps with the previous
6586       // pair. Adjust the offset accordingly.
6587       assert(i == NumMemOps-1 && i != 0);
6588       DstOff -= VTSize - Size;
6589     }
6590 
6591     // If this store is smaller than the largest store see whether we can get
6592     // the smaller value for free with a truncate.
6593     SDValue Value = MemSetValue;
6594     if (VT.bitsLT(LargestVT)) {
6595       if (!LargestVT.isVector() && !VT.isVector() &&
6596           TLI.isTruncateFree(LargestVT, VT))
6597         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6598       else
6599         Value = getMemsetValue(Src, VT, DAG, dl);
6600     }
6601     assert(Value.getValueType() == VT && "Value with wrong type.");
6602     SDValue Store = DAG.getStore(
6603         Chain, dl, Value,
6604         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6605         DstPtrInfo.getWithOffset(DstOff), Alignment,
6606         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
6607     OutChains.push_back(Store);
6608     DstOff += VT.getSizeInBits() / 8;
6609     Size -= VTSize;
6610   }
6611 
6612   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6613 }
6614 
6615 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6616                                             unsigned AS) {
6617   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6618   // pointer operands can be losslessly bitcasted to pointers of address space 0
6619   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6620     report_fatal_error("cannot lower memory intrinsic in address space " +
6621                        Twine(AS));
6622   }
6623 }
6624 
6625 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6626                                 SDValue Src, SDValue Size, Align Alignment,
6627                                 bool isVol, bool AlwaysInline, bool isTailCall,
6628                                 MachinePointerInfo DstPtrInfo,
6629                                 MachinePointerInfo SrcPtrInfo) {
6630   // Check to see if we should lower the memcpy to loads and stores first.
6631   // For cases within the target-specified limits, this is the best choice.
6632   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6633   if (ConstantSize) {
6634     // Memcpy with size zero? Just return the original chain.
6635     if (ConstantSize->isNullValue())
6636       return Chain;
6637 
6638     SDValue Result = getMemcpyLoadsAndStores(
6639         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6640         isVol, false, DstPtrInfo, SrcPtrInfo);
6641     if (Result.getNode())
6642       return Result;
6643   }
6644 
6645   // Then check to see if we should lower the memcpy with target-specific
6646   // code. If the target chooses to do this, this is the next best.
6647   if (TSI) {
6648     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6649         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6650         DstPtrInfo, SrcPtrInfo);
6651     if (Result.getNode())
6652       return Result;
6653   }
6654 
6655   // If we really need inline code and the target declined to provide it,
6656   // use a (potentially long) sequence of loads and stores.
6657   if (AlwaysInline) {
6658     assert(ConstantSize && "AlwaysInline requires a constant size!");
6659     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6660                                    ConstantSize->getZExtValue(), Alignment,
6661                                    isVol, true, DstPtrInfo, SrcPtrInfo);
6662   }
6663 
6664   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6665   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6666 
6667   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6668   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6669   // respect volatile, so they may do things like read or write memory
6670   // beyond the given memory regions. But fixing this isn't easy, and most
6671   // people don't care.
6672 
6673   // Emit a library call.
6674   TargetLowering::ArgListTy Args;
6675   TargetLowering::ArgListEntry Entry;
6676   Entry.Ty = Type::getInt8PtrTy(*getContext());
6677   Entry.Node = Dst; Args.push_back(Entry);
6678   Entry.Node = Src; Args.push_back(Entry);
6679 
6680   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6681   Entry.Node = Size; Args.push_back(Entry);
6682   // FIXME: pass in SDLoc
6683   TargetLowering::CallLoweringInfo CLI(*this);
6684   CLI.setDebugLoc(dl)
6685       .setChain(Chain)
6686       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6687                     Dst.getValueType().getTypeForEVT(*getContext()),
6688                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6689                                       TLI->getPointerTy(getDataLayout())),
6690                     std::move(Args))
6691       .setDiscardResult()
6692       .setTailCall(isTailCall);
6693 
6694   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6695   return CallResult.second;
6696 }
6697 
6698 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6699                                       SDValue Dst, unsigned DstAlign,
6700                                       SDValue Src, unsigned SrcAlign,
6701                                       SDValue Size, Type *SizeTy,
6702                                       unsigned ElemSz, bool isTailCall,
6703                                       MachinePointerInfo DstPtrInfo,
6704                                       MachinePointerInfo SrcPtrInfo) {
6705   // Emit a library call.
6706   TargetLowering::ArgListTy Args;
6707   TargetLowering::ArgListEntry Entry;
6708   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6709   Entry.Node = Dst;
6710   Args.push_back(Entry);
6711 
6712   Entry.Node = Src;
6713   Args.push_back(Entry);
6714 
6715   Entry.Ty = SizeTy;
6716   Entry.Node = Size;
6717   Args.push_back(Entry);
6718 
6719   RTLIB::Libcall LibraryCall =
6720       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6721   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6722     report_fatal_error("Unsupported element size");
6723 
6724   TargetLowering::CallLoweringInfo CLI(*this);
6725   CLI.setDebugLoc(dl)
6726       .setChain(Chain)
6727       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6728                     Type::getVoidTy(*getContext()),
6729                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6730                                       TLI->getPointerTy(getDataLayout())),
6731                     std::move(Args))
6732       .setDiscardResult()
6733       .setTailCall(isTailCall);
6734 
6735   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6736   return CallResult.second;
6737 }
6738 
6739 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6740                                  SDValue Src, SDValue Size, Align Alignment,
6741                                  bool isVol, bool isTailCall,
6742                                  MachinePointerInfo DstPtrInfo,
6743                                  MachinePointerInfo SrcPtrInfo) {
6744   // Check to see if we should lower the memmove to loads and stores first.
6745   // For cases within the target-specified limits, this is the best choice.
6746   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6747   if (ConstantSize) {
6748     // Memmove with size zero? Just return the original chain.
6749     if (ConstantSize->isNullValue())
6750       return Chain;
6751 
6752     SDValue Result = getMemmoveLoadsAndStores(
6753         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6754         isVol, false, DstPtrInfo, SrcPtrInfo);
6755     if (Result.getNode())
6756       return Result;
6757   }
6758 
6759   // Then check to see if we should lower the memmove with target-specific
6760   // code. If the target chooses to do this, this is the next best.
6761   if (TSI) {
6762     SDValue Result =
6763         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6764                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6765     if (Result.getNode())
6766       return Result;
6767   }
6768 
6769   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6770   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6771 
6772   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6773   // not be safe.  See memcpy above for more details.
6774 
6775   // Emit a library call.
6776   TargetLowering::ArgListTy Args;
6777   TargetLowering::ArgListEntry Entry;
6778   Entry.Ty = Type::getInt8PtrTy(*getContext());
6779   Entry.Node = Dst; Args.push_back(Entry);
6780   Entry.Node = Src; Args.push_back(Entry);
6781 
6782   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6783   Entry.Node = Size; Args.push_back(Entry);
6784   // FIXME:  pass in SDLoc
6785   TargetLowering::CallLoweringInfo CLI(*this);
6786   CLI.setDebugLoc(dl)
6787       .setChain(Chain)
6788       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6789                     Dst.getValueType().getTypeForEVT(*getContext()),
6790                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6791                                       TLI->getPointerTy(getDataLayout())),
6792                     std::move(Args))
6793       .setDiscardResult()
6794       .setTailCall(isTailCall);
6795 
6796   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6797   return CallResult.second;
6798 }
6799 
6800 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6801                                        SDValue Dst, unsigned DstAlign,
6802                                        SDValue Src, unsigned SrcAlign,
6803                                        SDValue Size, Type *SizeTy,
6804                                        unsigned ElemSz, bool isTailCall,
6805                                        MachinePointerInfo DstPtrInfo,
6806                                        MachinePointerInfo SrcPtrInfo) {
6807   // Emit a library call.
6808   TargetLowering::ArgListTy Args;
6809   TargetLowering::ArgListEntry Entry;
6810   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6811   Entry.Node = Dst;
6812   Args.push_back(Entry);
6813 
6814   Entry.Node = Src;
6815   Args.push_back(Entry);
6816 
6817   Entry.Ty = SizeTy;
6818   Entry.Node = Size;
6819   Args.push_back(Entry);
6820 
6821   RTLIB::Libcall LibraryCall =
6822       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6823   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6824     report_fatal_error("Unsupported element size");
6825 
6826   TargetLowering::CallLoweringInfo CLI(*this);
6827   CLI.setDebugLoc(dl)
6828       .setChain(Chain)
6829       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6830                     Type::getVoidTy(*getContext()),
6831                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6832                                       TLI->getPointerTy(getDataLayout())),
6833                     std::move(Args))
6834       .setDiscardResult()
6835       .setTailCall(isTailCall);
6836 
6837   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6838   return CallResult.second;
6839 }
6840 
6841 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6842                                 SDValue Src, SDValue Size, Align Alignment,
6843                                 bool isVol, bool isTailCall,
6844                                 MachinePointerInfo DstPtrInfo) {
6845   // Check to see if we should lower the memset to stores first.
6846   // For cases within the target-specified limits, this is the best choice.
6847   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6848   if (ConstantSize) {
6849     // Memset with size zero? Just return the original chain.
6850     if (ConstantSize->isNullValue())
6851       return Chain;
6852 
6853     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
6854                                      ConstantSize->getZExtValue(), Alignment,
6855                                      isVol, DstPtrInfo);
6856 
6857     if (Result.getNode())
6858       return Result;
6859   }
6860 
6861   // Then check to see if we should lower the memset with target-specific
6862   // code. If the target chooses to do this, this is the next best.
6863   if (TSI) {
6864     SDValue Result = TSI->EmitTargetCodeForMemset(
6865         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
6866     if (Result.getNode())
6867       return Result;
6868   }
6869 
6870   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6871 
6872   // Emit a library call.
6873   TargetLowering::ArgListTy Args;
6874   TargetLowering::ArgListEntry Entry;
6875   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
6876   Args.push_back(Entry);
6877   Entry.Node = Src;
6878   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6879   Args.push_back(Entry);
6880   Entry.Node = Size;
6881   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6882   Args.push_back(Entry);
6883 
6884   // FIXME: pass in SDLoc
6885   TargetLowering::CallLoweringInfo CLI(*this);
6886   CLI.setDebugLoc(dl)
6887       .setChain(Chain)
6888       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
6889                     Dst.getValueType().getTypeForEVT(*getContext()),
6890                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
6891                                       TLI->getPointerTy(getDataLayout())),
6892                     std::move(Args))
6893       .setDiscardResult()
6894       .setTailCall(isTailCall);
6895 
6896   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6897   return CallResult.second;
6898 }
6899 
6900 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6901                                       SDValue Dst, unsigned DstAlign,
6902                                       SDValue Value, SDValue Size, Type *SizeTy,
6903                                       unsigned ElemSz, bool isTailCall,
6904                                       MachinePointerInfo DstPtrInfo) {
6905   // Emit a library call.
6906   TargetLowering::ArgListTy Args;
6907   TargetLowering::ArgListEntry Entry;
6908   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6909   Entry.Node = Dst;
6910   Args.push_back(Entry);
6911 
6912   Entry.Ty = Type::getInt8Ty(*getContext());
6913   Entry.Node = Value;
6914   Args.push_back(Entry);
6915 
6916   Entry.Ty = SizeTy;
6917   Entry.Node = Size;
6918   Args.push_back(Entry);
6919 
6920   RTLIB::Libcall LibraryCall =
6921       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6922   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6923     report_fatal_error("Unsupported element size");
6924 
6925   TargetLowering::CallLoweringInfo CLI(*this);
6926   CLI.setDebugLoc(dl)
6927       .setChain(Chain)
6928       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6929                     Type::getVoidTy(*getContext()),
6930                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6931                                       TLI->getPointerTy(getDataLayout())),
6932                     std::move(Args))
6933       .setDiscardResult()
6934       .setTailCall(isTailCall);
6935 
6936   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6937   return CallResult.second;
6938 }
6939 
6940 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6941                                 SDVTList VTList, ArrayRef<SDValue> Ops,
6942                                 MachineMemOperand *MMO) {
6943   FoldingSetNodeID ID;
6944   ID.AddInteger(MemVT.getRawBits());
6945   AddNodeIDNode(ID, Opcode, VTList, Ops);
6946   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6947   void* IP = nullptr;
6948   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6949     cast<AtomicSDNode>(E)->refineAlignment(MMO);
6950     return SDValue(E, 0);
6951   }
6952 
6953   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6954                                     VTList, MemVT, MMO);
6955   createOperands(N, Ops);
6956 
6957   CSEMap.InsertNode(N, IP);
6958   InsertNode(N);
6959   return SDValue(N, 0);
6960 }
6961 
6962 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6963                                        EVT MemVT, SDVTList VTs, SDValue Chain,
6964                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
6965                                        MachineMemOperand *MMO) {
6966   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6967          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6968   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6969 
6970   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6971   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6972 }
6973 
6974 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6975                                 SDValue Chain, SDValue Ptr, SDValue Val,
6976                                 MachineMemOperand *MMO) {
6977   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6978           Opcode == ISD::ATOMIC_LOAD_SUB ||
6979           Opcode == ISD::ATOMIC_LOAD_AND ||
6980           Opcode == ISD::ATOMIC_LOAD_CLR ||
6981           Opcode == ISD::ATOMIC_LOAD_OR ||
6982           Opcode == ISD::ATOMIC_LOAD_XOR ||
6983           Opcode == ISD::ATOMIC_LOAD_NAND ||
6984           Opcode == ISD::ATOMIC_LOAD_MIN ||
6985           Opcode == ISD::ATOMIC_LOAD_MAX ||
6986           Opcode == ISD::ATOMIC_LOAD_UMIN ||
6987           Opcode == ISD::ATOMIC_LOAD_UMAX ||
6988           Opcode == ISD::ATOMIC_LOAD_FADD ||
6989           Opcode == ISD::ATOMIC_LOAD_FSUB ||
6990           Opcode == ISD::ATOMIC_SWAP ||
6991           Opcode == ISD::ATOMIC_STORE) &&
6992          "Invalid Atomic Op");
6993 
6994   EVT VT = Val.getValueType();
6995 
6996   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
6997                                                getVTList(VT, MVT::Other);
6998   SDValue Ops[] = {Chain, Ptr, Val};
6999   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7000 }
7001 
7002 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7003                                 EVT VT, SDValue Chain, SDValue Ptr,
7004                                 MachineMemOperand *MMO) {
7005   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7006 
7007   SDVTList VTs = getVTList(VT, MVT::Other);
7008   SDValue Ops[] = {Chain, Ptr};
7009   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7010 }
7011 
7012 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7013 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7014   if (Ops.size() == 1)
7015     return Ops[0];
7016 
7017   SmallVector<EVT, 4> VTs;
7018   VTs.reserve(Ops.size());
7019   for (const SDValue &Op : Ops)
7020     VTs.push_back(Op.getValueType());
7021   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7022 }
7023 
7024 SDValue SelectionDAG::getMemIntrinsicNode(
7025     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7026     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7027     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7028   if (!Size && MemVT.isScalableVector())
7029     Size = MemoryLocation::UnknownSize;
7030   else if (!Size)
7031     Size = MemVT.getStoreSize();
7032 
7033   MachineFunction &MF = getMachineFunction();
7034   MachineMemOperand *MMO =
7035       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7036 
7037   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7038 }
7039 
7040 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7041                                           SDVTList VTList,
7042                                           ArrayRef<SDValue> Ops, EVT MemVT,
7043                                           MachineMemOperand *MMO) {
7044   assert((Opcode == ISD::INTRINSIC_VOID ||
7045           Opcode == ISD::INTRINSIC_W_CHAIN ||
7046           Opcode == ISD::PREFETCH ||
7047           ((int)Opcode <= std::numeric_limits<int>::max() &&
7048            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7049          "Opcode is not a memory-accessing opcode!");
7050 
7051   // Memoize the node unless it returns a flag.
7052   MemIntrinsicSDNode *N;
7053   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7054     FoldingSetNodeID ID;
7055     AddNodeIDNode(ID, Opcode, VTList, Ops);
7056     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7057         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7058     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7059     void *IP = nullptr;
7060     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7061       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7062       return SDValue(E, 0);
7063     }
7064 
7065     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7066                                       VTList, MemVT, MMO);
7067     createOperands(N, Ops);
7068 
7069   CSEMap.InsertNode(N, IP);
7070   } else {
7071     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7072                                       VTList, MemVT, MMO);
7073     createOperands(N, Ops);
7074   }
7075   InsertNode(N);
7076   SDValue V(N, 0);
7077   NewSDValueDbgMsg(V, "Creating new node: ", this);
7078   return V;
7079 }
7080 
7081 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7082                                       SDValue Chain, int FrameIndex,
7083                                       int64_t Size, int64_t Offset) {
7084   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7085   const auto VTs = getVTList(MVT::Other);
7086   SDValue Ops[2] = {
7087       Chain,
7088       getFrameIndex(FrameIndex,
7089                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7090                     true)};
7091 
7092   FoldingSetNodeID ID;
7093   AddNodeIDNode(ID, Opcode, VTs, Ops);
7094   ID.AddInteger(FrameIndex);
7095   ID.AddInteger(Size);
7096   ID.AddInteger(Offset);
7097   void *IP = nullptr;
7098   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7099     return SDValue(E, 0);
7100 
7101   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7102       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7103   createOperands(N, Ops);
7104   CSEMap.InsertNode(N, IP);
7105   InsertNode(N);
7106   SDValue V(N, 0);
7107   NewSDValueDbgMsg(V, "Creating new node: ", this);
7108   return V;
7109 }
7110 
7111 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7112                                          uint64_t Guid, uint64_t Index,
7113                                          uint32_t Attr) {
7114   const unsigned Opcode = ISD::PSEUDO_PROBE;
7115   const auto VTs = getVTList(MVT::Other);
7116   SDValue Ops[] = {Chain};
7117   FoldingSetNodeID ID;
7118   AddNodeIDNode(ID, Opcode, VTs, Ops);
7119   ID.AddInteger(Guid);
7120   ID.AddInteger(Index);
7121   void *IP = nullptr;
7122   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7123     return SDValue(E, 0);
7124 
7125   auto *N = newSDNode<PseudoProbeSDNode>(
7126       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7127   createOperands(N, Ops);
7128   CSEMap.InsertNode(N, IP);
7129   InsertNode(N);
7130   SDValue V(N, 0);
7131   NewSDValueDbgMsg(V, "Creating new node: ", this);
7132   return V;
7133 }
7134 
7135 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7136 /// MachinePointerInfo record from it.  This is particularly useful because the
7137 /// code generator has many cases where it doesn't bother passing in a
7138 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7139 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7140                                            SelectionDAG &DAG, SDValue Ptr,
7141                                            int64_t Offset = 0) {
7142   // If this is FI+Offset, we can model it.
7143   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7144     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7145                                              FI->getIndex(), Offset);
7146 
7147   // If this is (FI+Offset1)+Offset2, we can model it.
7148   if (Ptr.getOpcode() != ISD::ADD ||
7149       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7150       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7151     return Info;
7152 
7153   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7154   return MachinePointerInfo::getFixedStack(
7155       DAG.getMachineFunction(), FI,
7156       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7157 }
7158 
7159 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7160 /// MachinePointerInfo record from it.  This is particularly useful because the
7161 /// code generator has many cases where it doesn't bother passing in a
7162 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7163 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7164                                            SelectionDAG &DAG, SDValue Ptr,
7165                                            SDValue OffsetOp) {
7166   // If the 'Offset' value isn't a constant, we can't handle this.
7167   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7168     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7169   if (OffsetOp.isUndef())
7170     return InferPointerInfo(Info, DAG, Ptr);
7171   return Info;
7172 }
7173 
7174 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7175                               EVT VT, const SDLoc &dl, SDValue Chain,
7176                               SDValue Ptr, SDValue Offset,
7177                               MachinePointerInfo PtrInfo, EVT MemVT,
7178                               Align Alignment,
7179                               MachineMemOperand::Flags MMOFlags,
7180                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7181   assert(Chain.getValueType() == MVT::Other &&
7182         "Invalid chain type");
7183 
7184   MMOFlags |= MachineMemOperand::MOLoad;
7185   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7186   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7187   // clients.
7188   if (PtrInfo.V.isNull())
7189     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7190 
7191   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7192   MachineFunction &MF = getMachineFunction();
7193   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7194                                                    Alignment, AAInfo, Ranges);
7195   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7196 }
7197 
7198 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7199                               EVT VT, const SDLoc &dl, SDValue Chain,
7200                               SDValue Ptr, SDValue Offset, EVT MemVT,
7201                               MachineMemOperand *MMO) {
7202   if (VT == MemVT) {
7203     ExtType = ISD::NON_EXTLOAD;
7204   } else if (ExtType == ISD::NON_EXTLOAD) {
7205     assert(VT == MemVT && "Non-extending load from different memory type!");
7206   } else {
7207     // Extending load.
7208     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7209            "Should only be an extending load, not truncating!");
7210     assert(VT.isInteger() == MemVT.isInteger() &&
7211            "Cannot convert from FP to Int or Int -> FP!");
7212     assert(VT.isVector() == MemVT.isVector() &&
7213            "Cannot use an ext load to convert to or from a vector!");
7214     assert((!VT.isVector() ||
7215             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7216            "Cannot use an ext load to change the number of vector elements!");
7217   }
7218 
7219   bool Indexed = AM != ISD::UNINDEXED;
7220   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7221 
7222   SDVTList VTs = Indexed ?
7223     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7224   SDValue Ops[] = { Chain, Ptr, Offset };
7225   FoldingSetNodeID ID;
7226   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7227   ID.AddInteger(MemVT.getRawBits());
7228   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7229       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7230   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7231   void *IP = nullptr;
7232   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7233     cast<LoadSDNode>(E)->refineAlignment(MMO);
7234     return SDValue(E, 0);
7235   }
7236   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7237                                   ExtType, MemVT, MMO);
7238   createOperands(N, Ops);
7239 
7240   CSEMap.InsertNode(N, IP);
7241   InsertNode(N);
7242   SDValue V(N, 0);
7243   NewSDValueDbgMsg(V, "Creating new node: ", this);
7244   return V;
7245 }
7246 
7247 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7248                               SDValue Ptr, MachinePointerInfo PtrInfo,
7249                               MaybeAlign Alignment,
7250                               MachineMemOperand::Flags MMOFlags,
7251                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7252   SDValue Undef = getUNDEF(Ptr.getValueType());
7253   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7254                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7255 }
7256 
7257 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7258                               SDValue Ptr, MachineMemOperand *MMO) {
7259   SDValue Undef = getUNDEF(Ptr.getValueType());
7260   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7261                  VT, MMO);
7262 }
7263 
7264 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7265                                  EVT VT, SDValue Chain, SDValue Ptr,
7266                                  MachinePointerInfo PtrInfo, EVT MemVT,
7267                                  MaybeAlign Alignment,
7268                                  MachineMemOperand::Flags MMOFlags,
7269                                  const AAMDNodes &AAInfo) {
7270   SDValue Undef = getUNDEF(Ptr.getValueType());
7271   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7272                  MemVT, Alignment, MMOFlags, AAInfo);
7273 }
7274 
7275 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7276                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7277                                  MachineMemOperand *MMO) {
7278   SDValue Undef = getUNDEF(Ptr.getValueType());
7279   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7280                  MemVT, MMO);
7281 }
7282 
7283 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7284                                      SDValue Base, SDValue Offset,
7285                                      ISD::MemIndexedMode AM) {
7286   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7287   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7288   // Don't propagate the invariant or dereferenceable flags.
7289   auto MMOFlags =
7290       LD->getMemOperand()->getFlags() &
7291       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7292   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7293                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7294                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7295 }
7296 
7297 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7298                                SDValue Ptr, MachinePointerInfo PtrInfo,
7299                                Align Alignment,
7300                                MachineMemOperand::Flags MMOFlags,
7301                                const AAMDNodes &AAInfo) {
7302   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7303 
7304   MMOFlags |= MachineMemOperand::MOStore;
7305   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7306 
7307   if (PtrInfo.V.isNull())
7308     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7309 
7310   MachineFunction &MF = getMachineFunction();
7311   uint64_t Size =
7312       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7313   MachineMemOperand *MMO =
7314       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7315   return getStore(Chain, dl, Val, Ptr, MMO);
7316 }
7317 
7318 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7319                                SDValue Ptr, MachineMemOperand *MMO) {
7320   assert(Chain.getValueType() == MVT::Other &&
7321         "Invalid chain type");
7322   EVT VT = Val.getValueType();
7323   SDVTList VTs = getVTList(MVT::Other);
7324   SDValue Undef = getUNDEF(Ptr.getValueType());
7325   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7326   FoldingSetNodeID ID;
7327   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7328   ID.AddInteger(VT.getRawBits());
7329   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7330       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7331   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7332   void *IP = nullptr;
7333   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7334     cast<StoreSDNode>(E)->refineAlignment(MMO);
7335     return SDValue(E, 0);
7336   }
7337   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7338                                    ISD::UNINDEXED, false, VT, MMO);
7339   createOperands(N, Ops);
7340 
7341   CSEMap.InsertNode(N, IP);
7342   InsertNode(N);
7343   SDValue V(N, 0);
7344   NewSDValueDbgMsg(V, "Creating new node: ", this);
7345   return V;
7346 }
7347 
7348 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7349                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7350                                     EVT SVT, Align Alignment,
7351                                     MachineMemOperand::Flags MMOFlags,
7352                                     const AAMDNodes &AAInfo) {
7353   assert(Chain.getValueType() == MVT::Other &&
7354         "Invalid chain type");
7355 
7356   MMOFlags |= MachineMemOperand::MOStore;
7357   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7358 
7359   if (PtrInfo.V.isNull())
7360     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7361 
7362   MachineFunction &MF = getMachineFunction();
7363   MachineMemOperand *MMO = MF.getMachineMemOperand(
7364       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7365       Alignment, AAInfo);
7366   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7367 }
7368 
7369 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7370                                     SDValue Ptr, EVT SVT,
7371                                     MachineMemOperand *MMO) {
7372   EVT VT = Val.getValueType();
7373 
7374   assert(Chain.getValueType() == MVT::Other &&
7375         "Invalid chain type");
7376   if (VT == SVT)
7377     return getStore(Chain, dl, Val, Ptr, MMO);
7378 
7379   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7380          "Should only be a truncating store, not extending!");
7381   assert(VT.isInteger() == SVT.isInteger() &&
7382          "Can't do FP-INT conversion!");
7383   assert(VT.isVector() == SVT.isVector() &&
7384          "Cannot use trunc store to convert to or from a vector!");
7385   assert((!VT.isVector() ||
7386           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7387          "Cannot use trunc store to change the number of vector elements!");
7388 
7389   SDVTList VTs = getVTList(MVT::Other);
7390   SDValue Undef = getUNDEF(Ptr.getValueType());
7391   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7392   FoldingSetNodeID ID;
7393   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7394   ID.AddInteger(SVT.getRawBits());
7395   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7396       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7397   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7398   void *IP = nullptr;
7399   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7400     cast<StoreSDNode>(E)->refineAlignment(MMO);
7401     return SDValue(E, 0);
7402   }
7403   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7404                                    ISD::UNINDEXED, true, SVT, MMO);
7405   createOperands(N, Ops);
7406 
7407   CSEMap.InsertNode(N, IP);
7408   InsertNode(N);
7409   SDValue V(N, 0);
7410   NewSDValueDbgMsg(V, "Creating new node: ", this);
7411   return V;
7412 }
7413 
7414 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7415                                       SDValue Base, SDValue Offset,
7416                                       ISD::MemIndexedMode AM) {
7417   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7418   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7419   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7420   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7421   FoldingSetNodeID ID;
7422   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7423   ID.AddInteger(ST->getMemoryVT().getRawBits());
7424   ID.AddInteger(ST->getRawSubclassData());
7425   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7426   void *IP = nullptr;
7427   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7428     return SDValue(E, 0);
7429 
7430   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7431                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7432                                    ST->getMemOperand());
7433   createOperands(N, Ops);
7434 
7435   CSEMap.InsertNode(N, IP);
7436   InsertNode(N);
7437   SDValue V(N, 0);
7438   NewSDValueDbgMsg(V, "Creating new node: ", this);
7439   return V;
7440 }
7441 
7442 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7443                                     SDValue Base, SDValue Offset, SDValue Mask,
7444                                     SDValue PassThru, EVT MemVT,
7445                                     MachineMemOperand *MMO,
7446                                     ISD::MemIndexedMode AM,
7447                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7448   bool Indexed = AM != ISD::UNINDEXED;
7449   assert((Indexed || Offset.isUndef()) &&
7450          "Unindexed masked load with an offset!");
7451   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
7452                          : getVTList(VT, MVT::Other);
7453   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
7454   FoldingSetNodeID ID;
7455   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
7456   ID.AddInteger(MemVT.getRawBits());
7457   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
7458       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
7459   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7460   void *IP = nullptr;
7461   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7462     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
7463     return SDValue(E, 0);
7464   }
7465   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7466                                         AM, ExtTy, isExpanding, MemVT, MMO);
7467   createOperands(N, Ops);
7468 
7469   CSEMap.InsertNode(N, IP);
7470   InsertNode(N);
7471   SDValue V(N, 0);
7472   NewSDValueDbgMsg(V, "Creating new node: ", this);
7473   return V;
7474 }
7475 
7476 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
7477                                            SDValue Base, SDValue Offset,
7478                                            ISD::MemIndexedMode AM) {
7479   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
7480   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
7481   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
7482                        Offset, LD->getMask(), LD->getPassThru(),
7483                        LD->getMemoryVT(), LD->getMemOperand(), AM,
7484                        LD->getExtensionType(), LD->isExpandingLoad());
7485 }
7486 
7487 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
7488                                      SDValue Val, SDValue Base, SDValue Offset,
7489                                      SDValue Mask, EVT MemVT,
7490                                      MachineMemOperand *MMO,
7491                                      ISD::MemIndexedMode AM, bool IsTruncating,
7492                                      bool IsCompressing) {
7493   assert(Chain.getValueType() == MVT::Other &&
7494         "Invalid chain type");
7495   bool Indexed = AM != ISD::UNINDEXED;
7496   assert((Indexed || Offset.isUndef()) &&
7497          "Unindexed masked store with an offset!");
7498   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
7499                          : getVTList(MVT::Other);
7500   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
7501   FoldingSetNodeID ID;
7502   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
7503   ID.AddInteger(MemVT.getRawBits());
7504   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
7505       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7506   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7507   void *IP = nullptr;
7508   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7509     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
7510     return SDValue(E, 0);
7511   }
7512   auto *N =
7513       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7514                                    IsTruncating, IsCompressing, MemVT, MMO);
7515   createOperands(N, Ops);
7516 
7517   CSEMap.InsertNode(N, IP);
7518   InsertNode(N);
7519   SDValue V(N, 0);
7520   NewSDValueDbgMsg(V, "Creating new node: ", this);
7521   return V;
7522 }
7523 
7524 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
7525                                             SDValue Base, SDValue Offset,
7526                                             ISD::MemIndexedMode AM) {
7527   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
7528   assert(ST->getOffset().isUndef() &&
7529          "Masked store is already a indexed store!");
7530   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
7531                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
7532                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
7533 }
7534 
7535 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
7536                                       ArrayRef<SDValue> Ops,
7537                                       MachineMemOperand *MMO,
7538                                       ISD::MemIndexType IndexType,
7539                                       ISD::LoadExtType ExtTy) {
7540   assert(Ops.size() == 6 && "Incompatible number of operands");
7541 
7542   FoldingSetNodeID ID;
7543   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7544   ID.AddInteger(VT.getRawBits());
7545   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7546       dl.getIROrder(), VTs, VT, MMO, IndexType, ExtTy));
7547   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7548   void *IP = nullptr;
7549   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7550     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7551     return SDValue(E, 0);
7552   }
7553 
7554   IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]);
7555   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7556                                           VTs, VT, MMO, IndexType, ExtTy);
7557   createOperands(N, Ops);
7558 
7559   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7560          "Incompatible type of the PassThru value in MaskedGatherSDNode");
7561   assert(N->getMask().getValueType().getVectorElementCount() ==
7562              N->getValueType(0).getVectorElementCount() &&
7563          "Vector width mismatch between mask and data");
7564   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7565              N->getValueType(0).getVectorElementCount().isScalable() &&
7566          "Scalable flags of index and data do not match");
7567   assert(ElementCount::isKnownGE(
7568              N->getIndex().getValueType().getVectorElementCount(),
7569              N->getValueType(0).getVectorElementCount()) &&
7570          "Vector width mismatch between index and data");
7571   assert(isa<ConstantSDNode>(N->getScale()) &&
7572          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7573          "Scale should be a constant power of 2");
7574 
7575   CSEMap.InsertNode(N, IP);
7576   InsertNode(N);
7577   SDValue V(N, 0);
7578   NewSDValueDbgMsg(V, "Creating new node: ", this);
7579   return V;
7580 }
7581 
7582 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
7583                                        ArrayRef<SDValue> Ops,
7584                                        MachineMemOperand *MMO,
7585                                        ISD::MemIndexType IndexType,
7586                                        bool IsTrunc) {
7587   assert(Ops.size() == 6 && "Incompatible number of operands");
7588 
7589   FoldingSetNodeID ID;
7590   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7591   ID.AddInteger(VT.getRawBits());
7592   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7593       dl.getIROrder(), VTs, VT, MMO, IndexType, IsTrunc));
7594   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7595   void *IP = nullptr;
7596   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7597     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7598     return SDValue(E, 0);
7599   }
7600 
7601   IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]);
7602   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7603                                            VTs, VT, MMO, IndexType, IsTrunc);
7604   createOperands(N, Ops);
7605 
7606   assert(N->getMask().getValueType().getVectorElementCount() ==
7607              N->getValue().getValueType().getVectorElementCount() &&
7608          "Vector width mismatch between mask and data");
7609   assert(
7610       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7611           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7612       "Scalable flags of index and data do not match");
7613   assert(ElementCount::isKnownGE(
7614              N->getIndex().getValueType().getVectorElementCount(),
7615              N->getValue().getValueType().getVectorElementCount()) &&
7616          "Vector width mismatch between index and data");
7617   assert(isa<ConstantSDNode>(N->getScale()) &&
7618          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7619          "Scale should be a constant power of 2");
7620 
7621   CSEMap.InsertNode(N, IP);
7622   InsertNode(N);
7623   SDValue V(N, 0);
7624   NewSDValueDbgMsg(V, "Creating new node: ", this);
7625   return V;
7626 }
7627 
7628 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7629   // select undef, T, F --> T (if T is a constant), otherwise F
7630   // select, ?, undef, F --> F
7631   // select, ?, T, undef --> T
7632   if (Cond.isUndef())
7633     return isConstantValueOfAnyType(T) ? T : F;
7634   if (T.isUndef())
7635     return F;
7636   if (F.isUndef())
7637     return T;
7638 
7639   // select true, T, F --> T
7640   // select false, T, F --> F
7641   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7642     return CondC->isNullValue() ? F : T;
7643 
7644   // TODO: This should simplify VSELECT with constant condition using something
7645   // like this (but check boolean contents to be complete?):
7646   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7647   //    return T;
7648   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7649   //    return F;
7650 
7651   // select ?, T, T --> T
7652   if (T == F)
7653     return T;
7654 
7655   return SDValue();
7656 }
7657 
7658 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7659   // shift undef, Y --> 0 (can always assume that the undef value is 0)
7660   if (X.isUndef())
7661     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7662   // shift X, undef --> undef (because it may shift by the bitwidth)
7663   if (Y.isUndef())
7664     return getUNDEF(X.getValueType());
7665 
7666   // shift 0, Y --> 0
7667   // shift X, 0 --> X
7668   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7669     return X;
7670 
7671   // shift X, C >= bitwidth(X) --> undef
7672   // All vector elements must be too big (or undef) to avoid partial undefs.
7673   auto isShiftTooBig = [X](ConstantSDNode *Val) {
7674     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7675   };
7676   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7677     return getUNDEF(X.getValueType());
7678 
7679   return SDValue();
7680 }
7681 
7682 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
7683                                       SDNodeFlags Flags) {
7684   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
7685   // (an undef operand can be chosen to be Nan/Inf), then the result of this
7686   // operation is poison. That result can be relaxed to undef.
7687   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
7688   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7689   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
7690                 (YC && YC->getValueAPF().isNaN());
7691   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
7692                 (YC && YC->getValueAPF().isInfinity());
7693 
7694   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
7695     return getUNDEF(X.getValueType());
7696 
7697   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
7698     return getUNDEF(X.getValueType());
7699 
7700   if (!YC)
7701     return SDValue();
7702 
7703   // X + -0.0 --> X
7704   if (Opcode == ISD::FADD)
7705     if (YC->getValueAPF().isNegZero())
7706       return X;
7707 
7708   // X - +0.0 --> X
7709   if (Opcode == ISD::FSUB)
7710     if (YC->getValueAPF().isPosZero())
7711       return X;
7712 
7713   // X * 1.0 --> X
7714   // X / 1.0 --> X
7715   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7716     if (YC->getValueAPF().isExactlyValue(1.0))
7717       return X;
7718 
7719   // X * 0.0 --> 0.0
7720   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
7721     if (YC->getValueAPF().isZero())
7722       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
7723 
7724   return SDValue();
7725 }
7726 
7727 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7728                                SDValue Ptr, SDValue SV, unsigned Align) {
7729   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7730   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7731 }
7732 
7733 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7734                               ArrayRef<SDUse> Ops) {
7735   switch (Ops.size()) {
7736   case 0: return getNode(Opcode, DL, VT);
7737   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7738   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7739   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7740   default: break;
7741   }
7742 
7743   // Copy from an SDUse array into an SDValue array for use with
7744   // the regular getNode logic.
7745   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7746   return getNode(Opcode, DL, VT, NewOps);
7747 }
7748 
7749 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7750                               ArrayRef<SDValue> Ops) {
7751   SDNodeFlags Flags;
7752   if (Inserter)
7753     Flags = Inserter->getFlags();
7754   return getNode(Opcode, DL, VT, Ops, Flags);
7755 }
7756 
7757 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7758                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7759   unsigned NumOps = Ops.size();
7760   switch (NumOps) {
7761   case 0: return getNode(Opcode, DL, VT);
7762   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7763   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7764   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7765   default: break;
7766   }
7767 
7768 #ifndef NDEBUG
7769   for (auto &Op : Ops)
7770     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7771            "Operand is DELETED_NODE!");
7772 #endif
7773 
7774   switch (Opcode) {
7775   default: break;
7776   case ISD::BUILD_VECTOR:
7777     // Attempt to simplify BUILD_VECTOR.
7778     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7779       return V;
7780     break;
7781   case ISD::CONCAT_VECTORS:
7782     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7783       return V;
7784     break;
7785   case ISD::SELECT_CC:
7786     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7787     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7788            "LHS and RHS of condition must have same type!");
7789     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7790            "True and False arms of SelectCC must have same type!");
7791     assert(Ops[2].getValueType() == VT &&
7792            "select_cc node must be of same type as true and false value!");
7793     break;
7794   case ISD::BR_CC:
7795     assert(NumOps == 5 && "BR_CC takes 5 operands!");
7796     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7797            "LHS/RHS of comparison should match types!");
7798     break;
7799   }
7800 
7801   // Memoize nodes.
7802   SDNode *N;
7803   SDVTList VTs = getVTList(VT);
7804 
7805   if (VT != MVT::Glue) {
7806     FoldingSetNodeID ID;
7807     AddNodeIDNode(ID, Opcode, VTs, Ops);
7808     void *IP = nullptr;
7809 
7810     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7811       return SDValue(E, 0);
7812 
7813     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7814     createOperands(N, Ops);
7815 
7816     CSEMap.InsertNode(N, IP);
7817   } else {
7818     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7819     createOperands(N, Ops);
7820   }
7821 
7822   N->setFlags(Flags);
7823   InsertNode(N);
7824   SDValue V(N, 0);
7825   NewSDValueDbgMsg(V, "Creating new node: ", this);
7826   return V;
7827 }
7828 
7829 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7830                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7831   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7832 }
7833 
7834 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7835                               ArrayRef<SDValue> Ops) {
7836   SDNodeFlags Flags;
7837   if (Inserter)
7838     Flags = Inserter->getFlags();
7839   return getNode(Opcode, DL, VTList, Ops, Flags);
7840 }
7841 
7842 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7843                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7844   if (VTList.NumVTs == 1)
7845     return getNode(Opcode, DL, VTList.VTs[0], Ops);
7846 
7847 #ifndef NDEBUG
7848   for (auto &Op : Ops)
7849     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7850            "Operand is DELETED_NODE!");
7851 #endif
7852 
7853   switch (Opcode) {
7854   case ISD::STRICT_FP_EXTEND:
7855     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
7856            "Invalid STRICT_FP_EXTEND!");
7857     assert(VTList.VTs[0].isFloatingPoint() &&
7858            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
7859     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7860            "STRICT_FP_EXTEND result type should be vector iff the operand "
7861            "type is vector!");
7862     assert((!VTList.VTs[0].isVector() ||
7863             VTList.VTs[0].getVectorNumElements() ==
7864             Ops[1].getValueType().getVectorNumElements()) &&
7865            "Vector element count mismatch!");
7866     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
7867            "Invalid fpext node, dst <= src!");
7868     break;
7869   case ISD::STRICT_FP_ROUND:
7870     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
7871     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7872            "STRICT_FP_ROUND result type should be vector iff the operand "
7873            "type is vector!");
7874     assert((!VTList.VTs[0].isVector() ||
7875             VTList.VTs[0].getVectorNumElements() ==
7876             Ops[1].getValueType().getVectorNumElements()) &&
7877            "Vector element count mismatch!");
7878     assert(VTList.VTs[0].isFloatingPoint() &&
7879            Ops[1].getValueType().isFloatingPoint() &&
7880            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
7881            isa<ConstantSDNode>(Ops[2]) &&
7882            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
7883             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
7884            "Invalid STRICT_FP_ROUND!");
7885     break;
7886 #if 0
7887   // FIXME: figure out how to safely handle things like
7888   // int foo(int x) { return 1 << (x & 255); }
7889   // int bar() { return foo(256); }
7890   case ISD::SRA_PARTS:
7891   case ISD::SRL_PARTS:
7892   case ISD::SHL_PARTS:
7893     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7894         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
7895       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7896     else if (N3.getOpcode() == ISD::AND)
7897       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
7898         // If the and is only masking out bits that cannot effect the shift,
7899         // eliminate the and.
7900         unsigned NumBits = VT.getScalarSizeInBits()*2;
7901         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
7902           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7903       }
7904     break;
7905 #endif
7906   }
7907 
7908   // Memoize the node unless it returns a flag.
7909   SDNode *N;
7910   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7911     FoldingSetNodeID ID;
7912     AddNodeIDNode(ID, Opcode, VTList, Ops);
7913     void *IP = nullptr;
7914     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7915       return SDValue(E, 0);
7916 
7917     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7918     createOperands(N, Ops);
7919     CSEMap.InsertNode(N, IP);
7920   } else {
7921     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7922     createOperands(N, Ops);
7923   }
7924 
7925   N->setFlags(Flags);
7926   InsertNode(N);
7927   SDValue V(N, 0);
7928   NewSDValueDbgMsg(V, "Creating new node: ", this);
7929   return V;
7930 }
7931 
7932 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7933                               SDVTList VTList) {
7934   return getNode(Opcode, DL, VTList, None);
7935 }
7936 
7937 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7938                               SDValue N1) {
7939   SDValue Ops[] = { N1 };
7940   return getNode(Opcode, DL, VTList, Ops);
7941 }
7942 
7943 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7944                               SDValue N1, SDValue N2) {
7945   SDValue Ops[] = { N1, N2 };
7946   return getNode(Opcode, DL, VTList, Ops);
7947 }
7948 
7949 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7950                               SDValue N1, SDValue N2, SDValue N3) {
7951   SDValue Ops[] = { N1, N2, N3 };
7952   return getNode(Opcode, DL, VTList, Ops);
7953 }
7954 
7955 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7956                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7957   SDValue Ops[] = { N1, N2, N3, N4 };
7958   return getNode(Opcode, DL, VTList, Ops);
7959 }
7960 
7961 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7962                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7963                               SDValue N5) {
7964   SDValue Ops[] = { N1, N2, N3, N4, N5 };
7965   return getNode(Opcode, DL, VTList, Ops);
7966 }
7967 
7968 SDVTList SelectionDAG::getVTList(EVT VT) {
7969   return makeVTList(SDNode::getValueTypeList(VT), 1);
7970 }
7971 
7972 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
7973   FoldingSetNodeID ID;
7974   ID.AddInteger(2U);
7975   ID.AddInteger(VT1.getRawBits());
7976   ID.AddInteger(VT2.getRawBits());
7977 
7978   void *IP = nullptr;
7979   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7980   if (!Result) {
7981     EVT *Array = Allocator.Allocate<EVT>(2);
7982     Array[0] = VT1;
7983     Array[1] = VT2;
7984     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
7985     VTListMap.InsertNode(Result, IP);
7986   }
7987   return Result->getSDVTList();
7988 }
7989 
7990 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
7991   FoldingSetNodeID ID;
7992   ID.AddInteger(3U);
7993   ID.AddInteger(VT1.getRawBits());
7994   ID.AddInteger(VT2.getRawBits());
7995   ID.AddInteger(VT3.getRawBits());
7996 
7997   void *IP = nullptr;
7998   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7999   if (!Result) {
8000     EVT *Array = Allocator.Allocate<EVT>(3);
8001     Array[0] = VT1;
8002     Array[1] = VT2;
8003     Array[2] = VT3;
8004     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8005     VTListMap.InsertNode(Result, IP);
8006   }
8007   return Result->getSDVTList();
8008 }
8009 
8010 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8011   FoldingSetNodeID ID;
8012   ID.AddInteger(4U);
8013   ID.AddInteger(VT1.getRawBits());
8014   ID.AddInteger(VT2.getRawBits());
8015   ID.AddInteger(VT3.getRawBits());
8016   ID.AddInteger(VT4.getRawBits());
8017 
8018   void *IP = nullptr;
8019   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8020   if (!Result) {
8021     EVT *Array = Allocator.Allocate<EVT>(4);
8022     Array[0] = VT1;
8023     Array[1] = VT2;
8024     Array[2] = VT3;
8025     Array[3] = VT4;
8026     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8027     VTListMap.InsertNode(Result, IP);
8028   }
8029   return Result->getSDVTList();
8030 }
8031 
8032 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8033   unsigned NumVTs = VTs.size();
8034   FoldingSetNodeID ID;
8035   ID.AddInteger(NumVTs);
8036   for (unsigned index = 0; index < NumVTs; index++) {
8037     ID.AddInteger(VTs[index].getRawBits());
8038   }
8039 
8040   void *IP = nullptr;
8041   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8042   if (!Result) {
8043     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8044     llvm::copy(VTs, Array);
8045     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8046     VTListMap.InsertNode(Result, IP);
8047   }
8048   return Result->getSDVTList();
8049 }
8050 
8051 
8052 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8053 /// specified operands.  If the resultant node already exists in the DAG,
8054 /// this does not modify the specified node, instead it returns the node that
8055 /// already exists.  If the resultant node does not exist in the DAG, the
8056 /// input node is returned.  As a degenerate case, if you specify the same
8057 /// input operands as the node already has, the input node is returned.
8058 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8059   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8060 
8061   // Check to see if there is no change.
8062   if (Op == N->getOperand(0)) return N;
8063 
8064   // See if the modified node already exists.
8065   void *InsertPos = nullptr;
8066   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8067     return Existing;
8068 
8069   // Nope it doesn't.  Remove the node from its current place in the maps.
8070   if (InsertPos)
8071     if (!RemoveNodeFromCSEMaps(N))
8072       InsertPos = nullptr;
8073 
8074   // Now we update the operands.
8075   N->OperandList[0].set(Op);
8076 
8077   updateDivergence(N);
8078   // If this gets put into a CSE map, add it.
8079   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8080   return N;
8081 }
8082 
8083 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8084   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8085 
8086   // Check to see if there is no change.
8087   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8088     return N;   // No operands changed, just return the input node.
8089 
8090   // See if the modified node already exists.
8091   void *InsertPos = nullptr;
8092   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8093     return Existing;
8094 
8095   // Nope it doesn't.  Remove the node from its current place in the maps.
8096   if (InsertPos)
8097     if (!RemoveNodeFromCSEMaps(N))
8098       InsertPos = nullptr;
8099 
8100   // Now we update the operands.
8101   if (N->OperandList[0] != Op1)
8102     N->OperandList[0].set(Op1);
8103   if (N->OperandList[1] != Op2)
8104     N->OperandList[1].set(Op2);
8105 
8106   updateDivergence(N);
8107   // If this gets put into a CSE map, add it.
8108   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8109   return N;
8110 }
8111 
8112 SDNode *SelectionDAG::
8113 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8114   SDValue Ops[] = { Op1, Op2, Op3 };
8115   return UpdateNodeOperands(N, Ops);
8116 }
8117 
8118 SDNode *SelectionDAG::
8119 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8120                    SDValue Op3, SDValue Op4) {
8121   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8122   return UpdateNodeOperands(N, Ops);
8123 }
8124 
8125 SDNode *SelectionDAG::
8126 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8127                    SDValue Op3, SDValue Op4, SDValue Op5) {
8128   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8129   return UpdateNodeOperands(N, Ops);
8130 }
8131 
8132 SDNode *SelectionDAG::
8133 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8134   unsigned NumOps = Ops.size();
8135   assert(N->getNumOperands() == NumOps &&
8136          "Update with wrong number of operands");
8137 
8138   // If no operands changed just return the input node.
8139   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8140     return N;
8141 
8142   // See if the modified node already exists.
8143   void *InsertPos = nullptr;
8144   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8145     return Existing;
8146 
8147   // Nope it doesn't.  Remove the node from its current place in the maps.
8148   if (InsertPos)
8149     if (!RemoveNodeFromCSEMaps(N))
8150       InsertPos = nullptr;
8151 
8152   // Now we update the operands.
8153   for (unsigned i = 0; i != NumOps; ++i)
8154     if (N->OperandList[i] != Ops[i])
8155       N->OperandList[i].set(Ops[i]);
8156 
8157   updateDivergence(N);
8158   // If this gets put into a CSE map, add it.
8159   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8160   return N;
8161 }
8162 
8163 /// DropOperands - Release the operands and set this node to have
8164 /// zero operands.
8165 void SDNode::DropOperands() {
8166   // Unlike the code in MorphNodeTo that does this, we don't need to
8167   // watch for dead nodes here.
8168   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8169     SDUse &Use = *I++;
8170     Use.set(SDValue());
8171   }
8172 }
8173 
8174 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8175                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8176   if (NewMemRefs.empty()) {
8177     N->clearMemRefs();
8178     return;
8179   }
8180 
8181   // Check if we can avoid allocating by storing a single reference directly.
8182   if (NewMemRefs.size() == 1) {
8183     N->MemRefs = NewMemRefs[0];
8184     N->NumMemRefs = 1;
8185     return;
8186   }
8187 
8188   MachineMemOperand **MemRefsBuffer =
8189       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8190   llvm::copy(NewMemRefs, MemRefsBuffer);
8191   N->MemRefs = MemRefsBuffer;
8192   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8193 }
8194 
8195 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8196 /// machine opcode.
8197 ///
8198 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8199                                    EVT VT) {
8200   SDVTList VTs = getVTList(VT);
8201   return SelectNodeTo(N, MachineOpc, VTs, None);
8202 }
8203 
8204 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8205                                    EVT VT, SDValue Op1) {
8206   SDVTList VTs = getVTList(VT);
8207   SDValue Ops[] = { Op1 };
8208   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8209 }
8210 
8211 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8212                                    EVT VT, SDValue Op1,
8213                                    SDValue Op2) {
8214   SDVTList VTs = getVTList(VT);
8215   SDValue Ops[] = { Op1, Op2 };
8216   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8217 }
8218 
8219 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8220                                    EVT VT, SDValue Op1,
8221                                    SDValue Op2, SDValue Op3) {
8222   SDVTList VTs = getVTList(VT);
8223   SDValue Ops[] = { Op1, Op2, Op3 };
8224   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8225 }
8226 
8227 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8228                                    EVT VT, ArrayRef<SDValue> Ops) {
8229   SDVTList VTs = getVTList(VT);
8230   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8231 }
8232 
8233 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8234                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8235   SDVTList VTs = getVTList(VT1, VT2);
8236   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8237 }
8238 
8239 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8240                                    EVT VT1, EVT VT2) {
8241   SDVTList VTs = getVTList(VT1, VT2);
8242   return SelectNodeTo(N, MachineOpc, VTs, None);
8243 }
8244 
8245 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8246                                    EVT VT1, EVT VT2, EVT VT3,
8247                                    ArrayRef<SDValue> Ops) {
8248   SDVTList VTs = getVTList(VT1, VT2, VT3);
8249   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8250 }
8251 
8252 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8253                                    EVT VT1, EVT VT2,
8254                                    SDValue Op1, SDValue Op2) {
8255   SDVTList VTs = getVTList(VT1, VT2);
8256   SDValue Ops[] = { Op1, Op2 };
8257   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8258 }
8259 
8260 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8261                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8262   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8263   // Reset the NodeID to -1.
8264   New->setNodeId(-1);
8265   if (New != N) {
8266     ReplaceAllUsesWith(N, New);
8267     RemoveDeadNode(N);
8268   }
8269   return New;
8270 }
8271 
8272 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8273 /// the line number information on the merged node since it is not possible to
8274 /// preserve the information that operation is associated with multiple lines.
8275 /// This will make the debugger working better at -O0, were there is a higher
8276 /// probability having other instructions associated with that line.
8277 ///
8278 /// For IROrder, we keep the smaller of the two
8279 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8280   DebugLoc NLoc = N->getDebugLoc();
8281   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8282     N->setDebugLoc(DebugLoc());
8283   }
8284   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8285   N->setIROrder(Order);
8286   return N;
8287 }
8288 
8289 /// MorphNodeTo - This *mutates* the specified node to have the specified
8290 /// return type, opcode, and operands.
8291 ///
8292 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8293 /// node of the specified opcode and operands, it returns that node instead of
8294 /// the current one.  Note that the SDLoc need not be the same.
8295 ///
8296 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8297 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8298 /// node, and because it doesn't require CSE recalculation for any of
8299 /// the node's users.
8300 ///
8301 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8302 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8303 /// the legalizer which maintain worklists that would need to be updated when
8304 /// deleting things.
8305 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8306                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8307   // If an identical node already exists, use it.
8308   void *IP = nullptr;
8309   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8310     FoldingSetNodeID ID;
8311     AddNodeIDNode(ID, Opc, VTs, Ops);
8312     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8313       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8314   }
8315 
8316   if (!RemoveNodeFromCSEMaps(N))
8317     IP = nullptr;
8318 
8319   // Start the morphing.
8320   N->NodeType = Opc;
8321   N->ValueList = VTs.VTs;
8322   N->NumValues = VTs.NumVTs;
8323 
8324   // Clear the operands list, updating used nodes to remove this from their
8325   // use list.  Keep track of any operands that become dead as a result.
8326   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8327   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8328     SDUse &Use = *I++;
8329     SDNode *Used = Use.getNode();
8330     Use.set(SDValue());
8331     if (Used->use_empty())
8332       DeadNodeSet.insert(Used);
8333   }
8334 
8335   // For MachineNode, initialize the memory references information.
8336   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8337     MN->clearMemRefs();
8338 
8339   // Swap for an appropriately sized array from the recycler.
8340   removeOperands(N);
8341   createOperands(N, Ops);
8342 
8343   // Delete any nodes that are still dead after adding the uses for the
8344   // new operands.
8345   if (!DeadNodeSet.empty()) {
8346     SmallVector<SDNode *, 16> DeadNodes;
8347     for (SDNode *N : DeadNodeSet)
8348       if (N->use_empty())
8349         DeadNodes.push_back(N);
8350     RemoveDeadNodes(DeadNodes);
8351   }
8352 
8353   if (IP)
8354     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8355   return N;
8356 }
8357 
8358 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8359   unsigned OrigOpc = Node->getOpcode();
8360   unsigned NewOpc;
8361   switch (OrigOpc) {
8362   default:
8363     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8364 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8365   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8366 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8367   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8368 #include "llvm/IR/ConstrainedOps.def"
8369   }
8370 
8371   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8372 
8373   // We're taking this node out of the chain, so we need to re-link things.
8374   SDValue InputChain = Node->getOperand(0);
8375   SDValue OutputChain = SDValue(Node, 1);
8376   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8377 
8378   SmallVector<SDValue, 3> Ops;
8379   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8380     Ops.push_back(Node->getOperand(i));
8381 
8382   SDVTList VTs = getVTList(Node->getValueType(0));
8383   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8384 
8385   // MorphNodeTo can operate in two ways: if an existing node with the
8386   // specified operands exists, it can just return it.  Otherwise, it
8387   // updates the node in place to have the requested operands.
8388   if (Res == Node) {
8389     // If we updated the node in place, reset the node ID.  To the isel,
8390     // this should be just like a newly allocated machine node.
8391     Res->setNodeId(-1);
8392   } else {
8393     ReplaceAllUsesWith(Node, Res);
8394     RemoveDeadNode(Node);
8395   }
8396 
8397   return Res;
8398 }
8399 
8400 /// getMachineNode - These are used for target selectors to create a new node
8401 /// with specified return type(s), MachineInstr opcode, and operands.
8402 ///
8403 /// Note that getMachineNode returns the resultant node.  If there is already a
8404 /// node of the specified opcode and operands, it returns that node instead of
8405 /// the current one.
8406 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8407                                             EVT VT) {
8408   SDVTList VTs = getVTList(VT);
8409   return getMachineNode(Opcode, dl, VTs, None);
8410 }
8411 
8412 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8413                                             EVT VT, SDValue Op1) {
8414   SDVTList VTs = getVTList(VT);
8415   SDValue Ops[] = { Op1 };
8416   return getMachineNode(Opcode, dl, VTs, Ops);
8417 }
8418 
8419 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8420                                             EVT VT, SDValue Op1, SDValue Op2) {
8421   SDVTList VTs = getVTList(VT);
8422   SDValue Ops[] = { Op1, Op2 };
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                                             SDValue Op3) {
8429   SDVTList VTs = getVTList(VT);
8430   SDValue Ops[] = { Op1, Op2, Op3 };
8431   return getMachineNode(Opcode, dl, VTs, Ops);
8432 }
8433 
8434 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8435                                             EVT VT, ArrayRef<SDValue> Ops) {
8436   SDVTList VTs = getVTList(VT);
8437   return getMachineNode(Opcode, dl, VTs, Ops);
8438 }
8439 
8440 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8441                                             EVT VT1, EVT VT2, SDValue Op1,
8442                                             SDValue Op2) {
8443   SDVTList VTs = getVTList(VT1, VT2);
8444   SDValue Ops[] = { Op1, Op2 };
8445   return getMachineNode(Opcode, dl, VTs, Ops);
8446 }
8447 
8448 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8449                                             EVT VT1, EVT VT2, SDValue Op1,
8450                                             SDValue Op2, SDValue Op3) {
8451   SDVTList VTs = getVTList(VT1, VT2);
8452   SDValue Ops[] = { Op1, Op2, Op3 };
8453   return getMachineNode(Opcode, dl, VTs, Ops);
8454 }
8455 
8456 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8457                                             EVT VT1, EVT VT2,
8458                                             ArrayRef<SDValue> Ops) {
8459   SDVTList VTs = getVTList(VT1, VT2);
8460   return getMachineNode(Opcode, dl, VTs, Ops);
8461 }
8462 
8463 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8464                                             EVT VT1, EVT VT2, EVT VT3,
8465                                             SDValue Op1, SDValue Op2) {
8466   SDVTList VTs = getVTList(VT1, VT2, VT3);
8467   SDValue Ops[] = { Op1, Op2 };
8468   return getMachineNode(Opcode, dl, VTs, Ops);
8469 }
8470 
8471 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8472                                             EVT VT1, EVT VT2, EVT VT3,
8473                                             SDValue Op1, SDValue Op2,
8474                                             SDValue Op3) {
8475   SDVTList VTs = getVTList(VT1, VT2, VT3);
8476   SDValue Ops[] = { Op1, Op2, Op3 };
8477   return getMachineNode(Opcode, dl, VTs, Ops);
8478 }
8479 
8480 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8481                                             EVT VT1, EVT VT2, EVT VT3,
8482                                             ArrayRef<SDValue> Ops) {
8483   SDVTList VTs = getVTList(VT1, VT2, VT3);
8484   return getMachineNode(Opcode, dl, VTs, Ops);
8485 }
8486 
8487 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8488                                             ArrayRef<EVT> ResultTys,
8489                                             ArrayRef<SDValue> Ops) {
8490   SDVTList VTs = getVTList(ResultTys);
8491   return getMachineNode(Opcode, dl, VTs, Ops);
8492 }
8493 
8494 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
8495                                             SDVTList VTs,
8496                                             ArrayRef<SDValue> Ops) {
8497   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
8498   MachineSDNode *N;
8499   void *IP = nullptr;
8500 
8501   if (DoCSE) {
8502     FoldingSetNodeID ID;
8503     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
8504     IP = nullptr;
8505     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8506       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
8507     }
8508   }
8509 
8510   // Allocate a new MachineSDNode.
8511   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8512   createOperands(N, Ops);
8513 
8514   if (DoCSE)
8515     CSEMap.InsertNode(N, IP);
8516 
8517   InsertNode(N);
8518   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
8519   return N;
8520 }
8521 
8522 /// getTargetExtractSubreg - A convenience function for creating
8523 /// TargetOpcode::EXTRACT_SUBREG nodes.
8524 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8525                                              SDValue Operand) {
8526   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8527   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
8528                                   VT, Operand, SRIdxVal);
8529   return SDValue(Subreg, 0);
8530 }
8531 
8532 /// getTargetInsertSubreg - A convenience function for creating
8533 /// TargetOpcode::INSERT_SUBREG nodes.
8534 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8535                                             SDValue Operand, SDValue Subreg) {
8536   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8537   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
8538                                   VT, Operand, Subreg, SRIdxVal);
8539   return SDValue(Result, 0);
8540 }
8541 
8542 /// getNodeIfExists - Get the specified node if it's already available, or
8543 /// else return NULL.
8544 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8545                                       ArrayRef<SDValue> Ops) {
8546   SDNodeFlags Flags;
8547   if (Inserter)
8548     Flags = Inserter->getFlags();
8549   return getNodeIfExists(Opcode, VTList, Ops, Flags);
8550 }
8551 
8552 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8553                                       ArrayRef<SDValue> Ops,
8554                                       const SDNodeFlags Flags) {
8555   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8556     FoldingSetNodeID ID;
8557     AddNodeIDNode(ID, Opcode, VTList, Ops);
8558     void *IP = nullptr;
8559     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
8560       E->intersectFlagsWith(Flags);
8561       return E;
8562     }
8563   }
8564   return nullptr;
8565 }
8566 
8567 /// doesNodeExist - Check if a node exists without modifying its flags.
8568 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
8569                                  ArrayRef<SDValue> Ops) {
8570   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8571     FoldingSetNodeID ID;
8572     AddNodeIDNode(ID, Opcode, VTList, Ops);
8573     void *IP = nullptr;
8574     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
8575       return true;
8576   }
8577   return false;
8578 }
8579 
8580 /// getDbgValue - Creates a SDDbgValue node.
8581 ///
8582 /// SDNode
8583 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
8584                                       SDNode *N, unsigned R, bool IsIndirect,
8585                                       const DebugLoc &DL, unsigned O) {
8586   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8587          "Expected inlined-at fields to agree");
8588   return new (DbgInfo->getAlloc())
8589       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
8590                  {}, IsIndirect, DL, O,
8591                  /*IsVariadic=*/false);
8592 }
8593 
8594 /// Constant
8595 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
8596                                               DIExpression *Expr,
8597                                               const Value *C,
8598                                               const DebugLoc &DL, unsigned O) {
8599   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8600          "Expected inlined-at fields to agree");
8601   return new (DbgInfo->getAlloc())
8602       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
8603                  /*IsIndirect=*/false, DL, O,
8604                  /*IsVariadic=*/false);
8605 }
8606 
8607 /// FrameIndex
8608 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8609                                                 DIExpression *Expr, unsigned FI,
8610                                                 bool IsIndirect,
8611                                                 const DebugLoc &DL,
8612                                                 unsigned O) {
8613   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8614          "Expected inlined-at fields to agree");
8615   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
8616 }
8617 
8618 /// FrameIndex with dependencies
8619 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8620                                                 DIExpression *Expr, unsigned FI,
8621                                                 ArrayRef<SDNode *> Dependencies,
8622                                                 bool IsIndirect,
8623                                                 const DebugLoc &DL,
8624                                                 unsigned O) {
8625   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8626          "Expected inlined-at fields to agree");
8627   return new (DbgInfo->getAlloc())
8628       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
8629                  Dependencies, IsIndirect, DL, O,
8630                  /*IsVariadic=*/false);
8631 }
8632 
8633 /// VReg
8634 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
8635                                           unsigned VReg, bool IsIndirect,
8636                                           const DebugLoc &DL, unsigned O) {
8637   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8638          "Expected inlined-at fields to agree");
8639   return new (DbgInfo->getAlloc())
8640       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
8641                  {}, IsIndirect, DL, O,
8642                  /*IsVariadic=*/false);
8643 }
8644 
8645 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
8646                                           ArrayRef<SDDbgOperand> Locs,
8647                                           ArrayRef<SDNode *> Dependencies,
8648                                           bool IsIndirect, const DebugLoc &DL,
8649                                           unsigned O, bool IsVariadic) {
8650   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8651          "Expected inlined-at fields to agree");
8652   return new (DbgInfo->getAlloc())
8653       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
8654                  DL, O, IsVariadic);
8655 }
8656 
8657 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8658                                      unsigned OffsetInBits, unsigned SizeInBits,
8659                                      bool InvalidateDbg) {
8660   SDNode *FromNode = From.getNode();
8661   SDNode *ToNode = To.getNode();
8662   assert(FromNode && ToNode && "Can't modify dbg values");
8663 
8664   // PR35338
8665   // TODO: assert(From != To && "Redundant dbg value transfer");
8666   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8667   if (From == To || FromNode == ToNode)
8668     return;
8669 
8670   if (!FromNode->getHasDebugValue())
8671     return;
8672 
8673   SDDbgOperand FromLocOp =
8674       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
8675   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
8676 
8677   SmallVector<SDDbgValue *, 2> ClonedDVs;
8678   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8679     if (Dbg->isInvalidated())
8680       continue;
8681 
8682     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8683 
8684     // Create a new location ops vector that is equal to the old vector, but
8685     // with each instance of FromLocOp replaced with ToLocOp.
8686     bool Changed = false;
8687     auto NewLocOps = Dbg->copyLocationOps();
8688     std::replace_if(
8689         NewLocOps.begin(), NewLocOps.end(),
8690         [&Changed, FromLocOp](const SDDbgOperand &Op) {
8691           bool Match = Op == FromLocOp;
8692           Changed |= Match;
8693           return Match;
8694         },
8695         ToLocOp);
8696     // Ignore this SDDbgValue if we didn't find a matching location.
8697     if (!Changed)
8698       continue;
8699 
8700     DIVariable *Var = Dbg->getVariable();
8701     auto *Expr = Dbg->getExpression();
8702     // If a fragment is requested, update the expression.
8703     if (SizeInBits) {
8704       // When splitting a larger (e.g., sign-extended) value whose
8705       // lower bits are described with an SDDbgValue, do not attempt
8706       // to transfer the SDDbgValue to the upper bits.
8707       if (auto FI = Expr->getFragmentInfo())
8708         if (OffsetInBits + SizeInBits > FI->SizeInBits)
8709           continue;
8710       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8711                                                              SizeInBits);
8712       if (!Fragment)
8713         continue;
8714       Expr = *Fragment;
8715     }
8716 
8717     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
8718     // Clone the SDDbgValue and move it to To.
8719     SDDbgValue *Clone = getDbgValueList(
8720         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
8721         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
8722         Dbg->isVariadic());
8723     ClonedDVs.push_back(Clone);
8724 
8725     if (InvalidateDbg) {
8726       // Invalidate value and indicate the SDDbgValue should not be emitted.
8727       Dbg->setIsInvalidated();
8728       Dbg->setIsEmitted();
8729     }
8730   }
8731 
8732   for (SDDbgValue *Dbg : ClonedDVs) {
8733     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
8734            "Transferred DbgValues should depend on the new SDNode");
8735     AddDbgValue(Dbg, false);
8736   }
8737 }
8738 
8739 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8740   if (!N.getHasDebugValue())
8741     return;
8742 
8743   SmallVector<SDDbgValue *, 2> ClonedDVs;
8744   for (auto DV : GetDbgValues(&N)) {
8745     if (DV->isInvalidated())
8746       continue;
8747     switch (N.getOpcode()) {
8748     default:
8749       break;
8750     case ISD::ADD:
8751       SDValue N0 = N.getOperand(0);
8752       SDValue N1 = N.getOperand(1);
8753       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8754           isConstantIntBuildVectorOrConstantInt(N1)) {
8755         uint64_t Offset = N.getConstantOperandVal(1);
8756 
8757         // Rewrite an ADD constant node into a DIExpression. Since we are
8758         // performing arithmetic to compute the variable's *value* in the
8759         // DIExpression, we need to mark the expression with a
8760         // DW_OP_stack_value.
8761         auto *DIExpr = DV->getExpression();
8762         auto NewLocOps = DV->copyLocationOps();
8763         bool Changed = false;
8764         for (size_t i = 0; i < NewLocOps.size(); ++i) {
8765           // We're not given a ResNo to compare against because the whole
8766           // node is going away. We know that any ISD::ADD only has one
8767           // result, so we can assume any node match is using the result.
8768           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
8769               NewLocOps[i].getSDNode() != &N)
8770             continue;
8771           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
8772           SmallVector<uint64_t, 3> ExprOps;
8773           DIExpression::appendOffset(ExprOps, Offset);
8774           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
8775           Changed = true;
8776         }
8777         (void)Changed;
8778         assert(Changed && "Salvage target doesn't use N");
8779 
8780         auto AdditionalDependencies = DV->getAdditionalDependencies();
8781         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
8782                                             NewLocOps, AdditionalDependencies,
8783                                             DV->isIndirect(), DV->getDebugLoc(),
8784                                             DV->getOrder(), DV->isVariadic());
8785         ClonedDVs.push_back(Clone);
8786         DV->setIsInvalidated();
8787         DV->setIsEmitted();
8788         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8789                    N0.getNode()->dumprFull(this);
8790                    dbgs() << " into " << *DIExpr << '\n');
8791       }
8792     }
8793   }
8794 
8795   for (SDDbgValue *Dbg : ClonedDVs) {
8796     assert(!Dbg->getSDNodes().empty() &&
8797            "Salvaged DbgValue should depend on a new SDNode");
8798     AddDbgValue(Dbg, false);
8799   }
8800 }
8801 
8802 /// Creates a SDDbgLabel node.
8803 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8804                                       const DebugLoc &DL, unsigned O) {
8805   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8806          "Expected inlined-at fields to agree");
8807   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8808 }
8809 
8810 namespace {
8811 
8812 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8813 /// pointed to by a use iterator is deleted, increment the use iterator
8814 /// so that it doesn't dangle.
8815 ///
8816 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8817   SDNode::use_iterator &UI;
8818   SDNode::use_iterator &UE;
8819 
8820   void NodeDeleted(SDNode *N, SDNode *E) override {
8821     // Increment the iterator as needed.
8822     while (UI != UE && N == *UI)
8823       ++UI;
8824   }
8825 
8826 public:
8827   RAUWUpdateListener(SelectionDAG &d,
8828                      SDNode::use_iterator &ui,
8829                      SDNode::use_iterator &ue)
8830     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8831 };
8832 
8833 } // end anonymous namespace
8834 
8835 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8836 /// This can cause recursive merging of nodes in the DAG.
8837 ///
8838 /// This version assumes From has a single result value.
8839 ///
8840 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8841   SDNode *From = FromN.getNode();
8842   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8843          "Cannot replace with this method!");
8844   assert(From != To.getNode() && "Cannot replace uses of with self");
8845 
8846   // Preserve Debug Values
8847   transferDbgValues(FromN, To);
8848 
8849   // Iterate over all the existing uses of From. New uses will be added
8850   // to the beginning of the use list, which we avoid visiting.
8851   // This specifically avoids visiting uses of From that arise while the
8852   // replacement is happening, because any such uses would be the result
8853   // of CSE: If an existing node looks like From after one of its operands
8854   // is replaced by To, we don't want to replace of all its users with To
8855   // too. See PR3018 for more info.
8856   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8857   RAUWUpdateListener Listener(*this, UI, UE);
8858   while (UI != UE) {
8859     SDNode *User = *UI;
8860 
8861     // This node is about to morph, remove its old self from the CSE maps.
8862     RemoveNodeFromCSEMaps(User);
8863 
8864     // A user can appear in a use list multiple times, and when this
8865     // happens the uses are usually next to each other in the list.
8866     // To help reduce the number of CSE recomputations, process all
8867     // the uses of this user that we can find this way.
8868     do {
8869       SDUse &Use = UI.getUse();
8870       ++UI;
8871       Use.set(To);
8872       if (To->isDivergent() != From->isDivergent())
8873         updateDivergence(User);
8874     } while (UI != UE && *UI == User);
8875     // Now that we have modified User, add it back to the CSE maps.  If it
8876     // already exists there, recursively merge the results together.
8877     AddModifiedNodeToCSEMaps(User);
8878   }
8879 
8880   // If we just RAUW'd the root, take note.
8881   if (FromN == getRoot())
8882     setRoot(To);
8883 }
8884 
8885 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8886 /// This can cause recursive merging of nodes in the DAG.
8887 ///
8888 /// This version assumes that for each value of From, there is a
8889 /// corresponding value in To in the same position with the same type.
8890 ///
8891 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
8892 #ifndef NDEBUG
8893   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8894     assert((!From->hasAnyUseOfValue(i) ||
8895             From->getValueType(i) == To->getValueType(i)) &&
8896            "Cannot use this version of ReplaceAllUsesWith!");
8897 #endif
8898 
8899   // Handle the trivial case.
8900   if (From == To)
8901     return;
8902 
8903   // Preserve Debug Info. Only do this if there's a use.
8904   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8905     if (From->hasAnyUseOfValue(i)) {
8906       assert((i < To->getNumValues()) && "Invalid To location");
8907       transferDbgValues(SDValue(From, i), SDValue(To, i));
8908     }
8909 
8910   // Iterate over just the existing users of From. See the comments in
8911   // the ReplaceAllUsesWith above.
8912   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8913   RAUWUpdateListener Listener(*this, UI, UE);
8914   while (UI != UE) {
8915     SDNode *User = *UI;
8916 
8917     // This node is about to morph, remove its old self from the CSE maps.
8918     RemoveNodeFromCSEMaps(User);
8919 
8920     // A user can appear in a use list multiple times, and when this
8921     // happens the uses are usually next to each other in the list.
8922     // To help reduce the number of CSE recomputations, process all
8923     // the uses of this user that we can find this way.
8924     do {
8925       SDUse &Use = UI.getUse();
8926       ++UI;
8927       Use.setNode(To);
8928       if (To->isDivergent() != From->isDivergent())
8929         updateDivergence(User);
8930     } while (UI != UE && *UI == User);
8931 
8932     // Now that we have modified User, add it back to the CSE maps.  If it
8933     // already exists there, recursively merge the results together.
8934     AddModifiedNodeToCSEMaps(User);
8935   }
8936 
8937   // If we just RAUW'd the root, take note.
8938   if (From == getRoot().getNode())
8939     setRoot(SDValue(To, getRoot().getResNo()));
8940 }
8941 
8942 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8943 /// This can cause recursive merging of nodes in the DAG.
8944 ///
8945 /// This version can replace From with any result values.  To must match the
8946 /// number and types of values returned by From.
8947 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
8948   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
8949     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
8950 
8951   // Preserve Debug Info.
8952   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8953     transferDbgValues(SDValue(From, i), To[i]);
8954 
8955   // Iterate over just the existing users of From. See the comments in
8956   // the ReplaceAllUsesWith above.
8957   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8958   RAUWUpdateListener Listener(*this, UI, UE);
8959   while (UI != UE) {
8960     SDNode *User = *UI;
8961 
8962     // This node is about to morph, remove its old self from the CSE maps.
8963     RemoveNodeFromCSEMaps(User);
8964 
8965     // A user can appear in a use list multiple times, and when this happens the
8966     // uses are usually next to each other in the list.  To help reduce the
8967     // number of CSE and divergence recomputations, process all the uses of this
8968     // user that we can find this way.
8969     bool To_IsDivergent = false;
8970     do {
8971       SDUse &Use = UI.getUse();
8972       const SDValue &ToOp = To[Use.getResNo()];
8973       ++UI;
8974       Use.set(ToOp);
8975       To_IsDivergent |= ToOp->isDivergent();
8976     } while (UI != UE && *UI == User);
8977 
8978     if (To_IsDivergent != From->isDivergent())
8979       updateDivergence(User);
8980 
8981     // Now that we have modified User, add it back to the CSE maps.  If it
8982     // already exists there, recursively merge the results together.
8983     AddModifiedNodeToCSEMaps(User);
8984   }
8985 
8986   // If we just RAUW'd the root, take note.
8987   if (From == getRoot().getNode())
8988     setRoot(SDValue(To[getRoot().getResNo()]));
8989 }
8990 
8991 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8992 /// uses of other values produced by From.getNode() alone.  The Deleted
8993 /// vector is handled the same way as for ReplaceAllUsesWith.
8994 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
8995   // Handle the really simple, really trivial case efficiently.
8996   if (From == To) return;
8997 
8998   // Handle the simple, trivial, case efficiently.
8999   if (From.getNode()->getNumValues() == 1) {
9000     ReplaceAllUsesWith(From, To);
9001     return;
9002   }
9003 
9004   // Preserve Debug Info.
9005   transferDbgValues(From, To);
9006 
9007   // Iterate over just the existing users of From. See the comments in
9008   // the ReplaceAllUsesWith above.
9009   SDNode::use_iterator UI = From.getNode()->use_begin(),
9010                        UE = From.getNode()->use_end();
9011   RAUWUpdateListener Listener(*this, UI, UE);
9012   while (UI != UE) {
9013     SDNode *User = *UI;
9014     bool UserRemovedFromCSEMaps = false;
9015 
9016     // A user can appear in a use list multiple times, and when this
9017     // happens the uses are usually next to each other in the list.
9018     // To help reduce the number of CSE recomputations, process all
9019     // the uses of this user that we can find this way.
9020     do {
9021       SDUse &Use = UI.getUse();
9022 
9023       // Skip uses of different values from the same node.
9024       if (Use.getResNo() != From.getResNo()) {
9025         ++UI;
9026         continue;
9027       }
9028 
9029       // If this node hasn't been modified yet, it's still in the CSE maps,
9030       // so remove its old self from the CSE maps.
9031       if (!UserRemovedFromCSEMaps) {
9032         RemoveNodeFromCSEMaps(User);
9033         UserRemovedFromCSEMaps = true;
9034       }
9035 
9036       ++UI;
9037       Use.set(To);
9038       if (To->isDivergent() != From->isDivergent())
9039         updateDivergence(User);
9040     } while (UI != UE && *UI == User);
9041     // We are iterating over all uses of the From node, so if a use
9042     // doesn't use the specific value, no changes are made.
9043     if (!UserRemovedFromCSEMaps)
9044       continue;
9045 
9046     // Now that we have modified User, add it back to the CSE maps.  If it
9047     // already exists there, recursively merge the results together.
9048     AddModifiedNodeToCSEMaps(User);
9049   }
9050 
9051   // If we just RAUW'd the root, take note.
9052   if (From == getRoot())
9053     setRoot(To);
9054 }
9055 
9056 namespace {
9057 
9058   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9059   /// to record information about a use.
9060   struct UseMemo {
9061     SDNode *User;
9062     unsigned Index;
9063     SDUse *Use;
9064   };
9065 
9066   /// operator< - Sort Memos by User.
9067   bool operator<(const UseMemo &L, const UseMemo &R) {
9068     return (intptr_t)L.User < (intptr_t)R.User;
9069   }
9070 
9071 } // end anonymous namespace
9072 
9073 bool SelectionDAG::calculateDivergence(SDNode *N) {
9074   if (TLI->isSDNodeAlwaysUniform(N)) {
9075     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9076            "Conflicting divergence information!");
9077     return false;
9078   }
9079   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9080     return true;
9081   for (auto &Op : N->ops()) {
9082     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9083       return true;
9084   }
9085   return false;
9086 }
9087 
9088 void SelectionDAG::updateDivergence(SDNode *N) {
9089   SmallVector<SDNode *, 16> Worklist(1, N);
9090   do {
9091     N = Worklist.pop_back_val();
9092     bool IsDivergent = calculateDivergence(N);
9093     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9094       N->SDNodeBits.IsDivergent = IsDivergent;
9095       llvm::append_range(Worklist, N->uses());
9096     }
9097   } while (!Worklist.empty());
9098 }
9099 
9100 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9101   DenseMap<SDNode *, unsigned> Degree;
9102   Order.reserve(AllNodes.size());
9103   for (auto &N : allnodes()) {
9104     unsigned NOps = N.getNumOperands();
9105     Degree[&N] = NOps;
9106     if (0 == NOps)
9107       Order.push_back(&N);
9108   }
9109   for (size_t I = 0; I != Order.size(); ++I) {
9110     SDNode *N = Order[I];
9111     for (auto U : N->uses()) {
9112       unsigned &UnsortedOps = Degree[U];
9113       if (0 == --UnsortedOps)
9114         Order.push_back(U);
9115     }
9116   }
9117 }
9118 
9119 #ifndef NDEBUG
9120 void SelectionDAG::VerifyDAGDiverence() {
9121   std::vector<SDNode *> TopoOrder;
9122   CreateTopologicalOrder(TopoOrder);
9123   for (auto *N : TopoOrder) {
9124     assert(calculateDivergence(N) == N->isDivergent() &&
9125            "Divergence bit inconsistency detected");
9126   }
9127 }
9128 #endif
9129 
9130 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9131 /// uses of other values produced by From.getNode() alone.  The same value
9132 /// may appear in both the From and To list.  The Deleted vector is
9133 /// handled the same way as for ReplaceAllUsesWith.
9134 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9135                                               const SDValue *To,
9136                                               unsigned Num){
9137   // Handle the simple, trivial case efficiently.
9138   if (Num == 1)
9139     return ReplaceAllUsesOfValueWith(*From, *To);
9140 
9141   transferDbgValues(*From, *To);
9142 
9143   // Read up all the uses and make records of them. This helps
9144   // processing new uses that are introduced during the
9145   // replacement process.
9146   SmallVector<UseMemo, 4> Uses;
9147   for (unsigned i = 0; i != Num; ++i) {
9148     unsigned FromResNo = From[i].getResNo();
9149     SDNode *FromNode = From[i].getNode();
9150     for (SDNode::use_iterator UI = FromNode->use_begin(),
9151          E = FromNode->use_end(); UI != E; ++UI) {
9152       SDUse &Use = UI.getUse();
9153       if (Use.getResNo() == FromResNo) {
9154         UseMemo Memo = { *UI, i, &Use };
9155         Uses.push_back(Memo);
9156       }
9157     }
9158   }
9159 
9160   // Sort the uses, so that all the uses from a given User are together.
9161   llvm::sort(Uses);
9162 
9163   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9164        UseIndex != UseIndexEnd; ) {
9165     // We know that this user uses some value of From.  If it is the right
9166     // value, update it.
9167     SDNode *User = Uses[UseIndex].User;
9168 
9169     // This node is about to morph, remove its old self from the CSE maps.
9170     RemoveNodeFromCSEMaps(User);
9171 
9172     // The Uses array is sorted, so all the uses for a given User
9173     // are next to each other in the list.
9174     // To help reduce the number of CSE recomputations, process all
9175     // the uses of this user that we can find this way.
9176     do {
9177       unsigned i = Uses[UseIndex].Index;
9178       SDUse &Use = *Uses[UseIndex].Use;
9179       ++UseIndex;
9180 
9181       Use.set(To[i]);
9182     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9183 
9184     // Now that we have modified User, add it back to the CSE maps.  If it
9185     // already exists there, recursively merge the results together.
9186     AddModifiedNodeToCSEMaps(User);
9187   }
9188 }
9189 
9190 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9191 /// based on their topological order. It returns the maximum id and a vector
9192 /// of the SDNodes* in assigned order by reference.
9193 unsigned SelectionDAG::AssignTopologicalOrder() {
9194   unsigned DAGSize = 0;
9195 
9196   // SortedPos tracks the progress of the algorithm. Nodes before it are
9197   // sorted, nodes after it are unsorted. When the algorithm completes
9198   // it is at the end of the list.
9199   allnodes_iterator SortedPos = allnodes_begin();
9200 
9201   // Visit all the nodes. Move nodes with no operands to the front of
9202   // the list immediately. Annotate nodes that do have operands with their
9203   // operand count. Before we do this, the Node Id fields of the nodes
9204   // may contain arbitrary values. After, the Node Id fields for nodes
9205   // before SortedPos will contain the topological sort index, and the
9206   // Node Id fields for nodes At SortedPos and after will contain the
9207   // count of outstanding operands.
9208   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
9209     SDNode *N = &*I++;
9210     checkForCycles(N, this);
9211     unsigned Degree = N->getNumOperands();
9212     if (Degree == 0) {
9213       // A node with no uses, add it to the result array immediately.
9214       N->setNodeId(DAGSize++);
9215       allnodes_iterator Q(N);
9216       if (Q != SortedPos)
9217         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9218       assert(SortedPos != AllNodes.end() && "Overran node list");
9219       ++SortedPos;
9220     } else {
9221       // Temporarily use the Node Id as scratch space for the degree count.
9222       N->setNodeId(Degree);
9223     }
9224   }
9225 
9226   // Visit all the nodes. As we iterate, move nodes into sorted order,
9227   // such that by the time the end is reached all nodes will be sorted.
9228   for (SDNode &Node : allnodes()) {
9229     SDNode *N = &Node;
9230     checkForCycles(N, this);
9231     // N is in sorted position, so all its uses have one less operand
9232     // that needs to be sorted.
9233     for (SDNode *P : N->uses()) {
9234       unsigned Degree = P->getNodeId();
9235       assert(Degree != 0 && "Invalid node degree");
9236       --Degree;
9237       if (Degree == 0) {
9238         // All of P's operands are sorted, so P may sorted now.
9239         P->setNodeId(DAGSize++);
9240         if (P->getIterator() != SortedPos)
9241           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9242         assert(SortedPos != AllNodes.end() && "Overran node list");
9243         ++SortedPos;
9244       } else {
9245         // Update P's outstanding operand count.
9246         P->setNodeId(Degree);
9247       }
9248     }
9249     if (Node.getIterator() == SortedPos) {
9250 #ifndef NDEBUG
9251       allnodes_iterator I(N);
9252       SDNode *S = &*++I;
9253       dbgs() << "Overran sorted position:\n";
9254       S->dumprFull(this); dbgs() << "\n";
9255       dbgs() << "Checking if this is due to cycles\n";
9256       checkForCycles(this, true);
9257 #endif
9258       llvm_unreachable(nullptr);
9259     }
9260   }
9261 
9262   assert(SortedPos == AllNodes.end() &&
9263          "Topological sort incomplete!");
9264   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9265          "First node in topological sort is not the entry token!");
9266   assert(AllNodes.front().getNodeId() == 0 &&
9267          "First node in topological sort has non-zero id!");
9268   assert(AllNodes.front().getNumOperands() == 0 &&
9269          "First node in topological sort has operands!");
9270   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9271          "Last node in topologic sort has unexpected id!");
9272   assert(AllNodes.back().use_empty() &&
9273          "Last node in topologic sort has users!");
9274   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9275   return DAGSize;
9276 }
9277 
9278 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9279 /// value is produced by SD.
9280 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9281   for (SDNode *SD : DB->getSDNodes()) {
9282     if (!SD)
9283       continue;
9284     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9285     SD->setHasDebugValue(true);
9286   }
9287   DbgInfo->add(DB, isParameter);
9288 }
9289 
9290 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9291 
9292 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9293                                                    SDValue NewMemOpChain) {
9294   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9295   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9296   // The new memory operation must have the same position as the old load in
9297   // terms of memory dependency. Create a TokenFactor for the old load and new
9298   // memory operation and update uses of the old load's output chain to use that
9299   // TokenFactor.
9300   if (OldChain == NewMemOpChain || OldChain.use_empty())
9301     return NewMemOpChain;
9302 
9303   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9304                                 OldChain, NewMemOpChain);
9305   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9306   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9307   return TokenFactor;
9308 }
9309 
9310 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9311                                                    SDValue NewMemOp) {
9312   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9313   SDValue OldChain = SDValue(OldLoad, 1);
9314   SDValue NewMemOpChain = NewMemOp.getValue(1);
9315   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9316 }
9317 
9318 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9319                                                      Function **OutFunction) {
9320   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9321 
9322   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9323   auto *Module = MF->getFunction().getParent();
9324   auto *Function = Module->getFunction(Symbol);
9325 
9326   if (OutFunction != nullptr)
9327       *OutFunction = Function;
9328 
9329   if (Function != nullptr) {
9330     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9331     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9332   }
9333 
9334   std::string ErrorStr;
9335   raw_string_ostream ErrorFormatter(ErrorStr);
9336 
9337   ErrorFormatter << "Undefined external symbol ";
9338   ErrorFormatter << '"' << Symbol << '"';
9339   ErrorFormatter.flush();
9340 
9341   report_fatal_error(ErrorStr);
9342 }
9343 
9344 //===----------------------------------------------------------------------===//
9345 //                              SDNode Class
9346 //===----------------------------------------------------------------------===//
9347 
9348 bool llvm::isNullConstant(SDValue V) {
9349   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9350   return Const != nullptr && Const->isNullValue();
9351 }
9352 
9353 bool llvm::isNullFPConstant(SDValue V) {
9354   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9355   return Const != nullptr && Const->isZero() && !Const->isNegative();
9356 }
9357 
9358 bool llvm::isAllOnesConstant(SDValue V) {
9359   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9360   return Const != nullptr && Const->isAllOnesValue();
9361 }
9362 
9363 bool llvm::isOneConstant(SDValue V) {
9364   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9365   return Const != nullptr && Const->isOne();
9366 }
9367 
9368 SDValue llvm::peekThroughBitcasts(SDValue V) {
9369   while (V.getOpcode() == ISD::BITCAST)
9370     V = V.getOperand(0);
9371   return V;
9372 }
9373 
9374 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9375   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9376     V = V.getOperand(0);
9377   return V;
9378 }
9379 
9380 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9381   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9382     V = V.getOperand(0);
9383   return V;
9384 }
9385 
9386 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9387   if (V.getOpcode() != ISD::XOR)
9388     return false;
9389   V = peekThroughBitcasts(V.getOperand(1));
9390   unsigned NumBits = V.getScalarValueSizeInBits();
9391   ConstantSDNode *C =
9392       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9393   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9394 }
9395 
9396 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9397                                           bool AllowTruncation) {
9398   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9399     return CN;
9400 
9401   // SplatVectors can truncate their operands. Ignore that case here unless
9402   // AllowTruncation is set.
9403   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9404     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9405     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9406       EVT CVT = CN->getValueType(0);
9407       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9408       if (AllowTruncation || CVT == VecEltVT)
9409         return CN;
9410     }
9411   }
9412 
9413   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9414     BitVector UndefElements;
9415     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9416 
9417     // BuildVectors can truncate their operands. Ignore that case here unless
9418     // AllowTruncation is set.
9419     if (CN && (UndefElements.none() || AllowUndefs)) {
9420       EVT CVT = CN->getValueType(0);
9421       EVT NSVT = N.getValueType().getScalarType();
9422       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9423       if (AllowTruncation || (CVT == NSVT))
9424         return CN;
9425     }
9426   }
9427 
9428   return nullptr;
9429 }
9430 
9431 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9432                                           bool AllowUndefs,
9433                                           bool AllowTruncation) {
9434   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9435     return CN;
9436 
9437   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9438     BitVector UndefElements;
9439     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9440 
9441     // BuildVectors can truncate their operands. Ignore that case here unless
9442     // AllowTruncation is set.
9443     if (CN && (UndefElements.none() || AllowUndefs)) {
9444       EVT CVT = CN->getValueType(0);
9445       EVT NSVT = N.getValueType().getScalarType();
9446       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9447       if (AllowTruncation || (CVT == NSVT))
9448         return CN;
9449     }
9450   }
9451 
9452   return nullptr;
9453 }
9454 
9455 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
9456   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9457     return CN;
9458 
9459   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9460     BitVector UndefElements;
9461     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
9462     if (CN && (UndefElements.none() || AllowUndefs))
9463       return CN;
9464   }
9465 
9466   if (N.getOpcode() == ISD::SPLAT_VECTOR)
9467     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
9468       return CN;
9469 
9470   return nullptr;
9471 }
9472 
9473 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
9474                                               const APInt &DemandedElts,
9475                                               bool AllowUndefs) {
9476   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9477     return CN;
9478 
9479   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9480     BitVector UndefElements;
9481     ConstantFPSDNode *CN =
9482         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
9483     if (CN && (UndefElements.none() || AllowUndefs))
9484       return CN;
9485   }
9486 
9487   return nullptr;
9488 }
9489 
9490 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
9491   // TODO: may want to use peekThroughBitcast() here.
9492   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9493   return C && C->isNullValue();
9494 }
9495 
9496 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
9497   // TODO: may want to use peekThroughBitcast() here.
9498   unsigned BitWidth = N.getScalarValueSizeInBits();
9499   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9500   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
9501 }
9502 
9503 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
9504   N = peekThroughBitcasts(N);
9505   unsigned BitWidth = N.getScalarValueSizeInBits();
9506   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9507   return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
9508 }
9509 
9510 HandleSDNode::~HandleSDNode() {
9511   DropOperands();
9512 }
9513 
9514 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
9515                                          const DebugLoc &DL,
9516                                          const GlobalValue *GA, EVT VT,
9517                                          int64_t o, unsigned TF)
9518     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
9519   TheGlobal = GA;
9520 }
9521 
9522 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
9523                                          EVT VT, unsigned SrcAS,
9524                                          unsigned DestAS)
9525     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
9526       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
9527 
9528 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
9529                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
9530     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
9531   MemSDNodeBits.IsVolatile = MMO->isVolatile();
9532   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
9533   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
9534   MemSDNodeBits.IsInvariant = MMO->isInvariant();
9535 
9536   // We check here that the size of the memory operand fits within the size of
9537   // the MMO. This is because the MMO might indicate only a possible address
9538   // range instead of specifying the affected memory addresses precisely.
9539   // TODO: Make MachineMemOperands aware of scalable vectors.
9540   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
9541          "Size mismatch!");
9542 }
9543 
9544 /// Profile - Gather unique data for the node.
9545 ///
9546 void SDNode::Profile(FoldingSetNodeID &ID) const {
9547   AddNodeIDNode(ID, this);
9548 }
9549 
9550 namespace {
9551 
9552   struct EVTArray {
9553     std::vector<EVT> VTs;
9554 
9555     EVTArray() {
9556       VTs.reserve(MVT::LAST_VALUETYPE);
9557       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
9558         VTs.push_back(MVT((MVT::SimpleValueType)i));
9559     }
9560   };
9561 
9562 } // end anonymous namespace
9563 
9564 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
9565 static ManagedStatic<EVTArray> SimpleVTArray;
9566 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
9567 
9568 /// getValueTypeList - Return a pointer to the specified value type.
9569 ///
9570 const EVT *SDNode::getValueTypeList(EVT VT) {
9571   if (VT.isExtended()) {
9572     sys::SmartScopedLock<true> Lock(*VTMutex);
9573     return &(*EVTs->insert(VT).first);
9574   } else {
9575     assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
9576            "Value type out of range!");
9577     return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
9578   }
9579 }
9580 
9581 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
9582 /// indicated value.  This method ignores uses of other values defined by this
9583 /// operation.
9584 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
9585   assert(Value < getNumValues() && "Bad value!");
9586 
9587   // TODO: Only iterate over uses of a given value of the node
9588   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
9589     if (UI.getUse().getResNo() == Value) {
9590       if (NUses == 0)
9591         return false;
9592       --NUses;
9593     }
9594   }
9595 
9596   // Found exactly the right number of uses?
9597   return NUses == 0;
9598 }
9599 
9600 /// hasAnyUseOfValue - Return true if there are any use of the indicated
9601 /// value. This method ignores uses of other values defined by this operation.
9602 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
9603   assert(Value < getNumValues() && "Bad value!");
9604 
9605   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
9606     if (UI.getUse().getResNo() == Value)
9607       return true;
9608 
9609   return false;
9610 }
9611 
9612 /// isOnlyUserOf - Return true if this node is the only use of N.
9613 bool SDNode::isOnlyUserOf(const SDNode *N) const {
9614   bool Seen = false;
9615   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9616     SDNode *User = *I;
9617     if (User == this)
9618       Seen = true;
9619     else
9620       return false;
9621   }
9622 
9623   return Seen;
9624 }
9625 
9626 /// Return true if the only users of N are contained in Nodes.
9627 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
9628   bool Seen = false;
9629   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9630     SDNode *User = *I;
9631     if (llvm::is_contained(Nodes, User))
9632       Seen = true;
9633     else
9634       return false;
9635   }
9636 
9637   return Seen;
9638 }
9639 
9640 /// isOperand - Return true if this node is an operand of N.
9641 bool SDValue::isOperandOf(const SDNode *N) const {
9642   return is_contained(N->op_values(), *this);
9643 }
9644 
9645 bool SDNode::isOperandOf(const SDNode *N) const {
9646   return any_of(N->op_values(),
9647                 [this](SDValue Op) { return this == Op.getNode(); });
9648 }
9649 
9650 /// reachesChainWithoutSideEffects - Return true if this operand (which must
9651 /// be a chain) reaches the specified operand without crossing any
9652 /// side-effecting instructions on any chain path.  In practice, this looks
9653 /// through token factors and non-volatile loads.  In order to remain efficient,
9654 /// this only looks a couple of nodes in, it does not do an exhaustive search.
9655 ///
9656 /// Note that we only need to examine chains when we're searching for
9657 /// side-effects; SelectionDAG requires that all side-effects are represented
9658 /// by chains, even if another operand would force a specific ordering. This
9659 /// constraint is necessary to allow transformations like splitting loads.
9660 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
9661                                              unsigned Depth) const {
9662   if (*this == Dest) return true;
9663 
9664   // Don't search too deeply, we just want to be able to see through
9665   // TokenFactor's etc.
9666   if (Depth == 0) return false;
9667 
9668   // If this is a token factor, all inputs to the TF happen in parallel.
9669   if (getOpcode() == ISD::TokenFactor) {
9670     // First, try a shallow search.
9671     if (is_contained((*this)->ops(), Dest)) {
9672       // We found the chain we want as an operand of this TokenFactor.
9673       // Essentially, we reach the chain without side-effects if we could
9674       // serialize the TokenFactor into a simple chain of operations with
9675       // Dest as the last operation. This is automatically true if the
9676       // chain has one use: there are no other ordering constraints.
9677       // If the chain has more than one use, we give up: some other
9678       // use of Dest might force a side-effect between Dest and the current
9679       // node.
9680       if (Dest.hasOneUse())
9681         return true;
9682     }
9683     // Next, try a deep search: check whether every operand of the TokenFactor
9684     // reaches Dest.
9685     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
9686       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
9687     });
9688   }
9689 
9690   // Loads don't have side effects, look through them.
9691   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
9692     if (Ld->isUnordered())
9693       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
9694   }
9695   return false;
9696 }
9697 
9698 bool SDNode::hasPredecessor(const SDNode *N) const {
9699   SmallPtrSet<const SDNode *, 32> Visited;
9700   SmallVector<const SDNode *, 16> Worklist;
9701   Worklist.push_back(this);
9702   return hasPredecessorHelper(N, Visited, Worklist);
9703 }
9704 
9705 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
9706   this->Flags.intersectWith(Flags);
9707 }
9708 
9709 SDValue
9710 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
9711                                   ArrayRef<ISD::NodeType> CandidateBinOps,
9712                                   bool AllowPartials) {
9713   // The pattern must end in an extract from index 0.
9714   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9715       !isNullConstant(Extract->getOperand(1)))
9716     return SDValue();
9717 
9718   // Match against one of the candidate binary ops.
9719   SDValue Op = Extract->getOperand(0);
9720   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9721         return Op.getOpcode() == unsigned(BinOp);
9722       }))
9723     return SDValue();
9724 
9725   // Floating-point reductions may require relaxed constraints on the final step
9726   // of the reduction because they may reorder intermediate operations.
9727   unsigned CandidateBinOp = Op.getOpcode();
9728   if (Op.getValueType().isFloatingPoint()) {
9729     SDNodeFlags Flags = Op->getFlags();
9730     switch (CandidateBinOp) {
9731     case ISD::FADD:
9732       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
9733         return SDValue();
9734       break;
9735     default:
9736       llvm_unreachable("Unhandled FP opcode for binop reduction");
9737     }
9738   }
9739 
9740   // Matching failed - attempt to see if we did enough stages that a partial
9741   // reduction from a subvector is possible.
9742   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
9743     if (!AllowPartials || !Op)
9744       return SDValue();
9745     EVT OpVT = Op.getValueType();
9746     EVT OpSVT = OpVT.getScalarType();
9747     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
9748     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
9749       return SDValue();
9750     BinOp = (ISD::NodeType)CandidateBinOp;
9751     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
9752                    getVectorIdxConstant(0, SDLoc(Op)));
9753   };
9754 
9755   // At each stage, we're looking for something that looks like:
9756   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9757   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9758   //                               i32 undef, i32 undef, i32 undef, i32 undef>
9759   // %a = binop <8 x i32> %op, %s
9760   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9761   // we expect something like:
9762   // <4,5,6,7,u,u,u,u>
9763   // <2,3,u,u,u,u,u,u>
9764   // <1,u,u,u,u,u,u,u>
9765   // While a partial reduction match would be:
9766   // <2,3,u,u,u,u,u,u>
9767   // <1,u,u,u,u,u,u,u>
9768   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9769   SDValue PrevOp;
9770   for (unsigned i = 0; i < Stages; ++i) {
9771     unsigned MaskEnd = (1 << i);
9772 
9773     if (Op.getOpcode() != CandidateBinOp)
9774       return PartialReduction(PrevOp, MaskEnd);
9775 
9776     SDValue Op0 = Op.getOperand(0);
9777     SDValue Op1 = Op.getOperand(1);
9778 
9779     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9780     if (Shuffle) {
9781       Op = Op1;
9782     } else {
9783       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9784       Op = Op0;
9785     }
9786 
9787     // The first operand of the shuffle should be the same as the other operand
9788     // of the binop.
9789     if (!Shuffle || Shuffle->getOperand(0) != Op)
9790       return PartialReduction(PrevOp, MaskEnd);
9791 
9792     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9793     for (int Index = 0; Index < (int)MaskEnd; ++Index)
9794       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
9795         return PartialReduction(PrevOp, MaskEnd);
9796 
9797     PrevOp = Op;
9798   }
9799 
9800   // Handle subvector reductions, which tend to appear after the shuffle
9801   // reduction stages.
9802   while (Op.getOpcode() == CandidateBinOp) {
9803     unsigned NumElts = Op.getValueType().getVectorNumElements();
9804     SDValue Op0 = Op.getOperand(0);
9805     SDValue Op1 = Op.getOperand(1);
9806     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9807         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9808         Op0.getOperand(0) != Op1.getOperand(0))
9809       break;
9810     SDValue Src = Op0.getOperand(0);
9811     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
9812     if (NumSrcElts != (2 * NumElts))
9813       break;
9814     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
9815           Op1.getConstantOperandAPInt(1) == NumElts) &&
9816         !(Op1.getConstantOperandAPInt(1) == 0 &&
9817           Op0.getConstantOperandAPInt(1) == NumElts))
9818       break;
9819     Op = Src;
9820   }
9821 
9822   BinOp = (ISD::NodeType)CandidateBinOp;
9823   return Op;
9824 }
9825 
9826 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9827   assert(N->getNumValues() == 1 &&
9828          "Can't unroll a vector with multiple results!");
9829 
9830   EVT VT = N->getValueType(0);
9831   unsigned NE = VT.getVectorNumElements();
9832   EVT EltVT = VT.getVectorElementType();
9833   SDLoc dl(N);
9834 
9835   SmallVector<SDValue, 8> Scalars;
9836   SmallVector<SDValue, 4> Operands(N->getNumOperands());
9837 
9838   // If ResNE is 0, fully unroll the vector op.
9839   if (ResNE == 0)
9840     ResNE = NE;
9841   else if (NE > ResNE)
9842     NE = ResNE;
9843 
9844   unsigned i;
9845   for (i= 0; i != NE; ++i) {
9846     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9847       SDValue Operand = N->getOperand(j);
9848       EVT OperandVT = Operand.getValueType();
9849       if (OperandVT.isVector()) {
9850         // A vector operand; extract a single element.
9851         EVT OperandEltVT = OperandVT.getVectorElementType();
9852         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
9853                               Operand, getVectorIdxConstant(i, dl));
9854       } else {
9855         // A scalar operand; just use it as is.
9856         Operands[j] = Operand;
9857       }
9858     }
9859 
9860     switch (N->getOpcode()) {
9861     default: {
9862       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9863                                 N->getFlags()));
9864       break;
9865     }
9866     case ISD::VSELECT:
9867       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
9868       break;
9869     case ISD::SHL:
9870     case ISD::SRA:
9871     case ISD::SRL:
9872     case ISD::ROTL:
9873     case ISD::ROTR:
9874       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
9875                                getShiftAmountOperand(Operands[0].getValueType(),
9876                                                      Operands[1])));
9877       break;
9878     case ISD::SIGN_EXTEND_INREG: {
9879       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
9880       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
9881                                 Operands[0],
9882                                 getValueType(ExtVT)));
9883     }
9884     }
9885   }
9886 
9887   for (; i < ResNE; ++i)
9888     Scalars.push_back(getUNDEF(EltVT));
9889 
9890   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
9891   return getBuildVector(VecVT, dl, Scalars);
9892 }
9893 
9894 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
9895     SDNode *N, unsigned ResNE) {
9896   unsigned Opcode = N->getOpcode();
9897   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
9898           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
9899           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
9900          "Expected an overflow opcode");
9901 
9902   EVT ResVT = N->getValueType(0);
9903   EVT OvVT = N->getValueType(1);
9904   EVT ResEltVT = ResVT.getVectorElementType();
9905   EVT OvEltVT = OvVT.getVectorElementType();
9906   SDLoc dl(N);
9907 
9908   // If ResNE is 0, fully unroll the vector op.
9909   unsigned NE = ResVT.getVectorNumElements();
9910   if (ResNE == 0)
9911     ResNE = NE;
9912   else if (NE > ResNE)
9913     NE = ResNE;
9914 
9915   SmallVector<SDValue, 8> LHSScalars;
9916   SmallVector<SDValue, 8> RHSScalars;
9917   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
9918   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
9919 
9920   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
9921   SDVTList VTs = getVTList(ResEltVT, SVT);
9922   SmallVector<SDValue, 8> ResScalars;
9923   SmallVector<SDValue, 8> OvScalars;
9924   for (unsigned i = 0; i < NE; ++i) {
9925     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
9926     SDValue Ov =
9927         getSelect(dl, OvEltVT, Res.getValue(1),
9928                   getBoolConstant(true, dl, OvEltVT, ResVT),
9929                   getConstant(0, dl, OvEltVT));
9930 
9931     ResScalars.push_back(Res);
9932     OvScalars.push_back(Ov);
9933   }
9934 
9935   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
9936   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
9937 
9938   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
9939   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
9940   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
9941                         getBuildVector(NewOvVT, dl, OvScalars));
9942 }
9943 
9944 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
9945                                                   LoadSDNode *Base,
9946                                                   unsigned Bytes,
9947                                                   int Dist) const {
9948   if (LD->isVolatile() || Base->isVolatile())
9949     return false;
9950   // TODO: probably too restrictive for atomics, revisit
9951   if (!LD->isSimple())
9952     return false;
9953   if (LD->isIndexed() || Base->isIndexed())
9954     return false;
9955   if (LD->getChain() != Base->getChain())
9956     return false;
9957   EVT VT = LD->getValueType(0);
9958   if (VT.getSizeInBits() / 8 != Bytes)
9959     return false;
9960 
9961   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
9962   auto LocDecomp = BaseIndexOffset::match(LD, *this);
9963 
9964   int64_t Offset = 0;
9965   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
9966     return (Dist * Bytes == Offset);
9967   return false;
9968 }
9969 
9970 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
9971 /// if it cannot be inferred.
9972 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
9973   // If this is a GlobalAddress + cst, return the alignment.
9974   const GlobalValue *GV = nullptr;
9975   int64_t GVOffset = 0;
9976   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
9977     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
9978     KnownBits Known(PtrWidth);
9979     llvm::computeKnownBits(GV, Known, getDataLayout());
9980     unsigned AlignBits = Known.countMinTrailingZeros();
9981     if (AlignBits)
9982       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
9983   }
9984 
9985   // If this is a direct reference to a stack slot, use information about the
9986   // stack slot's alignment.
9987   int FrameIdx = INT_MIN;
9988   int64_t FrameOffset = 0;
9989   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
9990     FrameIdx = FI->getIndex();
9991   } else if (isBaseWithConstantOffset(Ptr) &&
9992              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
9993     // Handle FI+Cst
9994     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9995     FrameOffset = Ptr.getConstantOperandVal(1);
9996   }
9997 
9998   if (FrameIdx != INT_MIN) {
9999     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10000     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10001   }
10002 
10003   return None;
10004 }
10005 
10006 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10007 /// which is split (or expanded) into two not necessarily identical pieces.
10008 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10009   // Currently all types are split in half.
10010   EVT LoVT, HiVT;
10011   if (!VT.isVector())
10012     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10013   else
10014     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10015 
10016   return std::make_pair(LoVT, HiVT);
10017 }
10018 
10019 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10020 /// type, dependent on an enveloping VT that has been split into two identical
10021 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10022 std::pair<EVT, EVT>
10023 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10024                                        bool *HiIsEmpty) const {
10025   EVT EltTp = VT.getVectorElementType();
10026   // Examples:
10027   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10028   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10029   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10030   //   etc.
10031   ElementCount VTNumElts = VT.getVectorElementCount();
10032   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10033   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10034          "Mixing fixed width and scalable vectors when enveloping a type");
10035   EVT LoVT, HiVT;
10036   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10037     LoVT = EnvVT;
10038     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10039     *HiIsEmpty = false;
10040   } else {
10041     // Flag that hi type has zero storage size, but return split envelop type
10042     // (this would be easier if vector types with zero elements were allowed).
10043     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10044     HiVT = EnvVT;
10045     *HiIsEmpty = true;
10046   }
10047   return std::make_pair(LoVT, HiVT);
10048 }
10049 
10050 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10051 /// low/high part.
10052 std::pair<SDValue, SDValue>
10053 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10054                           const EVT &HiVT) {
10055   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10056          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10057          "Splitting vector with an invalid mixture of fixed and scalable "
10058          "vector types");
10059   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10060              N.getValueType().getVectorMinNumElements() &&
10061          "More vector elements requested than available!");
10062   SDValue Lo, Hi;
10063   Lo =
10064       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10065   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10066   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10067   // IDX with the runtime scaling factor of the result vector type. For
10068   // fixed-width result vectors, that runtime scaling factor is 1.
10069   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10070                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10071   return std::make_pair(Lo, Hi);
10072 }
10073 
10074 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10075 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10076   EVT VT = N.getValueType();
10077   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10078                                 NextPowerOf2(VT.getVectorNumElements()));
10079   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10080                  getVectorIdxConstant(0, DL));
10081 }
10082 
10083 void SelectionDAG::ExtractVectorElements(SDValue Op,
10084                                          SmallVectorImpl<SDValue> &Args,
10085                                          unsigned Start, unsigned Count,
10086                                          EVT EltVT) {
10087   EVT VT = Op.getValueType();
10088   if (Count == 0)
10089     Count = VT.getVectorNumElements();
10090   if (EltVT == EVT())
10091     EltVT = VT.getVectorElementType();
10092   SDLoc SL(Op);
10093   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10094     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10095                            getVectorIdxConstant(i, SL)));
10096   }
10097 }
10098 
10099 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10100 unsigned GlobalAddressSDNode::getAddressSpace() const {
10101   return getGlobal()->getType()->getAddressSpace();
10102 }
10103 
10104 Type *ConstantPoolSDNode::getType() const {
10105   if (isMachineConstantPoolEntry())
10106     return Val.MachineCPVal->getType();
10107   return Val.ConstVal->getType();
10108 }
10109 
10110 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10111                                         unsigned &SplatBitSize,
10112                                         bool &HasAnyUndefs,
10113                                         unsigned MinSplatBits,
10114                                         bool IsBigEndian) const {
10115   EVT VT = getValueType(0);
10116   assert(VT.isVector() && "Expected a vector type");
10117   unsigned VecWidth = VT.getSizeInBits();
10118   if (MinSplatBits > VecWidth)
10119     return false;
10120 
10121   // FIXME: The widths are based on this node's type, but build vectors can
10122   // truncate their operands.
10123   SplatValue = APInt(VecWidth, 0);
10124   SplatUndef = APInt(VecWidth, 0);
10125 
10126   // Get the bits. Bits with undefined values (when the corresponding element
10127   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10128   // in SplatValue. If any of the values are not constant, give up and return
10129   // false.
10130   unsigned int NumOps = getNumOperands();
10131   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10132   unsigned EltWidth = VT.getScalarSizeInBits();
10133 
10134   for (unsigned j = 0; j < NumOps; ++j) {
10135     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10136     SDValue OpVal = getOperand(i);
10137     unsigned BitPos = j * EltWidth;
10138 
10139     if (OpVal.isUndef())
10140       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10141     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10142       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10143     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10144       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10145     else
10146       return false;
10147   }
10148 
10149   // The build_vector is all constants or undefs. Find the smallest element
10150   // size that splats the vector.
10151   HasAnyUndefs = (SplatUndef != 0);
10152 
10153   // FIXME: This does not work for vectors with elements less than 8 bits.
10154   while (VecWidth > 8) {
10155     unsigned HalfSize = VecWidth / 2;
10156     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
10157     APInt LowValue = SplatValue.trunc(HalfSize);
10158     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
10159     APInt LowUndef = SplatUndef.trunc(HalfSize);
10160 
10161     // If the two halves do not match (ignoring undef bits), stop here.
10162     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10163         MinSplatBits > HalfSize)
10164       break;
10165 
10166     SplatValue = HighValue | LowValue;
10167     SplatUndef = HighUndef & LowUndef;
10168 
10169     VecWidth = HalfSize;
10170   }
10171 
10172   SplatBitSize = VecWidth;
10173   return true;
10174 }
10175 
10176 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10177                                          BitVector *UndefElements) const {
10178   unsigned NumOps = getNumOperands();
10179   if (UndefElements) {
10180     UndefElements->clear();
10181     UndefElements->resize(NumOps);
10182   }
10183   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10184   if (!DemandedElts)
10185     return SDValue();
10186   SDValue Splatted;
10187   for (unsigned i = 0; i != NumOps; ++i) {
10188     if (!DemandedElts[i])
10189       continue;
10190     SDValue Op = getOperand(i);
10191     if (Op.isUndef()) {
10192       if (UndefElements)
10193         (*UndefElements)[i] = true;
10194     } else if (!Splatted) {
10195       Splatted = Op;
10196     } else if (Splatted != Op) {
10197       return SDValue();
10198     }
10199   }
10200 
10201   if (!Splatted) {
10202     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10203     assert(getOperand(FirstDemandedIdx).isUndef() &&
10204            "Can only have a splat without a constant for all undefs.");
10205     return getOperand(FirstDemandedIdx);
10206   }
10207 
10208   return Splatted;
10209 }
10210 
10211 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10212   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10213   return getSplatValue(DemandedElts, UndefElements);
10214 }
10215 
10216 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10217                                             SmallVectorImpl<SDValue> &Sequence,
10218                                             BitVector *UndefElements) const {
10219   unsigned NumOps = getNumOperands();
10220   Sequence.clear();
10221   if (UndefElements) {
10222     UndefElements->clear();
10223     UndefElements->resize(NumOps);
10224   }
10225   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10226   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10227     return false;
10228 
10229   // Set the undefs even if we don't find a sequence (like getSplatValue).
10230   if (UndefElements)
10231     for (unsigned I = 0; I != NumOps; ++I)
10232       if (DemandedElts[I] && getOperand(I).isUndef())
10233         (*UndefElements)[I] = true;
10234 
10235   // Iteratively widen the sequence length looking for repetitions.
10236   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10237     Sequence.append(SeqLen, SDValue());
10238     for (unsigned I = 0; I != NumOps; ++I) {
10239       if (!DemandedElts[I])
10240         continue;
10241       SDValue &SeqOp = Sequence[I % SeqLen];
10242       SDValue Op = getOperand(I);
10243       if (Op.isUndef()) {
10244         if (!SeqOp)
10245           SeqOp = Op;
10246         continue;
10247       }
10248       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10249         Sequence.clear();
10250         break;
10251       }
10252       SeqOp = Op;
10253     }
10254     if (!Sequence.empty())
10255       return true;
10256   }
10257 
10258   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10259   return false;
10260 }
10261 
10262 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10263                                             BitVector *UndefElements) const {
10264   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10265   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10266 }
10267 
10268 ConstantSDNode *
10269 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10270                                         BitVector *UndefElements) const {
10271   return dyn_cast_or_null<ConstantSDNode>(
10272       getSplatValue(DemandedElts, UndefElements));
10273 }
10274 
10275 ConstantSDNode *
10276 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10277   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10278 }
10279 
10280 ConstantFPSDNode *
10281 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10282                                           BitVector *UndefElements) const {
10283   return dyn_cast_or_null<ConstantFPSDNode>(
10284       getSplatValue(DemandedElts, UndefElements));
10285 }
10286 
10287 ConstantFPSDNode *
10288 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10289   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10290 }
10291 
10292 int32_t
10293 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10294                                                    uint32_t BitWidth) const {
10295   if (ConstantFPSDNode *CN =
10296           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10297     bool IsExact;
10298     APSInt IntVal(BitWidth);
10299     const APFloat &APF = CN->getValueAPF();
10300     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10301             APFloat::opOK ||
10302         !IsExact)
10303       return -1;
10304 
10305     return IntVal.exactLogBase2();
10306   }
10307   return -1;
10308 }
10309 
10310 bool BuildVectorSDNode::isConstant() const {
10311   for (const SDValue &Op : op_values()) {
10312     unsigned Opc = Op.getOpcode();
10313     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10314       return false;
10315   }
10316   return true;
10317 }
10318 
10319 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10320   // Find the first non-undef value in the shuffle mask.
10321   unsigned i, e;
10322   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10323     /* search */;
10324 
10325   // If all elements are undefined, this shuffle can be considered a splat
10326   // (although it should eventually get simplified away completely).
10327   if (i == e)
10328     return true;
10329 
10330   // Make sure all remaining elements are either undef or the same as the first
10331   // non-undef value.
10332   for (int Idx = Mask[i]; i != e; ++i)
10333     if (Mask[i] >= 0 && Mask[i] != Idx)
10334       return false;
10335   return true;
10336 }
10337 
10338 // Returns the SDNode if it is a constant integer BuildVector
10339 // or constant integer.
10340 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10341   if (isa<ConstantSDNode>(N))
10342     return N.getNode();
10343   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10344     return N.getNode();
10345   // Treat a GlobalAddress supporting constant offset folding as a
10346   // constant integer.
10347   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10348     if (GA->getOpcode() == ISD::GlobalAddress &&
10349         TLI->isOffsetFoldingLegal(GA))
10350       return GA;
10351   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10352       isa<ConstantSDNode>(N.getOperand(0)))
10353     return N.getNode();
10354   return nullptr;
10355 }
10356 
10357 // Returns the SDNode if it is a constant float BuildVector
10358 // or constant float.
10359 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10360   if (isa<ConstantFPSDNode>(N))
10361     return N.getNode();
10362 
10363   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10364     return N.getNode();
10365 
10366   return nullptr;
10367 }
10368 
10369 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10370   assert(!Node->OperandList && "Node already has operands");
10371   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
10372          "too many operands to fit into SDNode");
10373   SDUse *Ops = OperandRecycler.allocate(
10374       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10375 
10376   bool IsDivergent = false;
10377   for (unsigned I = 0; I != Vals.size(); ++I) {
10378     Ops[I].setUser(Node);
10379     Ops[I].setInitial(Vals[I]);
10380     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10381       IsDivergent |= Ops[I].getNode()->isDivergent();
10382   }
10383   Node->NumOperands = Vals.size();
10384   Node->OperandList = Ops;
10385   if (!TLI->isSDNodeAlwaysUniform(Node)) {
10386     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10387     Node->SDNodeBits.IsDivergent = IsDivergent;
10388   }
10389   checkForCycles(Node);
10390 }
10391 
10392 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10393                                      SmallVectorImpl<SDValue> &Vals) {
10394   size_t Limit = SDNode::getMaxNumOperands();
10395   while (Vals.size() > Limit) {
10396     unsigned SliceIdx = Vals.size() - Limit;
10397     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
10398     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
10399     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
10400     Vals.emplace_back(NewTF);
10401   }
10402   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
10403 }
10404 
10405 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
10406                                         EVT VT, SDNodeFlags Flags) {
10407   switch (Opcode) {
10408   default:
10409     return SDValue();
10410   case ISD::ADD:
10411   case ISD::OR:
10412   case ISD::XOR:
10413   case ISD::UMAX:
10414     return getConstant(0, DL, VT);
10415   case ISD::MUL:
10416     return getConstant(1, DL, VT);
10417   case ISD::AND:
10418   case ISD::UMIN:
10419     return getAllOnesConstant(DL, VT);
10420   case ISD::SMAX:
10421     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
10422   case ISD::SMIN:
10423     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
10424   case ISD::FADD:
10425     return getConstantFP(-0.0, DL, VT);
10426   case ISD::FMUL:
10427     return getConstantFP(1.0, DL, VT);
10428   case ISD::FMINNUM:
10429   case ISD::FMAXNUM: {
10430     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
10431     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
10432     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
10433                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
10434                         APFloat::getLargest(Semantics);
10435     if (Opcode == ISD::FMAXNUM)
10436       NeutralAF.changeSign();
10437 
10438     return getConstantFP(NeutralAF, DL, VT);
10439   }
10440   }
10441 }
10442 
10443 #ifndef NDEBUG
10444 static void checkForCyclesHelper(const SDNode *N,
10445                                  SmallPtrSetImpl<const SDNode*> &Visited,
10446                                  SmallPtrSetImpl<const SDNode*> &Checked,
10447                                  const llvm::SelectionDAG *DAG) {
10448   // If this node has already been checked, don't check it again.
10449   if (Checked.count(N))
10450     return;
10451 
10452   // If a node has already been visited on this depth-first walk, reject it as
10453   // a cycle.
10454   if (!Visited.insert(N).second) {
10455     errs() << "Detected cycle in SelectionDAG\n";
10456     dbgs() << "Offending node:\n";
10457     N->dumprFull(DAG); dbgs() << "\n";
10458     abort();
10459   }
10460 
10461   for (const SDValue &Op : N->op_values())
10462     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
10463 
10464   Checked.insert(N);
10465   Visited.erase(N);
10466 }
10467 #endif
10468 
10469 void llvm::checkForCycles(const llvm::SDNode *N,
10470                           const llvm::SelectionDAG *DAG,
10471                           bool force) {
10472 #ifndef NDEBUG
10473   bool check = force;
10474 #ifdef EXPENSIVE_CHECKS
10475   check = true;
10476 #endif  // EXPENSIVE_CHECKS
10477   if (check) {
10478     assert(N && "Checking nonexistent SDNode");
10479     SmallPtrSet<const SDNode*, 32> visited;
10480     SmallPtrSet<const SDNode*, 32> checked;
10481     checkForCyclesHelper(N, visited, checked, DAG);
10482   }
10483 #endif  // !NDEBUG
10484 }
10485 
10486 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
10487   checkForCycles(DAG->getRoot().getNode(), DAG, force);
10488 }
10489