1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/FunctionLoweringInfo.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineConstantPool.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/RuntimeLibcalls.h"
39 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
40 #include "llvm/CodeGen/SelectionDAGNodes.h"
41 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
42 #include "llvm/CodeGen/TargetFrameLowering.h"
43 #include "llvm/CodeGen/TargetLowering.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Constant.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugInfoMetadata.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CodeGen.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/KnownBits.h"
64 #include "llvm/Support/MachineValueType.h"
65 #include "llvm/Support/ManagedStatic.h"
66 #include "llvm/Support/MathExtras.h"
67 #include "llvm/Support/Mutex.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include "llvm/Target/TargetOptions.h"
71 #include "llvm/Transforms/Utils/SizeOpts.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstdint>
75 #include <cstdlib>
76 #include <limits>
77 #include <set>
78 #include <string>
79 #include <utility>
80 #include <vector>
81 
82 using namespace llvm;
83 
84 /// makeVTList - Return an instance of the SDVTList struct initialized with the
85 /// specified members.
86 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
87   SDVTList Res = {VTs, NumVTs};
88   return Res;
89 }
90 
91 // Default null implementations of the callbacks.
92 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
93 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
94 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
95 
96 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
97 
98 #define DEBUG_TYPE "selectiondag"
99 
100 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
101        cl::Hidden, cl::init(true),
102        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
103 
104 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
105        cl::desc("Number limit for gluing ld/st of memcpy."),
106        cl::Hidden, cl::init(0));
107 
108 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
109   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
110 }
111 
112 //===----------------------------------------------------------------------===//
113 //                              ConstantFPSDNode Class
114 //===----------------------------------------------------------------------===//
115 
116 /// isExactlyValue - We don't rely on operator== working on double values, as
117 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
118 /// As such, this method can be used to do an exact bit-for-bit comparison of
119 /// two floating point values.
120 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
121   return getValueAPF().bitwiseIsEqual(V);
122 }
123 
124 bool ConstantFPSDNode::isValueValidForType(EVT VT,
125                                            const APFloat& Val) {
126   assert(VT.isFloatingPoint() && "Can only convert between FP types");
127 
128   // convert modifies in place, so make a copy.
129   APFloat Val2 = APFloat(Val);
130   bool losesInfo;
131   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
132                       APFloat::rmNearestTiesToEven,
133                       &losesInfo);
134   return !losesInfo;
135 }
136 
137 //===----------------------------------------------------------------------===//
138 //                              ISD Namespace
139 //===----------------------------------------------------------------------===//
140 
141 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
142   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
143     unsigned EltSize =
144         N->getValueType(0).getVectorElementType().getSizeInBits();
145     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
146       SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
147       return true;
148     }
149     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
150       SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
151       return true;
152     }
153   }
154 
155   auto *BV = dyn_cast<BuildVectorSDNode>(N);
156   if (!BV)
157     return false;
158 
159   APInt SplatUndef;
160   unsigned SplatBitSize;
161   bool HasUndefs;
162   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
163   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
164                              EltSize) &&
165          EltSize == SplatBitSize;
166 }
167 
168 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
169 // specializations of the more general isConstantSplatVector()?
170 
171 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
172   // Look through a bit convert.
173   while (N->getOpcode() == ISD::BITCAST)
174     N = N->getOperand(0).getNode();
175 
176   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
177     APInt SplatVal;
178     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnesValue();
179   }
180 
181   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
182 
183   unsigned i = 0, e = N->getNumOperands();
184 
185   // Skip over all of the undef values.
186   while (i != e && N->getOperand(i).isUndef())
187     ++i;
188 
189   // Do not accept an all-undef vector.
190   if (i == e) return false;
191 
192   // Do not accept build_vectors that aren't all constants or which have non-~0
193   // elements. We have to be a bit careful here, as the type of the constant
194   // may not be the same as the type of the vector elements due to type
195   // legalization (the elements are promoted to a legal type for the target and
196   // a vector of a type may be legal when the base element type is not).
197   // We only want to check enough bits to cover the vector elements, because
198   // we care if the resultant vector is all ones, not whether the individual
199   // constants are.
200   SDValue NotZero = N->getOperand(i);
201   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
202   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
203     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
204       return false;
205   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
206     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
207       return false;
208   } else
209     return false;
210 
211   // Okay, we have at least one ~0 value, check to see if the rest match or are
212   // undefs. Even with the above element type twiddling, this should be OK, as
213   // the same type legalization should have applied to all the elements.
214   for (++i; i != e; ++i)
215     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
216       return false;
217   return true;
218 }
219 
220 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
221   // Look through a bit convert.
222   while (N->getOpcode() == ISD::BITCAST)
223     N = N->getOperand(0).getNode();
224 
225   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
226     APInt SplatVal;
227     return isConstantSplatVector(N, SplatVal) && SplatVal.isNullValue();
228   }
229 
230   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
231 
232   bool IsAllUndef = true;
233   for (const SDValue &Op : N->op_values()) {
234     if (Op.isUndef())
235       continue;
236     IsAllUndef = false;
237     // Do not accept build_vectors that aren't all constants or which have non-0
238     // elements. We have to be a bit careful here, as the type of the constant
239     // may not be the same as the type of the vector elements due to type
240     // legalization (the elements are promoted to a legal type for the target
241     // and a vector of a type may be legal when the base element type is not).
242     // We only want to check enough bits to cover the vector elements, because
243     // we care if the resultant vector is all zeros, not whether the individual
244     // constants are.
245     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
246     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
247       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
248         return false;
249     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
250       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
251         return false;
252     } else
253       return false;
254   }
255 
256   // Do not accept an all-undef vector.
257   if (IsAllUndef)
258     return false;
259   return true;
260 }
261 
262 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
263   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
264 }
265 
266 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
267   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
268 }
269 
270 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
271   if (N->getOpcode() != ISD::BUILD_VECTOR)
272     return false;
273 
274   for (const SDValue &Op : N->op_values()) {
275     if (Op.isUndef())
276       continue;
277     if (!isa<ConstantSDNode>(Op))
278       return false;
279   }
280   return true;
281 }
282 
283 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
284   if (N->getOpcode() != ISD::BUILD_VECTOR)
285     return false;
286 
287   for (const SDValue &Op : N->op_values()) {
288     if (Op.isUndef())
289       continue;
290     if (!isa<ConstantFPSDNode>(Op))
291       return false;
292   }
293   return true;
294 }
295 
296 bool ISD::allOperandsUndef(const SDNode *N) {
297   // Return false if the node has no operands.
298   // This is "logically inconsistent" with the definition of "all" but
299   // is probably the desired behavior.
300   if (N->getNumOperands() == 0)
301     return false;
302   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
303 }
304 
305 bool ISD::matchUnaryPredicate(SDValue Op,
306                               std::function<bool(ConstantSDNode *)> Match,
307                               bool AllowUndefs) {
308   // FIXME: Add support for scalar UNDEF cases?
309   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
310     return Match(Cst);
311 
312   // FIXME: Add support for vector UNDEF cases?
313   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
314       ISD::SPLAT_VECTOR != Op.getOpcode())
315     return false;
316 
317   EVT SVT = Op.getValueType().getScalarType();
318   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
319     if (AllowUndefs && Op.getOperand(i).isUndef()) {
320       if (!Match(nullptr))
321         return false;
322       continue;
323     }
324 
325     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
326     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
327       return false;
328   }
329   return true;
330 }
331 
332 bool ISD::matchBinaryPredicate(
333     SDValue LHS, SDValue RHS,
334     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
335     bool AllowUndefs, bool AllowTypeMismatch) {
336   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
337     return false;
338 
339   // TODO: Add support for scalar UNDEF cases?
340   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
341     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
342       return Match(LHSCst, RHSCst);
343 
344   // TODO: Add support for vector UNDEF cases?
345   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
346       ISD::BUILD_VECTOR != RHS.getOpcode())
347     return false;
348 
349   EVT SVT = LHS.getValueType().getScalarType();
350   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
351     SDValue LHSOp = LHS.getOperand(i);
352     SDValue RHSOp = RHS.getOperand(i);
353     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
354     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
355     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
356     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
357     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
358       return false;
359     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
360                                LHSOp.getValueType() != RHSOp.getValueType()))
361       return false;
362     if (!Match(LHSCst, RHSCst))
363       return false;
364   }
365   return true;
366 }
367 
368 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
369   switch (VecReduceOpcode) {
370   default:
371     llvm_unreachable("Expected VECREDUCE opcode");
372   case ISD::VECREDUCE_FADD:
373   case ISD::VECREDUCE_SEQ_FADD:
374     return ISD::FADD;
375   case ISD::VECREDUCE_FMUL:
376   case ISD::VECREDUCE_SEQ_FMUL:
377     return ISD::FMUL;
378   case ISD::VECREDUCE_ADD:
379     return ISD::ADD;
380   case ISD::VECREDUCE_MUL:
381     return ISD::MUL;
382   case ISD::VECREDUCE_AND:
383     return ISD::AND;
384   case ISD::VECREDUCE_OR:
385     return ISD::OR;
386   case ISD::VECREDUCE_XOR:
387     return ISD::XOR;
388   case ISD::VECREDUCE_SMAX:
389     return ISD::SMAX;
390   case ISD::VECREDUCE_SMIN:
391     return ISD::SMIN;
392   case ISD::VECREDUCE_UMAX:
393     return ISD::UMAX;
394   case ISD::VECREDUCE_UMIN:
395     return ISD::UMIN;
396   case ISD::VECREDUCE_FMAX:
397     return ISD::FMAXNUM;
398   case ISD::VECREDUCE_FMIN:
399     return ISD::FMINNUM;
400   }
401 }
402 
403 bool ISD::isVPOpcode(unsigned Opcode) {
404   switch (Opcode) {
405   default:
406     return false;
407 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
408   case ISD::SDOPC:                                                             \
409     return true;
410 #include "llvm/IR/VPIntrinsics.def"
411   }
412 }
413 
414 /// The operand position of the vector mask.
415 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
416   switch (Opcode) {
417   default:
418     return None;
419 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...)        \
420   case ISD::SDOPC:                                                             \
421     return MASKPOS;
422 #include "llvm/IR/VPIntrinsics.def"
423   }
424 }
425 
426 /// The operand position of the explicit vector length parameter.
427 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
428   switch (Opcode) {
429   default:
430     return None;
431 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS)     \
432   case ISD::SDOPC:                                                             \
433     return EVLPOS;
434 #include "llvm/IR/VPIntrinsics.def"
435   }
436 }
437 
438 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
439   switch (ExtType) {
440   case ISD::EXTLOAD:
441     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
442   case ISD::SEXTLOAD:
443     return ISD::SIGN_EXTEND;
444   case ISD::ZEXTLOAD:
445     return ISD::ZERO_EXTEND;
446   default:
447     break;
448   }
449 
450   llvm_unreachable("Invalid LoadExtType");
451 }
452 
453 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
454   // To perform this operation, we just need to swap the L and G bits of the
455   // operation.
456   unsigned OldL = (Operation >> 2) & 1;
457   unsigned OldG = (Operation >> 1) & 1;
458   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
459                        (OldL << 1) |       // New G bit
460                        (OldG << 2));       // New L bit.
461 }
462 
463 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
464   unsigned Operation = Op;
465   if (isIntegerLike)
466     Operation ^= 7;   // Flip L, G, E bits, but not U.
467   else
468     Operation ^= 15;  // Flip all of the condition bits.
469 
470   if (Operation > ISD::SETTRUE2)
471     Operation &= ~8;  // Don't let N and U bits get set.
472 
473   return ISD::CondCode(Operation);
474 }
475 
476 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
477   return getSetCCInverseImpl(Op, Type.isInteger());
478 }
479 
480 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
481                                                bool isIntegerLike) {
482   return getSetCCInverseImpl(Op, isIntegerLike);
483 }
484 
485 /// For an integer comparison, return 1 if the comparison is a signed operation
486 /// and 2 if the result is an unsigned comparison. Return zero if the operation
487 /// does not depend on the sign of the input (setne and seteq).
488 static int isSignedOp(ISD::CondCode Opcode) {
489   switch (Opcode) {
490   default: llvm_unreachable("Illegal integer setcc operation!");
491   case ISD::SETEQ:
492   case ISD::SETNE: return 0;
493   case ISD::SETLT:
494   case ISD::SETLE:
495   case ISD::SETGT:
496   case ISD::SETGE: return 1;
497   case ISD::SETULT:
498   case ISD::SETULE:
499   case ISD::SETUGT:
500   case ISD::SETUGE: return 2;
501   }
502 }
503 
504 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
505                                        EVT Type) {
506   bool IsInteger = Type.isInteger();
507   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
508     // Cannot fold a signed integer setcc with an unsigned integer setcc.
509     return ISD::SETCC_INVALID;
510 
511   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
512 
513   // If the N and U bits get set, then the resultant comparison DOES suddenly
514   // care about orderedness, and it is true when ordered.
515   if (Op > ISD::SETTRUE2)
516     Op &= ~16;     // Clear the U bit if the N bit is set.
517 
518   // Canonicalize illegal integer setcc's.
519   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
520     Op = ISD::SETNE;
521 
522   return ISD::CondCode(Op);
523 }
524 
525 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
526                                         EVT Type) {
527   bool IsInteger = Type.isInteger();
528   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
529     // Cannot fold a signed setcc with an unsigned setcc.
530     return ISD::SETCC_INVALID;
531 
532   // Combine all of the condition bits.
533   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
534 
535   // Canonicalize illegal integer setcc's.
536   if (IsInteger) {
537     switch (Result) {
538     default: break;
539     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
540     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
541     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
542     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
543     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
544     }
545   }
546 
547   return Result;
548 }
549 
550 //===----------------------------------------------------------------------===//
551 //                           SDNode Profile Support
552 //===----------------------------------------------------------------------===//
553 
554 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
555 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
556   ID.AddInteger(OpC);
557 }
558 
559 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
560 /// solely with their pointer.
561 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
562   ID.AddPointer(VTList.VTs);
563 }
564 
565 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
566 static void AddNodeIDOperands(FoldingSetNodeID &ID,
567                               ArrayRef<SDValue> Ops) {
568   for (auto& Op : Ops) {
569     ID.AddPointer(Op.getNode());
570     ID.AddInteger(Op.getResNo());
571   }
572 }
573 
574 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
575 static void AddNodeIDOperands(FoldingSetNodeID &ID,
576                               ArrayRef<SDUse> Ops) {
577   for (auto& Op : Ops) {
578     ID.AddPointer(Op.getNode());
579     ID.AddInteger(Op.getResNo());
580   }
581 }
582 
583 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
584                           SDVTList VTList, ArrayRef<SDValue> OpList) {
585   AddNodeIDOpcode(ID, OpC);
586   AddNodeIDValueTypes(ID, VTList);
587   AddNodeIDOperands(ID, OpList);
588 }
589 
590 /// If this is an SDNode with special info, add this info to the NodeID data.
591 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
592   switch (N->getOpcode()) {
593   case ISD::TargetExternalSymbol:
594   case ISD::ExternalSymbol:
595   case ISD::MCSymbol:
596     llvm_unreachable("Should only be used on nodes with operands");
597   default: break;  // Normal nodes don't need extra info.
598   case ISD::TargetConstant:
599   case ISD::Constant: {
600     const ConstantSDNode *C = cast<ConstantSDNode>(N);
601     ID.AddPointer(C->getConstantIntValue());
602     ID.AddBoolean(C->isOpaque());
603     break;
604   }
605   case ISD::TargetConstantFP:
606   case ISD::ConstantFP:
607     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
608     break;
609   case ISD::TargetGlobalAddress:
610   case ISD::GlobalAddress:
611   case ISD::TargetGlobalTLSAddress:
612   case ISD::GlobalTLSAddress: {
613     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
614     ID.AddPointer(GA->getGlobal());
615     ID.AddInteger(GA->getOffset());
616     ID.AddInteger(GA->getTargetFlags());
617     break;
618   }
619   case ISD::BasicBlock:
620     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
621     break;
622   case ISD::Register:
623     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
624     break;
625   case ISD::RegisterMask:
626     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
627     break;
628   case ISD::SRCVALUE:
629     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
630     break;
631   case ISD::FrameIndex:
632   case ISD::TargetFrameIndex:
633     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
634     break;
635   case ISD::LIFETIME_START:
636   case ISD::LIFETIME_END:
637     if (cast<LifetimeSDNode>(N)->hasOffset()) {
638       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
639       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
640     }
641     break;
642   case ISD::PSEUDO_PROBE:
643     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
644     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
645     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
646     break;
647   case ISD::JumpTable:
648   case ISD::TargetJumpTable:
649     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
650     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
651     break;
652   case ISD::ConstantPool:
653   case ISD::TargetConstantPool: {
654     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
655     ID.AddInteger(CP->getAlign().value());
656     ID.AddInteger(CP->getOffset());
657     if (CP->isMachineConstantPoolEntry())
658       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
659     else
660       ID.AddPointer(CP->getConstVal());
661     ID.AddInteger(CP->getTargetFlags());
662     break;
663   }
664   case ISD::TargetIndex: {
665     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
666     ID.AddInteger(TI->getIndex());
667     ID.AddInteger(TI->getOffset());
668     ID.AddInteger(TI->getTargetFlags());
669     break;
670   }
671   case ISD::LOAD: {
672     const LoadSDNode *LD = cast<LoadSDNode>(N);
673     ID.AddInteger(LD->getMemoryVT().getRawBits());
674     ID.AddInteger(LD->getRawSubclassData());
675     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
676     break;
677   }
678   case ISD::STORE: {
679     const StoreSDNode *ST = cast<StoreSDNode>(N);
680     ID.AddInteger(ST->getMemoryVT().getRawBits());
681     ID.AddInteger(ST->getRawSubclassData());
682     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
683     break;
684   }
685   case ISD::MLOAD: {
686     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
687     ID.AddInteger(MLD->getMemoryVT().getRawBits());
688     ID.AddInteger(MLD->getRawSubclassData());
689     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
690     break;
691   }
692   case ISD::MSTORE: {
693     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
694     ID.AddInteger(MST->getMemoryVT().getRawBits());
695     ID.AddInteger(MST->getRawSubclassData());
696     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
697     break;
698   }
699   case ISD::MGATHER: {
700     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
701     ID.AddInteger(MG->getMemoryVT().getRawBits());
702     ID.AddInteger(MG->getRawSubclassData());
703     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
704     break;
705   }
706   case ISD::MSCATTER: {
707     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
708     ID.AddInteger(MS->getMemoryVT().getRawBits());
709     ID.AddInteger(MS->getRawSubclassData());
710     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
711     break;
712   }
713   case ISD::ATOMIC_CMP_SWAP:
714   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
715   case ISD::ATOMIC_SWAP:
716   case ISD::ATOMIC_LOAD_ADD:
717   case ISD::ATOMIC_LOAD_SUB:
718   case ISD::ATOMIC_LOAD_AND:
719   case ISD::ATOMIC_LOAD_CLR:
720   case ISD::ATOMIC_LOAD_OR:
721   case ISD::ATOMIC_LOAD_XOR:
722   case ISD::ATOMIC_LOAD_NAND:
723   case ISD::ATOMIC_LOAD_MIN:
724   case ISD::ATOMIC_LOAD_MAX:
725   case ISD::ATOMIC_LOAD_UMIN:
726   case ISD::ATOMIC_LOAD_UMAX:
727   case ISD::ATOMIC_LOAD:
728   case ISD::ATOMIC_STORE: {
729     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
730     ID.AddInteger(AT->getMemoryVT().getRawBits());
731     ID.AddInteger(AT->getRawSubclassData());
732     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
733     break;
734   }
735   case ISD::PREFETCH: {
736     const MemSDNode *PF = cast<MemSDNode>(N);
737     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
738     break;
739   }
740   case ISD::VECTOR_SHUFFLE: {
741     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
742     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
743          i != e; ++i)
744       ID.AddInteger(SVN->getMaskElt(i));
745     break;
746   }
747   case ISD::TargetBlockAddress:
748   case ISD::BlockAddress: {
749     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
750     ID.AddPointer(BA->getBlockAddress());
751     ID.AddInteger(BA->getOffset());
752     ID.AddInteger(BA->getTargetFlags());
753     break;
754   }
755   } // end switch (N->getOpcode())
756 
757   // Target specific memory nodes could also have address spaces to check.
758   if (N->isTargetMemoryOpcode())
759     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
760 }
761 
762 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
763 /// data.
764 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
765   AddNodeIDOpcode(ID, N->getOpcode());
766   // Add the return value info.
767   AddNodeIDValueTypes(ID, N->getVTList());
768   // Add the operand info.
769   AddNodeIDOperands(ID, N->ops());
770 
771   // Handle SDNode leafs with special info.
772   AddNodeIDCustom(ID, N);
773 }
774 
775 //===----------------------------------------------------------------------===//
776 //                              SelectionDAG Class
777 //===----------------------------------------------------------------------===//
778 
779 /// doNotCSE - Return true if CSE should not be performed for this node.
780 static bool doNotCSE(SDNode *N) {
781   if (N->getValueType(0) == MVT::Glue)
782     return true; // Never CSE anything that produces a flag.
783 
784   switch (N->getOpcode()) {
785   default: break;
786   case ISD::HANDLENODE:
787   case ISD::EH_LABEL:
788     return true;   // Never CSE these nodes.
789   }
790 
791   // Check that remaining values produced are not flags.
792   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
793     if (N->getValueType(i) == MVT::Glue)
794       return true; // Never CSE anything that produces a flag.
795 
796   return false;
797 }
798 
799 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
800 /// SelectionDAG.
801 void SelectionDAG::RemoveDeadNodes() {
802   // Create a dummy node (which is not added to allnodes), that adds a reference
803   // to the root node, preventing it from being deleted.
804   HandleSDNode Dummy(getRoot());
805 
806   SmallVector<SDNode*, 128> DeadNodes;
807 
808   // Add all obviously-dead nodes to the DeadNodes worklist.
809   for (SDNode &Node : allnodes())
810     if (Node.use_empty())
811       DeadNodes.push_back(&Node);
812 
813   RemoveDeadNodes(DeadNodes);
814 
815   // If the root changed (e.g. it was a dead load, update the root).
816   setRoot(Dummy.getValue());
817 }
818 
819 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
820 /// given list, and any nodes that become unreachable as a result.
821 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
822 
823   // Process the worklist, deleting the nodes and adding their uses to the
824   // worklist.
825   while (!DeadNodes.empty()) {
826     SDNode *N = DeadNodes.pop_back_val();
827     // Skip to next node if we've already managed to delete the node. This could
828     // happen if replacing a node causes a node previously added to the node to
829     // be deleted.
830     if (N->getOpcode() == ISD::DELETED_NODE)
831       continue;
832 
833     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
834       DUL->NodeDeleted(N, nullptr);
835 
836     // Take the node out of the appropriate CSE map.
837     RemoveNodeFromCSEMaps(N);
838 
839     // Next, brutally remove the operand list.  This is safe to do, as there are
840     // no cycles in the graph.
841     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
842       SDUse &Use = *I++;
843       SDNode *Operand = Use.getNode();
844       Use.set(SDValue());
845 
846       // Now that we removed this operand, see if there are no uses of it left.
847       if (Operand->use_empty())
848         DeadNodes.push_back(Operand);
849     }
850 
851     DeallocateNode(N);
852   }
853 }
854 
855 void SelectionDAG::RemoveDeadNode(SDNode *N){
856   SmallVector<SDNode*, 16> DeadNodes(1, N);
857 
858   // Create a dummy node that adds a reference to the root node, preventing
859   // it from being deleted.  (This matters if the root is an operand of the
860   // dead node.)
861   HandleSDNode Dummy(getRoot());
862 
863   RemoveDeadNodes(DeadNodes);
864 }
865 
866 void SelectionDAG::DeleteNode(SDNode *N) {
867   // First take this out of the appropriate CSE map.
868   RemoveNodeFromCSEMaps(N);
869 
870   // Finally, remove uses due to operands of this node, remove from the
871   // AllNodes list, and delete the node.
872   DeleteNodeNotInCSEMaps(N);
873 }
874 
875 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
876   assert(N->getIterator() != AllNodes.begin() &&
877          "Cannot delete the entry node!");
878   assert(N->use_empty() && "Cannot delete a node that is not dead!");
879 
880   // Drop all of the operands and decrement used node's use counts.
881   N->DropOperands();
882 
883   DeallocateNode(N);
884 }
885 
886 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
887   assert(!(V->isVariadic() && isParameter));
888   if (isParameter)
889     ByvalParmDbgValues.push_back(V);
890   else
891     DbgValues.push_back(V);
892   for (const SDNode *Node : V->getSDNodes())
893     if (Node)
894       DbgValMap[Node].push_back(V);
895 }
896 
897 void SDDbgInfo::erase(const SDNode *Node) {
898   DbgValMapType::iterator I = DbgValMap.find(Node);
899   if (I == DbgValMap.end())
900     return;
901   for (auto &Val: I->second)
902     Val->setIsInvalidated();
903   DbgValMap.erase(I);
904 }
905 
906 void SelectionDAG::DeallocateNode(SDNode *N) {
907   // If we have operands, deallocate them.
908   removeOperands(N);
909 
910   NodeAllocator.Deallocate(AllNodes.remove(N));
911 
912   // Set the opcode to DELETED_NODE to help catch bugs when node
913   // memory is reallocated.
914   // FIXME: There are places in SDag that have grown a dependency on the opcode
915   // value in the released node.
916   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
917   N->NodeType = ISD::DELETED_NODE;
918 
919   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
920   // them and forget about that node.
921   DbgInfo->erase(N);
922 }
923 
924 #ifndef NDEBUG
925 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
926 static void VerifySDNode(SDNode *N) {
927   switch (N->getOpcode()) {
928   default:
929     break;
930   case ISD::BUILD_PAIR: {
931     EVT VT = N->getValueType(0);
932     assert(N->getNumValues() == 1 && "Too many results!");
933     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
934            "Wrong return type!");
935     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
936     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
937            "Mismatched operand types!");
938     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
939            "Wrong operand type!");
940     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
941            "Wrong return type size");
942     break;
943   }
944   case ISD::BUILD_VECTOR: {
945     assert(N->getNumValues() == 1 && "Too many results!");
946     assert(N->getValueType(0).isVector() && "Wrong return type!");
947     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
948            "Wrong number of operands!");
949     EVT EltVT = N->getValueType(0).getVectorElementType();
950     for (const SDUse &Op : N->ops()) {
951       assert((Op.getValueType() == EltVT ||
952               (EltVT.isInteger() && Op.getValueType().isInteger() &&
953                EltVT.bitsLE(Op.getValueType()))) &&
954              "Wrong operand type!");
955       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
956              "Operands must all have the same type");
957     }
958     break;
959   }
960   }
961 }
962 #endif // NDEBUG
963 
964 /// Insert a newly allocated node into the DAG.
965 ///
966 /// Handles insertion into the all nodes list and CSE map, as well as
967 /// verification and other common operations when a new node is allocated.
968 void SelectionDAG::InsertNode(SDNode *N) {
969   AllNodes.push_back(N);
970 #ifndef NDEBUG
971   N->PersistentId = NextPersistentId++;
972   VerifySDNode(N);
973 #endif
974   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
975     DUL->NodeInserted(N);
976 }
977 
978 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
979 /// correspond to it.  This is useful when we're about to delete or repurpose
980 /// the node.  We don't want future request for structurally identical nodes
981 /// to return N anymore.
982 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
983   bool Erased = false;
984   switch (N->getOpcode()) {
985   case ISD::HANDLENODE: return false;  // noop.
986   case ISD::CONDCODE:
987     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
988            "Cond code doesn't exist!");
989     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
990     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
991     break;
992   case ISD::ExternalSymbol:
993     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
994     break;
995   case ISD::TargetExternalSymbol: {
996     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
997     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
998         ESN->getSymbol(), ESN->getTargetFlags()));
999     break;
1000   }
1001   case ISD::MCSymbol: {
1002     auto *MCSN = cast<MCSymbolSDNode>(N);
1003     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1004     break;
1005   }
1006   case ISD::VALUETYPE: {
1007     EVT VT = cast<VTSDNode>(N)->getVT();
1008     if (VT.isExtended()) {
1009       Erased = ExtendedValueTypeNodes.erase(VT);
1010     } else {
1011       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1012       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1013     }
1014     break;
1015   }
1016   default:
1017     // Remove it from the CSE Map.
1018     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1019     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1020     Erased = CSEMap.RemoveNode(N);
1021     break;
1022   }
1023 #ifndef NDEBUG
1024   // Verify that the node was actually in one of the CSE maps, unless it has a
1025   // flag result (which cannot be CSE'd) or is one of the special cases that are
1026   // not subject to CSE.
1027   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1028       !N->isMachineOpcode() && !doNotCSE(N)) {
1029     N->dump(this);
1030     dbgs() << "\n";
1031     llvm_unreachable("Node is not in map!");
1032   }
1033 #endif
1034   return Erased;
1035 }
1036 
1037 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1038 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1039 /// node already exists, in which case transfer all its users to the existing
1040 /// node. This transfer can potentially trigger recursive merging.
1041 void
1042 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1043   // For node types that aren't CSE'd, just act as if no identical node
1044   // already exists.
1045   if (!doNotCSE(N)) {
1046     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1047     if (Existing != N) {
1048       // If there was already an existing matching node, use ReplaceAllUsesWith
1049       // to replace the dead one with the existing one.  This can cause
1050       // recursive merging of other unrelated nodes down the line.
1051       ReplaceAllUsesWith(N, Existing);
1052 
1053       // N is now dead. Inform the listeners and delete it.
1054       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1055         DUL->NodeDeleted(N, Existing);
1056       DeleteNodeNotInCSEMaps(N);
1057       return;
1058     }
1059   }
1060 
1061   // If the node doesn't already exist, we updated it.  Inform listeners.
1062   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1063     DUL->NodeUpdated(N);
1064 }
1065 
1066 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1067 /// were replaced with those specified.  If this node is never memoized,
1068 /// return null, otherwise return a pointer to the slot it would take.  If a
1069 /// node already exists with these operands, the slot will be non-null.
1070 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1071                                            void *&InsertPos) {
1072   if (doNotCSE(N))
1073     return nullptr;
1074 
1075   SDValue Ops[] = { Op };
1076   FoldingSetNodeID ID;
1077   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1078   AddNodeIDCustom(ID, N);
1079   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1080   if (Node)
1081     Node->intersectFlagsWith(N->getFlags());
1082   return Node;
1083 }
1084 
1085 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1086 /// were replaced with those specified.  If this node is never memoized,
1087 /// return null, otherwise return a pointer to the slot it would take.  If a
1088 /// node already exists with these operands, the slot will be non-null.
1089 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1090                                            SDValue Op1, SDValue Op2,
1091                                            void *&InsertPos) {
1092   if (doNotCSE(N))
1093     return nullptr;
1094 
1095   SDValue Ops[] = { Op1, Op2 };
1096   FoldingSetNodeID ID;
1097   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1098   AddNodeIDCustom(ID, N);
1099   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1100   if (Node)
1101     Node->intersectFlagsWith(N->getFlags());
1102   return Node;
1103 }
1104 
1105 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1106 /// were replaced with those specified.  If this node is never memoized,
1107 /// return null, otherwise return a pointer to the slot it would take.  If a
1108 /// node already exists with these operands, the slot will be non-null.
1109 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1110                                            void *&InsertPos) {
1111   if (doNotCSE(N))
1112     return nullptr;
1113 
1114   FoldingSetNodeID ID;
1115   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1116   AddNodeIDCustom(ID, N);
1117   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1118   if (Node)
1119     Node->intersectFlagsWith(N->getFlags());
1120   return Node;
1121 }
1122 
1123 Align SelectionDAG::getEVTAlign(EVT VT) const {
1124   Type *Ty = VT == MVT::iPTR ?
1125                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1126                    VT.getTypeForEVT(*getContext());
1127 
1128   return getDataLayout().getABITypeAlign(Ty);
1129 }
1130 
1131 // EntryNode could meaningfully have debug info if we can find it...
1132 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1133     : TM(tm), OptLevel(OL),
1134       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1135       Root(getEntryNode()) {
1136   InsertNode(&EntryNode);
1137   DbgInfo = new SDDbgInfo();
1138 }
1139 
1140 void SelectionDAG::init(MachineFunction &NewMF,
1141                         OptimizationRemarkEmitter &NewORE,
1142                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1143                         LegacyDivergenceAnalysis * Divergence,
1144                         ProfileSummaryInfo *PSIin,
1145                         BlockFrequencyInfo *BFIin) {
1146   MF = &NewMF;
1147   SDAGISelPass = PassPtr;
1148   ORE = &NewORE;
1149   TLI = getSubtarget().getTargetLowering();
1150   TSI = getSubtarget().getSelectionDAGInfo();
1151   LibInfo = LibraryInfo;
1152   Context = &MF->getFunction().getContext();
1153   DA = Divergence;
1154   PSI = PSIin;
1155   BFI = BFIin;
1156 }
1157 
1158 SelectionDAG::~SelectionDAG() {
1159   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1160   allnodes_clear();
1161   OperandRecycler.clear(OperandAllocator);
1162   delete DbgInfo;
1163 }
1164 
1165 bool SelectionDAG::shouldOptForSize() const {
1166   return MF->getFunction().hasOptSize() ||
1167       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1168 }
1169 
1170 void SelectionDAG::allnodes_clear() {
1171   assert(&*AllNodes.begin() == &EntryNode);
1172   AllNodes.remove(AllNodes.begin());
1173   while (!AllNodes.empty())
1174     DeallocateNode(&AllNodes.front());
1175 #ifndef NDEBUG
1176   NextPersistentId = 0;
1177 #endif
1178 }
1179 
1180 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1181                                           void *&InsertPos) {
1182   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1183   if (N) {
1184     switch (N->getOpcode()) {
1185     default: break;
1186     case ISD::Constant:
1187     case ISD::ConstantFP:
1188       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1189                        "debug location.  Use another overload.");
1190     }
1191   }
1192   return N;
1193 }
1194 
1195 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1196                                           const SDLoc &DL, void *&InsertPos) {
1197   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1198   if (N) {
1199     switch (N->getOpcode()) {
1200     case ISD::Constant:
1201     case ISD::ConstantFP:
1202       // Erase debug location from the node if the node is used at several
1203       // different places. Do not propagate one location to all uses as it
1204       // will cause a worse single stepping debugging experience.
1205       if (N->getDebugLoc() != DL.getDebugLoc())
1206         N->setDebugLoc(DebugLoc());
1207       break;
1208     default:
1209       // When the node's point of use is located earlier in the instruction
1210       // sequence than its prior point of use, update its debug info to the
1211       // earlier location.
1212       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1213         N->setDebugLoc(DL.getDebugLoc());
1214       break;
1215     }
1216   }
1217   return N;
1218 }
1219 
1220 void SelectionDAG::clear() {
1221   allnodes_clear();
1222   OperandRecycler.clear(OperandAllocator);
1223   OperandAllocator.Reset();
1224   CSEMap.clear();
1225 
1226   ExtendedValueTypeNodes.clear();
1227   ExternalSymbols.clear();
1228   TargetExternalSymbols.clear();
1229   MCSymbols.clear();
1230   SDCallSiteDbgInfo.clear();
1231   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1232             static_cast<CondCodeSDNode*>(nullptr));
1233   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1234             static_cast<SDNode*>(nullptr));
1235 
1236   EntryNode.UseList = nullptr;
1237   InsertNode(&EntryNode);
1238   Root = getEntryNode();
1239   DbgInfo->clear();
1240 }
1241 
1242 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1243   return VT.bitsGT(Op.getValueType())
1244              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1245              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1246 }
1247 
1248 std::pair<SDValue, SDValue>
1249 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1250                                        const SDLoc &DL, EVT VT) {
1251   assert(!VT.bitsEq(Op.getValueType()) &&
1252          "Strict no-op FP extend/round not allowed.");
1253   SDValue Res =
1254       VT.bitsGT(Op.getValueType())
1255           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1256           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1257                     {Chain, Op, getIntPtrConstant(0, DL)});
1258 
1259   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1260 }
1261 
1262 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1263   return VT.bitsGT(Op.getValueType()) ?
1264     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1265     getNode(ISD::TRUNCATE, DL, VT, Op);
1266 }
1267 
1268 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1269   return VT.bitsGT(Op.getValueType()) ?
1270     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1271     getNode(ISD::TRUNCATE, DL, VT, Op);
1272 }
1273 
1274 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1275   return VT.bitsGT(Op.getValueType()) ?
1276     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1277     getNode(ISD::TRUNCATE, DL, VT, Op);
1278 }
1279 
1280 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1281                                         EVT OpVT) {
1282   if (VT.bitsLE(Op.getValueType()))
1283     return getNode(ISD::TRUNCATE, SL, VT, Op);
1284 
1285   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1286   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1287 }
1288 
1289 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1290   EVT OpVT = Op.getValueType();
1291   assert(VT.isInteger() && OpVT.isInteger() &&
1292          "Cannot getZeroExtendInReg FP types");
1293   assert(VT.isVector() == OpVT.isVector() &&
1294          "getZeroExtendInReg type should be vector iff the operand "
1295          "type is vector!");
1296   assert((!VT.isVector() ||
1297           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1298          "Vector element counts must match in getZeroExtendInReg");
1299   assert(VT.bitsLE(OpVT) && "Not extending!");
1300   if (OpVT == VT)
1301     return Op;
1302   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1303                                    VT.getScalarSizeInBits());
1304   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1305 }
1306 
1307 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1308   // Only unsigned pointer semantics are supported right now. In the future this
1309   // might delegate to TLI to check pointer signedness.
1310   return getZExtOrTrunc(Op, DL, VT);
1311 }
1312 
1313 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1314   // Only unsigned pointer semantics are supported right now. In the future this
1315   // might delegate to TLI to check pointer signedness.
1316   return getZeroExtendInReg(Op, DL, VT);
1317 }
1318 
1319 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1320 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1321   EVT EltVT = VT.getScalarType();
1322   SDValue NegOne =
1323     getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1324   return getNode(ISD::XOR, DL, VT, Val, NegOne);
1325 }
1326 
1327 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1328   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1329   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1330 }
1331 
1332 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1333                                       EVT OpVT) {
1334   if (!V)
1335     return getConstant(0, DL, VT);
1336 
1337   switch (TLI->getBooleanContents(OpVT)) {
1338   case TargetLowering::ZeroOrOneBooleanContent:
1339   case TargetLowering::UndefinedBooleanContent:
1340     return getConstant(1, DL, VT);
1341   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1342     return getAllOnesConstant(DL, VT);
1343   }
1344   llvm_unreachable("Unexpected boolean content enum!");
1345 }
1346 
1347 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1348                                   bool isT, bool isO) {
1349   EVT EltVT = VT.getScalarType();
1350   assert((EltVT.getSizeInBits() >= 64 ||
1351           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1352          "getConstant with a uint64_t value that doesn't fit in the type!");
1353   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1354 }
1355 
1356 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1357                                   bool isT, bool isO) {
1358   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1359 }
1360 
1361 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1362                                   EVT VT, bool isT, bool isO) {
1363   assert(VT.isInteger() && "Cannot create FP integer constant!");
1364 
1365   EVT EltVT = VT.getScalarType();
1366   const ConstantInt *Elt = &Val;
1367 
1368   // In some cases the vector type is legal but the element type is illegal and
1369   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1370   // inserted value (the type does not need to match the vector element type).
1371   // Any extra bits introduced will be truncated away.
1372   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1373                            TargetLowering::TypePromoteInteger) {
1374     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1375     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1376     Elt = ConstantInt::get(*getContext(), NewVal);
1377   }
1378   // In other cases the element type is illegal and needs to be expanded, for
1379   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1380   // the value into n parts and use a vector type with n-times the elements.
1381   // Then bitcast to the type requested.
1382   // Legalizing constants too early makes the DAGCombiner's job harder so we
1383   // only legalize if the DAG tells us we must produce legal types.
1384   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1385            TLI->getTypeAction(*getContext(), EltVT) ==
1386                TargetLowering::TypeExpandInteger) {
1387     const APInt &NewVal = Elt->getValue();
1388     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1389     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1390 
1391     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1392     if (VT.isScalableVector()) {
1393       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1394              "Can only handle an even split!");
1395       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1396 
1397       SmallVector<SDValue, 2> ScalarParts;
1398       for (unsigned i = 0; i != Parts; ++i)
1399         ScalarParts.push_back(getConstant(
1400             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1401             ViaEltVT, isT, isO));
1402 
1403       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1404     }
1405 
1406     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1407     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1408 
1409     // Check the temporary vector is the correct size. If this fails then
1410     // getTypeToTransformTo() probably returned a type whose size (in bits)
1411     // isn't a power-of-2 factor of the requested type size.
1412     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1413 
1414     SmallVector<SDValue, 2> EltParts;
1415     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1416       EltParts.push_back(getConstant(
1417           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1418           ViaEltVT, isT, isO));
1419 
1420     // EltParts is currently in little endian order. If we actually want
1421     // big-endian order then reverse it now.
1422     if (getDataLayout().isBigEndian())
1423       std::reverse(EltParts.begin(), EltParts.end());
1424 
1425     // The elements must be reversed when the element order is different
1426     // to the endianness of the elements (because the BITCAST is itself a
1427     // vector shuffle in this situation). However, we do not need any code to
1428     // perform this reversal because getConstant() is producing a vector
1429     // splat.
1430     // This situation occurs in MIPS MSA.
1431 
1432     SmallVector<SDValue, 8> Ops;
1433     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1434       llvm::append_range(Ops, EltParts);
1435 
1436     SDValue V =
1437         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1438     return V;
1439   }
1440 
1441   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1442          "APInt size does not match type size!");
1443   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1444   FoldingSetNodeID ID;
1445   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1446   ID.AddPointer(Elt);
1447   ID.AddBoolean(isO);
1448   void *IP = nullptr;
1449   SDNode *N = nullptr;
1450   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1451     if (!VT.isVector())
1452       return SDValue(N, 0);
1453 
1454   if (!N) {
1455     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1456     CSEMap.InsertNode(N, IP);
1457     InsertNode(N);
1458     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1459   }
1460 
1461   SDValue Result(N, 0);
1462   if (VT.isScalableVector())
1463     Result = getSplatVector(VT, DL, Result);
1464   else if (VT.isVector())
1465     Result = getSplatBuildVector(VT, DL, Result);
1466 
1467   return Result;
1468 }
1469 
1470 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1471                                         bool isTarget) {
1472   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1473 }
1474 
1475 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1476                                              const SDLoc &DL, bool LegalTypes) {
1477   assert(VT.isInteger() && "Shift amount is not an integer type!");
1478   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1479   return getConstant(Val, DL, ShiftVT);
1480 }
1481 
1482 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1483                                            bool isTarget) {
1484   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1485 }
1486 
1487 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1488                                     bool isTarget) {
1489   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1490 }
1491 
1492 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1493                                     EVT VT, bool isTarget) {
1494   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1495 
1496   EVT EltVT = VT.getScalarType();
1497 
1498   // Do the map lookup using the actual bit pattern for the floating point
1499   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1500   // we don't have issues with SNANs.
1501   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1502   FoldingSetNodeID ID;
1503   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1504   ID.AddPointer(&V);
1505   void *IP = nullptr;
1506   SDNode *N = nullptr;
1507   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1508     if (!VT.isVector())
1509       return SDValue(N, 0);
1510 
1511   if (!N) {
1512     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1513     CSEMap.InsertNode(N, IP);
1514     InsertNode(N);
1515   }
1516 
1517   SDValue Result(N, 0);
1518   if (VT.isScalableVector())
1519     Result = getSplatVector(VT, DL, Result);
1520   else if (VT.isVector())
1521     Result = getSplatBuildVector(VT, DL, Result);
1522   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1523   return Result;
1524 }
1525 
1526 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1527                                     bool isTarget) {
1528   EVT EltVT = VT.getScalarType();
1529   if (EltVT == MVT::f32)
1530     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1531   if (EltVT == MVT::f64)
1532     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1533   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1534       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1535     bool Ignored;
1536     APFloat APF = APFloat(Val);
1537     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1538                 &Ignored);
1539     return getConstantFP(APF, DL, VT, isTarget);
1540   }
1541   llvm_unreachable("Unsupported type in getConstantFP");
1542 }
1543 
1544 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1545                                        EVT VT, int64_t Offset, bool isTargetGA,
1546                                        unsigned TargetFlags) {
1547   assert((TargetFlags == 0 || isTargetGA) &&
1548          "Cannot set target flags on target-independent globals");
1549 
1550   // Truncate (with sign-extension) the offset value to the pointer size.
1551   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1552   if (BitWidth < 64)
1553     Offset = SignExtend64(Offset, BitWidth);
1554 
1555   unsigned Opc;
1556   if (GV->isThreadLocal())
1557     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1558   else
1559     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1560 
1561   FoldingSetNodeID ID;
1562   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1563   ID.AddPointer(GV);
1564   ID.AddInteger(Offset);
1565   ID.AddInteger(TargetFlags);
1566   void *IP = nullptr;
1567   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1568     return SDValue(E, 0);
1569 
1570   auto *N = newSDNode<GlobalAddressSDNode>(
1571       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1572   CSEMap.InsertNode(N, IP);
1573     InsertNode(N);
1574   return SDValue(N, 0);
1575 }
1576 
1577 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1578   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1579   FoldingSetNodeID ID;
1580   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1581   ID.AddInteger(FI);
1582   void *IP = nullptr;
1583   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1584     return SDValue(E, 0);
1585 
1586   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1587   CSEMap.InsertNode(N, IP);
1588   InsertNode(N);
1589   return SDValue(N, 0);
1590 }
1591 
1592 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1593                                    unsigned TargetFlags) {
1594   assert((TargetFlags == 0 || isTarget) &&
1595          "Cannot set target flags on target-independent jump tables");
1596   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1597   FoldingSetNodeID ID;
1598   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1599   ID.AddInteger(JTI);
1600   ID.AddInteger(TargetFlags);
1601   void *IP = nullptr;
1602   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1603     return SDValue(E, 0);
1604 
1605   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1606   CSEMap.InsertNode(N, IP);
1607   InsertNode(N);
1608   return SDValue(N, 0);
1609 }
1610 
1611 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1612                                       MaybeAlign Alignment, int Offset,
1613                                       bool isTarget, unsigned TargetFlags) {
1614   assert((TargetFlags == 0 || isTarget) &&
1615          "Cannot set target flags on target-independent globals");
1616   if (!Alignment)
1617     Alignment = shouldOptForSize()
1618                     ? getDataLayout().getABITypeAlign(C->getType())
1619                     : getDataLayout().getPrefTypeAlign(C->getType());
1620   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1621   FoldingSetNodeID ID;
1622   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1623   ID.AddInteger(Alignment->value());
1624   ID.AddInteger(Offset);
1625   ID.AddPointer(C);
1626   ID.AddInteger(TargetFlags);
1627   void *IP = nullptr;
1628   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1629     return SDValue(E, 0);
1630 
1631   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1632                                           TargetFlags);
1633   CSEMap.InsertNode(N, IP);
1634   InsertNode(N);
1635   SDValue V = SDValue(N, 0);
1636   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1637   return V;
1638 }
1639 
1640 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1641                                       MaybeAlign Alignment, int Offset,
1642                                       bool isTarget, unsigned TargetFlags) {
1643   assert((TargetFlags == 0 || isTarget) &&
1644          "Cannot set target flags on target-independent globals");
1645   if (!Alignment)
1646     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1647   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1648   FoldingSetNodeID ID;
1649   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1650   ID.AddInteger(Alignment->value());
1651   ID.AddInteger(Offset);
1652   C->addSelectionDAGCSEId(ID);
1653   ID.AddInteger(TargetFlags);
1654   void *IP = nullptr;
1655   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1656     return SDValue(E, 0);
1657 
1658   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1659                                           TargetFlags);
1660   CSEMap.InsertNode(N, IP);
1661   InsertNode(N);
1662   return SDValue(N, 0);
1663 }
1664 
1665 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1666                                      unsigned TargetFlags) {
1667   FoldingSetNodeID ID;
1668   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1669   ID.AddInteger(Index);
1670   ID.AddInteger(Offset);
1671   ID.AddInteger(TargetFlags);
1672   void *IP = nullptr;
1673   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1674     return SDValue(E, 0);
1675 
1676   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1677   CSEMap.InsertNode(N, IP);
1678   InsertNode(N);
1679   return SDValue(N, 0);
1680 }
1681 
1682 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1683   FoldingSetNodeID ID;
1684   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1685   ID.AddPointer(MBB);
1686   void *IP = nullptr;
1687   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1688     return SDValue(E, 0);
1689 
1690   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1691   CSEMap.InsertNode(N, IP);
1692   InsertNode(N);
1693   return SDValue(N, 0);
1694 }
1695 
1696 SDValue SelectionDAG::getValueType(EVT VT) {
1697   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1698       ValueTypeNodes.size())
1699     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1700 
1701   SDNode *&N = VT.isExtended() ?
1702     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1703 
1704   if (N) return SDValue(N, 0);
1705   N = newSDNode<VTSDNode>(VT);
1706   InsertNode(N);
1707   return SDValue(N, 0);
1708 }
1709 
1710 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1711   SDNode *&N = ExternalSymbols[Sym];
1712   if (N) return SDValue(N, 0);
1713   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1714   InsertNode(N);
1715   return SDValue(N, 0);
1716 }
1717 
1718 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1719   SDNode *&N = MCSymbols[Sym];
1720   if (N)
1721     return SDValue(N, 0);
1722   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1723   InsertNode(N);
1724   return SDValue(N, 0);
1725 }
1726 
1727 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1728                                               unsigned TargetFlags) {
1729   SDNode *&N =
1730       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1731   if (N) return SDValue(N, 0);
1732   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1733   InsertNode(N);
1734   return SDValue(N, 0);
1735 }
1736 
1737 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1738   if ((unsigned)Cond >= CondCodeNodes.size())
1739     CondCodeNodes.resize(Cond+1);
1740 
1741   if (!CondCodeNodes[Cond]) {
1742     auto *N = newSDNode<CondCodeSDNode>(Cond);
1743     CondCodeNodes[Cond] = N;
1744     InsertNode(N);
1745   }
1746 
1747   return SDValue(CondCodeNodes[Cond], 0);
1748 }
1749 
1750 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1751   EVT OpVT = TLI->getTypeToTransformTo(*getContext(), ResVT.getScalarType());
1752   return getStepVector(DL, ResVT, getConstant(1, DL, OpVT));
1753 }
1754 
1755 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, SDValue Step) {
1756   if (ResVT.isScalableVector())
1757     return getNode(ISD::STEP_VECTOR, DL, ResVT, Step);
1758 
1759   EVT OpVT = Step.getValueType();
1760   APInt StepVal = cast<ConstantSDNode>(Step)->getAPIntValue();
1761   SmallVector<SDValue, 16> OpsStepConstants;
1762   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1763     OpsStepConstants.push_back(getConstant(StepVal * i, DL, OpVT));
1764   return getBuildVector(ResVT, DL, OpsStepConstants);
1765 }
1766 
1767 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1768 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1769 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1770   std::swap(N1, N2);
1771   ShuffleVectorSDNode::commuteMask(M);
1772 }
1773 
1774 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1775                                        SDValue N2, ArrayRef<int> Mask) {
1776   assert(VT.getVectorNumElements() == Mask.size() &&
1777          "Must have the same number of vector elements as mask elements!");
1778   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1779          "Invalid VECTOR_SHUFFLE");
1780 
1781   // Canonicalize shuffle undef, undef -> undef
1782   if (N1.isUndef() && N2.isUndef())
1783     return getUNDEF(VT);
1784 
1785   // Validate that all indices in Mask are within the range of the elements
1786   // input to the shuffle.
1787   int NElts = Mask.size();
1788   assert(llvm::all_of(Mask,
1789                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1790          "Index out of range");
1791 
1792   // Copy the mask so we can do any needed cleanup.
1793   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1794 
1795   // Canonicalize shuffle v, v -> v, undef
1796   if (N1 == N2) {
1797     N2 = getUNDEF(VT);
1798     for (int i = 0; i != NElts; ++i)
1799       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1800   }
1801 
1802   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1803   if (N1.isUndef())
1804     commuteShuffle(N1, N2, MaskVec);
1805 
1806   if (TLI->hasVectorBlend()) {
1807     // If shuffling a splat, try to blend the splat instead. We do this here so
1808     // that even when this arises during lowering we don't have to re-handle it.
1809     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1810       BitVector UndefElements;
1811       SDValue Splat = BV->getSplatValue(&UndefElements);
1812       if (!Splat)
1813         return;
1814 
1815       for (int i = 0; i < NElts; ++i) {
1816         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1817           continue;
1818 
1819         // If this input comes from undef, mark it as such.
1820         if (UndefElements[MaskVec[i] - Offset]) {
1821           MaskVec[i] = -1;
1822           continue;
1823         }
1824 
1825         // If we can blend a non-undef lane, use that instead.
1826         if (!UndefElements[i])
1827           MaskVec[i] = i + Offset;
1828       }
1829     };
1830     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1831       BlendSplat(N1BV, 0);
1832     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1833       BlendSplat(N2BV, NElts);
1834   }
1835 
1836   // Canonicalize all index into lhs, -> shuffle lhs, undef
1837   // Canonicalize all index into rhs, -> shuffle rhs, undef
1838   bool AllLHS = true, AllRHS = true;
1839   bool N2Undef = N2.isUndef();
1840   for (int i = 0; i != NElts; ++i) {
1841     if (MaskVec[i] >= NElts) {
1842       if (N2Undef)
1843         MaskVec[i] = -1;
1844       else
1845         AllLHS = false;
1846     } else if (MaskVec[i] >= 0) {
1847       AllRHS = false;
1848     }
1849   }
1850   if (AllLHS && AllRHS)
1851     return getUNDEF(VT);
1852   if (AllLHS && !N2Undef)
1853     N2 = getUNDEF(VT);
1854   if (AllRHS) {
1855     N1 = getUNDEF(VT);
1856     commuteShuffle(N1, N2, MaskVec);
1857   }
1858   // Reset our undef status after accounting for the mask.
1859   N2Undef = N2.isUndef();
1860   // Re-check whether both sides ended up undef.
1861   if (N1.isUndef() && N2Undef)
1862     return getUNDEF(VT);
1863 
1864   // If Identity shuffle return that node.
1865   bool Identity = true, AllSame = true;
1866   for (int i = 0; i != NElts; ++i) {
1867     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1868     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1869   }
1870   if (Identity && NElts)
1871     return N1;
1872 
1873   // Shuffling a constant splat doesn't change the result.
1874   if (N2Undef) {
1875     SDValue V = N1;
1876 
1877     // Look through any bitcasts. We check that these don't change the number
1878     // (and size) of elements and just changes their types.
1879     while (V.getOpcode() == ISD::BITCAST)
1880       V = V->getOperand(0);
1881 
1882     // A splat should always show up as a build vector node.
1883     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1884       BitVector UndefElements;
1885       SDValue Splat = BV->getSplatValue(&UndefElements);
1886       // If this is a splat of an undef, shuffling it is also undef.
1887       if (Splat && Splat.isUndef())
1888         return getUNDEF(VT);
1889 
1890       bool SameNumElts =
1891           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1892 
1893       // We only have a splat which can skip shuffles if there is a splatted
1894       // value and no undef lanes rearranged by the shuffle.
1895       if (Splat && UndefElements.none()) {
1896         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1897         // number of elements match or the value splatted is a zero constant.
1898         if (SameNumElts)
1899           return N1;
1900         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1901           if (C->isNullValue())
1902             return N1;
1903       }
1904 
1905       // If the shuffle itself creates a splat, build the vector directly.
1906       if (AllSame && SameNumElts) {
1907         EVT BuildVT = BV->getValueType(0);
1908         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1909         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1910 
1911         // We may have jumped through bitcasts, so the type of the
1912         // BUILD_VECTOR may not match the type of the shuffle.
1913         if (BuildVT != VT)
1914           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1915         return NewBV;
1916       }
1917     }
1918   }
1919 
1920   FoldingSetNodeID ID;
1921   SDValue Ops[2] = { N1, N2 };
1922   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1923   for (int i = 0; i != NElts; ++i)
1924     ID.AddInteger(MaskVec[i]);
1925 
1926   void* IP = nullptr;
1927   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1928     return SDValue(E, 0);
1929 
1930   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1931   // SDNode doesn't have access to it.  This memory will be "leaked" when
1932   // the node is deallocated, but recovered when the NodeAllocator is released.
1933   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1934   llvm::copy(MaskVec, MaskAlloc);
1935 
1936   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1937                                            dl.getDebugLoc(), MaskAlloc);
1938   createOperands(N, Ops);
1939 
1940   CSEMap.InsertNode(N, IP);
1941   InsertNode(N);
1942   SDValue V = SDValue(N, 0);
1943   NewSDValueDbgMsg(V, "Creating new node: ", this);
1944   return V;
1945 }
1946 
1947 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1948   EVT VT = SV.getValueType(0);
1949   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1950   ShuffleVectorSDNode::commuteMask(MaskVec);
1951 
1952   SDValue Op0 = SV.getOperand(0);
1953   SDValue Op1 = SV.getOperand(1);
1954   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1955 }
1956 
1957 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1958   FoldingSetNodeID ID;
1959   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1960   ID.AddInteger(RegNo);
1961   void *IP = nullptr;
1962   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1963     return SDValue(E, 0);
1964 
1965   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1966   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1967   CSEMap.InsertNode(N, IP);
1968   InsertNode(N);
1969   return SDValue(N, 0);
1970 }
1971 
1972 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1973   FoldingSetNodeID ID;
1974   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1975   ID.AddPointer(RegMask);
1976   void *IP = nullptr;
1977   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1978     return SDValue(E, 0);
1979 
1980   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1981   CSEMap.InsertNode(N, IP);
1982   InsertNode(N);
1983   return SDValue(N, 0);
1984 }
1985 
1986 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1987                                  MCSymbol *Label) {
1988   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1989 }
1990 
1991 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1992                                    SDValue Root, MCSymbol *Label) {
1993   FoldingSetNodeID ID;
1994   SDValue Ops[] = { Root };
1995   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1996   ID.AddPointer(Label);
1997   void *IP = nullptr;
1998   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1999     return SDValue(E, 0);
2000 
2001   auto *N =
2002       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2003   createOperands(N, Ops);
2004 
2005   CSEMap.InsertNode(N, IP);
2006   InsertNode(N);
2007   return SDValue(N, 0);
2008 }
2009 
2010 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2011                                       int64_t Offset, bool isTarget,
2012                                       unsigned TargetFlags) {
2013   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2014 
2015   FoldingSetNodeID ID;
2016   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2017   ID.AddPointer(BA);
2018   ID.AddInteger(Offset);
2019   ID.AddInteger(TargetFlags);
2020   void *IP = nullptr;
2021   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2022     return SDValue(E, 0);
2023 
2024   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2025   CSEMap.InsertNode(N, IP);
2026   InsertNode(N);
2027   return SDValue(N, 0);
2028 }
2029 
2030 SDValue SelectionDAG::getSrcValue(const Value *V) {
2031   FoldingSetNodeID ID;
2032   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2033   ID.AddPointer(V);
2034 
2035   void *IP = nullptr;
2036   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2037     return SDValue(E, 0);
2038 
2039   auto *N = newSDNode<SrcValueSDNode>(V);
2040   CSEMap.InsertNode(N, IP);
2041   InsertNode(N);
2042   return SDValue(N, 0);
2043 }
2044 
2045 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2046   FoldingSetNodeID ID;
2047   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2048   ID.AddPointer(MD);
2049 
2050   void *IP = nullptr;
2051   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2052     return SDValue(E, 0);
2053 
2054   auto *N = newSDNode<MDNodeSDNode>(MD);
2055   CSEMap.InsertNode(N, IP);
2056   InsertNode(N);
2057   return SDValue(N, 0);
2058 }
2059 
2060 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2061   if (VT == V.getValueType())
2062     return V;
2063 
2064   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2065 }
2066 
2067 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2068                                        unsigned SrcAS, unsigned DestAS) {
2069   SDValue Ops[] = {Ptr};
2070   FoldingSetNodeID ID;
2071   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2072   ID.AddInteger(SrcAS);
2073   ID.AddInteger(DestAS);
2074 
2075   void *IP = nullptr;
2076   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2077     return SDValue(E, 0);
2078 
2079   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2080                                            VT, SrcAS, DestAS);
2081   createOperands(N, Ops);
2082 
2083   CSEMap.InsertNode(N, IP);
2084   InsertNode(N);
2085   return SDValue(N, 0);
2086 }
2087 
2088 SDValue SelectionDAG::getFreeze(SDValue V) {
2089   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2090 }
2091 
2092 /// getShiftAmountOperand - Return the specified value casted to
2093 /// the target's desired shift amount type.
2094 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2095   EVT OpTy = Op.getValueType();
2096   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2097   if (OpTy == ShTy || OpTy.isVector()) return Op;
2098 
2099   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2100 }
2101 
2102 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2103   SDLoc dl(Node);
2104   const TargetLowering &TLI = getTargetLoweringInfo();
2105   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2106   EVT VT = Node->getValueType(0);
2107   SDValue Tmp1 = Node->getOperand(0);
2108   SDValue Tmp2 = Node->getOperand(1);
2109   const MaybeAlign MA(Node->getConstantOperandVal(3));
2110 
2111   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2112                                Tmp2, MachinePointerInfo(V));
2113   SDValue VAList = VAListLoad;
2114 
2115   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2116     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2117                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2118 
2119     VAList =
2120         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2121                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2122   }
2123 
2124   // Increment the pointer, VAList, to the next vaarg
2125   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2126                  getConstant(getDataLayout().getTypeAllocSize(
2127                                                VT.getTypeForEVT(*getContext())),
2128                              dl, VAList.getValueType()));
2129   // Store the incremented VAList to the legalized pointer
2130   Tmp1 =
2131       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2132   // Load the actual argument out of the pointer VAList
2133   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2134 }
2135 
2136 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2137   SDLoc dl(Node);
2138   const TargetLowering &TLI = getTargetLoweringInfo();
2139   // This defaults to loading a pointer from the input and storing it to the
2140   // output, returning the chain.
2141   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2142   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2143   SDValue Tmp1 =
2144       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2145               Node->getOperand(2), MachinePointerInfo(VS));
2146   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2147                   MachinePointerInfo(VD));
2148 }
2149 
2150 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2151   const DataLayout &DL = getDataLayout();
2152   Type *Ty = VT.getTypeForEVT(*getContext());
2153   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2154 
2155   if (TLI->isTypeLegal(VT) || !VT.isVector())
2156     return RedAlign;
2157 
2158   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2159   const Align StackAlign = TFI->getStackAlign();
2160 
2161   // See if we can choose a smaller ABI alignment in cases where it's an
2162   // illegal vector type that will get broken down.
2163   if (RedAlign > StackAlign) {
2164     EVT IntermediateVT;
2165     MVT RegisterVT;
2166     unsigned NumIntermediates;
2167     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2168                                 NumIntermediates, RegisterVT);
2169     Ty = IntermediateVT.getTypeForEVT(*getContext());
2170     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2171     if (RedAlign2 < RedAlign)
2172       RedAlign = RedAlign2;
2173   }
2174 
2175   return RedAlign;
2176 }
2177 
2178 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2179   MachineFrameInfo &MFI = MF->getFrameInfo();
2180   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2181   int StackID = 0;
2182   if (Bytes.isScalable())
2183     StackID = TFI->getStackIDForScalableVectors();
2184   // The stack id gives an indication of whether the object is scalable or
2185   // not, so it's safe to pass in the minimum size here.
2186   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2187                                        false, nullptr, StackID);
2188   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2189 }
2190 
2191 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2192   Type *Ty = VT.getTypeForEVT(*getContext());
2193   Align StackAlign =
2194       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2195   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2196 }
2197 
2198 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2199   TypeSize VT1Size = VT1.getStoreSize();
2200   TypeSize VT2Size = VT2.getStoreSize();
2201   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2202          "Don't know how to choose the maximum size when creating a stack "
2203          "temporary");
2204   TypeSize Bytes =
2205       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2206 
2207   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2208   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2209   const DataLayout &DL = getDataLayout();
2210   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2211   return CreateStackTemporary(Bytes, Align);
2212 }
2213 
2214 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2215                                 ISD::CondCode Cond, const SDLoc &dl) {
2216   EVT OpVT = N1.getValueType();
2217 
2218   // These setcc operations always fold.
2219   switch (Cond) {
2220   default: break;
2221   case ISD::SETFALSE:
2222   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2223   case ISD::SETTRUE:
2224   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2225 
2226   case ISD::SETOEQ:
2227   case ISD::SETOGT:
2228   case ISD::SETOGE:
2229   case ISD::SETOLT:
2230   case ISD::SETOLE:
2231   case ISD::SETONE:
2232   case ISD::SETO:
2233   case ISD::SETUO:
2234   case ISD::SETUEQ:
2235   case ISD::SETUNE:
2236     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2237     break;
2238   }
2239 
2240   if (OpVT.isInteger()) {
2241     // For EQ and NE, we can always pick a value for the undef to make the
2242     // predicate pass or fail, so we can return undef.
2243     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2244     // icmp eq/ne X, undef -> undef.
2245     if ((N1.isUndef() || N2.isUndef()) &&
2246         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2247       return getUNDEF(VT);
2248 
2249     // If both operands are undef, we can return undef for int comparison.
2250     // icmp undef, undef -> undef.
2251     if (N1.isUndef() && N2.isUndef())
2252       return getUNDEF(VT);
2253 
2254     // icmp X, X -> true/false
2255     // icmp X, undef -> true/false because undef could be X.
2256     if (N1 == N2)
2257       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2258   }
2259 
2260   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2261     const APInt &C2 = N2C->getAPIntValue();
2262     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2263       const APInt &C1 = N1C->getAPIntValue();
2264 
2265       switch (Cond) {
2266       default: llvm_unreachable("Unknown integer setcc!");
2267       case ISD::SETEQ:  return getBoolConstant(C1 == C2, dl, VT, OpVT);
2268       case ISD::SETNE:  return getBoolConstant(C1 != C2, dl, VT, OpVT);
2269       case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2270       case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2271       case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2272       case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2273       case ISD::SETLT:  return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2274       case ISD::SETGT:  return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2275       case ISD::SETLE:  return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2276       case ISD::SETGE:  return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2277       }
2278     }
2279   }
2280 
2281   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2282   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2283 
2284   if (N1CFP && N2CFP) {
2285     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2286     switch (Cond) {
2287     default: break;
2288     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2289                         return getUNDEF(VT);
2290                       LLVM_FALLTHROUGH;
2291     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2292                                              OpVT);
2293     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2294                         return getUNDEF(VT);
2295                       LLVM_FALLTHROUGH;
2296     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2297                                              R==APFloat::cmpLessThan, dl, VT,
2298                                              OpVT);
2299     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2300                         return getUNDEF(VT);
2301                       LLVM_FALLTHROUGH;
2302     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2303                                              OpVT);
2304     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2305                         return getUNDEF(VT);
2306                       LLVM_FALLTHROUGH;
2307     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2308                                              VT, OpVT);
2309     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2310                         return getUNDEF(VT);
2311                       LLVM_FALLTHROUGH;
2312     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2313                                              R==APFloat::cmpEqual, dl, VT,
2314                                              OpVT);
2315     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2316                         return getUNDEF(VT);
2317                       LLVM_FALLTHROUGH;
2318     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2319                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2320     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2321                                              OpVT);
2322     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2323                                              OpVT);
2324     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2325                                              R==APFloat::cmpEqual, dl, VT,
2326                                              OpVT);
2327     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2328                                              OpVT);
2329     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2330                                              R==APFloat::cmpLessThan, dl, VT,
2331                                              OpVT);
2332     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2333                                              R==APFloat::cmpUnordered, dl, VT,
2334                                              OpVT);
2335     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2336                                              VT, OpVT);
2337     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2338                                              OpVT);
2339     }
2340   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2341     // Ensure that the constant occurs on the RHS.
2342     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2343     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2344       return SDValue();
2345     return getSetCC(dl, VT, N2, N1, SwappedCond);
2346   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2347              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2348     // If an operand is known to be a nan (or undef that could be a nan), we can
2349     // fold it.
2350     // Choosing NaN for the undef will always make unordered comparison succeed
2351     // and ordered comparison fails.
2352     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2353     switch (ISD::getUnorderedFlavor(Cond)) {
2354     default:
2355       llvm_unreachable("Unknown flavor!");
2356     case 0: // Known false.
2357       return getBoolConstant(false, dl, VT, OpVT);
2358     case 1: // Known true.
2359       return getBoolConstant(true, dl, VT, OpVT);
2360     case 2: // Undefined.
2361       return getUNDEF(VT);
2362     }
2363   }
2364 
2365   // Could not fold it.
2366   return SDValue();
2367 }
2368 
2369 /// See if the specified operand can be simplified with the knowledge that only
2370 /// the bits specified by DemandedBits are used.
2371 /// TODO: really we should be making this into the DAG equivalent of
2372 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2373 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2374   EVT VT = V.getValueType();
2375 
2376   if (VT.isScalableVector())
2377     return SDValue();
2378 
2379   APInt DemandedElts = VT.isVector()
2380                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2381                            : APInt(1, 1);
2382   return GetDemandedBits(V, DemandedBits, DemandedElts);
2383 }
2384 
2385 /// See if the specified operand can be simplified with the knowledge that only
2386 /// the bits specified by DemandedBits are used in the elements specified by
2387 /// DemandedElts.
2388 /// TODO: really we should be making this into the DAG equivalent of
2389 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2390 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2391                                       const APInt &DemandedElts) {
2392   switch (V.getOpcode()) {
2393   default:
2394     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2395                                                 *this, 0);
2396   case ISD::Constant: {
2397     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2398     APInt NewVal = CVal & DemandedBits;
2399     if (NewVal != CVal)
2400       return getConstant(NewVal, SDLoc(V), V.getValueType());
2401     break;
2402   }
2403   case ISD::SRL:
2404     // Only look at single-use SRLs.
2405     if (!V.getNode()->hasOneUse())
2406       break;
2407     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2408       // See if we can recursively simplify the LHS.
2409       unsigned Amt = RHSC->getZExtValue();
2410 
2411       // Watch out for shift count overflow though.
2412       if (Amt >= DemandedBits.getBitWidth())
2413         break;
2414       APInt SrcDemandedBits = DemandedBits << Amt;
2415       if (SDValue SimplifyLHS =
2416               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2417         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2418                        V.getOperand(1));
2419     }
2420     break;
2421   }
2422   return SDValue();
2423 }
2424 
2425 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2426 /// use this predicate to simplify operations downstream.
2427 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2428   unsigned BitWidth = Op.getScalarValueSizeInBits();
2429   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2430 }
2431 
2432 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2433 /// this predicate to simplify operations downstream.  Mask is known to be zero
2434 /// for bits that V cannot have.
2435 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2436                                      unsigned Depth) const {
2437   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2438 }
2439 
2440 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2441 /// DemandedElts.  We use this predicate to simplify operations downstream.
2442 /// Mask is known to be zero for bits that V cannot have.
2443 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2444                                      const APInt &DemandedElts,
2445                                      unsigned Depth) const {
2446   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2447 }
2448 
2449 /// Return true if the DemandedElts of the vector Op are all zero.  We
2450 /// use this predicate to simplify operations downstream.
2451 bool SelectionDAG::MaskedElementsAreZero(SDValue Op, const APInt &DemandedElts,
2452                                          unsigned Depth) const {
2453   assert(Op.getValueType().isFixedLengthVector() &&
2454          Op.getValueType().getVectorNumElements() ==
2455              DemandedElts.getBitWidth() &&
2456          "MaskedElementsAreZero vector size mismatch");
2457   unsigned BitWidth = Op.getScalarValueSizeInBits();
2458   APInt DemandedBits = APInt::getAllOnesValue(BitWidth);
2459   return MaskedValueIsZero(Op, DemandedBits, DemandedElts, Depth);
2460 }
2461 
2462 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2463 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2464                                         unsigned Depth) const {
2465   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2466 }
2467 
2468 /// isSplatValue - Return true if the vector V has the same value
2469 /// across all DemandedElts. For scalable vectors it does not make
2470 /// sense to specify which elements are demanded or undefined, therefore
2471 /// they are simply ignored.
2472 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2473                                 APInt &UndefElts, unsigned Depth) {
2474   EVT VT = V.getValueType();
2475   assert(VT.isVector() && "Vector type expected");
2476 
2477   if (!VT.isScalableVector() && !DemandedElts)
2478     return false; // No demanded elts, better to assume we don't know anything.
2479 
2480   if (Depth >= MaxRecursionDepth)
2481     return false; // Limit search depth.
2482 
2483   // Deal with some common cases here that work for both fixed and scalable
2484   // vector types.
2485   switch (V.getOpcode()) {
2486   case ISD::SPLAT_VECTOR:
2487     UndefElts = V.getOperand(0).isUndef()
2488                     ? APInt::getAllOnesValue(DemandedElts.getBitWidth())
2489                     : APInt(DemandedElts.getBitWidth(), 0);
2490     return true;
2491   case ISD::ADD:
2492   case ISD::SUB:
2493   case ISD::AND:
2494   case ISD::XOR:
2495   case ISD::OR: {
2496     APInt UndefLHS, UndefRHS;
2497     SDValue LHS = V.getOperand(0);
2498     SDValue RHS = V.getOperand(1);
2499     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2500         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2501       UndefElts = UndefLHS | UndefRHS;
2502       return true;
2503     }
2504     return false;
2505   }
2506   case ISD::ABS:
2507   case ISD::TRUNCATE:
2508   case ISD::SIGN_EXTEND:
2509   case ISD::ZERO_EXTEND:
2510     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2511   }
2512 
2513   // We don't support other cases than those above for scalable vectors at
2514   // the moment.
2515   if (VT.isScalableVector())
2516     return false;
2517 
2518   unsigned NumElts = VT.getVectorNumElements();
2519   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2520   UndefElts = APInt::getNullValue(NumElts);
2521 
2522   switch (V.getOpcode()) {
2523   case ISD::BUILD_VECTOR: {
2524     SDValue Scl;
2525     for (unsigned i = 0; i != NumElts; ++i) {
2526       SDValue Op = V.getOperand(i);
2527       if (Op.isUndef()) {
2528         UndefElts.setBit(i);
2529         continue;
2530       }
2531       if (!DemandedElts[i])
2532         continue;
2533       if (Scl && Scl != Op)
2534         return false;
2535       Scl = Op;
2536     }
2537     return true;
2538   }
2539   case ISD::VECTOR_SHUFFLE: {
2540     // Check if this is a shuffle node doing a splat.
2541     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2542     int SplatIndex = -1;
2543     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2544     for (int i = 0; i != (int)NumElts; ++i) {
2545       int M = Mask[i];
2546       if (M < 0) {
2547         UndefElts.setBit(i);
2548         continue;
2549       }
2550       if (!DemandedElts[i])
2551         continue;
2552       if (0 <= SplatIndex && SplatIndex != M)
2553         return false;
2554       SplatIndex = M;
2555     }
2556     return true;
2557   }
2558   case ISD::EXTRACT_SUBVECTOR: {
2559     // Offset the demanded elts by the subvector index.
2560     SDValue Src = V.getOperand(0);
2561     // We don't support scalable vectors at the moment.
2562     if (Src.getValueType().isScalableVector())
2563       return false;
2564     uint64_t Idx = V.getConstantOperandVal(1);
2565     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2566     APInt UndefSrcElts;
2567     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2568     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2569       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2570       return true;
2571     }
2572     break;
2573   }
2574   }
2575 
2576   return false;
2577 }
2578 
2579 /// Helper wrapper to main isSplatValue function.
2580 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2581   EVT VT = V.getValueType();
2582   assert(VT.isVector() && "Vector type expected");
2583 
2584   APInt UndefElts;
2585   APInt DemandedElts;
2586 
2587   // For now we don't support this with scalable vectors.
2588   if (!VT.isScalableVector())
2589     DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2590   return isSplatValue(V, DemandedElts, UndefElts) &&
2591          (AllowUndefs || !UndefElts);
2592 }
2593 
2594 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2595   V = peekThroughExtractSubvectors(V);
2596 
2597   EVT VT = V.getValueType();
2598   unsigned Opcode = V.getOpcode();
2599   switch (Opcode) {
2600   default: {
2601     APInt UndefElts;
2602     APInt DemandedElts;
2603 
2604     if (!VT.isScalableVector())
2605       DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2606 
2607     if (isSplatValue(V, DemandedElts, UndefElts)) {
2608       if (VT.isScalableVector()) {
2609         // DemandedElts and UndefElts are ignored for scalable vectors, since
2610         // the only supported cases are SPLAT_VECTOR nodes.
2611         SplatIdx = 0;
2612       } else {
2613         // Handle case where all demanded elements are UNDEF.
2614         if (DemandedElts.isSubsetOf(UndefElts)) {
2615           SplatIdx = 0;
2616           return getUNDEF(VT);
2617         }
2618         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2619       }
2620       return V;
2621     }
2622     break;
2623   }
2624   case ISD::SPLAT_VECTOR:
2625     SplatIdx = 0;
2626     return V;
2627   case ISD::VECTOR_SHUFFLE: {
2628     if (VT.isScalableVector())
2629       return SDValue();
2630 
2631     // Check if this is a shuffle node doing a splat.
2632     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2633     // getTargetVShiftNode currently struggles without the splat source.
2634     auto *SVN = cast<ShuffleVectorSDNode>(V);
2635     if (!SVN->isSplat())
2636       break;
2637     int Idx = SVN->getSplatIndex();
2638     int NumElts = V.getValueType().getVectorNumElements();
2639     SplatIdx = Idx % NumElts;
2640     return V.getOperand(Idx / NumElts);
2641   }
2642   }
2643 
2644   return SDValue();
2645 }
2646 
2647 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2648   int SplatIdx;
2649   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2650     EVT SVT = SrcVector.getValueType().getScalarType();
2651     EVT LegalSVT = SVT;
2652     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2653       if (!SVT.isInteger())
2654         return SDValue();
2655       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2656       if (LegalSVT.bitsLT(SVT))
2657         return SDValue();
2658     }
2659     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2660                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2661   }
2662   return SDValue();
2663 }
2664 
2665 const APInt *
2666 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2667                                           const APInt &DemandedElts) const {
2668   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2669           V.getOpcode() == ISD::SRA) &&
2670          "Unknown shift node");
2671   unsigned BitWidth = V.getScalarValueSizeInBits();
2672   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2673     // Shifting more than the bitwidth is not valid.
2674     const APInt &ShAmt = SA->getAPIntValue();
2675     if (ShAmt.ult(BitWidth))
2676       return &ShAmt;
2677   }
2678   return nullptr;
2679 }
2680 
2681 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2682     SDValue V, const APInt &DemandedElts) const {
2683   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2684           V.getOpcode() == ISD::SRA) &&
2685          "Unknown shift node");
2686   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2687     return ValidAmt;
2688   unsigned BitWidth = V.getScalarValueSizeInBits();
2689   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2690   if (!BV)
2691     return nullptr;
2692   const APInt *MinShAmt = nullptr;
2693   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2694     if (!DemandedElts[i])
2695       continue;
2696     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2697     if (!SA)
2698       return nullptr;
2699     // Shifting more than the bitwidth is not valid.
2700     const APInt &ShAmt = SA->getAPIntValue();
2701     if (ShAmt.uge(BitWidth))
2702       return nullptr;
2703     if (MinShAmt && MinShAmt->ule(ShAmt))
2704       continue;
2705     MinShAmt = &ShAmt;
2706   }
2707   return MinShAmt;
2708 }
2709 
2710 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2711     SDValue V, const APInt &DemandedElts) const {
2712   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2713           V.getOpcode() == ISD::SRA) &&
2714          "Unknown shift node");
2715   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2716     return ValidAmt;
2717   unsigned BitWidth = V.getScalarValueSizeInBits();
2718   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2719   if (!BV)
2720     return nullptr;
2721   const APInt *MaxShAmt = nullptr;
2722   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2723     if (!DemandedElts[i])
2724       continue;
2725     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2726     if (!SA)
2727       return nullptr;
2728     // Shifting more than the bitwidth is not valid.
2729     const APInt &ShAmt = SA->getAPIntValue();
2730     if (ShAmt.uge(BitWidth))
2731       return nullptr;
2732     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2733       continue;
2734     MaxShAmt = &ShAmt;
2735   }
2736   return MaxShAmt;
2737 }
2738 
2739 /// Determine which bits of Op are known to be either zero or one and return
2740 /// them in Known. For vectors, the known bits are those that are shared by
2741 /// every vector element.
2742 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2743   EVT VT = Op.getValueType();
2744 
2745   // TOOD: Until we have a plan for how to represent demanded elements for
2746   // scalable vectors, we can just bail out for now.
2747   if (Op.getValueType().isScalableVector()) {
2748     unsigned BitWidth = Op.getScalarValueSizeInBits();
2749     return KnownBits(BitWidth);
2750   }
2751 
2752   APInt DemandedElts = VT.isVector()
2753                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2754                            : APInt(1, 1);
2755   return computeKnownBits(Op, DemandedElts, Depth);
2756 }
2757 
2758 /// Determine which bits of Op are known to be either zero or one and return
2759 /// them in Known. The DemandedElts argument allows us to only collect the known
2760 /// bits that are shared by the requested vector elements.
2761 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2762                                          unsigned Depth) const {
2763   unsigned BitWidth = Op.getScalarValueSizeInBits();
2764 
2765   KnownBits Known(BitWidth);   // Don't know anything.
2766 
2767   // TOOD: Until we have a plan for how to represent demanded elements for
2768   // scalable vectors, we can just bail out for now.
2769   if (Op.getValueType().isScalableVector())
2770     return Known;
2771 
2772   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2773     // We know all of the bits for a constant!
2774     return KnownBits::makeConstant(C->getAPIntValue());
2775   }
2776   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2777     // We know all of the bits for a constant fp!
2778     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2779   }
2780 
2781   if (Depth >= MaxRecursionDepth)
2782     return Known;  // Limit search depth.
2783 
2784   KnownBits Known2;
2785   unsigned NumElts = DemandedElts.getBitWidth();
2786   assert((!Op.getValueType().isVector() ||
2787           NumElts == Op.getValueType().getVectorNumElements()) &&
2788          "Unexpected vector size");
2789 
2790   if (!DemandedElts)
2791     return Known;  // No demanded elts, better to assume we don't know anything.
2792 
2793   unsigned Opcode = Op.getOpcode();
2794   switch (Opcode) {
2795   case ISD::BUILD_VECTOR:
2796     // Collect the known bits that are shared by every demanded vector element.
2797     Known.Zero.setAllBits(); Known.One.setAllBits();
2798     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2799       if (!DemandedElts[i])
2800         continue;
2801 
2802       SDValue SrcOp = Op.getOperand(i);
2803       Known2 = computeKnownBits(SrcOp, Depth + 1);
2804 
2805       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2806       if (SrcOp.getValueSizeInBits() != BitWidth) {
2807         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2808                "Expected BUILD_VECTOR implicit truncation");
2809         Known2 = Known2.trunc(BitWidth);
2810       }
2811 
2812       // Known bits are the values that are shared by every demanded element.
2813       Known = KnownBits::commonBits(Known, Known2);
2814 
2815       // If we don't know any bits, early out.
2816       if (Known.isUnknown())
2817         break;
2818     }
2819     break;
2820   case ISD::VECTOR_SHUFFLE: {
2821     // Collect the known bits that are shared by every vector element referenced
2822     // by the shuffle.
2823     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2824     Known.Zero.setAllBits(); Known.One.setAllBits();
2825     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2826     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2827     for (unsigned i = 0; i != NumElts; ++i) {
2828       if (!DemandedElts[i])
2829         continue;
2830 
2831       int M = SVN->getMaskElt(i);
2832       if (M < 0) {
2833         // For UNDEF elements, we don't know anything about the common state of
2834         // the shuffle result.
2835         Known.resetAll();
2836         DemandedLHS.clearAllBits();
2837         DemandedRHS.clearAllBits();
2838         break;
2839       }
2840 
2841       if ((unsigned)M < NumElts)
2842         DemandedLHS.setBit((unsigned)M % NumElts);
2843       else
2844         DemandedRHS.setBit((unsigned)M % NumElts);
2845     }
2846     // Known bits are the values that are shared by every demanded element.
2847     if (!!DemandedLHS) {
2848       SDValue LHS = Op.getOperand(0);
2849       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2850       Known = KnownBits::commonBits(Known, Known2);
2851     }
2852     // If we don't know any bits, early out.
2853     if (Known.isUnknown())
2854       break;
2855     if (!!DemandedRHS) {
2856       SDValue RHS = Op.getOperand(1);
2857       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2858       Known = KnownBits::commonBits(Known, Known2);
2859     }
2860     break;
2861   }
2862   case ISD::CONCAT_VECTORS: {
2863     // Split DemandedElts and test each of the demanded subvectors.
2864     Known.Zero.setAllBits(); Known.One.setAllBits();
2865     EVT SubVectorVT = Op.getOperand(0).getValueType();
2866     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2867     unsigned NumSubVectors = Op.getNumOperands();
2868     for (unsigned i = 0; i != NumSubVectors; ++i) {
2869       APInt DemandedSub =
2870           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2871       if (!!DemandedSub) {
2872         SDValue Sub = Op.getOperand(i);
2873         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2874         Known = KnownBits::commonBits(Known, Known2);
2875       }
2876       // If we don't know any bits, early out.
2877       if (Known.isUnknown())
2878         break;
2879     }
2880     break;
2881   }
2882   case ISD::INSERT_SUBVECTOR: {
2883     // Demand any elements from the subvector and the remainder from the src its
2884     // inserted into.
2885     SDValue Src = Op.getOperand(0);
2886     SDValue Sub = Op.getOperand(1);
2887     uint64_t Idx = Op.getConstantOperandVal(2);
2888     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2889     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2890     APInt DemandedSrcElts = DemandedElts;
2891     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2892 
2893     Known.One.setAllBits();
2894     Known.Zero.setAllBits();
2895     if (!!DemandedSubElts) {
2896       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2897       if (Known.isUnknown())
2898         break; // early-out.
2899     }
2900     if (!!DemandedSrcElts) {
2901       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2902       Known = KnownBits::commonBits(Known, Known2);
2903     }
2904     break;
2905   }
2906   case ISD::EXTRACT_SUBVECTOR: {
2907     // Offset the demanded elts by the subvector index.
2908     SDValue Src = Op.getOperand(0);
2909     // Bail until we can represent demanded elements for scalable vectors.
2910     if (Src.getValueType().isScalableVector())
2911       break;
2912     uint64_t Idx = Op.getConstantOperandVal(1);
2913     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2914     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2915     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2916     break;
2917   }
2918   case ISD::SCALAR_TO_VECTOR: {
2919     // We know about scalar_to_vector as much as we know about it source,
2920     // which becomes the first element of otherwise unknown vector.
2921     if (DemandedElts != 1)
2922       break;
2923 
2924     SDValue N0 = Op.getOperand(0);
2925     Known = computeKnownBits(N0, Depth + 1);
2926     if (N0.getValueSizeInBits() != BitWidth)
2927       Known = Known.trunc(BitWidth);
2928 
2929     break;
2930   }
2931   case ISD::BITCAST: {
2932     SDValue N0 = Op.getOperand(0);
2933     EVT SubVT = N0.getValueType();
2934     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2935 
2936     // Ignore bitcasts from unsupported types.
2937     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2938       break;
2939 
2940     // Fast handling of 'identity' bitcasts.
2941     if (BitWidth == SubBitWidth) {
2942       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2943       break;
2944     }
2945 
2946     bool IsLE = getDataLayout().isLittleEndian();
2947 
2948     // Bitcast 'small element' vector to 'large element' scalar/vector.
2949     if ((BitWidth % SubBitWidth) == 0) {
2950       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2951 
2952       // Collect known bits for the (larger) output by collecting the known
2953       // bits from each set of sub elements and shift these into place.
2954       // We need to separately call computeKnownBits for each set of
2955       // sub elements as the knownbits for each is likely to be different.
2956       unsigned SubScale = BitWidth / SubBitWidth;
2957       APInt SubDemandedElts(NumElts * SubScale, 0);
2958       for (unsigned i = 0; i != NumElts; ++i)
2959         if (DemandedElts[i])
2960           SubDemandedElts.setBit(i * SubScale);
2961 
2962       for (unsigned i = 0; i != SubScale; ++i) {
2963         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2964                          Depth + 1);
2965         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2966         Known.insertBits(Known2, SubBitWidth * Shifts);
2967       }
2968     }
2969 
2970     // Bitcast 'large element' scalar/vector to 'small element' vector.
2971     if ((SubBitWidth % BitWidth) == 0) {
2972       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2973 
2974       // Collect known bits for the (smaller) output by collecting the known
2975       // bits from the overlapping larger input elements and extracting the
2976       // sub sections we actually care about.
2977       unsigned SubScale = SubBitWidth / BitWidth;
2978       APInt SubDemandedElts(NumElts / SubScale, 0);
2979       for (unsigned i = 0; i != NumElts; ++i)
2980         if (DemandedElts[i])
2981           SubDemandedElts.setBit(i / SubScale);
2982 
2983       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2984 
2985       Known.Zero.setAllBits(); Known.One.setAllBits();
2986       for (unsigned i = 0; i != NumElts; ++i)
2987         if (DemandedElts[i]) {
2988           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2989           unsigned Offset = (Shifts % SubScale) * BitWidth;
2990           Known = KnownBits::commonBits(Known,
2991                                         Known2.extractBits(BitWidth, Offset));
2992           // If we don't know any bits, early out.
2993           if (Known.isUnknown())
2994             break;
2995         }
2996     }
2997     break;
2998   }
2999   case ISD::AND:
3000     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3001     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3002 
3003     Known &= Known2;
3004     break;
3005   case ISD::OR:
3006     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3007     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3008 
3009     Known |= Known2;
3010     break;
3011   case ISD::XOR:
3012     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3013     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3014 
3015     Known ^= Known2;
3016     break;
3017   case ISD::MUL: {
3018     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3019     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3020     Known = KnownBits::mul(Known, Known2);
3021     break;
3022   }
3023   case ISD::MULHU: {
3024     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3025     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3026     Known = KnownBits::mulhu(Known, Known2);
3027     break;
3028   }
3029   case ISD::MULHS: {
3030     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3031     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3032     Known = KnownBits::mulhs(Known, Known2);
3033     break;
3034   }
3035   case ISD::UMUL_LOHI: {
3036     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3037     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3038     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3039     if (Op.getResNo() == 0)
3040       Known = KnownBits::mul(Known, Known2);
3041     else
3042       Known = KnownBits::mulhu(Known, Known2);
3043     break;
3044   }
3045   case ISD::SMUL_LOHI: {
3046     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3047     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3048     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3049     if (Op.getResNo() == 0)
3050       Known = KnownBits::mul(Known, Known2);
3051     else
3052       Known = KnownBits::mulhs(Known, Known2);
3053     break;
3054   }
3055   case ISD::UDIV: {
3056     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3057     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3058     Known = KnownBits::udiv(Known, Known2);
3059     break;
3060   }
3061   case ISD::SELECT:
3062   case ISD::VSELECT:
3063     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3064     // If we don't know any bits, early out.
3065     if (Known.isUnknown())
3066       break;
3067     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3068 
3069     // Only known if known in both the LHS and RHS.
3070     Known = KnownBits::commonBits(Known, Known2);
3071     break;
3072   case ISD::SELECT_CC:
3073     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3074     // If we don't know any bits, early out.
3075     if (Known.isUnknown())
3076       break;
3077     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3078 
3079     // Only known if known in both the LHS and RHS.
3080     Known = KnownBits::commonBits(Known, Known2);
3081     break;
3082   case ISD::SMULO:
3083   case ISD::UMULO:
3084     if (Op.getResNo() != 1)
3085       break;
3086     // The boolean result conforms to getBooleanContents.
3087     // If we know the result of a setcc has the top bits zero, use this info.
3088     // We know that we have an integer-based boolean since these operations
3089     // are only available for integer.
3090     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3091             TargetLowering::ZeroOrOneBooleanContent &&
3092         BitWidth > 1)
3093       Known.Zero.setBitsFrom(1);
3094     break;
3095   case ISD::SETCC:
3096   case ISD::STRICT_FSETCC:
3097   case ISD::STRICT_FSETCCS: {
3098     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3099     // If we know the result of a setcc has the top bits zero, use this info.
3100     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3101             TargetLowering::ZeroOrOneBooleanContent &&
3102         BitWidth > 1)
3103       Known.Zero.setBitsFrom(1);
3104     break;
3105   }
3106   case ISD::SHL:
3107     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3108     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3109     Known = KnownBits::shl(Known, Known2);
3110 
3111     // Minimum shift low bits are known zero.
3112     if (const APInt *ShMinAmt =
3113             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3114       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3115     break;
3116   case ISD::SRL:
3117     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3118     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3119     Known = KnownBits::lshr(Known, Known2);
3120 
3121     // Minimum shift high bits are known zero.
3122     if (const APInt *ShMinAmt =
3123             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3124       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3125     break;
3126   case ISD::SRA:
3127     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3128     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3129     Known = KnownBits::ashr(Known, Known2);
3130     // TODO: Add minimum shift high known sign bits.
3131     break;
3132   case ISD::FSHL:
3133   case ISD::FSHR:
3134     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3135       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3136 
3137       // For fshl, 0-shift returns the 1st arg.
3138       // For fshr, 0-shift returns the 2nd arg.
3139       if (Amt == 0) {
3140         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3141                                  DemandedElts, Depth + 1);
3142         break;
3143       }
3144 
3145       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3146       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3147       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3148       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3149       if (Opcode == ISD::FSHL) {
3150         Known.One <<= Amt;
3151         Known.Zero <<= Amt;
3152         Known2.One.lshrInPlace(BitWidth - Amt);
3153         Known2.Zero.lshrInPlace(BitWidth - Amt);
3154       } else {
3155         Known.One <<= BitWidth - Amt;
3156         Known.Zero <<= BitWidth - Amt;
3157         Known2.One.lshrInPlace(Amt);
3158         Known2.Zero.lshrInPlace(Amt);
3159       }
3160       Known.One |= Known2.One;
3161       Known.Zero |= Known2.Zero;
3162     }
3163     break;
3164   case ISD::SIGN_EXTEND_INREG: {
3165     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3166     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3167     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3168     break;
3169   }
3170   case ISD::CTTZ:
3171   case ISD::CTTZ_ZERO_UNDEF: {
3172     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3173     // If we have a known 1, its position is our upper bound.
3174     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3175     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3176     Known.Zero.setBitsFrom(LowBits);
3177     break;
3178   }
3179   case ISD::CTLZ:
3180   case ISD::CTLZ_ZERO_UNDEF: {
3181     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3182     // If we have a known 1, its position is our upper bound.
3183     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3184     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3185     Known.Zero.setBitsFrom(LowBits);
3186     break;
3187   }
3188   case ISD::CTPOP: {
3189     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3190     // If we know some of the bits are zero, they can't be one.
3191     unsigned PossibleOnes = Known2.countMaxPopulation();
3192     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3193     break;
3194   }
3195   case ISD::PARITY: {
3196     // Parity returns 0 everywhere but the LSB.
3197     Known.Zero.setBitsFrom(1);
3198     break;
3199   }
3200   case ISD::LOAD: {
3201     LoadSDNode *LD = cast<LoadSDNode>(Op);
3202     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3203     if (ISD::isNON_EXTLoad(LD) && Cst) {
3204       // Determine any common known bits from the loaded constant pool value.
3205       Type *CstTy = Cst->getType();
3206       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3207         // If its a vector splat, then we can (quickly) reuse the scalar path.
3208         // NOTE: We assume all elements match and none are UNDEF.
3209         if (CstTy->isVectorTy()) {
3210           if (const Constant *Splat = Cst->getSplatValue()) {
3211             Cst = Splat;
3212             CstTy = Cst->getType();
3213           }
3214         }
3215         // TODO - do we need to handle different bitwidths?
3216         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3217           // Iterate across all vector elements finding common known bits.
3218           Known.One.setAllBits();
3219           Known.Zero.setAllBits();
3220           for (unsigned i = 0; i != NumElts; ++i) {
3221             if (!DemandedElts[i])
3222               continue;
3223             if (Constant *Elt = Cst->getAggregateElement(i)) {
3224               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3225                 const APInt &Value = CInt->getValue();
3226                 Known.One &= Value;
3227                 Known.Zero &= ~Value;
3228                 continue;
3229               }
3230               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3231                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3232                 Known.One &= Value;
3233                 Known.Zero &= ~Value;
3234                 continue;
3235               }
3236             }
3237             Known.One.clearAllBits();
3238             Known.Zero.clearAllBits();
3239             break;
3240           }
3241         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3242           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3243             Known = KnownBits::makeConstant(CInt->getValue());
3244           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3245             Known =
3246                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3247           }
3248         }
3249       }
3250     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3251       // If this is a ZEXTLoad and we are looking at the loaded value.
3252       EVT VT = LD->getMemoryVT();
3253       unsigned MemBits = VT.getScalarSizeInBits();
3254       Known.Zero.setBitsFrom(MemBits);
3255     } else if (const MDNode *Ranges = LD->getRanges()) {
3256       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3257         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3258     }
3259     break;
3260   }
3261   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3262     EVT InVT = Op.getOperand(0).getValueType();
3263     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3264     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3265     Known = Known.zext(BitWidth);
3266     break;
3267   }
3268   case ISD::ZERO_EXTEND: {
3269     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3270     Known = Known.zext(BitWidth);
3271     break;
3272   }
3273   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3274     EVT InVT = Op.getOperand(0).getValueType();
3275     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3276     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3277     // If the sign bit is known to be zero or one, then sext will extend
3278     // it to the top bits, else it will just zext.
3279     Known = Known.sext(BitWidth);
3280     break;
3281   }
3282   case ISD::SIGN_EXTEND: {
3283     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3284     // If the sign bit is known to be zero or one, then sext will extend
3285     // it to the top bits, else it will just zext.
3286     Known = Known.sext(BitWidth);
3287     break;
3288   }
3289   case ISD::ANY_EXTEND_VECTOR_INREG: {
3290     EVT InVT = Op.getOperand(0).getValueType();
3291     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3292     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3293     Known = Known.anyext(BitWidth);
3294     break;
3295   }
3296   case ISD::ANY_EXTEND: {
3297     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3298     Known = Known.anyext(BitWidth);
3299     break;
3300   }
3301   case ISD::TRUNCATE: {
3302     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3303     Known = Known.trunc(BitWidth);
3304     break;
3305   }
3306   case ISD::AssertZext: {
3307     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3308     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3309     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3310     Known.Zero |= (~InMask);
3311     Known.One  &= (~Known.Zero);
3312     break;
3313   }
3314   case ISD::AssertAlign: {
3315     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3316     assert(LogOfAlign != 0);
3317     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3318     // well as clearing one bits.
3319     Known.Zero.setLowBits(LogOfAlign);
3320     Known.One.clearLowBits(LogOfAlign);
3321     break;
3322   }
3323   case ISD::FGETSIGN:
3324     // All bits are zero except the low bit.
3325     Known.Zero.setBitsFrom(1);
3326     break;
3327   case ISD::USUBO:
3328   case ISD::SSUBO:
3329     if (Op.getResNo() == 1) {
3330       // If we know the result of a setcc has the top bits zero, use this info.
3331       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3332               TargetLowering::ZeroOrOneBooleanContent &&
3333           BitWidth > 1)
3334         Known.Zero.setBitsFrom(1);
3335       break;
3336     }
3337     LLVM_FALLTHROUGH;
3338   case ISD::SUB:
3339   case ISD::SUBC: {
3340     assert(Op.getResNo() == 0 &&
3341            "We only compute knownbits for the difference here.");
3342 
3343     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3344     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3345     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3346                                         Known, Known2);
3347     break;
3348   }
3349   case ISD::UADDO:
3350   case ISD::SADDO:
3351   case ISD::ADDCARRY:
3352     if (Op.getResNo() == 1) {
3353       // If we know the result of a setcc has the top bits zero, use this info.
3354       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3355               TargetLowering::ZeroOrOneBooleanContent &&
3356           BitWidth > 1)
3357         Known.Zero.setBitsFrom(1);
3358       break;
3359     }
3360     LLVM_FALLTHROUGH;
3361   case ISD::ADD:
3362   case ISD::ADDC:
3363   case ISD::ADDE: {
3364     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3365 
3366     // With ADDE and ADDCARRY, a carry bit may be added in.
3367     KnownBits Carry(1);
3368     if (Opcode == ISD::ADDE)
3369       // Can't track carry from glue, set carry to unknown.
3370       Carry.resetAll();
3371     else if (Opcode == ISD::ADDCARRY)
3372       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3373       // the trouble (how often will we find a known carry bit). And I haven't
3374       // tested this very much yet, but something like this might work:
3375       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3376       //   Carry = Carry.zextOrTrunc(1, false);
3377       Carry.resetAll();
3378     else
3379       Carry.setAllZero();
3380 
3381     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3382     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3383     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3384     break;
3385   }
3386   case ISD::SREM: {
3387     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3388     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3389     Known = KnownBits::srem(Known, Known2);
3390     break;
3391   }
3392   case ISD::UREM: {
3393     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3394     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3395     Known = KnownBits::urem(Known, Known2);
3396     break;
3397   }
3398   case ISD::EXTRACT_ELEMENT: {
3399     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3400     const unsigned Index = Op.getConstantOperandVal(1);
3401     const unsigned EltBitWidth = Op.getValueSizeInBits();
3402 
3403     // Remove low part of known bits mask
3404     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3405     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3406 
3407     // Remove high part of known bit mask
3408     Known = Known.trunc(EltBitWidth);
3409     break;
3410   }
3411   case ISD::EXTRACT_VECTOR_ELT: {
3412     SDValue InVec = Op.getOperand(0);
3413     SDValue EltNo = Op.getOperand(1);
3414     EVT VecVT = InVec.getValueType();
3415     // computeKnownBits not yet implemented for scalable vectors.
3416     if (VecVT.isScalableVector())
3417       break;
3418     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3419     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3420 
3421     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3422     // anything about the extended bits.
3423     if (BitWidth > EltBitWidth)
3424       Known = Known.trunc(EltBitWidth);
3425 
3426     // If we know the element index, just demand that vector element, else for
3427     // an unknown element index, ignore DemandedElts and demand them all.
3428     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3429     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3430     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3431       DemandedSrcElts =
3432           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3433 
3434     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3435     if (BitWidth > EltBitWidth)
3436       Known = Known.anyext(BitWidth);
3437     break;
3438   }
3439   case ISD::INSERT_VECTOR_ELT: {
3440     // If we know the element index, split the demand between the
3441     // source vector and the inserted element, otherwise assume we need
3442     // the original demanded vector elements and the value.
3443     SDValue InVec = Op.getOperand(0);
3444     SDValue InVal = Op.getOperand(1);
3445     SDValue EltNo = Op.getOperand(2);
3446     bool DemandedVal = true;
3447     APInt DemandedVecElts = DemandedElts;
3448     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3449     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3450       unsigned EltIdx = CEltNo->getZExtValue();
3451       DemandedVal = !!DemandedElts[EltIdx];
3452       DemandedVecElts.clearBit(EltIdx);
3453     }
3454     Known.One.setAllBits();
3455     Known.Zero.setAllBits();
3456     if (DemandedVal) {
3457       Known2 = computeKnownBits(InVal, Depth + 1);
3458       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3459     }
3460     if (!!DemandedVecElts) {
3461       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3462       Known = KnownBits::commonBits(Known, Known2);
3463     }
3464     break;
3465   }
3466   case ISD::BITREVERSE: {
3467     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3468     Known = Known2.reverseBits();
3469     break;
3470   }
3471   case ISD::BSWAP: {
3472     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3473     Known = Known2.byteSwap();
3474     break;
3475   }
3476   case ISD::ABS: {
3477     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3478     Known = Known2.abs();
3479     break;
3480   }
3481   case ISD::USUBSAT: {
3482     // The result of usubsat will never be larger than the LHS.
3483     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3484     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3485     break;
3486   }
3487   case ISD::UMIN: {
3488     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3489     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3490     Known = KnownBits::umin(Known, Known2);
3491     break;
3492   }
3493   case ISD::UMAX: {
3494     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3495     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3496     Known = KnownBits::umax(Known, Known2);
3497     break;
3498   }
3499   case ISD::SMIN:
3500   case ISD::SMAX: {
3501     // If we have a clamp pattern, we know that the number of sign bits will be
3502     // the minimum of the clamp min/max range.
3503     bool IsMax = (Opcode == ISD::SMAX);
3504     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3505     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3506       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3507         CstHigh =
3508             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3509     if (CstLow && CstHigh) {
3510       if (!IsMax)
3511         std::swap(CstLow, CstHigh);
3512 
3513       const APInt &ValueLow = CstLow->getAPIntValue();
3514       const APInt &ValueHigh = CstHigh->getAPIntValue();
3515       if (ValueLow.sle(ValueHigh)) {
3516         unsigned LowSignBits = ValueLow.getNumSignBits();
3517         unsigned HighSignBits = ValueHigh.getNumSignBits();
3518         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3519         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3520           Known.One.setHighBits(MinSignBits);
3521           break;
3522         }
3523         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3524           Known.Zero.setHighBits(MinSignBits);
3525           break;
3526         }
3527       }
3528     }
3529 
3530     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3531     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3532     if (IsMax)
3533       Known = KnownBits::smax(Known, Known2);
3534     else
3535       Known = KnownBits::smin(Known, Known2);
3536     break;
3537   }
3538   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3539     if (Op.getResNo() == 1) {
3540       // The boolean result conforms to getBooleanContents.
3541       // If we know the result of a setcc has the top bits zero, use this info.
3542       // We know that we have an integer-based boolean since these operations
3543       // are only available for integer.
3544       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3545               TargetLowering::ZeroOrOneBooleanContent &&
3546           BitWidth > 1)
3547         Known.Zero.setBitsFrom(1);
3548       break;
3549     }
3550     LLVM_FALLTHROUGH;
3551   case ISD::ATOMIC_CMP_SWAP:
3552   case ISD::ATOMIC_SWAP:
3553   case ISD::ATOMIC_LOAD_ADD:
3554   case ISD::ATOMIC_LOAD_SUB:
3555   case ISD::ATOMIC_LOAD_AND:
3556   case ISD::ATOMIC_LOAD_CLR:
3557   case ISD::ATOMIC_LOAD_OR:
3558   case ISD::ATOMIC_LOAD_XOR:
3559   case ISD::ATOMIC_LOAD_NAND:
3560   case ISD::ATOMIC_LOAD_MIN:
3561   case ISD::ATOMIC_LOAD_MAX:
3562   case ISD::ATOMIC_LOAD_UMIN:
3563   case ISD::ATOMIC_LOAD_UMAX:
3564   case ISD::ATOMIC_LOAD: {
3565     unsigned MemBits =
3566         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3567     // If we are looking at the loaded value.
3568     if (Op.getResNo() == 0) {
3569       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3570         Known.Zero.setBitsFrom(MemBits);
3571     }
3572     break;
3573   }
3574   case ISD::FrameIndex:
3575   case ISD::TargetFrameIndex:
3576     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3577                                        Known, getMachineFunction());
3578     break;
3579 
3580   default:
3581     if (Opcode < ISD::BUILTIN_OP_END)
3582       break;
3583     LLVM_FALLTHROUGH;
3584   case ISD::INTRINSIC_WO_CHAIN:
3585   case ISD::INTRINSIC_W_CHAIN:
3586   case ISD::INTRINSIC_VOID:
3587     // Allow the target to implement this method for its nodes.
3588     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3589     break;
3590   }
3591 
3592   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3593   return Known;
3594 }
3595 
3596 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3597                                                              SDValue N1) const {
3598   // X + 0 never overflow
3599   if (isNullConstant(N1))
3600     return OFK_Never;
3601 
3602   KnownBits N1Known = computeKnownBits(N1);
3603   if (N1Known.Zero.getBoolValue()) {
3604     KnownBits N0Known = computeKnownBits(N0);
3605 
3606     bool overflow;
3607     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3608     if (!overflow)
3609       return OFK_Never;
3610   }
3611 
3612   // mulhi + 1 never overflow
3613   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3614       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3615     return OFK_Never;
3616 
3617   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3618     KnownBits N0Known = computeKnownBits(N0);
3619 
3620     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3621       return OFK_Never;
3622   }
3623 
3624   return OFK_Sometime;
3625 }
3626 
3627 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3628   EVT OpVT = Val.getValueType();
3629   unsigned BitWidth = OpVT.getScalarSizeInBits();
3630 
3631   // Is the constant a known power of 2?
3632   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3633     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3634 
3635   // A left-shift of a constant one will have exactly one bit set because
3636   // shifting the bit off the end is undefined.
3637   if (Val.getOpcode() == ISD::SHL) {
3638     auto *C = isConstOrConstSplat(Val.getOperand(0));
3639     if (C && C->getAPIntValue() == 1)
3640       return true;
3641   }
3642 
3643   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3644   // one bit set.
3645   if (Val.getOpcode() == ISD::SRL) {
3646     auto *C = isConstOrConstSplat(Val.getOperand(0));
3647     if (C && C->getAPIntValue().isSignMask())
3648       return true;
3649   }
3650 
3651   // Are all operands of a build vector constant powers of two?
3652   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3653     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3654           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3655             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3656           return false;
3657         }))
3658       return true;
3659 
3660   // More could be done here, though the above checks are enough
3661   // to handle some common cases.
3662 
3663   // Fall back to computeKnownBits to catch other known cases.
3664   KnownBits Known = computeKnownBits(Val);
3665   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3666 }
3667 
3668 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3669   EVT VT = Op.getValueType();
3670 
3671   // TODO: Assume we don't know anything for now.
3672   if (VT.isScalableVector())
3673     return 1;
3674 
3675   APInt DemandedElts = VT.isVector()
3676                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
3677                            : APInt(1, 1);
3678   return ComputeNumSignBits(Op, DemandedElts, Depth);
3679 }
3680 
3681 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3682                                           unsigned Depth) const {
3683   EVT VT = Op.getValueType();
3684   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3685   unsigned VTBits = VT.getScalarSizeInBits();
3686   unsigned NumElts = DemandedElts.getBitWidth();
3687   unsigned Tmp, Tmp2;
3688   unsigned FirstAnswer = 1;
3689 
3690   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3691     const APInt &Val = C->getAPIntValue();
3692     return Val.getNumSignBits();
3693   }
3694 
3695   if (Depth >= MaxRecursionDepth)
3696     return 1;  // Limit search depth.
3697 
3698   if (!DemandedElts || VT.isScalableVector())
3699     return 1;  // No demanded elts, better to assume we don't know anything.
3700 
3701   unsigned Opcode = Op.getOpcode();
3702   switch (Opcode) {
3703   default: break;
3704   case ISD::AssertSext:
3705     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3706     return VTBits-Tmp+1;
3707   case ISD::AssertZext:
3708     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3709     return VTBits-Tmp;
3710 
3711   case ISD::BUILD_VECTOR:
3712     Tmp = VTBits;
3713     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3714       if (!DemandedElts[i])
3715         continue;
3716 
3717       SDValue SrcOp = Op.getOperand(i);
3718       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3719 
3720       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3721       if (SrcOp.getValueSizeInBits() != VTBits) {
3722         assert(SrcOp.getValueSizeInBits() > VTBits &&
3723                "Expected BUILD_VECTOR implicit truncation");
3724         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3725         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3726       }
3727       Tmp = std::min(Tmp, Tmp2);
3728     }
3729     return Tmp;
3730 
3731   case ISD::VECTOR_SHUFFLE: {
3732     // Collect the minimum number of sign bits that are shared by every vector
3733     // element referenced by the shuffle.
3734     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3735     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3736     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3737     for (unsigned i = 0; i != NumElts; ++i) {
3738       int M = SVN->getMaskElt(i);
3739       if (!DemandedElts[i])
3740         continue;
3741       // For UNDEF elements, we don't know anything about the common state of
3742       // the shuffle result.
3743       if (M < 0)
3744         return 1;
3745       if ((unsigned)M < NumElts)
3746         DemandedLHS.setBit((unsigned)M % NumElts);
3747       else
3748         DemandedRHS.setBit((unsigned)M % NumElts);
3749     }
3750     Tmp = std::numeric_limits<unsigned>::max();
3751     if (!!DemandedLHS)
3752       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3753     if (!!DemandedRHS) {
3754       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3755       Tmp = std::min(Tmp, Tmp2);
3756     }
3757     // If we don't know anything, early out and try computeKnownBits fall-back.
3758     if (Tmp == 1)
3759       break;
3760     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3761     return Tmp;
3762   }
3763 
3764   case ISD::BITCAST: {
3765     SDValue N0 = Op.getOperand(0);
3766     EVT SrcVT = N0.getValueType();
3767     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3768 
3769     // Ignore bitcasts from unsupported types..
3770     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3771       break;
3772 
3773     // Fast handling of 'identity' bitcasts.
3774     if (VTBits == SrcBits)
3775       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3776 
3777     bool IsLE = getDataLayout().isLittleEndian();
3778 
3779     // Bitcast 'large element' scalar/vector to 'small element' vector.
3780     if ((SrcBits % VTBits) == 0) {
3781       assert(VT.isVector() && "Expected bitcast to vector");
3782 
3783       unsigned Scale = SrcBits / VTBits;
3784       APInt SrcDemandedElts(NumElts / Scale, 0);
3785       for (unsigned i = 0; i != NumElts; ++i)
3786         if (DemandedElts[i])
3787           SrcDemandedElts.setBit(i / Scale);
3788 
3789       // Fast case - sign splat can be simply split across the small elements.
3790       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3791       if (Tmp == SrcBits)
3792         return VTBits;
3793 
3794       // Slow case - determine how far the sign extends into each sub-element.
3795       Tmp2 = VTBits;
3796       for (unsigned i = 0; i != NumElts; ++i)
3797         if (DemandedElts[i]) {
3798           unsigned SubOffset = i % Scale;
3799           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3800           SubOffset = SubOffset * VTBits;
3801           if (Tmp <= SubOffset)
3802             return 1;
3803           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3804         }
3805       return Tmp2;
3806     }
3807     break;
3808   }
3809 
3810   case ISD::SIGN_EXTEND:
3811     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3812     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3813   case ISD::SIGN_EXTEND_INREG:
3814     // Max of the input and what this extends.
3815     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3816     Tmp = VTBits-Tmp+1;
3817     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3818     return std::max(Tmp, Tmp2);
3819   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3820     SDValue Src = Op.getOperand(0);
3821     EVT SrcVT = Src.getValueType();
3822     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3823     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3824     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3825   }
3826   case ISD::SRA:
3827     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3828     // SRA X, C -> adds C sign bits.
3829     if (const APInt *ShAmt =
3830             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3831       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3832     return Tmp;
3833   case ISD::SHL:
3834     if (const APInt *ShAmt =
3835             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3836       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3837       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3838       if (ShAmt->ult(Tmp))
3839         return Tmp - ShAmt->getZExtValue();
3840     }
3841     break;
3842   case ISD::AND:
3843   case ISD::OR:
3844   case ISD::XOR:    // NOT is handled here.
3845     // Logical binary ops preserve the number of sign bits at the worst.
3846     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3847     if (Tmp != 1) {
3848       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3849       FirstAnswer = std::min(Tmp, Tmp2);
3850       // We computed what we know about the sign bits as our first
3851       // answer. Now proceed to the generic code that uses
3852       // computeKnownBits, and pick whichever answer is better.
3853     }
3854     break;
3855 
3856   case ISD::SELECT:
3857   case ISD::VSELECT:
3858     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3859     if (Tmp == 1) return 1;  // Early out.
3860     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3861     return std::min(Tmp, Tmp2);
3862   case ISD::SELECT_CC:
3863     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3864     if (Tmp == 1) return 1;  // Early out.
3865     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3866     return std::min(Tmp, Tmp2);
3867 
3868   case ISD::SMIN:
3869   case ISD::SMAX: {
3870     // If we have a clamp pattern, we know that the number of sign bits will be
3871     // the minimum of the clamp min/max range.
3872     bool IsMax = (Opcode == ISD::SMAX);
3873     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3874     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3875       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3876         CstHigh =
3877             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3878     if (CstLow && CstHigh) {
3879       if (!IsMax)
3880         std::swap(CstLow, CstHigh);
3881       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3882         Tmp = CstLow->getAPIntValue().getNumSignBits();
3883         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3884         return std::min(Tmp, Tmp2);
3885       }
3886     }
3887 
3888     // Fallback - just get the minimum number of sign bits of the operands.
3889     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3890     if (Tmp == 1)
3891       return 1;  // Early out.
3892     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3893     return std::min(Tmp, Tmp2);
3894   }
3895   case ISD::UMIN:
3896   case ISD::UMAX:
3897     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3898     if (Tmp == 1)
3899       return 1;  // Early out.
3900     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3901     return std::min(Tmp, Tmp2);
3902   case ISD::SADDO:
3903   case ISD::UADDO:
3904   case ISD::SSUBO:
3905   case ISD::USUBO:
3906   case ISD::SMULO:
3907   case ISD::UMULO:
3908     if (Op.getResNo() != 1)
3909       break;
3910     // The boolean result conforms to getBooleanContents.  Fall through.
3911     // If setcc returns 0/-1, all bits are sign bits.
3912     // We know that we have an integer-based boolean since these operations
3913     // are only available for integer.
3914     if (TLI->getBooleanContents(VT.isVector(), false) ==
3915         TargetLowering::ZeroOrNegativeOneBooleanContent)
3916       return VTBits;
3917     break;
3918   case ISD::SETCC:
3919   case ISD::STRICT_FSETCC:
3920   case ISD::STRICT_FSETCCS: {
3921     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3922     // If setcc returns 0/-1, all bits are sign bits.
3923     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3924         TargetLowering::ZeroOrNegativeOneBooleanContent)
3925       return VTBits;
3926     break;
3927   }
3928   case ISD::ROTL:
3929   case ISD::ROTR:
3930     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3931 
3932     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3933     if (Tmp == VTBits)
3934       return VTBits;
3935 
3936     if (ConstantSDNode *C =
3937             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3938       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3939 
3940       // Handle rotate right by N like a rotate left by 32-N.
3941       if (Opcode == ISD::ROTR)
3942         RotAmt = (VTBits - RotAmt) % VTBits;
3943 
3944       // If we aren't rotating out all of the known-in sign bits, return the
3945       // number that are left.  This handles rotl(sext(x), 1) for example.
3946       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3947     }
3948     break;
3949   case ISD::ADD:
3950   case ISD::ADDC:
3951     // Add can have at most one carry bit.  Thus we know that the output
3952     // is, at worst, one more bit than the inputs.
3953     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3954     if (Tmp == 1) return 1; // Early out.
3955 
3956     // Special case decrementing a value (ADD X, -1):
3957     if (ConstantSDNode *CRHS =
3958             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3959       if (CRHS->isAllOnesValue()) {
3960         KnownBits Known =
3961             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3962 
3963         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3964         // sign bits set.
3965         if ((Known.Zero | 1).isAllOnesValue())
3966           return VTBits;
3967 
3968         // If we are subtracting one from a positive number, there is no carry
3969         // out of the result.
3970         if (Known.isNonNegative())
3971           return Tmp;
3972       }
3973 
3974     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3975     if (Tmp2 == 1) return 1; // Early out.
3976     return std::min(Tmp, Tmp2) - 1;
3977   case ISD::SUB:
3978     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3979     if (Tmp2 == 1) return 1; // Early out.
3980 
3981     // Handle NEG.
3982     if (ConstantSDNode *CLHS =
3983             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
3984       if (CLHS->isNullValue()) {
3985         KnownBits Known =
3986             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3987         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3988         // sign bits set.
3989         if ((Known.Zero | 1).isAllOnesValue())
3990           return VTBits;
3991 
3992         // If the input is known to be positive (the sign bit is known clear),
3993         // the output of the NEG has the same number of sign bits as the input.
3994         if (Known.isNonNegative())
3995           return Tmp2;
3996 
3997         // Otherwise, we treat this like a SUB.
3998       }
3999 
4000     // Sub can have at most one carry bit.  Thus we know that the output
4001     // is, at worst, one more bit than the inputs.
4002     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4003     if (Tmp == 1) return 1; // Early out.
4004     return std::min(Tmp, Tmp2) - 1;
4005   case ISD::MUL: {
4006     // The output of the Mul can be at most twice the valid bits in the inputs.
4007     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4008     if (SignBitsOp0 == 1)
4009       break;
4010     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4011     if (SignBitsOp1 == 1)
4012       break;
4013     unsigned OutValidBits =
4014         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4015     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4016   }
4017   case ISD::SREM:
4018     // The sign bit is the LHS's sign bit, except when the result of the
4019     // remainder is zero. The magnitude of the result should be less than or
4020     // equal to the magnitude of the LHS. Therefore, the result should have
4021     // at least as many sign bits as the left hand side.
4022     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4023   case ISD::TRUNCATE: {
4024     // Check if the sign bits of source go down as far as the truncated value.
4025     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4026     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4027     if (NumSrcSignBits > (NumSrcBits - VTBits))
4028       return NumSrcSignBits - (NumSrcBits - VTBits);
4029     break;
4030   }
4031   case ISD::EXTRACT_ELEMENT: {
4032     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4033     const int BitWidth = Op.getValueSizeInBits();
4034     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4035 
4036     // Get reverse index (starting from 1), Op1 value indexes elements from
4037     // little end. Sign starts at big end.
4038     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4039 
4040     // If the sign portion ends in our element the subtraction gives correct
4041     // result. Otherwise it gives either negative or > bitwidth result
4042     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4043   }
4044   case ISD::INSERT_VECTOR_ELT: {
4045     // If we know the element index, split the demand between the
4046     // source vector and the inserted element, otherwise assume we need
4047     // the original demanded vector elements and the value.
4048     SDValue InVec = Op.getOperand(0);
4049     SDValue InVal = Op.getOperand(1);
4050     SDValue EltNo = Op.getOperand(2);
4051     bool DemandedVal = true;
4052     APInt DemandedVecElts = DemandedElts;
4053     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4054     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4055       unsigned EltIdx = CEltNo->getZExtValue();
4056       DemandedVal = !!DemandedElts[EltIdx];
4057       DemandedVecElts.clearBit(EltIdx);
4058     }
4059     Tmp = std::numeric_limits<unsigned>::max();
4060     if (DemandedVal) {
4061       // TODO - handle implicit truncation of inserted elements.
4062       if (InVal.getScalarValueSizeInBits() != VTBits)
4063         break;
4064       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4065       Tmp = std::min(Tmp, Tmp2);
4066     }
4067     if (!!DemandedVecElts) {
4068       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4069       Tmp = std::min(Tmp, Tmp2);
4070     }
4071     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4072     return Tmp;
4073   }
4074   case ISD::EXTRACT_VECTOR_ELT: {
4075     SDValue InVec = Op.getOperand(0);
4076     SDValue EltNo = Op.getOperand(1);
4077     EVT VecVT = InVec.getValueType();
4078     // ComputeNumSignBits not yet implemented for scalable vectors.
4079     if (VecVT.isScalableVector())
4080       break;
4081     const unsigned BitWidth = Op.getValueSizeInBits();
4082     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4083     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4084 
4085     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4086     // anything about sign bits. But if the sizes match we can derive knowledge
4087     // about sign bits from the vector operand.
4088     if (BitWidth != EltBitWidth)
4089       break;
4090 
4091     // If we know the element index, just demand that vector element, else for
4092     // an unknown element index, ignore DemandedElts and demand them all.
4093     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
4094     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4095     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4096       DemandedSrcElts =
4097           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4098 
4099     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4100   }
4101   case ISD::EXTRACT_SUBVECTOR: {
4102     // Offset the demanded elts by the subvector index.
4103     SDValue Src = Op.getOperand(0);
4104     // Bail until we can represent demanded elements for scalable vectors.
4105     if (Src.getValueType().isScalableVector())
4106       break;
4107     uint64_t Idx = Op.getConstantOperandVal(1);
4108     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4109     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4110     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4111   }
4112   case ISD::CONCAT_VECTORS: {
4113     // Determine the minimum number of sign bits across all demanded
4114     // elts of the input vectors. Early out if the result is already 1.
4115     Tmp = std::numeric_limits<unsigned>::max();
4116     EVT SubVectorVT = Op.getOperand(0).getValueType();
4117     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4118     unsigned NumSubVectors = Op.getNumOperands();
4119     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4120       APInt DemandedSub =
4121           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4122       if (!DemandedSub)
4123         continue;
4124       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4125       Tmp = std::min(Tmp, Tmp2);
4126     }
4127     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4128     return Tmp;
4129   }
4130   case ISD::INSERT_SUBVECTOR: {
4131     // Demand any elements from the subvector and the remainder from the src its
4132     // inserted into.
4133     SDValue Src = Op.getOperand(0);
4134     SDValue Sub = Op.getOperand(1);
4135     uint64_t Idx = Op.getConstantOperandVal(2);
4136     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4137     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4138     APInt DemandedSrcElts = DemandedElts;
4139     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
4140 
4141     Tmp = std::numeric_limits<unsigned>::max();
4142     if (!!DemandedSubElts) {
4143       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4144       if (Tmp == 1)
4145         return 1; // early-out
4146     }
4147     if (!!DemandedSrcElts) {
4148       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4149       Tmp = std::min(Tmp, Tmp2);
4150     }
4151     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4152     return Tmp;
4153   }
4154   case ISD::ATOMIC_CMP_SWAP:
4155   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4156   case ISD::ATOMIC_SWAP:
4157   case ISD::ATOMIC_LOAD_ADD:
4158   case ISD::ATOMIC_LOAD_SUB:
4159   case ISD::ATOMIC_LOAD_AND:
4160   case ISD::ATOMIC_LOAD_CLR:
4161   case ISD::ATOMIC_LOAD_OR:
4162   case ISD::ATOMIC_LOAD_XOR:
4163   case ISD::ATOMIC_LOAD_NAND:
4164   case ISD::ATOMIC_LOAD_MIN:
4165   case ISD::ATOMIC_LOAD_MAX:
4166   case ISD::ATOMIC_LOAD_UMIN:
4167   case ISD::ATOMIC_LOAD_UMAX:
4168   case ISD::ATOMIC_LOAD: {
4169     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4170     // If we are looking at the loaded value.
4171     if (Op.getResNo() == 0) {
4172       if (Tmp == VTBits)
4173         return 1; // early-out
4174       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4175         return VTBits - Tmp + 1;
4176       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4177         return VTBits - Tmp;
4178     }
4179     break;
4180   }
4181   }
4182 
4183   // If we are looking at the loaded value of the SDNode.
4184   if (Op.getResNo() == 0) {
4185     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4186     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4187       unsigned ExtType = LD->getExtensionType();
4188       switch (ExtType) {
4189       default: break;
4190       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4191         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4192         return VTBits - Tmp + 1;
4193       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4194         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4195         return VTBits - Tmp;
4196       case ISD::NON_EXTLOAD:
4197         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4198           // We only need to handle vectors - computeKnownBits should handle
4199           // scalar cases.
4200           Type *CstTy = Cst->getType();
4201           if (CstTy->isVectorTy() &&
4202               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4203             Tmp = VTBits;
4204             for (unsigned i = 0; i != NumElts; ++i) {
4205               if (!DemandedElts[i])
4206                 continue;
4207               if (Constant *Elt = Cst->getAggregateElement(i)) {
4208                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4209                   const APInt &Value = CInt->getValue();
4210                   Tmp = std::min(Tmp, Value.getNumSignBits());
4211                   continue;
4212                 }
4213                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4214                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4215                   Tmp = std::min(Tmp, Value.getNumSignBits());
4216                   continue;
4217                 }
4218               }
4219               // Unknown type. Conservatively assume no bits match sign bit.
4220               return 1;
4221             }
4222             return Tmp;
4223           }
4224         }
4225         break;
4226       }
4227     }
4228   }
4229 
4230   // Allow the target to implement this method for its nodes.
4231   if (Opcode >= ISD::BUILTIN_OP_END ||
4232       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4233       Opcode == ISD::INTRINSIC_W_CHAIN ||
4234       Opcode == ISD::INTRINSIC_VOID) {
4235     unsigned NumBits =
4236         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4237     if (NumBits > 1)
4238       FirstAnswer = std::max(FirstAnswer, NumBits);
4239   }
4240 
4241   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4242   // use this information.
4243   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4244 
4245   APInt Mask;
4246   if (Known.isNonNegative()) {        // sign bit is 0
4247     Mask = Known.Zero;
4248   } else if (Known.isNegative()) {  // sign bit is 1;
4249     Mask = Known.One;
4250   } else {
4251     // Nothing known.
4252     return FirstAnswer;
4253   }
4254 
4255   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4256   // the number of identical bits in the top of the input value.
4257   Mask <<= Mask.getBitWidth()-VTBits;
4258   return std::max(FirstAnswer, Mask.countLeadingOnes());
4259 }
4260 
4261 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4262   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4263       !isa<ConstantSDNode>(Op.getOperand(1)))
4264     return false;
4265 
4266   if (Op.getOpcode() == ISD::OR &&
4267       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4268     return false;
4269 
4270   return true;
4271 }
4272 
4273 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4274   // If we're told that NaNs won't happen, assume they won't.
4275   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4276     return true;
4277 
4278   if (Depth >= MaxRecursionDepth)
4279     return false; // Limit search depth.
4280 
4281   // TODO: Handle vectors.
4282   // If the value is a constant, we can obviously see if it is a NaN or not.
4283   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4284     return !C->getValueAPF().isNaN() ||
4285            (SNaN && !C->getValueAPF().isSignaling());
4286   }
4287 
4288   unsigned Opcode = Op.getOpcode();
4289   switch (Opcode) {
4290   case ISD::FADD:
4291   case ISD::FSUB:
4292   case ISD::FMUL:
4293   case ISD::FDIV:
4294   case ISD::FREM:
4295   case ISD::FSIN:
4296   case ISD::FCOS: {
4297     if (SNaN)
4298       return true;
4299     // TODO: Need isKnownNeverInfinity
4300     return false;
4301   }
4302   case ISD::FCANONICALIZE:
4303   case ISD::FEXP:
4304   case ISD::FEXP2:
4305   case ISD::FTRUNC:
4306   case ISD::FFLOOR:
4307   case ISD::FCEIL:
4308   case ISD::FROUND:
4309   case ISD::FROUNDEVEN:
4310   case ISD::FRINT:
4311   case ISD::FNEARBYINT: {
4312     if (SNaN)
4313       return true;
4314     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4315   }
4316   case ISD::FABS:
4317   case ISD::FNEG:
4318   case ISD::FCOPYSIGN: {
4319     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4320   }
4321   case ISD::SELECT:
4322     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4323            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4324   case ISD::FP_EXTEND:
4325   case ISD::FP_ROUND: {
4326     if (SNaN)
4327       return true;
4328     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4329   }
4330   case ISD::SINT_TO_FP:
4331   case ISD::UINT_TO_FP:
4332     return true;
4333   case ISD::FMA:
4334   case ISD::FMAD: {
4335     if (SNaN)
4336       return true;
4337     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4338            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4339            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4340   }
4341   case ISD::FSQRT: // Need is known positive
4342   case ISD::FLOG:
4343   case ISD::FLOG2:
4344   case ISD::FLOG10:
4345   case ISD::FPOWI:
4346   case ISD::FPOW: {
4347     if (SNaN)
4348       return true;
4349     // TODO: Refine on operand
4350     return false;
4351   }
4352   case ISD::FMINNUM:
4353   case ISD::FMAXNUM: {
4354     // Only one needs to be known not-nan, since it will be returned if the
4355     // other ends up being one.
4356     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4357            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4358   }
4359   case ISD::FMINNUM_IEEE:
4360   case ISD::FMAXNUM_IEEE: {
4361     if (SNaN)
4362       return true;
4363     // This can return a NaN if either operand is an sNaN, or if both operands
4364     // are NaN.
4365     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4366             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4367            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4368             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4369   }
4370   case ISD::FMINIMUM:
4371   case ISD::FMAXIMUM: {
4372     // TODO: Does this quiet or return the origina NaN as-is?
4373     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4374            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4375   }
4376   case ISD::EXTRACT_VECTOR_ELT: {
4377     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4378   }
4379   default:
4380     if (Opcode >= ISD::BUILTIN_OP_END ||
4381         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4382         Opcode == ISD::INTRINSIC_W_CHAIN ||
4383         Opcode == ISD::INTRINSIC_VOID) {
4384       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4385     }
4386 
4387     return false;
4388   }
4389 }
4390 
4391 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4392   assert(Op.getValueType().isFloatingPoint() &&
4393          "Floating point type expected");
4394 
4395   // If the value is a constant, we can obviously see if it is a zero or not.
4396   // TODO: Add BuildVector support.
4397   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4398     return !C->isZero();
4399   return false;
4400 }
4401 
4402 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4403   assert(!Op.getValueType().isFloatingPoint() &&
4404          "Floating point types unsupported - use isKnownNeverZeroFloat");
4405 
4406   // If the value is a constant, we can obviously see if it is a zero or not.
4407   if (ISD::matchUnaryPredicate(
4408           Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4409     return true;
4410 
4411   // TODO: Recognize more cases here.
4412   switch (Op.getOpcode()) {
4413   default: break;
4414   case ISD::OR:
4415     if (isKnownNeverZero(Op.getOperand(1)) ||
4416         isKnownNeverZero(Op.getOperand(0)))
4417       return true;
4418     break;
4419   }
4420 
4421   return false;
4422 }
4423 
4424 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4425   // Check the obvious case.
4426   if (A == B) return true;
4427 
4428   // For for negative and positive zero.
4429   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4430     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4431       if (CA->isZero() && CB->isZero()) return true;
4432 
4433   // Otherwise they may not be equal.
4434   return false;
4435 }
4436 
4437 // FIXME: unify with llvm::haveNoCommonBitsSet.
4438 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4439 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4440   assert(A.getValueType() == B.getValueType() &&
4441          "Values must have the same type");
4442   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4443                                         computeKnownBits(B));
4444 }
4445 
4446 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4447                                SelectionDAG &DAG) {
4448   if (cast<ConstantSDNode>(Step)->isNullValue())
4449     return DAG.getConstant(0, DL, VT);
4450 
4451   return SDValue();
4452 }
4453 
4454 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4455                                 ArrayRef<SDValue> Ops,
4456                                 SelectionDAG &DAG) {
4457   int NumOps = Ops.size();
4458   assert(NumOps != 0 && "Can't build an empty vector!");
4459   assert(!VT.isScalableVector() &&
4460          "BUILD_VECTOR cannot be used with scalable types");
4461   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4462          "Incorrect element count in BUILD_VECTOR!");
4463 
4464   // BUILD_VECTOR of UNDEFs is UNDEF.
4465   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4466     return DAG.getUNDEF(VT);
4467 
4468   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4469   SDValue IdentitySrc;
4470   bool IsIdentity = true;
4471   for (int i = 0; i != NumOps; ++i) {
4472     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4473         Ops[i].getOperand(0).getValueType() != VT ||
4474         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4475         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4476         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4477       IsIdentity = false;
4478       break;
4479     }
4480     IdentitySrc = Ops[i].getOperand(0);
4481   }
4482   if (IsIdentity)
4483     return IdentitySrc;
4484 
4485   return SDValue();
4486 }
4487 
4488 /// Try to simplify vector concatenation to an input value, undef, or build
4489 /// vector.
4490 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4491                                   ArrayRef<SDValue> Ops,
4492                                   SelectionDAG &DAG) {
4493   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4494   assert(llvm::all_of(Ops,
4495                       [Ops](SDValue Op) {
4496                         return Ops[0].getValueType() == Op.getValueType();
4497                       }) &&
4498          "Concatenation of vectors with inconsistent value types!");
4499   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4500              VT.getVectorElementCount() &&
4501          "Incorrect element count in vector concatenation!");
4502 
4503   if (Ops.size() == 1)
4504     return Ops[0];
4505 
4506   // Concat of UNDEFs is UNDEF.
4507   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4508     return DAG.getUNDEF(VT);
4509 
4510   // Scan the operands and look for extract operations from a single source
4511   // that correspond to insertion at the same location via this concatenation:
4512   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4513   SDValue IdentitySrc;
4514   bool IsIdentity = true;
4515   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4516     SDValue Op = Ops[i];
4517     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4518     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4519         Op.getOperand(0).getValueType() != VT ||
4520         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4521         Op.getConstantOperandVal(1) != IdentityIndex) {
4522       IsIdentity = false;
4523       break;
4524     }
4525     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4526            "Unexpected identity source vector for concat of extracts");
4527     IdentitySrc = Op.getOperand(0);
4528   }
4529   if (IsIdentity) {
4530     assert(IdentitySrc && "Failed to set source vector of extracts");
4531     return IdentitySrc;
4532   }
4533 
4534   // The code below this point is only designed to work for fixed width
4535   // vectors, so we bail out for now.
4536   if (VT.isScalableVector())
4537     return SDValue();
4538 
4539   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4540   // simplified to one big BUILD_VECTOR.
4541   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4542   EVT SVT = VT.getScalarType();
4543   SmallVector<SDValue, 16> Elts;
4544   for (SDValue Op : Ops) {
4545     EVT OpVT = Op.getValueType();
4546     if (Op.isUndef())
4547       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4548     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4549       Elts.append(Op->op_begin(), Op->op_end());
4550     else
4551       return SDValue();
4552   }
4553 
4554   // BUILD_VECTOR requires all inputs to be of the same type, find the
4555   // maximum type and extend them all.
4556   for (SDValue Op : Elts)
4557     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4558 
4559   if (SVT.bitsGT(VT.getScalarType())) {
4560     for (SDValue &Op : Elts) {
4561       if (Op.isUndef())
4562         Op = DAG.getUNDEF(SVT);
4563       else
4564         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4565                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4566                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4567     }
4568   }
4569 
4570   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4571   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4572   return V;
4573 }
4574 
4575 /// Gets or creates the specified node.
4576 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4577   FoldingSetNodeID ID;
4578   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4579   void *IP = nullptr;
4580   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4581     return SDValue(E, 0);
4582 
4583   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4584                               getVTList(VT));
4585   CSEMap.InsertNode(N, IP);
4586 
4587   InsertNode(N);
4588   SDValue V = SDValue(N, 0);
4589   NewSDValueDbgMsg(V, "Creating new node: ", this);
4590   return V;
4591 }
4592 
4593 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4594                               SDValue Operand) {
4595   SDNodeFlags Flags;
4596   if (Inserter)
4597     Flags = Inserter->getFlags();
4598   return getNode(Opcode, DL, VT, Operand, Flags);
4599 }
4600 
4601 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4602                               SDValue Operand, const SDNodeFlags Flags) {
4603   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4604          "Operand is DELETED_NODE!");
4605   // Constant fold unary operations with an integer constant operand. Even
4606   // opaque constant will be folded, because the folding of unary operations
4607   // doesn't create new constants with different values. Nevertheless, the
4608   // opaque flag is preserved during folding to prevent future folding with
4609   // other constants.
4610   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4611     const APInt &Val = C->getAPIntValue();
4612     switch (Opcode) {
4613     default: break;
4614     case ISD::SIGN_EXTEND:
4615       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4616                          C->isTargetOpcode(), C->isOpaque());
4617     case ISD::TRUNCATE:
4618       if (C->isOpaque())
4619         break;
4620       LLVM_FALLTHROUGH;
4621     case ISD::ANY_EXTEND:
4622     case ISD::ZERO_EXTEND:
4623       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4624                          C->isTargetOpcode(), C->isOpaque());
4625     case ISD::UINT_TO_FP:
4626     case ISD::SINT_TO_FP: {
4627       APFloat apf(EVTToAPFloatSemantics(VT),
4628                   APInt::getNullValue(VT.getSizeInBits()));
4629       (void)apf.convertFromAPInt(Val,
4630                                  Opcode==ISD::SINT_TO_FP,
4631                                  APFloat::rmNearestTiesToEven);
4632       return getConstantFP(apf, DL, VT);
4633     }
4634     case ISD::BITCAST:
4635       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4636         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4637       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4638         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4639       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4640         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4641       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4642         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4643       break;
4644     case ISD::ABS:
4645       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4646                          C->isOpaque());
4647     case ISD::BITREVERSE:
4648       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4649                          C->isOpaque());
4650     case ISD::BSWAP:
4651       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4652                          C->isOpaque());
4653     case ISD::CTPOP:
4654       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4655                          C->isOpaque());
4656     case ISD::CTLZ:
4657     case ISD::CTLZ_ZERO_UNDEF:
4658       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4659                          C->isOpaque());
4660     case ISD::CTTZ:
4661     case ISD::CTTZ_ZERO_UNDEF:
4662       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4663                          C->isOpaque());
4664     case ISD::FP16_TO_FP: {
4665       bool Ignored;
4666       APFloat FPV(APFloat::IEEEhalf(),
4667                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4668 
4669       // This can return overflow, underflow, or inexact; we don't care.
4670       // FIXME need to be more flexible about rounding mode.
4671       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4672                         APFloat::rmNearestTiesToEven, &Ignored);
4673       return getConstantFP(FPV, DL, VT);
4674     }
4675     case ISD::STEP_VECTOR: {
4676       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4677         return V;
4678       break;
4679     }
4680     }
4681   }
4682 
4683   // Constant fold unary operations with a floating point constant operand.
4684   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4685     APFloat V = C->getValueAPF();    // make copy
4686     switch (Opcode) {
4687     case ISD::FNEG:
4688       V.changeSign();
4689       return getConstantFP(V, DL, VT);
4690     case ISD::FABS:
4691       V.clearSign();
4692       return getConstantFP(V, DL, VT);
4693     case ISD::FCEIL: {
4694       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4695       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4696         return getConstantFP(V, DL, VT);
4697       break;
4698     }
4699     case ISD::FTRUNC: {
4700       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4701       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4702         return getConstantFP(V, DL, VT);
4703       break;
4704     }
4705     case ISD::FFLOOR: {
4706       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4707       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4708         return getConstantFP(V, DL, VT);
4709       break;
4710     }
4711     case ISD::FP_EXTEND: {
4712       bool ignored;
4713       // This can return overflow, underflow, or inexact; we don't care.
4714       // FIXME need to be more flexible about rounding mode.
4715       (void)V.convert(EVTToAPFloatSemantics(VT),
4716                       APFloat::rmNearestTiesToEven, &ignored);
4717       return getConstantFP(V, DL, VT);
4718     }
4719     case ISD::FP_TO_SINT:
4720     case ISD::FP_TO_UINT: {
4721       bool ignored;
4722       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4723       // FIXME need to be more flexible about rounding mode.
4724       APFloat::opStatus s =
4725           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4726       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4727         break;
4728       return getConstant(IntVal, DL, VT);
4729     }
4730     case ISD::BITCAST:
4731       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4732         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4733       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4734         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4735       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4736         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4737       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4738         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4739       break;
4740     case ISD::FP_TO_FP16: {
4741       bool Ignored;
4742       // This can return overflow, underflow, or inexact; we don't care.
4743       // FIXME need to be more flexible about rounding mode.
4744       (void)V.convert(APFloat::IEEEhalf(),
4745                       APFloat::rmNearestTiesToEven, &Ignored);
4746       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4747     }
4748     }
4749   }
4750 
4751   // Constant fold unary operations with a vector integer or float operand.
4752   switch (Opcode) {
4753   default:
4754     // FIXME: Entirely reasonable to perform folding of other unary
4755     // operations here as the need arises.
4756     break;
4757   case ISD::FNEG:
4758   case ISD::FABS:
4759   case ISD::FCEIL:
4760   case ISD::FTRUNC:
4761   case ISD::FFLOOR:
4762   case ISD::FP_EXTEND:
4763   case ISD::FP_TO_SINT:
4764   case ISD::FP_TO_UINT:
4765   case ISD::TRUNCATE:
4766   case ISD::ANY_EXTEND:
4767   case ISD::ZERO_EXTEND:
4768   case ISD::SIGN_EXTEND:
4769   case ISD::UINT_TO_FP:
4770   case ISD::SINT_TO_FP:
4771   case ISD::ABS:
4772   case ISD::BITREVERSE:
4773   case ISD::BSWAP:
4774   case ISD::CTLZ:
4775   case ISD::CTLZ_ZERO_UNDEF:
4776   case ISD::CTTZ:
4777   case ISD::CTTZ_ZERO_UNDEF:
4778   case ISD::CTPOP: {
4779     SDValue Ops = {Operand};
4780     if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4781       return Fold;
4782   }
4783   }
4784 
4785   unsigned OpOpcode = Operand.getNode()->getOpcode();
4786   switch (Opcode) {
4787   case ISD::STEP_VECTOR:
4788     assert(VT.isScalableVector() &&
4789            "STEP_VECTOR can only be used with scalable types");
4790     assert(VT.getScalarSizeInBits() >= 8 &&
4791            "STEP_VECTOR can only be used with vectors of integers that are at "
4792            "least 8 bits wide");
4793     assert(isa<ConstantSDNode>(Operand) &&
4794            cast<ConstantSDNode>(Operand)->getAPIntValue().isSignedIntN(
4795                VT.getScalarSizeInBits()) &&
4796            "Expected STEP_VECTOR integer constant to fit in "
4797            "the vector element type");
4798     break;
4799   case ISD::FREEZE:
4800     assert(VT == Operand.getValueType() && "Unexpected VT!");
4801     break;
4802   case ISD::TokenFactor:
4803   case ISD::MERGE_VALUES:
4804   case ISD::CONCAT_VECTORS:
4805     return Operand;         // Factor, merge or concat of one node?  No need.
4806   case ISD::BUILD_VECTOR: {
4807     // Attempt to simplify BUILD_VECTOR.
4808     SDValue Ops[] = {Operand};
4809     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4810       return V;
4811     break;
4812   }
4813   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4814   case ISD::FP_EXTEND:
4815     assert(VT.isFloatingPoint() &&
4816            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4817     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4818     assert((!VT.isVector() ||
4819             VT.getVectorElementCount() ==
4820             Operand.getValueType().getVectorElementCount()) &&
4821            "Vector element count mismatch!");
4822     assert(Operand.getValueType().bitsLT(VT) &&
4823            "Invalid fpext node, dst < src!");
4824     if (Operand.isUndef())
4825       return getUNDEF(VT);
4826     break;
4827   case ISD::FP_TO_SINT:
4828   case ISD::FP_TO_UINT:
4829     if (Operand.isUndef())
4830       return getUNDEF(VT);
4831     break;
4832   case ISD::SINT_TO_FP:
4833   case ISD::UINT_TO_FP:
4834     // [us]itofp(undef) = 0, because the result value is bounded.
4835     if (Operand.isUndef())
4836       return getConstantFP(0.0, DL, VT);
4837     break;
4838   case ISD::SIGN_EXTEND:
4839     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4840            "Invalid SIGN_EXTEND!");
4841     assert(VT.isVector() == Operand.getValueType().isVector() &&
4842            "SIGN_EXTEND result type type should be vector iff the operand "
4843            "type is vector!");
4844     if (Operand.getValueType() == VT) return Operand;   // noop extension
4845     assert((!VT.isVector() ||
4846             VT.getVectorElementCount() ==
4847                 Operand.getValueType().getVectorElementCount()) &&
4848            "Vector element count mismatch!");
4849     assert(Operand.getValueType().bitsLT(VT) &&
4850            "Invalid sext node, dst < src!");
4851     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4852       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4853     if (OpOpcode == ISD::UNDEF)
4854       // sext(undef) = 0, because the top bits will all be the same.
4855       return getConstant(0, DL, VT);
4856     break;
4857   case ISD::ZERO_EXTEND:
4858     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4859            "Invalid ZERO_EXTEND!");
4860     assert(VT.isVector() == Operand.getValueType().isVector() &&
4861            "ZERO_EXTEND result type type should be vector iff the operand "
4862            "type is vector!");
4863     if (Operand.getValueType() == VT) return Operand;   // noop extension
4864     assert((!VT.isVector() ||
4865             VT.getVectorElementCount() ==
4866                 Operand.getValueType().getVectorElementCount()) &&
4867            "Vector element count mismatch!");
4868     assert(Operand.getValueType().bitsLT(VT) &&
4869            "Invalid zext node, dst < src!");
4870     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4871       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4872     if (OpOpcode == ISD::UNDEF)
4873       // zext(undef) = 0, because the top bits will be zero.
4874       return getConstant(0, DL, VT);
4875     break;
4876   case ISD::ANY_EXTEND:
4877     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4878            "Invalid ANY_EXTEND!");
4879     assert(VT.isVector() == Operand.getValueType().isVector() &&
4880            "ANY_EXTEND result type type should be vector iff the operand "
4881            "type is vector!");
4882     if (Operand.getValueType() == VT) return Operand;   // noop extension
4883     assert((!VT.isVector() ||
4884             VT.getVectorElementCount() ==
4885                 Operand.getValueType().getVectorElementCount()) &&
4886            "Vector element count mismatch!");
4887     assert(Operand.getValueType().bitsLT(VT) &&
4888            "Invalid anyext node, dst < src!");
4889 
4890     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4891         OpOpcode == ISD::ANY_EXTEND)
4892       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4893       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4894     if (OpOpcode == ISD::UNDEF)
4895       return getUNDEF(VT);
4896 
4897     // (ext (trunc x)) -> x
4898     if (OpOpcode == ISD::TRUNCATE) {
4899       SDValue OpOp = Operand.getOperand(0);
4900       if (OpOp.getValueType() == VT) {
4901         transferDbgValues(Operand, OpOp);
4902         return OpOp;
4903       }
4904     }
4905     break;
4906   case ISD::TRUNCATE:
4907     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4908            "Invalid TRUNCATE!");
4909     assert(VT.isVector() == Operand.getValueType().isVector() &&
4910            "TRUNCATE result type type should be vector iff the operand "
4911            "type is vector!");
4912     if (Operand.getValueType() == VT) return Operand;   // noop truncate
4913     assert((!VT.isVector() ||
4914             VT.getVectorElementCount() ==
4915                 Operand.getValueType().getVectorElementCount()) &&
4916            "Vector element count mismatch!");
4917     assert(Operand.getValueType().bitsGT(VT) &&
4918            "Invalid truncate node, src < dst!");
4919     if (OpOpcode == ISD::TRUNCATE)
4920       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4921     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4922         OpOpcode == ISD::ANY_EXTEND) {
4923       // If the source is smaller than the dest, we still need an extend.
4924       if (Operand.getOperand(0).getValueType().getScalarType()
4925             .bitsLT(VT.getScalarType()))
4926         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4927       if (Operand.getOperand(0).getValueType().bitsGT(VT))
4928         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4929       return Operand.getOperand(0);
4930     }
4931     if (OpOpcode == ISD::UNDEF)
4932       return getUNDEF(VT);
4933     break;
4934   case ISD::ANY_EXTEND_VECTOR_INREG:
4935   case ISD::ZERO_EXTEND_VECTOR_INREG:
4936   case ISD::SIGN_EXTEND_VECTOR_INREG:
4937     assert(VT.isVector() && "This DAG node is restricted to vector types.");
4938     assert(Operand.getValueType().bitsLE(VT) &&
4939            "The input must be the same size or smaller than the result.");
4940     assert(VT.getVectorMinNumElements() <
4941                Operand.getValueType().getVectorMinNumElements() &&
4942            "The destination vector type must have fewer lanes than the input.");
4943     break;
4944   case ISD::ABS:
4945     assert(VT.isInteger() && VT == Operand.getValueType() &&
4946            "Invalid ABS!");
4947     if (OpOpcode == ISD::UNDEF)
4948       return getUNDEF(VT);
4949     break;
4950   case ISD::BSWAP:
4951     assert(VT.isInteger() && VT == Operand.getValueType() &&
4952            "Invalid BSWAP!");
4953     assert((VT.getScalarSizeInBits() % 16 == 0) &&
4954            "BSWAP types must be a multiple of 16 bits!");
4955     if (OpOpcode == ISD::UNDEF)
4956       return getUNDEF(VT);
4957     break;
4958   case ISD::BITREVERSE:
4959     assert(VT.isInteger() && VT == Operand.getValueType() &&
4960            "Invalid BITREVERSE!");
4961     if (OpOpcode == ISD::UNDEF)
4962       return getUNDEF(VT);
4963     break;
4964   case ISD::BITCAST:
4965     // Basic sanity checking.
4966     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4967            "Cannot BITCAST between types of different sizes!");
4968     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
4969     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
4970       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4971     if (OpOpcode == ISD::UNDEF)
4972       return getUNDEF(VT);
4973     break;
4974   case ISD::SCALAR_TO_VECTOR:
4975     assert(VT.isVector() && !Operand.getValueType().isVector() &&
4976            (VT.getVectorElementType() == Operand.getValueType() ||
4977             (VT.getVectorElementType().isInteger() &&
4978              Operand.getValueType().isInteger() &&
4979              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4980            "Illegal SCALAR_TO_VECTOR node!");
4981     if (OpOpcode == ISD::UNDEF)
4982       return getUNDEF(VT);
4983     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4984     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4985         isa<ConstantSDNode>(Operand.getOperand(1)) &&
4986         Operand.getConstantOperandVal(1) == 0 &&
4987         Operand.getOperand(0).getValueType() == VT)
4988       return Operand.getOperand(0);
4989     break;
4990   case ISD::FNEG:
4991     // Negation of an unknown bag of bits is still completely undefined.
4992     if (OpOpcode == ISD::UNDEF)
4993       return getUNDEF(VT);
4994 
4995     if (OpOpcode == ISD::FNEG)  // --X -> X
4996       return Operand.getOperand(0);
4997     break;
4998   case ISD::FABS:
4999     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5000       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5001     break;
5002   case ISD::VSCALE:
5003     assert(VT == Operand.getValueType() && "Unexpected VT!");
5004     break;
5005   case ISD::CTPOP:
5006     if (Operand.getValueType().getScalarType() == MVT::i1)
5007       return Operand;
5008     break;
5009   case ISD::CTLZ:
5010   case ISD::CTTZ:
5011     if (Operand.getValueType().getScalarType() == MVT::i1)
5012       return getNOT(DL, Operand, Operand.getValueType());
5013     break;
5014   case ISD::VECREDUCE_SMIN:
5015   case ISD::VECREDUCE_UMAX:
5016     if (Operand.getValueType().getScalarType() == MVT::i1)
5017       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5018     break;
5019   case ISD::VECREDUCE_SMAX:
5020   case ISD::VECREDUCE_UMIN:
5021     if (Operand.getValueType().getScalarType() == MVT::i1)
5022       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5023     break;
5024   }
5025 
5026   SDNode *N;
5027   SDVTList VTs = getVTList(VT);
5028   SDValue Ops[] = {Operand};
5029   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5030     FoldingSetNodeID ID;
5031     AddNodeIDNode(ID, Opcode, VTs, Ops);
5032     void *IP = nullptr;
5033     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5034       E->intersectFlagsWith(Flags);
5035       return SDValue(E, 0);
5036     }
5037 
5038     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5039     N->setFlags(Flags);
5040     createOperands(N, Ops);
5041     CSEMap.InsertNode(N, IP);
5042   } else {
5043     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5044     createOperands(N, Ops);
5045   }
5046 
5047   InsertNode(N);
5048   SDValue V = SDValue(N, 0);
5049   NewSDValueDbgMsg(V, "Creating new node: ", this);
5050   return V;
5051 }
5052 
5053 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5054                                        const APInt &C2) {
5055   switch (Opcode) {
5056   case ISD::ADD:  return C1 + C2;
5057   case ISD::SUB:  return C1 - C2;
5058   case ISD::MUL:  return C1 * C2;
5059   case ISD::AND:  return C1 & C2;
5060   case ISD::OR:   return C1 | C2;
5061   case ISD::XOR:  return C1 ^ C2;
5062   case ISD::SHL:  return C1 << C2;
5063   case ISD::SRL:  return C1.lshr(C2);
5064   case ISD::SRA:  return C1.ashr(C2);
5065   case ISD::ROTL: return C1.rotl(C2);
5066   case ISD::ROTR: return C1.rotr(C2);
5067   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5068   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5069   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5070   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5071   case ISD::SADDSAT: return C1.sadd_sat(C2);
5072   case ISD::UADDSAT: return C1.uadd_sat(C2);
5073   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5074   case ISD::USUBSAT: return C1.usub_sat(C2);
5075   case ISD::UDIV:
5076     if (!C2.getBoolValue())
5077       break;
5078     return C1.udiv(C2);
5079   case ISD::UREM:
5080     if (!C2.getBoolValue())
5081       break;
5082     return C1.urem(C2);
5083   case ISD::SDIV:
5084     if (!C2.getBoolValue())
5085       break;
5086     return C1.sdiv(C2);
5087   case ISD::SREM:
5088     if (!C2.getBoolValue())
5089       break;
5090     return C1.srem(C2);
5091   case ISD::MULHS: {
5092     unsigned FullWidth = C1.getBitWidth() * 2;
5093     APInt C1Ext = C1.sext(FullWidth);
5094     APInt C2Ext = C2.sext(FullWidth);
5095     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5096   }
5097   case ISD::MULHU: {
5098     unsigned FullWidth = C1.getBitWidth() * 2;
5099     APInt C1Ext = C1.zext(FullWidth);
5100     APInt C2Ext = C2.zext(FullWidth);
5101     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5102   }
5103   }
5104   return llvm::None;
5105 }
5106 
5107 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5108                                        const GlobalAddressSDNode *GA,
5109                                        const SDNode *N2) {
5110   if (GA->getOpcode() != ISD::GlobalAddress)
5111     return SDValue();
5112   if (!TLI->isOffsetFoldingLegal(GA))
5113     return SDValue();
5114   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5115   if (!C2)
5116     return SDValue();
5117   int64_t Offset = C2->getSExtValue();
5118   switch (Opcode) {
5119   case ISD::ADD: break;
5120   case ISD::SUB: Offset = -uint64_t(Offset); break;
5121   default: return SDValue();
5122   }
5123   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5124                           GA->getOffset() + uint64_t(Offset));
5125 }
5126 
5127 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5128   switch (Opcode) {
5129   case ISD::SDIV:
5130   case ISD::UDIV:
5131   case ISD::SREM:
5132   case ISD::UREM: {
5133     // If a divisor is zero/undef or any element of a divisor vector is
5134     // zero/undef, the whole op is undef.
5135     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5136     SDValue Divisor = Ops[1];
5137     if (Divisor.isUndef() || isNullConstant(Divisor))
5138       return true;
5139 
5140     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5141            llvm::any_of(Divisor->op_values(),
5142                         [](SDValue V) { return V.isUndef() ||
5143                                         isNullConstant(V); });
5144     // TODO: Handle signed overflow.
5145   }
5146   // TODO: Handle oversized shifts.
5147   default:
5148     return false;
5149   }
5150 }
5151 
5152 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5153                                              EVT VT, ArrayRef<SDValue> Ops) {
5154   // If the opcode is a target-specific ISD node, there's nothing we can
5155   // do here and the operand rules may not line up with the below, so
5156   // bail early.
5157   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5158   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5159   // foldCONCAT_VECTORS in getNode before this is called.
5160   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5161     return SDValue();
5162 
5163   // For now, the array Ops should only contain two values.
5164   // This enforcement will be removed once this function is merged with
5165   // FoldConstantVectorArithmetic
5166   if (Ops.size() != 2)
5167     return SDValue();
5168 
5169   if (isUndef(Opcode, Ops))
5170     return getUNDEF(VT);
5171 
5172   SDNode *N1 = Ops[0].getNode();
5173   SDNode *N2 = Ops[1].getNode();
5174 
5175   // Handle the case of two scalars.
5176   if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
5177     if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
5178       if (C1->isOpaque() || C2->isOpaque())
5179         return SDValue();
5180 
5181       Optional<APInt> FoldAttempt =
5182           FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5183       if (!FoldAttempt)
5184         return SDValue();
5185 
5186       SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5187       assert((!Folded || !VT.isVector()) &&
5188              "Can't fold vectors ops with scalar operands");
5189       return Folded;
5190     }
5191   }
5192 
5193   // fold (add Sym, c) -> Sym+c
5194   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
5195     return FoldSymbolOffset(Opcode, VT, GA, N2);
5196   if (TLI->isCommutativeBinOp(Opcode))
5197     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
5198       return FoldSymbolOffset(Opcode, VT, GA, N1);
5199 
5200   // For fixed width vectors, extract each constant element and fold them
5201   // individually. Either input may be an undef value.
5202   bool IsBVOrSV1 = N1->getOpcode() == ISD::BUILD_VECTOR ||
5203                    N1->getOpcode() == ISD::SPLAT_VECTOR;
5204   if (!IsBVOrSV1 && !N1->isUndef())
5205     return SDValue();
5206   bool IsBVOrSV2 = N2->getOpcode() == ISD::BUILD_VECTOR ||
5207                    N2->getOpcode() == ISD::SPLAT_VECTOR;
5208   if (!IsBVOrSV2 && !N2->isUndef())
5209     return SDValue();
5210   // If both operands are undef, that's handled the same way as scalars.
5211   if (!IsBVOrSV1 && !IsBVOrSV2)
5212     return SDValue();
5213 
5214   EVT SVT = VT.getScalarType();
5215   EVT LegalSVT = SVT;
5216   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5217     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5218     if (LegalSVT.bitsLT(SVT))
5219       return SDValue();
5220   }
5221 
5222   SmallVector<SDValue, 4> Outputs;
5223   unsigned NumOps = 0;
5224   if (IsBVOrSV1)
5225     NumOps = std::max(NumOps, N1->getNumOperands());
5226   if (IsBVOrSV2)
5227     NumOps = std::max(NumOps, N2->getNumOperands());
5228   assert(NumOps != 0 && "Expected non-zero operands");
5229   // Scalable vectors should only be SPLAT_VECTOR or UNDEF here. We only need
5230   // one iteration for that.
5231   assert((!VT.isScalableVector() || NumOps == 1) &&
5232          "Scalable vector should only have one scalar");
5233 
5234   for (unsigned I = 0; I != NumOps; ++I) {
5235     // We can have a fixed length SPLAT_VECTOR and a BUILD_VECTOR so we need
5236     // to use operand 0 of the SPLAT_VECTOR for each fixed element.
5237     SDValue V1;
5238     if (N1->getOpcode() == ISD::BUILD_VECTOR)
5239       V1 = N1->getOperand(I);
5240     else if (N1->getOpcode() == ISD::SPLAT_VECTOR)
5241       V1 = N1->getOperand(0);
5242     else
5243       V1 = getUNDEF(SVT);
5244 
5245     SDValue V2;
5246     if (N2->getOpcode() == ISD::BUILD_VECTOR)
5247       V2 = N2->getOperand(I);
5248     else if (N2->getOpcode() == ISD::SPLAT_VECTOR)
5249       V2 = N2->getOperand(0);
5250     else
5251       V2 = getUNDEF(SVT);
5252 
5253     if (SVT.isInteger()) {
5254       if (V1.getValueType().bitsGT(SVT))
5255         V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
5256       if (V2.getValueType().bitsGT(SVT))
5257         V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
5258     }
5259 
5260     if (V1.getValueType() != SVT || V2.getValueType() != SVT)
5261       return SDValue();
5262 
5263     // Fold one vector element.
5264     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
5265     if (LegalSVT != SVT)
5266       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5267 
5268     // Scalar folding only succeeded if the result is a constant or UNDEF.
5269     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5270         ScalarResult.getOpcode() != ISD::ConstantFP)
5271       return SDValue();
5272     Outputs.push_back(ScalarResult);
5273   }
5274 
5275   if (N1->getOpcode() == ISD::BUILD_VECTOR ||
5276       N2->getOpcode() == ISD::BUILD_VECTOR) {
5277     assert(VT.getVectorNumElements() == Outputs.size() &&
5278            "Vector size mismatch!");
5279 
5280     // Build a big vector out of the scalar elements we generated.
5281     return getBuildVector(VT, SDLoc(), Outputs);
5282   }
5283 
5284   assert((N1->getOpcode() == ISD::SPLAT_VECTOR ||
5285           N2->getOpcode() == ISD::SPLAT_VECTOR) &&
5286          "One operand should be a splat vector");
5287 
5288   assert(Outputs.size() == 1 && "Vector size mismatch!");
5289   return getSplatVector(VT, SDLoc(), Outputs[0]);
5290 }
5291 
5292 // TODO: Merge with FoldConstantArithmetic
5293 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
5294                                                    const SDLoc &DL, EVT VT,
5295                                                    ArrayRef<SDValue> Ops,
5296                                                    const SDNodeFlags Flags) {
5297   // If the opcode is a target-specific ISD node, there's nothing we can
5298   // do here and the operand rules may not line up with the below, so
5299   // bail early.
5300   if (Opcode >= ISD::BUILTIN_OP_END)
5301     return SDValue();
5302 
5303   if (isUndef(Opcode, Ops))
5304     return getUNDEF(VT);
5305 
5306   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
5307   if (!VT.isVector())
5308     return SDValue();
5309 
5310   ElementCount NumElts = VT.getVectorElementCount();
5311 
5312   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5313     return !Op.getValueType().isVector() ||
5314            Op.getValueType().getVectorElementCount() == NumElts;
5315   };
5316 
5317   auto IsConstantBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5318     APInt SplatVal;
5319     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
5320     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5321            (BV && BV->isConstant()) ||
5322            (Op.getOpcode() == ISD::SPLAT_VECTOR &&
5323             ISD::isConstantSplatVector(Op.getNode(), SplatVal));
5324   };
5325 
5326   // All operands must be vector types with the same number of elements as
5327   // the result type and must be either UNDEF or a build vector of constant
5328   // or UNDEF scalars.
5329   if (!llvm::all_of(Ops, IsConstantBuildVectorSplatVectorOrUndef) ||
5330       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5331     return SDValue();
5332 
5333   // If we are comparing vectors, then the result needs to be a i1 boolean
5334   // that is then sign-extended back to the legal result type.
5335   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5336 
5337   // Find legal integer scalar type for constant promotion and
5338   // ensure that its scalar size is at least as large as source.
5339   EVT LegalSVT = VT.getScalarType();
5340   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5341     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5342     if (LegalSVT.bitsLT(VT.getScalarType()))
5343       return SDValue();
5344   }
5345 
5346   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5347   // only have one operand to check. For fixed-length vector types we may have
5348   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5349   unsigned NumOperands = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5350 
5351   // Constant fold each scalar lane separately.
5352   SmallVector<SDValue, 4> ScalarResults;
5353   for (unsigned I = 0; I != NumOperands; I++) {
5354     SmallVector<SDValue, 4> ScalarOps;
5355     for (SDValue Op : Ops) {
5356       EVT InSVT = Op.getValueType().getScalarType();
5357       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5358           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5359         // We've checked that this is UNDEF or a constant of some kind.
5360         if (Op.isUndef())
5361           ScalarOps.push_back(getUNDEF(InSVT));
5362         else
5363           ScalarOps.push_back(Op);
5364         continue;
5365       }
5366 
5367       SDValue ScalarOp =
5368           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5369       EVT ScalarVT = ScalarOp.getValueType();
5370 
5371       // Build vector (integer) scalar operands may need implicit
5372       // truncation - do this before constant folding.
5373       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5374         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5375 
5376       ScalarOps.push_back(ScalarOp);
5377     }
5378 
5379     // Constant fold the scalar operands.
5380     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
5381 
5382     // Legalize the (integer) scalar constant if necessary.
5383     if (LegalSVT != SVT)
5384       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5385 
5386     // Scalar folding only succeeded if the result is a constant or UNDEF.
5387     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5388         ScalarResult.getOpcode() != ISD::ConstantFP)
5389       return SDValue();
5390     ScalarResults.push_back(ScalarResult);
5391   }
5392 
5393   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5394                                    : getBuildVector(VT, DL, ScalarResults);
5395   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5396   return V;
5397 }
5398 
5399 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5400                                          EVT VT, SDValue N1, SDValue N2) {
5401   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5402   //       should. That will require dealing with a potentially non-default
5403   //       rounding mode, checking the "opStatus" return value from the APFloat
5404   //       math calculations, and possibly other variations.
5405   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5406   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5407   if (N1CFP && N2CFP) {
5408     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5409     switch (Opcode) {
5410     case ISD::FADD:
5411       C1.add(C2, APFloat::rmNearestTiesToEven);
5412       return getConstantFP(C1, DL, VT);
5413     case ISD::FSUB:
5414       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5415       return getConstantFP(C1, DL, VT);
5416     case ISD::FMUL:
5417       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5418       return getConstantFP(C1, DL, VT);
5419     case ISD::FDIV:
5420       C1.divide(C2, APFloat::rmNearestTiesToEven);
5421       return getConstantFP(C1, DL, VT);
5422     case ISD::FREM:
5423       C1.mod(C2);
5424       return getConstantFP(C1, DL, VT);
5425     case ISD::FCOPYSIGN:
5426       C1.copySign(C2);
5427       return getConstantFP(C1, DL, VT);
5428     default: break;
5429     }
5430   }
5431   if (N1CFP && Opcode == ISD::FP_ROUND) {
5432     APFloat C1 = N1CFP->getValueAPF();    // make copy
5433     bool Unused;
5434     // This can return overflow, underflow, or inexact; we don't care.
5435     // FIXME need to be more flexible about rounding mode.
5436     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5437                       &Unused);
5438     return getConstantFP(C1, DL, VT);
5439   }
5440 
5441   switch (Opcode) {
5442   case ISD::FSUB:
5443     // -0.0 - undef --> undef (consistent with "fneg undef")
5444     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5445       return getUNDEF(VT);
5446     LLVM_FALLTHROUGH;
5447 
5448   case ISD::FADD:
5449   case ISD::FMUL:
5450   case ISD::FDIV:
5451   case ISD::FREM:
5452     // If both operands are undef, the result is undef. If 1 operand is undef,
5453     // the result is NaN. This should match the behavior of the IR optimizer.
5454     if (N1.isUndef() && N2.isUndef())
5455       return getUNDEF(VT);
5456     if (N1.isUndef() || N2.isUndef())
5457       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5458   }
5459   return SDValue();
5460 }
5461 
5462 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5463   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5464 
5465   // There's no need to assert on a byte-aligned pointer. All pointers are at
5466   // least byte aligned.
5467   if (A == Align(1))
5468     return Val;
5469 
5470   FoldingSetNodeID ID;
5471   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5472   ID.AddInteger(A.value());
5473 
5474   void *IP = nullptr;
5475   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5476     return SDValue(E, 0);
5477 
5478   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5479                                          Val.getValueType(), A);
5480   createOperands(N, {Val});
5481 
5482   CSEMap.InsertNode(N, IP);
5483   InsertNode(N);
5484 
5485   SDValue V(N, 0);
5486   NewSDValueDbgMsg(V, "Creating new node: ", this);
5487   return V;
5488 }
5489 
5490 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5491                               SDValue N1, SDValue N2) {
5492   SDNodeFlags Flags;
5493   if (Inserter)
5494     Flags = Inserter->getFlags();
5495   return getNode(Opcode, DL, VT, N1, N2, Flags);
5496 }
5497 
5498 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5499                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5500   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5501          N2.getOpcode() != ISD::DELETED_NODE &&
5502          "Operand is DELETED_NODE!");
5503   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5504   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5505   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5506   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5507 
5508   // Canonicalize constant to RHS if commutative.
5509   if (TLI->isCommutativeBinOp(Opcode)) {
5510     if (N1C && !N2C) {
5511       std::swap(N1C, N2C);
5512       std::swap(N1, N2);
5513     } else if (N1CFP && !N2CFP) {
5514       std::swap(N1CFP, N2CFP);
5515       std::swap(N1, N2);
5516     }
5517   }
5518 
5519   switch (Opcode) {
5520   default: break;
5521   case ISD::TokenFactor:
5522     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5523            N2.getValueType() == MVT::Other && "Invalid token factor!");
5524     // Fold trivial token factors.
5525     if (N1.getOpcode() == ISD::EntryToken) return N2;
5526     if (N2.getOpcode() == ISD::EntryToken) return N1;
5527     if (N1 == N2) return N1;
5528     break;
5529   case ISD::BUILD_VECTOR: {
5530     // Attempt to simplify BUILD_VECTOR.
5531     SDValue Ops[] = {N1, N2};
5532     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5533       return V;
5534     break;
5535   }
5536   case ISD::CONCAT_VECTORS: {
5537     SDValue Ops[] = {N1, N2};
5538     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5539       return V;
5540     break;
5541   }
5542   case ISD::AND:
5543     assert(VT.isInteger() && "This operator does not apply to FP types!");
5544     assert(N1.getValueType() == N2.getValueType() &&
5545            N1.getValueType() == VT && "Binary operator types must match!");
5546     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5547     // worth handling here.
5548     if (N2C && N2C->isNullValue())
5549       return N2;
5550     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
5551       return N1;
5552     break;
5553   case ISD::OR:
5554   case ISD::XOR:
5555   case ISD::ADD:
5556   case ISD::SUB:
5557     assert(VT.isInteger() && "This operator does not apply to FP types!");
5558     assert(N1.getValueType() == N2.getValueType() &&
5559            N1.getValueType() == VT && "Binary operator types must match!");
5560     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5561     // it's worth handling here.
5562     if (N2C && N2C->isNullValue())
5563       return N1;
5564     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5565         VT.getVectorElementType() == MVT::i1)
5566       return getNode(ISD::XOR, DL, VT, N1, N2);
5567     break;
5568   case ISD::MUL:
5569     assert(VT.isInteger() && "This operator does not apply to FP types!");
5570     assert(N1.getValueType() == N2.getValueType() &&
5571            N1.getValueType() == VT && "Binary operator types must match!");
5572     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5573       return getNode(ISD::AND, DL, VT, N1, N2);
5574     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5575       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5576       const APInt &N2CImm = N2C->getAPIntValue();
5577       return getVScale(DL, VT, MulImm * N2CImm);
5578     }
5579     break;
5580   case ISD::UDIV:
5581   case ISD::UREM:
5582   case ISD::MULHU:
5583   case ISD::MULHS:
5584   case ISD::SDIV:
5585   case ISD::SREM:
5586   case ISD::SADDSAT:
5587   case ISD::SSUBSAT:
5588   case ISD::UADDSAT:
5589   case ISD::USUBSAT:
5590     assert(VT.isInteger() && "This operator does not apply to FP types!");
5591     assert(N1.getValueType() == N2.getValueType() &&
5592            N1.getValueType() == VT && "Binary operator types must match!");
5593     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5594       // fold (add_sat x, y) -> (or x, y) for bool types.
5595       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5596         return getNode(ISD::OR, DL, VT, N1, N2);
5597       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5598       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5599         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5600     }
5601     break;
5602   case ISD::SMIN:
5603   case ISD::UMAX:
5604     assert(VT.isInteger() && "This operator does not apply to FP types!");
5605     assert(N1.getValueType() == N2.getValueType() &&
5606            N1.getValueType() == VT && "Binary operator types must match!");
5607     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5608       return getNode(ISD::OR, DL, VT, N1, N2);
5609     break;
5610   case ISD::SMAX:
5611   case ISD::UMIN:
5612     assert(VT.isInteger() && "This operator does not apply to FP types!");
5613     assert(N1.getValueType() == N2.getValueType() &&
5614            N1.getValueType() == VT && "Binary operator types must match!");
5615     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5616       return getNode(ISD::AND, DL, VT, N1, N2);
5617     break;
5618   case ISD::FADD:
5619   case ISD::FSUB:
5620   case ISD::FMUL:
5621   case ISD::FDIV:
5622   case ISD::FREM:
5623     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5624     assert(N1.getValueType() == N2.getValueType() &&
5625            N1.getValueType() == VT && "Binary operator types must match!");
5626     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5627       return V;
5628     break;
5629   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5630     assert(N1.getValueType() == VT &&
5631            N1.getValueType().isFloatingPoint() &&
5632            N2.getValueType().isFloatingPoint() &&
5633            "Invalid FCOPYSIGN!");
5634     break;
5635   case ISD::SHL:
5636     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5637       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5638       const APInt &ShiftImm = N2C->getAPIntValue();
5639       return getVScale(DL, VT, MulImm << ShiftImm);
5640     }
5641     LLVM_FALLTHROUGH;
5642   case ISD::SRA:
5643   case ISD::SRL:
5644     if (SDValue V = simplifyShift(N1, N2))
5645       return V;
5646     LLVM_FALLTHROUGH;
5647   case ISD::ROTL:
5648   case ISD::ROTR:
5649     assert(VT == N1.getValueType() &&
5650            "Shift operators return type must be the same as their first arg");
5651     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5652            "Shifts only work on integers");
5653     assert((!VT.isVector() || VT == N2.getValueType()) &&
5654            "Vector shift amounts must be in the same as their first arg");
5655     // Verify that the shift amount VT is big enough to hold valid shift
5656     // amounts.  This catches things like trying to shift an i1024 value by an
5657     // i8, which is easy to fall into in generic code that uses
5658     // TLI.getShiftAmount().
5659     assert(N2.getValueType().getScalarSizeInBits() >=
5660                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5661            "Invalid use of small shift amount with oversized value!");
5662 
5663     // Always fold shifts of i1 values so the code generator doesn't need to
5664     // handle them.  Since we know the size of the shift has to be less than the
5665     // size of the value, the shift/rotate count is guaranteed to be zero.
5666     if (VT == MVT::i1)
5667       return N1;
5668     if (N2C && N2C->isNullValue())
5669       return N1;
5670     break;
5671   case ISD::FP_ROUND:
5672     assert(VT.isFloatingPoint() &&
5673            N1.getValueType().isFloatingPoint() &&
5674            VT.bitsLE(N1.getValueType()) &&
5675            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5676            "Invalid FP_ROUND!");
5677     if (N1.getValueType() == VT) return N1;  // noop conversion.
5678     break;
5679   case ISD::AssertSext:
5680   case ISD::AssertZext: {
5681     EVT EVT = cast<VTSDNode>(N2)->getVT();
5682     assert(VT == N1.getValueType() && "Not an inreg extend!");
5683     assert(VT.isInteger() && EVT.isInteger() &&
5684            "Cannot *_EXTEND_INREG FP types");
5685     assert(!EVT.isVector() &&
5686            "AssertSExt/AssertZExt type should be the vector element type "
5687            "rather than the vector type!");
5688     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5689     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5690     break;
5691   }
5692   case ISD::SIGN_EXTEND_INREG: {
5693     EVT EVT = cast<VTSDNode>(N2)->getVT();
5694     assert(VT == N1.getValueType() && "Not an inreg extend!");
5695     assert(VT.isInteger() && EVT.isInteger() &&
5696            "Cannot *_EXTEND_INREG FP types");
5697     assert(EVT.isVector() == VT.isVector() &&
5698            "SIGN_EXTEND_INREG type should be vector iff the operand "
5699            "type is vector!");
5700     assert((!EVT.isVector() ||
5701             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5702            "Vector element counts must match in SIGN_EXTEND_INREG");
5703     assert(EVT.bitsLE(VT) && "Not extending!");
5704     if (EVT == VT) return N1;  // Not actually extending
5705 
5706     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5707       unsigned FromBits = EVT.getScalarSizeInBits();
5708       Val <<= Val.getBitWidth() - FromBits;
5709       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5710       return getConstant(Val, DL, ConstantVT);
5711     };
5712 
5713     if (N1C) {
5714       const APInt &Val = N1C->getAPIntValue();
5715       return SignExtendInReg(Val, VT);
5716     }
5717 
5718     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5719       SmallVector<SDValue, 8> Ops;
5720       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5721       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5722         SDValue Op = N1.getOperand(i);
5723         if (Op.isUndef()) {
5724           Ops.push_back(getUNDEF(OpVT));
5725           continue;
5726         }
5727         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5728         APInt Val = C->getAPIntValue();
5729         Ops.push_back(SignExtendInReg(Val, OpVT));
5730       }
5731       return getBuildVector(VT, DL, Ops);
5732     }
5733     break;
5734   }
5735   case ISD::FP_TO_SINT_SAT:
5736   case ISD::FP_TO_UINT_SAT: {
5737     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5738            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5739     assert(N1.getValueType().isVector() == VT.isVector() &&
5740            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5741            "vector!");
5742     assert((!VT.isVector() || VT.getVectorNumElements() ==
5743                                   N1.getValueType().getVectorNumElements()) &&
5744            "Vector element counts must match in FP_TO_*INT_SAT");
5745     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5746            "Type to saturate to must be a scalar.");
5747     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5748            "Not extending!");
5749     break;
5750   }
5751   case ISD::EXTRACT_VECTOR_ELT:
5752     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5753            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5754              element type of the vector.");
5755 
5756     // Extract from an undefined value or using an undefined index is undefined.
5757     if (N1.isUndef() || N2.isUndef())
5758       return getUNDEF(VT);
5759 
5760     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5761     // vectors. For scalable vectors we will provide appropriate support for
5762     // dealing with arbitrary indices.
5763     if (N2C && N1.getValueType().isFixedLengthVector() &&
5764         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5765       return getUNDEF(VT);
5766 
5767     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5768     // expanding copies of large vectors from registers. This only works for
5769     // fixed length vectors, since we need to know the exact number of
5770     // elements.
5771     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5772         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5773       unsigned Factor =
5774         N1.getOperand(0).getValueType().getVectorNumElements();
5775       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5776                      N1.getOperand(N2C->getZExtValue() / Factor),
5777                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5778     }
5779 
5780     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5781     // lowering is expanding large vector constants.
5782     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5783                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5784       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5785               N1.getValueType().isFixedLengthVector()) &&
5786              "BUILD_VECTOR used for scalable vectors");
5787       unsigned Index =
5788           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5789       SDValue Elt = N1.getOperand(Index);
5790 
5791       if (VT != Elt.getValueType())
5792         // If the vector element type is not legal, the BUILD_VECTOR operands
5793         // are promoted and implicitly truncated, and the result implicitly
5794         // extended. Make that explicit here.
5795         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5796 
5797       return Elt;
5798     }
5799 
5800     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5801     // operations are lowered to scalars.
5802     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5803       // If the indices are the same, return the inserted element else
5804       // if the indices are known different, extract the element from
5805       // the original vector.
5806       SDValue N1Op2 = N1.getOperand(2);
5807       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5808 
5809       if (N1Op2C && N2C) {
5810         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5811           if (VT == N1.getOperand(1).getValueType())
5812             return N1.getOperand(1);
5813           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5814         }
5815         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5816       }
5817     }
5818 
5819     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5820     // when vector types are scalarized and v1iX is legal.
5821     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5822     // Here we are completely ignoring the extract element index (N2),
5823     // which is fine for fixed width vectors, since any index other than 0
5824     // is undefined anyway. However, this cannot be ignored for scalable
5825     // vectors - in theory we could support this, but we don't want to do this
5826     // without a profitability check.
5827     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5828         N1.getValueType().isFixedLengthVector() &&
5829         N1.getValueType().getVectorNumElements() == 1) {
5830       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5831                      N1.getOperand(1));
5832     }
5833     break;
5834   case ISD::EXTRACT_ELEMENT:
5835     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5836     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5837            (N1.getValueType().isInteger() == VT.isInteger()) &&
5838            N1.getValueType() != VT &&
5839            "Wrong types for EXTRACT_ELEMENT!");
5840 
5841     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5842     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5843     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5844     if (N1.getOpcode() == ISD::BUILD_PAIR)
5845       return N1.getOperand(N2C->getZExtValue());
5846 
5847     // EXTRACT_ELEMENT of a constant int is also very common.
5848     if (N1C) {
5849       unsigned ElementSize = VT.getSizeInBits();
5850       unsigned Shift = ElementSize * N2C->getZExtValue();
5851       const APInt &Val = N1C->getAPIntValue();
5852       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5853     }
5854     break;
5855   case ISD::EXTRACT_SUBVECTOR: {
5856     EVT N1VT = N1.getValueType();
5857     assert(VT.isVector() && N1VT.isVector() &&
5858            "Extract subvector VTs must be vectors!");
5859     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5860            "Extract subvector VTs must have the same element type!");
5861     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5862            "Cannot extract a scalable vector from a fixed length vector!");
5863     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5864             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5865            "Extract subvector must be from larger vector to smaller vector!");
5866     assert(N2C && "Extract subvector index must be a constant");
5867     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5868             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5869                 N1VT.getVectorMinNumElements()) &&
5870            "Extract subvector overflow!");
5871     assert(N2C->getAPIntValue().getBitWidth() ==
5872                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5873            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5874 
5875     // Trivial extraction.
5876     if (VT == N1VT)
5877       return N1;
5878 
5879     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5880     if (N1.isUndef())
5881       return getUNDEF(VT);
5882 
5883     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5884     // the concat have the same type as the extract.
5885     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5886         VT == N1.getOperand(0).getValueType()) {
5887       unsigned Factor = VT.getVectorMinNumElements();
5888       return N1.getOperand(N2C->getZExtValue() / Factor);
5889     }
5890 
5891     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5892     // during shuffle legalization.
5893     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5894         VT == N1.getOperand(1).getValueType())
5895       return N1.getOperand(1);
5896     break;
5897   }
5898   }
5899 
5900   // Perform trivial constant folding.
5901   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5902     return SV;
5903 
5904   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5905     return V;
5906 
5907   // Canonicalize an UNDEF to the RHS, even over a constant.
5908   if (N1.isUndef()) {
5909     if (TLI->isCommutativeBinOp(Opcode)) {
5910       std::swap(N1, N2);
5911     } else {
5912       switch (Opcode) {
5913       case ISD::SIGN_EXTEND_INREG:
5914       case ISD::SUB:
5915         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5916       case ISD::UDIV:
5917       case ISD::SDIV:
5918       case ISD::UREM:
5919       case ISD::SREM:
5920       case ISD::SSUBSAT:
5921       case ISD::USUBSAT:
5922         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5923       }
5924     }
5925   }
5926 
5927   // Fold a bunch of operators when the RHS is undef.
5928   if (N2.isUndef()) {
5929     switch (Opcode) {
5930     case ISD::XOR:
5931       if (N1.isUndef())
5932         // Handle undef ^ undef -> 0 special case. This is a common
5933         // idiom (misuse).
5934         return getConstant(0, DL, VT);
5935       LLVM_FALLTHROUGH;
5936     case ISD::ADD:
5937     case ISD::SUB:
5938     case ISD::UDIV:
5939     case ISD::SDIV:
5940     case ISD::UREM:
5941     case ISD::SREM:
5942       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5943     case ISD::MUL:
5944     case ISD::AND:
5945     case ISD::SSUBSAT:
5946     case ISD::USUBSAT:
5947       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5948     case ISD::OR:
5949     case ISD::SADDSAT:
5950     case ISD::UADDSAT:
5951       return getAllOnesConstant(DL, VT);
5952     }
5953   }
5954 
5955   // Memoize this node if possible.
5956   SDNode *N;
5957   SDVTList VTs = getVTList(VT);
5958   SDValue Ops[] = {N1, N2};
5959   if (VT != MVT::Glue) {
5960     FoldingSetNodeID ID;
5961     AddNodeIDNode(ID, Opcode, VTs, Ops);
5962     void *IP = nullptr;
5963     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5964       E->intersectFlagsWith(Flags);
5965       return SDValue(E, 0);
5966     }
5967 
5968     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5969     N->setFlags(Flags);
5970     createOperands(N, Ops);
5971     CSEMap.InsertNode(N, IP);
5972   } else {
5973     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5974     createOperands(N, Ops);
5975   }
5976 
5977   InsertNode(N);
5978   SDValue V = SDValue(N, 0);
5979   NewSDValueDbgMsg(V, "Creating new node: ", this);
5980   return V;
5981 }
5982 
5983 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5984                               SDValue N1, SDValue N2, SDValue N3) {
5985   SDNodeFlags Flags;
5986   if (Inserter)
5987     Flags = Inserter->getFlags();
5988   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
5989 }
5990 
5991 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5992                               SDValue N1, SDValue N2, SDValue N3,
5993                               const SDNodeFlags Flags) {
5994   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5995          N2.getOpcode() != ISD::DELETED_NODE &&
5996          N3.getOpcode() != ISD::DELETED_NODE &&
5997          "Operand is DELETED_NODE!");
5998   // Perform various simplifications.
5999   switch (Opcode) {
6000   case ISD::FMA: {
6001     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6002     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6003            N3.getValueType() == VT && "FMA types must match!");
6004     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6005     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6006     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6007     if (N1CFP && N2CFP && N3CFP) {
6008       APFloat  V1 = N1CFP->getValueAPF();
6009       const APFloat &V2 = N2CFP->getValueAPF();
6010       const APFloat &V3 = N3CFP->getValueAPF();
6011       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6012       return getConstantFP(V1, DL, VT);
6013     }
6014     break;
6015   }
6016   case ISD::BUILD_VECTOR: {
6017     // Attempt to simplify BUILD_VECTOR.
6018     SDValue Ops[] = {N1, N2, N3};
6019     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6020       return V;
6021     break;
6022   }
6023   case ISD::CONCAT_VECTORS: {
6024     SDValue Ops[] = {N1, N2, N3};
6025     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6026       return V;
6027     break;
6028   }
6029   case ISD::SETCC: {
6030     assert(VT.isInteger() && "SETCC result type must be an integer!");
6031     assert(N1.getValueType() == N2.getValueType() &&
6032            "SETCC operands must have the same type!");
6033     assert(VT.isVector() == N1.getValueType().isVector() &&
6034            "SETCC type should be vector iff the operand type is vector!");
6035     assert((!VT.isVector() || VT.getVectorElementCount() ==
6036                                   N1.getValueType().getVectorElementCount()) &&
6037            "SETCC vector element counts must match!");
6038     // Use FoldSetCC to simplify SETCC's.
6039     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6040       return V;
6041     // Vector constant folding.
6042     SDValue Ops[] = {N1, N2, N3};
6043     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
6044       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6045       return V;
6046     }
6047     break;
6048   }
6049   case ISD::SELECT:
6050   case ISD::VSELECT:
6051     if (SDValue V = simplifySelect(N1, N2, N3))
6052       return V;
6053     break;
6054   case ISD::VECTOR_SHUFFLE:
6055     llvm_unreachable("should use getVectorShuffle constructor!");
6056   case ISD::INSERT_VECTOR_ELT: {
6057     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6058     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6059     // for scalable vectors where we will generate appropriate code to
6060     // deal with out-of-bounds cases correctly.
6061     if (N3C && N1.getValueType().isFixedLengthVector() &&
6062         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6063       return getUNDEF(VT);
6064 
6065     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6066     if (N3.isUndef())
6067       return getUNDEF(VT);
6068 
6069     // If the inserted element is an UNDEF, just use the input vector.
6070     if (N2.isUndef())
6071       return N1;
6072 
6073     break;
6074   }
6075   case ISD::INSERT_SUBVECTOR: {
6076     // Inserting undef into undef is still undef.
6077     if (N1.isUndef() && N2.isUndef())
6078       return getUNDEF(VT);
6079 
6080     EVT N2VT = N2.getValueType();
6081     assert(VT == N1.getValueType() &&
6082            "Dest and insert subvector source types must match!");
6083     assert(VT.isVector() && N2VT.isVector() &&
6084            "Insert subvector VTs must be vectors!");
6085     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6086            "Cannot insert a scalable vector into a fixed length vector!");
6087     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6088             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6089            "Insert subvector must be from smaller vector to larger vector!");
6090     assert(isa<ConstantSDNode>(N3) &&
6091            "Insert subvector index must be constant");
6092     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6093             (N2VT.getVectorMinNumElements() +
6094              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6095                 VT.getVectorMinNumElements()) &&
6096            "Insert subvector overflow!");
6097     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6098                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6099            "Constant index for INSERT_SUBVECTOR has an invalid size");
6100 
6101     // Trivial insertion.
6102     if (VT == N2VT)
6103       return N2;
6104 
6105     // If this is an insert of an extracted vector into an undef vector, we
6106     // can just use the input to the extract.
6107     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6108         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6109       return N2.getOperand(0);
6110     break;
6111   }
6112   case ISD::BITCAST:
6113     // Fold bit_convert nodes from a type to themselves.
6114     if (N1.getValueType() == VT)
6115       return N1;
6116     break;
6117   }
6118 
6119   // Memoize node if it doesn't produce a flag.
6120   SDNode *N;
6121   SDVTList VTs = getVTList(VT);
6122   SDValue Ops[] = {N1, N2, N3};
6123   if (VT != MVT::Glue) {
6124     FoldingSetNodeID ID;
6125     AddNodeIDNode(ID, Opcode, VTs, Ops);
6126     void *IP = nullptr;
6127     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6128       E->intersectFlagsWith(Flags);
6129       return SDValue(E, 0);
6130     }
6131 
6132     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6133     N->setFlags(Flags);
6134     createOperands(N, Ops);
6135     CSEMap.InsertNode(N, IP);
6136   } else {
6137     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6138     createOperands(N, Ops);
6139   }
6140 
6141   InsertNode(N);
6142   SDValue V = SDValue(N, 0);
6143   NewSDValueDbgMsg(V, "Creating new node: ", this);
6144   return V;
6145 }
6146 
6147 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6148                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6149   SDValue Ops[] = { N1, N2, N3, N4 };
6150   return getNode(Opcode, DL, VT, Ops);
6151 }
6152 
6153 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6154                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6155                               SDValue N5) {
6156   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6157   return getNode(Opcode, DL, VT, Ops);
6158 }
6159 
6160 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6161 /// the incoming stack arguments to be loaded from the stack.
6162 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6163   SmallVector<SDValue, 8> ArgChains;
6164 
6165   // Include the original chain at the beginning of the list. When this is
6166   // used by target LowerCall hooks, this helps legalize find the
6167   // CALLSEQ_BEGIN node.
6168   ArgChains.push_back(Chain);
6169 
6170   // Add a chain value for each stack argument.
6171   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
6172        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
6173     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
6174       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6175         if (FI->getIndex() < 0)
6176           ArgChains.push_back(SDValue(L, 1));
6177 
6178   // Build a tokenfactor for all the chains.
6179   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6180 }
6181 
6182 /// getMemsetValue - Vectorized representation of the memset value
6183 /// operand.
6184 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6185                               const SDLoc &dl) {
6186   assert(!Value.isUndef());
6187 
6188   unsigned NumBits = VT.getScalarSizeInBits();
6189   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6190     assert(C->getAPIntValue().getBitWidth() == 8);
6191     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6192     if (VT.isInteger()) {
6193       bool IsOpaque = VT.getSizeInBits() > 64 ||
6194           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6195       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6196     }
6197     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6198                              VT);
6199   }
6200 
6201   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6202   EVT IntVT = VT.getScalarType();
6203   if (!IntVT.isInteger())
6204     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6205 
6206   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6207   if (NumBits > 8) {
6208     // Use a multiplication with 0x010101... to extend the input to the
6209     // required length.
6210     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6211     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6212                         DAG.getConstant(Magic, dl, IntVT));
6213   }
6214 
6215   if (VT != Value.getValueType() && !VT.isInteger())
6216     Value = DAG.getBitcast(VT.getScalarType(), Value);
6217   if (VT != Value.getValueType())
6218     Value = DAG.getSplatBuildVector(VT, dl, Value);
6219 
6220   return Value;
6221 }
6222 
6223 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6224 /// used when a memcpy is turned into a memset when the source is a constant
6225 /// string ptr.
6226 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6227                                   const TargetLowering &TLI,
6228                                   const ConstantDataArraySlice &Slice) {
6229   // Handle vector with all elements zero.
6230   if (Slice.Array == nullptr) {
6231     if (VT.isInteger())
6232       return DAG.getConstant(0, dl, VT);
6233     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6234       return DAG.getConstantFP(0.0, dl, VT);
6235     if (VT.isVector()) {
6236       unsigned NumElts = VT.getVectorNumElements();
6237       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6238       return DAG.getNode(ISD::BITCAST, dl, VT,
6239                          DAG.getConstant(0, dl,
6240                                          EVT::getVectorVT(*DAG.getContext(),
6241                                                           EltVT, NumElts)));
6242     }
6243     llvm_unreachable("Expected type!");
6244   }
6245 
6246   assert(!VT.isVector() && "Can't handle vector type here!");
6247   unsigned NumVTBits = VT.getSizeInBits();
6248   unsigned NumVTBytes = NumVTBits / 8;
6249   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6250 
6251   APInt Val(NumVTBits, 0);
6252   if (DAG.getDataLayout().isLittleEndian()) {
6253     for (unsigned i = 0; i != NumBytes; ++i)
6254       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6255   } else {
6256     for (unsigned i = 0; i != NumBytes; ++i)
6257       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6258   }
6259 
6260   // If the "cost" of materializing the integer immediate is less than the cost
6261   // of a load, then it is cost effective to turn the load into the immediate.
6262   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6263   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6264     return DAG.getConstant(Val, dl, VT);
6265   return SDValue(nullptr, 0);
6266 }
6267 
6268 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6269                                            const SDLoc &DL,
6270                                            const SDNodeFlags Flags) {
6271   EVT VT = Base.getValueType();
6272   SDValue Index;
6273 
6274   if (Offset.isScalable())
6275     Index = getVScale(DL, Base.getValueType(),
6276                       APInt(Base.getValueSizeInBits().getFixedSize(),
6277                             Offset.getKnownMinSize()));
6278   else
6279     Index = getConstant(Offset.getFixedSize(), DL, VT);
6280 
6281   return getMemBasePlusOffset(Base, Index, DL, Flags);
6282 }
6283 
6284 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6285                                            const SDLoc &DL,
6286                                            const SDNodeFlags Flags) {
6287   assert(Offset.getValueType().isInteger());
6288   EVT BasePtrVT = Ptr.getValueType();
6289   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6290 }
6291 
6292 /// Returns true if memcpy source is constant data.
6293 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6294   uint64_t SrcDelta = 0;
6295   GlobalAddressSDNode *G = nullptr;
6296   if (Src.getOpcode() == ISD::GlobalAddress)
6297     G = cast<GlobalAddressSDNode>(Src);
6298   else if (Src.getOpcode() == ISD::ADD &&
6299            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6300            Src.getOperand(1).getOpcode() == ISD::Constant) {
6301     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6302     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6303   }
6304   if (!G)
6305     return false;
6306 
6307   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6308                                   SrcDelta + G->getOffset());
6309 }
6310 
6311 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6312                                       SelectionDAG &DAG) {
6313   // On Darwin, -Os means optimize for size without hurting performance, so
6314   // only really optimize for size when -Oz (MinSize) is used.
6315   if (MF.getTarget().getTargetTriple().isOSDarwin())
6316     return MF.getFunction().hasMinSize();
6317   return DAG.shouldOptForSize();
6318 }
6319 
6320 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6321                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6322                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6323                           SmallVector<SDValue, 16> &OutStoreChains) {
6324   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6325   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6326   SmallVector<SDValue, 16> GluedLoadChains;
6327   for (unsigned i = From; i < To; ++i) {
6328     OutChains.push_back(OutLoadChains[i]);
6329     GluedLoadChains.push_back(OutLoadChains[i]);
6330   }
6331 
6332   // Chain for all loads.
6333   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6334                                   GluedLoadChains);
6335 
6336   for (unsigned i = From; i < To; ++i) {
6337     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6338     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6339                                   ST->getBasePtr(), ST->getMemoryVT(),
6340                                   ST->getMemOperand());
6341     OutChains.push_back(NewStore);
6342   }
6343 }
6344 
6345 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6346                                        SDValue Chain, SDValue Dst, SDValue Src,
6347                                        uint64_t Size, Align Alignment,
6348                                        bool isVol, bool AlwaysInline,
6349                                        MachinePointerInfo DstPtrInfo,
6350                                        MachinePointerInfo SrcPtrInfo,
6351                                        const AAMDNodes &AAInfo) {
6352   // Turn a memcpy of undef to nop.
6353   // FIXME: We need to honor volatile even is Src is undef.
6354   if (Src.isUndef())
6355     return Chain;
6356 
6357   // Expand memcpy to a series of load and store ops if the size operand falls
6358   // below a certain threshold.
6359   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6360   // rather than maybe a humongous number of loads and stores.
6361   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6362   const DataLayout &DL = DAG.getDataLayout();
6363   LLVMContext &C = *DAG.getContext();
6364   std::vector<EVT> MemOps;
6365   bool DstAlignCanChange = false;
6366   MachineFunction &MF = DAG.getMachineFunction();
6367   MachineFrameInfo &MFI = MF.getFrameInfo();
6368   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6369   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6370   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6371     DstAlignCanChange = true;
6372   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6373   if (!SrcAlign || Alignment > *SrcAlign)
6374     SrcAlign = Alignment;
6375   assert(SrcAlign && "SrcAlign must be set");
6376   ConstantDataArraySlice Slice;
6377   // If marked as volatile, perform a copy even when marked as constant.
6378   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6379   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6380   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6381   const MemOp Op = isZeroConstant
6382                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6383                                     /*IsZeroMemset*/ true, isVol)
6384                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6385                                      *SrcAlign, isVol, CopyFromConstant);
6386   if (!TLI.findOptimalMemOpLowering(
6387           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6388           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6389     return SDValue();
6390 
6391   if (DstAlignCanChange) {
6392     Type *Ty = MemOps[0].getTypeForEVT(C);
6393     Align NewAlign = DL.getABITypeAlign(Ty);
6394 
6395     // Don't promote to an alignment that would require dynamic stack
6396     // realignment.
6397     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6398     if (!TRI->hasStackRealignment(MF))
6399       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6400         NewAlign = NewAlign / 2;
6401 
6402     if (NewAlign > Alignment) {
6403       // Give the stack frame object a larger alignment if needed.
6404       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6405         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6406       Alignment = NewAlign;
6407     }
6408   }
6409 
6410   // Prepare AAInfo for loads/stores after lowering this memcpy.
6411   AAMDNodes NewAAInfo = AAInfo;
6412   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6413 
6414   MachineMemOperand::Flags MMOFlags =
6415       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6416   SmallVector<SDValue, 16> OutLoadChains;
6417   SmallVector<SDValue, 16> OutStoreChains;
6418   SmallVector<SDValue, 32> OutChains;
6419   unsigned NumMemOps = MemOps.size();
6420   uint64_t SrcOff = 0, DstOff = 0;
6421   for (unsigned i = 0; i != NumMemOps; ++i) {
6422     EVT VT = MemOps[i];
6423     unsigned VTSize = VT.getSizeInBits() / 8;
6424     SDValue Value, Store;
6425 
6426     if (VTSize > Size) {
6427       // Issuing an unaligned load / store pair  that overlaps with the previous
6428       // pair. Adjust the offset accordingly.
6429       assert(i == NumMemOps-1 && i != 0);
6430       SrcOff -= VTSize - Size;
6431       DstOff -= VTSize - Size;
6432     }
6433 
6434     if (CopyFromConstant &&
6435         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6436       // It's unlikely a store of a vector immediate can be done in a single
6437       // instruction. It would require a load from a constantpool first.
6438       // We only handle zero vectors here.
6439       // FIXME: Handle other cases where store of vector immediate is done in
6440       // a single instruction.
6441       ConstantDataArraySlice SubSlice;
6442       if (SrcOff < Slice.Length) {
6443         SubSlice = Slice;
6444         SubSlice.move(SrcOff);
6445       } else {
6446         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6447         SubSlice.Array = nullptr;
6448         SubSlice.Offset = 0;
6449         SubSlice.Length = VTSize;
6450       }
6451       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6452       if (Value.getNode()) {
6453         Store = DAG.getStore(
6454             Chain, dl, Value,
6455             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6456             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6457         OutChains.push_back(Store);
6458       }
6459     }
6460 
6461     if (!Store.getNode()) {
6462       // The type might not be legal for the target.  This should only happen
6463       // if the type is smaller than a legal type, as on PPC, so the right
6464       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6465       // to Load/Store if NVT==VT.
6466       // FIXME does the case above also need this?
6467       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6468       assert(NVT.bitsGE(VT));
6469 
6470       bool isDereferenceable =
6471         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6472       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6473       if (isDereferenceable)
6474         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6475 
6476       Value = DAG.getExtLoad(
6477           ISD::EXTLOAD, dl, NVT, Chain,
6478           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6479           SrcPtrInfo.getWithOffset(SrcOff), VT,
6480           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6481       OutLoadChains.push_back(Value.getValue(1));
6482 
6483       Store = DAG.getTruncStore(
6484           Chain, dl, Value,
6485           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6486           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6487       OutStoreChains.push_back(Store);
6488     }
6489     SrcOff += VTSize;
6490     DstOff += VTSize;
6491     Size -= VTSize;
6492   }
6493 
6494   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6495                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6496   unsigned NumLdStInMemcpy = OutStoreChains.size();
6497 
6498   if (NumLdStInMemcpy) {
6499     // It may be that memcpy might be converted to memset if it's memcpy
6500     // of constants. In such a case, we won't have loads and stores, but
6501     // just stores. In the absence of loads, there is nothing to gang up.
6502     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6503       // If target does not care, just leave as it.
6504       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6505         OutChains.push_back(OutLoadChains[i]);
6506         OutChains.push_back(OutStoreChains[i]);
6507       }
6508     } else {
6509       // Ld/St less than/equal limit set by target.
6510       if (NumLdStInMemcpy <= GluedLdStLimit) {
6511           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6512                                         NumLdStInMemcpy, OutLoadChains,
6513                                         OutStoreChains);
6514       } else {
6515         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6516         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6517         unsigned GlueIter = 0;
6518 
6519         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6520           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6521           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6522 
6523           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6524                                        OutLoadChains, OutStoreChains);
6525           GlueIter += GluedLdStLimit;
6526         }
6527 
6528         // Residual ld/st.
6529         if (RemainingLdStInMemcpy) {
6530           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6531                                         RemainingLdStInMemcpy, OutLoadChains,
6532                                         OutStoreChains);
6533         }
6534       }
6535     }
6536   }
6537   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6538 }
6539 
6540 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6541                                         SDValue Chain, SDValue Dst, SDValue Src,
6542                                         uint64_t Size, Align Alignment,
6543                                         bool isVol, bool AlwaysInline,
6544                                         MachinePointerInfo DstPtrInfo,
6545                                         MachinePointerInfo SrcPtrInfo,
6546                                         const AAMDNodes &AAInfo) {
6547   // Turn a memmove of undef to nop.
6548   // FIXME: We need to honor volatile even is Src is undef.
6549   if (Src.isUndef())
6550     return Chain;
6551 
6552   // Expand memmove to a series of load and store ops if the size operand falls
6553   // below a certain threshold.
6554   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6555   const DataLayout &DL = DAG.getDataLayout();
6556   LLVMContext &C = *DAG.getContext();
6557   std::vector<EVT> MemOps;
6558   bool DstAlignCanChange = false;
6559   MachineFunction &MF = DAG.getMachineFunction();
6560   MachineFrameInfo &MFI = MF.getFrameInfo();
6561   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6562   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6563   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6564     DstAlignCanChange = true;
6565   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6566   if (!SrcAlign || Alignment > *SrcAlign)
6567     SrcAlign = Alignment;
6568   assert(SrcAlign && "SrcAlign must be set");
6569   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6570   if (!TLI.findOptimalMemOpLowering(
6571           MemOps, Limit,
6572           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6573                       /*IsVolatile*/ true),
6574           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6575           MF.getFunction().getAttributes()))
6576     return SDValue();
6577 
6578   if (DstAlignCanChange) {
6579     Type *Ty = MemOps[0].getTypeForEVT(C);
6580     Align NewAlign = DL.getABITypeAlign(Ty);
6581     if (NewAlign > Alignment) {
6582       // Give the stack frame object a larger alignment if needed.
6583       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6584         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6585       Alignment = NewAlign;
6586     }
6587   }
6588 
6589   // Prepare AAInfo for loads/stores after lowering this memmove.
6590   AAMDNodes NewAAInfo = AAInfo;
6591   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6592 
6593   MachineMemOperand::Flags MMOFlags =
6594       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6595   uint64_t SrcOff = 0, DstOff = 0;
6596   SmallVector<SDValue, 8> LoadValues;
6597   SmallVector<SDValue, 8> LoadChains;
6598   SmallVector<SDValue, 8> OutChains;
6599   unsigned NumMemOps = MemOps.size();
6600   for (unsigned i = 0; i < NumMemOps; i++) {
6601     EVT VT = MemOps[i];
6602     unsigned VTSize = VT.getSizeInBits() / 8;
6603     SDValue Value;
6604 
6605     bool isDereferenceable =
6606       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6607     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6608     if (isDereferenceable)
6609       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6610 
6611     Value = DAG.getLoad(
6612         VT, dl, Chain,
6613         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6614         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6615     LoadValues.push_back(Value);
6616     LoadChains.push_back(Value.getValue(1));
6617     SrcOff += VTSize;
6618   }
6619   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6620   OutChains.clear();
6621   for (unsigned i = 0; i < NumMemOps; i++) {
6622     EVT VT = MemOps[i];
6623     unsigned VTSize = VT.getSizeInBits() / 8;
6624     SDValue Store;
6625 
6626     Store = DAG.getStore(
6627         Chain, dl, LoadValues[i],
6628         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6629         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6630     OutChains.push_back(Store);
6631     DstOff += VTSize;
6632   }
6633 
6634   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6635 }
6636 
6637 /// Lower the call to 'memset' intrinsic function into a series of store
6638 /// operations.
6639 ///
6640 /// \param DAG Selection DAG where lowered code is placed.
6641 /// \param dl Link to corresponding IR location.
6642 /// \param Chain Control flow dependency.
6643 /// \param Dst Pointer to destination memory location.
6644 /// \param Src Value of byte to write into the memory.
6645 /// \param Size Number of bytes to write.
6646 /// \param Alignment Alignment of the destination in bytes.
6647 /// \param isVol True if destination is volatile.
6648 /// \param DstPtrInfo IR information on the memory pointer.
6649 /// \returns New head in the control flow, if lowering was successful, empty
6650 /// SDValue otherwise.
6651 ///
6652 /// The function tries to replace 'llvm.memset' intrinsic with several store
6653 /// operations and value calculation code. This is usually profitable for small
6654 /// memory size.
6655 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6656                                SDValue Chain, SDValue Dst, SDValue Src,
6657                                uint64_t Size, Align Alignment, bool isVol,
6658                                MachinePointerInfo DstPtrInfo,
6659                                const AAMDNodes &AAInfo) {
6660   // Turn a memset of undef to nop.
6661   // FIXME: We need to honor volatile even is Src is undef.
6662   if (Src.isUndef())
6663     return Chain;
6664 
6665   // Expand memset to a series of load/store ops if the size operand
6666   // falls below a certain threshold.
6667   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6668   std::vector<EVT> MemOps;
6669   bool DstAlignCanChange = false;
6670   MachineFunction &MF = DAG.getMachineFunction();
6671   MachineFrameInfo &MFI = MF.getFrameInfo();
6672   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6673   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6674   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6675     DstAlignCanChange = true;
6676   bool IsZeroVal =
6677     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6678   if (!TLI.findOptimalMemOpLowering(
6679           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6680           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6681           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6682     return SDValue();
6683 
6684   if (DstAlignCanChange) {
6685     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6686     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6687     if (NewAlign > Alignment) {
6688       // Give the stack frame object a larger alignment if needed.
6689       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6690         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6691       Alignment = NewAlign;
6692     }
6693   }
6694 
6695   SmallVector<SDValue, 8> OutChains;
6696   uint64_t DstOff = 0;
6697   unsigned NumMemOps = MemOps.size();
6698 
6699   // Find the largest store and generate the bit pattern for it.
6700   EVT LargestVT = MemOps[0];
6701   for (unsigned i = 1; i < NumMemOps; i++)
6702     if (MemOps[i].bitsGT(LargestVT))
6703       LargestVT = MemOps[i];
6704   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6705 
6706   // Prepare AAInfo for loads/stores after lowering this memset.
6707   AAMDNodes NewAAInfo = AAInfo;
6708   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6709 
6710   for (unsigned i = 0; i < NumMemOps; i++) {
6711     EVT VT = MemOps[i];
6712     unsigned VTSize = VT.getSizeInBits() / 8;
6713     if (VTSize > Size) {
6714       // Issuing an unaligned load / store pair  that overlaps with the previous
6715       // pair. Adjust the offset accordingly.
6716       assert(i == NumMemOps-1 && i != 0);
6717       DstOff -= VTSize - Size;
6718     }
6719 
6720     // If this store is smaller than the largest store see whether we can get
6721     // the smaller value for free with a truncate.
6722     SDValue Value = MemSetValue;
6723     if (VT.bitsLT(LargestVT)) {
6724       if (!LargestVT.isVector() && !VT.isVector() &&
6725           TLI.isTruncateFree(LargestVT, VT))
6726         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6727       else
6728         Value = getMemsetValue(Src, VT, DAG, dl);
6729     }
6730     assert(Value.getValueType() == VT && "Value with wrong type.");
6731     SDValue Store = DAG.getStore(
6732         Chain, dl, Value,
6733         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6734         DstPtrInfo.getWithOffset(DstOff), Alignment,
6735         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6736         NewAAInfo);
6737     OutChains.push_back(Store);
6738     DstOff += VT.getSizeInBits() / 8;
6739     Size -= VTSize;
6740   }
6741 
6742   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6743 }
6744 
6745 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6746                                             unsigned AS) {
6747   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6748   // pointer operands can be losslessly bitcasted to pointers of address space 0
6749   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6750     report_fatal_error("cannot lower memory intrinsic in address space " +
6751                        Twine(AS));
6752   }
6753 }
6754 
6755 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6756                                 SDValue Src, SDValue Size, Align Alignment,
6757                                 bool isVol, bool AlwaysInline, bool isTailCall,
6758                                 MachinePointerInfo DstPtrInfo,
6759                                 MachinePointerInfo SrcPtrInfo,
6760                                 const AAMDNodes &AAInfo) {
6761   // Check to see if we should lower the memcpy to loads and stores first.
6762   // For cases within the target-specified limits, this is the best choice.
6763   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6764   if (ConstantSize) {
6765     // Memcpy with size zero? Just return the original chain.
6766     if (ConstantSize->isNullValue())
6767       return Chain;
6768 
6769     SDValue Result = getMemcpyLoadsAndStores(
6770         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6771         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6772     if (Result.getNode())
6773       return Result;
6774   }
6775 
6776   // Then check to see if we should lower the memcpy with target-specific
6777   // code. If the target chooses to do this, this is the next best.
6778   if (TSI) {
6779     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6780         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6781         DstPtrInfo, SrcPtrInfo);
6782     if (Result.getNode())
6783       return Result;
6784   }
6785 
6786   // If we really need inline code and the target declined to provide it,
6787   // use a (potentially long) sequence of loads and stores.
6788   if (AlwaysInline) {
6789     assert(ConstantSize && "AlwaysInline requires a constant size!");
6790     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6791                                    ConstantSize->getZExtValue(), Alignment,
6792                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6793   }
6794 
6795   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6796   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6797 
6798   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6799   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6800   // respect volatile, so they may do things like read or write memory
6801   // beyond the given memory regions. But fixing this isn't easy, and most
6802   // people don't care.
6803 
6804   // Emit a library call.
6805   TargetLowering::ArgListTy Args;
6806   TargetLowering::ArgListEntry Entry;
6807   Entry.Ty = Type::getInt8PtrTy(*getContext());
6808   Entry.Node = Dst; Args.push_back(Entry);
6809   Entry.Node = Src; Args.push_back(Entry);
6810 
6811   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6812   Entry.Node = Size; Args.push_back(Entry);
6813   // FIXME: pass in SDLoc
6814   TargetLowering::CallLoweringInfo CLI(*this);
6815   CLI.setDebugLoc(dl)
6816       .setChain(Chain)
6817       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6818                     Dst.getValueType().getTypeForEVT(*getContext()),
6819                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6820                                       TLI->getPointerTy(getDataLayout())),
6821                     std::move(Args))
6822       .setDiscardResult()
6823       .setTailCall(isTailCall);
6824 
6825   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6826   return CallResult.second;
6827 }
6828 
6829 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6830                                       SDValue Dst, unsigned DstAlign,
6831                                       SDValue Src, unsigned SrcAlign,
6832                                       SDValue Size, Type *SizeTy,
6833                                       unsigned ElemSz, bool isTailCall,
6834                                       MachinePointerInfo DstPtrInfo,
6835                                       MachinePointerInfo SrcPtrInfo) {
6836   // Emit a library call.
6837   TargetLowering::ArgListTy Args;
6838   TargetLowering::ArgListEntry Entry;
6839   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6840   Entry.Node = Dst;
6841   Args.push_back(Entry);
6842 
6843   Entry.Node = Src;
6844   Args.push_back(Entry);
6845 
6846   Entry.Ty = SizeTy;
6847   Entry.Node = Size;
6848   Args.push_back(Entry);
6849 
6850   RTLIB::Libcall LibraryCall =
6851       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6852   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6853     report_fatal_error("Unsupported element size");
6854 
6855   TargetLowering::CallLoweringInfo CLI(*this);
6856   CLI.setDebugLoc(dl)
6857       .setChain(Chain)
6858       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6859                     Type::getVoidTy(*getContext()),
6860                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6861                                       TLI->getPointerTy(getDataLayout())),
6862                     std::move(Args))
6863       .setDiscardResult()
6864       .setTailCall(isTailCall);
6865 
6866   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6867   return CallResult.second;
6868 }
6869 
6870 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6871                                  SDValue Src, SDValue Size, Align Alignment,
6872                                  bool isVol, bool isTailCall,
6873                                  MachinePointerInfo DstPtrInfo,
6874                                  MachinePointerInfo SrcPtrInfo,
6875                                  const AAMDNodes &AAInfo) {
6876   // Check to see if we should lower the memmove to loads and stores first.
6877   // For cases within the target-specified limits, this is the best choice.
6878   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6879   if (ConstantSize) {
6880     // Memmove with size zero? Just return the original chain.
6881     if (ConstantSize->isNullValue())
6882       return Chain;
6883 
6884     SDValue Result = getMemmoveLoadsAndStores(
6885         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6886         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6887     if (Result.getNode())
6888       return Result;
6889   }
6890 
6891   // Then check to see if we should lower the memmove with target-specific
6892   // code. If the target chooses to do this, this is the next best.
6893   if (TSI) {
6894     SDValue Result =
6895         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6896                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6897     if (Result.getNode())
6898       return Result;
6899   }
6900 
6901   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6902   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6903 
6904   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6905   // not be safe.  See memcpy above for more details.
6906 
6907   // Emit a library call.
6908   TargetLowering::ArgListTy Args;
6909   TargetLowering::ArgListEntry Entry;
6910   Entry.Ty = Type::getInt8PtrTy(*getContext());
6911   Entry.Node = Dst; Args.push_back(Entry);
6912   Entry.Node = Src; Args.push_back(Entry);
6913 
6914   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6915   Entry.Node = Size; Args.push_back(Entry);
6916   // FIXME:  pass in SDLoc
6917   TargetLowering::CallLoweringInfo CLI(*this);
6918   CLI.setDebugLoc(dl)
6919       .setChain(Chain)
6920       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6921                     Dst.getValueType().getTypeForEVT(*getContext()),
6922                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6923                                       TLI->getPointerTy(getDataLayout())),
6924                     std::move(Args))
6925       .setDiscardResult()
6926       .setTailCall(isTailCall);
6927 
6928   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6929   return CallResult.second;
6930 }
6931 
6932 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6933                                        SDValue Dst, unsigned DstAlign,
6934                                        SDValue Src, unsigned SrcAlign,
6935                                        SDValue Size, Type *SizeTy,
6936                                        unsigned ElemSz, bool isTailCall,
6937                                        MachinePointerInfo DstPtrInfo,
6938                                        MachinePointerInfo SrcPtrInfo) {
6939   // Emit a library call.
6940   TargetLowering::ArgListTy Args;
6941   TargetLowering::ArgListEntry Entry;
6942   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6943   Entry.Node = Dst;
6944   Args.push_back(Entry);
6945 
6946   Entry.Node = Src;
6947   Args.push_back(Entry);
6948 
6949   Entry.Ty = SizeTy;
6950   Entry.Node = Size;
6951   Args.push_back(Entry);
6952 
6953   RTLIB::Libcall LibraryCall =
6954       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6955   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6956     report_fatal_error("Unsupported element size");
6957 
6958   TargetLowering::CallLoweringInfo CLI(*this);
6959   CLI.setDebugLoc(dl)
6960       .setChain(Chain)
6961       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6962                     Type::getVoidTy(*getContext()),
6963                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6964                                       TLI->getPointerTy(getDataLayout())),
6965                     std::move(Args))
6966       .setDiscardResult()
6967       .setTailCall(isTailCall);
6968 
6969   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6970   return CallResult.second;
6971 }
6972 
6973 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6974                                 SDValue Src, SDValue Size, Align Alignment,
6975                                 bool isVol, bool isTailCall,
6976                                 MachinePointerInfo DstPtrInfo,
6977                                 const AAMDNodes &AAInfo) {
6978   // Check to see if we should lower the memset to stores first.
6979   // For cases within the target-specified limits, this is the best choice.
6980   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6981   if (ConstantSize) {
6982     // Memset with size zero? Just return the original chain.
6983     if (ConstantSize->isNullValue())
6984       return Chain;
6985 
6986     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
6987                                      ConstantSize->getZExtValue(), Alignment,
6988                                      isVol, DstPtrInfo, AAInfo);
6989 
6990     if (Result.getNode())
6991       return Result;
6992   }
6993 
6994   // Then check to see if we should lower the memset with target-specific
6995   // code. If the target chooses to do this, this is the next best.
6996   if (TSI) {
6997     SDValue Result = TSI->EmitTargetCodeForMemset(
6998         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
6999     if (Result.getNode())
7000       return Result;
7001   }
7002 
7003   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7004 
7005   // Emit a library call.
7006   TargetLowering::ArgListTy Args;
7007   TargetLowering::ArgListEntry Entry;
7008   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7009   Args.push_back(Entry);
7010   Entry.Node = Src;
7011   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7012   Args.push_back(Entry);
7013   Entry.Node = Size;
7014   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7015   Args.push_back(Entry);
7016 
7017   // FIXME: pass in SDLoc
7018   TargetLowering::CallLoweringInfo CLI(*this);
7019   CLI.setDebugLoc(dl)
7020       .setChain(Chain)
7021       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7022                     Dst.getValueType().getTypeForEVT(*getContext()),
7023                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7024                                       TLI->getPointerTy(getDataLayout())),
7025                     std::move(Args))
7026       .setDiscardResult()
7027       .setTailCall(isTailCall);
7028 
7029   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7030   return CallResult.second;
7031 }
7032 
7033 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7034                                       SDValue Dst, unsigned DstAlign,
7035                                       SDValue Value, SDValue Size, Type *SizeTy,
7036                                       unsigned ElemSz, bool isTailCall,
7037                                       MachinePointerInfo DstPtrInfo) {
7038   // Emit a library call.
7039   TargetLowering::ArgListTy Args;
7040   TargetLowering::ArgListEntry Entry;
7041   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7042   Entry.Node = Dst;
7043   Args.push_back(Entry);
7044 
7045   Entry.Ty = Type::getInt8Ty(*getContext());
7046   Entry.Node = Value;
7047   Args.push_back(Entry);
7048 
7049   Entry.Ty = SizeTy;
7050   Entry.Node = Size;
7051   Args.push_back(Entry);
7052 
7053   RTLIB::Libcall LibraryCall =
7054       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7055   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7056     report_fatal_error("Unsupported element size");
7057 
7058   TargetLowering::CallLoweringInfo CLI(*this);
7059   CLI.setDebugLoc(dl)
7060       .setChain(Chain)
7061       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7062                     Type::getVoidTy(*getContext()),
7063                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7064                                       TLI->getPointerTy(getDataLayout())),
7065                     std::move(Args))
7066       .setDiscardResult()
7067       .setTailCall(isTailCall);
7068 
7069   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7070   return CallResult.second;
7071 }
7072 
7073 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7074                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7075                                 MachineMemOperand *MMO) {
7076   FoldingSetNodeID ID;
7077   ID.AddInteger(MemVT.getRawBits());
7078   AddNodeIDNode(ID, Opcode, VTList, Ops);
7079   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7080   void* IP = nullptr;
7081   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7082     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7083     return SDValue(E, 0);
7084   }
7085 
7086   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7087                                     VTList, MemVT, MMO);
7088   createOperands(N, Ops);
7089 
7090   CSEMap.InsertNode(N, IP);
7091   InsertNode(N);
7092   return SDValue(N, 0);
7093 }
7094 
7095 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7096                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7097                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7098                                        MachineMemOperand *MMO) {
7099   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7100          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7101   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7102 
7103   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7104   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7105 }
7106 
7107 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7108                                 SDValue Chain, SDValue Ptr, SDValue Val,
7109                                 MachineMemOperand *MMO) {
7110   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7111           Opcode == ISD::ATOMIC_LOAD_SUB ||
7112           Opcode == ISD::ATOMIC_LOAD_AND ||
7113           Opcode == ISD::ATOMIC_LOAD_CLR ||
7114           Opcode == ISD::ATOMIC_LOAD_OR ||
7115           Opcode == ISD::ATOMIC_LOAD_XOR ||
7116           Opcode == ISD::ATOMIC_LOAD_NAND ||
7117           Opcode == ISD::ATOMIC_LOAD_MIN ||
7118           Opcode == ISD::ATOMIC_LOAD_MAX ||
7119           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7120           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7121           Opcode == ISD::ATOMIC_LOAD_FADD ||
7122           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7123           Opcode == ISD::ATOMIC_SWAP ||
7124           Opcode == ISD::ATOMIC_STORE) &&
7125          "Invalid Atomic Op");
7126 
7127   EVT VT = Val.getValueType();
7128 
7129   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7130                                                getVTList(VT, MVT::Other);
7131   SDValue Ops[] = {Chain, Ptr, Val};
7132   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7133 }
7134 
7135 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7136                                 EVT VT, SDValue Chain, SDValue Ptr,
7137                                 MachineMemOperand *MMO) {
7138   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7139 
7140   SDVTList VTs = getVTList(VT, MVT::Other);
7141   SDValue Ops[] = {Chain, Ptr};
7142   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7143 }
7144 
7145 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7146 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7147   if (Ops.size() == 1)
7148     return Ops[0];
7149 
7150   SmallVector<EVT, 4> VTs;
7151   VTs.reserve(Ops.size());
7152   for (const SDValue &Op : Ops)
7153     VTs.push_back(Op.getValueType());
7154   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7155 }
7156 
7157 SDValue SelectionDAG::getMemIntrinsicNode(
7158     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7159     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7160     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7161   if (!Size && MemVT.isScalableVector())
7162     Size = MemoryLocation::UnknownSize;
7163   else if (!Size)
7164     Size = MemVT.getStoreSize();
7165 
7166   MachineFunction &MF = getMachineFunction();
7167   MachineMemOperand *MMO =
7168       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7169 
7170   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7171 }
7172 
7173 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7174                                           SDVTList VTList,
7175                                           ArrayRef<SDValue> Ops, EVT MemVT,
7176                                           MachineMemOperand *MMO) {
7177   assert((Opcode == ISD::INTRINSIC_VOID ||
7178           Opcode == ISD::INTRINSIC_W_CHAIN ||
7179           Opcode == ISD::PREFETCH ||
7180           ((int)Opcode <= std::numeric_limits<int>::max() &&
7181            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7182          "Opcode is not a memory-accessing opcode!");
7183 
7184   // Memoize the node unless it returns a flag.
7185   MemIntrinsicSDNode *N;
7186   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7187     FoldingSetNodeID ID;
7188     AddNodeIDNode(ID, Opcode, VTList, Ops);
7189     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7190         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7191     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7192     void *IP = nullptr;
7193     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7194       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7195       return SDValue(E, 0);
7196     }
7197 
7198     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7199                                       VTList, MemVT, MMO);
7200     createOperands(N, Ops);
7201 
7202   CSEMap.InsertNode(N, IP);
7203   } else {
7204     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7205                                       VTList, MemVT, MMO);
7206     createOperands(N, Ops);
7207   }
7208   InsertNode(N);
7209   SDValue V(N, 0);
7210   NewSDValueDbgMsg(V, "Creating new node: ", this);
7211   return V;
7212 }
7213 
7214 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7215                                       SDValue Chain, int FrameIndex,
7216                                       int64_t Size, int64_t Offset) {
7217   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7218   const auto VTs = getVTList(MVT::Other);
7219   SDValue Ops[2] = {
7220       Chain,
7221       getFrameIndex(FrameIndex,
7222                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7223                     true)};
7224 
7225   FoldingSetNodeID ID;
7226   AddNodeIDNode(ID, Opcode, VTs, Ops);
7227   ID.AddInteger(FrameIndex);
7228   ID.AddInteger(Size);
7229   ID.AddInteger(Offset);
7230   void *IP = nullptr;
7231   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7232     return SDValue(E, 0);
7233 
7234   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7235       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7236   createOperands(N, Ops);
7237   CSEMap.InsertNode(N, IP);
7238   InsertNode(N);
7239   SDValue V(N, 0);
7240   NewSDValueDbgMsg(V, "Creating new node: ", this);
7241   return V;
7242 }
7243 
7244 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7245                                          uint64_t Guid, uint64_t Index,
7246                                          uint32_t Attr) {
7247   const unsigned Opcode = ISD::PSEUDO_PROBE;
7248   const auto VTs = getVTList(MVT::Other);
7249   SDValue Ops[] = {Chain};
7250   FoldingSetNodeID ID;
7251   AddNodeIDNode(ID, Opcode, VTs, Ops);
7252   ID.AddInteger(Guid);
7253   ID.AddInteger(Index);
7254   void *IP = nullptr;
7255   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7256     return SDValue(E, 0);
7257 
7258   auto *N = newSDNode<PseudoProbeSDNode>(
7259       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7260   createOperands(N, Ops);
7261   CSEMap.InsertNode(N, IP);
7262   InsertNode(N);
7263   SDValue V(N, 0);
7264   NewSDValueDbgMsg(V, "Creating new node: ", this);
7265   return V;
7266 }
7267 
7268 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7269 /// MachinePointerInfo record from it.  This is particularly useful because the
7270 /// code generator has many cases where it doesn't bother passing in a
7271 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7272 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7273                                            SelectionDAG &DAG, SDValue Ptr,
7274                                            int64_t Offset = 0) {
7275   // If this is FI+Offset, we can model it.
7276   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7277     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7278                                              FI->getIndex(), Offset);
7279 
7280   // If this is (FI+Offset1)+Offset2, we can model it.
7281   if (Ptr.getOpcode() != ISD::ADD ||
7282       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7283       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7284     return Info;
7285 
7286   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7287   return MachinePointerInfo::getFixedStack(
7288       DAG.getMachineFunction(), FI,
7289       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7290 }
7291 
7292 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7293 /// MachinePointerInfo record from it.  This is particularly useful because the
7294 /// code generator has many cases where it doesn't bother passing in a
7295 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7296 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7297                                            SelectionDAG &DAG, SDValue Ptr,
7298                                            SDValue OffsetOp) {
7299   // If the 'Offset' value isn't a constant, we can't handle this.
7300   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7301     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7302   if (OffsetOp.isUndef())
7303     return InferPointerInfo(Info, DAG, Ptr);
7304   return Info;
7305 }
7306 
7307 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7308                               EVT VT, const SDLoc &dl, SDValue Chain,
7309                               SDValue Ptr, SDValue Offset,
7310                               MachinePointerInfo PtrInfo, EVT MemVT,
7311                               Align Alignment,
7312                               MachineMemOperand::Flags MMOFlags,
7313                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7314   assert(Chain.getValueType() == MVT::Other &&
7315         "Invalid chain type");
7316 
7317   MMOFlags |= MachineMemOperand::MOLoad;
7318   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7319   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7320   // clients.
7321   if (PtrInfo.V.isNull())
7322     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7323 
7324   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7325   MachineFunction &MF = getMachineFunction();
7326   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7327                                                    Alignment, AAInfo, Ranges);
7328   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7329 }
7330 
7331 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7332                               EVT VT, const SDLoc &dl, SDValue Chain,
7333                               SDValue Ptr, SDValue Offset, EVT MemVT,
7334                               MachineMemOperand *MMO) {
7335   if (VT == MemVT) {
7336     ExtType = ISD::NON_EXTLOAD;
7337   } else if (ExtType == ISD::NON_EXTLOAD) {
7338     assert(VT == MemVT && "Non-extending load from different memory type!");
7339   } else {
7340     // Extending load.
7341     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7342            "Should only be an extending load, not truncating!");
7343     assert(VT.isInteger() == MemVT.isInteger() &&
7344            "Cannot convert from FP to Int or Int -> FP!");
7345     assert(VT.isVector() == MemVT.isVector() &&
7346            "Cannot use an ext load to convert to or from a vector!");
7347     assert((!VT.isVector() ||
7348             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7349            "Cannot use an ext load to change the number of vector elements!");
7350   }
7351 
7352   bool Indexed = AM != ISD::UNINDEXED;
7353   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7354 
7355   SDVTList VTs = Indexed ?
7356     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7357   SDValue Ops[] = { Chain, Ptr, Offset };
7358   FoldingSetNodeID ID;
7359   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7360   ID.AddInteger(MemVT.getRawBits());
7361   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7362       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7363   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7364   void *IP = nullptr;
7365   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7366     cast<LoadSDNode>(E)->refineAlignment(MMO);
7367     return SDValue(E, 0);
7368   }
7369   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7370                                   ExtType, MemVT, MMO);
7371   createOperands(N, Ops);
7372 
7373   CSEMap.InsertNode(N, IP);
7374   InsertNode(N);
7375   SDValue V(N, 0);
7376   NewSDValueDbgMsg(V, "Creating new node: ", this);
7377   return V;
7378 }
7379 
7380 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7381                               SDValue Ptr, MachinePointerInfo PtrInfo,
7382                               MaybeAlign Alignment,
7383                               MachineMemOperand::Flags MMOFlags,
7384                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7385   SDValue Undef = getUNDEF(Ptr.getValueType());
7386   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7387                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7388 }
7389 
7390 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7391                               SDValue Ptr, MachineMemOperand *MMO) {
7392   SDValue Undef = getUNDEF(Ptr.getValueType());
7393   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7394                  VT, MMO);
7395 }
7396 
7397 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7398                                  EVT VT, SDValue Chain, SDValue Ptr,
7399                                  MachinePointerInfo PtrInfo, EVT MemVT,
7400                                  MaybeAlign Alignment,
7401                                  MachineMemOperand::Flags MMOFlags,
7402                                  const AAMDNodes &AAInfo) {
7403   SDValue Undef = getUNDEF(Ptr.getValueType());
7404   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7405                  MemVT, Alignment, MMOFlags, AAInfo);
7406 }
7407 
7408 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7409                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7410                                  MachineMemOperand *MMO) {
7411   SDValue Undef = getUNDEF(Ptr.getValueType());
7412   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7413                  MemVT, MMO);
7414 }
7415 
7416 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7417                                      SDValue Base, SDValue Offset,
7418                                      ISD::MemIndexedMode AM) {
7419   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7420   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7421   // Don't propagate the invariant or dereferenceable flags.
7422   auto MMOFlags =
7423       LD->getMemOperand()->getFlags() &
7424       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7425   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7426                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7427                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7428 }
7429 
7430 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7431                                SDValue Ptr, MachinePointerInfo PtrInfo,
7432                                Align Alignment,
7433                                MachineMemOperand::Flags MMOFlags,
7434                                const AAMDNodes &AAInfo) {
7435   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7436 
7437   MMOFlags |= MachineMemOperand::MOStore;
7438   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7439 
7440   if (PtrInfo.V.isNull())
7441     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7442 
7443   MachineFunction &MF = getMachineFunction();
7444   uint64_t Size =
7445       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7446   MachineMemOperand *MMO =
7447       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7448   return getStore(Chain, dl, Val, Ptr, MMO);
7449 }
7450 
7451 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7452                                SDValue Ptr, MachineMemOperand *MMO) {
7453   assert(Chain.getValueType() == MVT::Other &&
7454         "Invalid chain type");
7455   EVT VT = Val.getValueType();
7456   SDVTList VTs = getVTList(MVT::Other);
7457   SDValue Undef = getUNDEF(Ptr.getValueType());
7458   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7459   FoldingSetNodeID ID;
7460   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7461   ID.AddInteger(VT.getRawBits());
7462   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7463       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7464   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7465   void *IP = nullptr;
7466   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7467     cast<StoreSDNode>(E)->refineAlignment(MMO);
7468     return SDValue(E, 0);
7469   }
7470   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7471                                    ISD::UNINDEXED, false, VT, MMO);
7472   createOperands(N, Ops);
7473 
7474   CSEMap.InsertNode(N, IP);
7475   InsertNode(N);
7476   SDValue V(N, 0);
7477   NewSDValueDbgMsg(V, "Creating new node: ", this);
7478   return V;
7479 }
7480 
7481 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7482                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7483                                     EVT SVT, Align Alignment,
7484                                     MachineMemOperand::Flags MMOFlags,
7485                                     const AAMDNodes &AAInfo) {
7486   assert(Chain.getValueType() == MVT::Other &&
7487         "Invalid chain type");
7488 
7489   MMOFlags |= MachineMemOperand::MOStore;
7490   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7491 
7492   if (PtrInfo.V.isNull())
7493     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7494 
7495   MachineFunction &MF = getMachineFunction();
7496   MachineMemOperand *MMO = MF.getMachineMemOperand(
7497       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7498       Alignment, AAInfo);
7499   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7500 }
7501 
7502 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7503                                     SDValue Ptr, EVT SVT,
7504                                     MachineMemOperand *MMO) {
7505   EVT VT = Val.getValueType();
7506 
7507   assert(Chain.getValueType() == MVT::Other &&
7508         "Invalid chain type");
7509   if (VT == SVT)
7510     return getStore(Chain, dl, Val, Ptr, MMO);
7511 
7512   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7513          "Should only be a truncating store, not extending!");
7514   assert(VT.isInteger() == SVT.isInteger() &&
7515          "Can't do FP-INT conversion!");
7516   assert(VT.isVector() == SVT.isVector() &&
7517          "Cannot use trunc store to convert to or from a vector!");
7518   assert((!VT.isVector() ||
7519           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7520          "Cannot use trunc store to change the number of vector elements!");
7521 
7522   SDVTList VTs = getVTList(MVT::Other);
7523   SDValue Undef = getUNDEF(Ptr.getValueType());
7524   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7525   FoldingSetNodeID ID;
7526   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7527   ID.AddInteger(SVT.getRawBits());
7528   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7529       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7530   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7531   void *IP = nullptr;
7532   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7533     cast<StoreSDNode>(E)->refineAlignment(MMO);
7534     return SDValue(E, 0);
7535   }
7536   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7537                                    ISD::UNINDEXED, true, SVT, MMO);
7538   createOperands(N, Ops);
7539 
7540   CSEMap.InsertNode(N, IP);
7541   InsertNode(N);
7542   SDValue V(N, 0);
7543   NewSDValueDbgMsg(V, "Creating new node: ", this);
7544   return V;
7545 }
7546 
7547 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7548                                       SDValue Base, SDValue Offset,
7549                                       ISD::MemIndexedMode AM) {
7550   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7551   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7552   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7553   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7554   FoldingSetNodeID ID;
7555   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7556   ID.AddInteger(ST->getMemoryVT().getRawBits());
7557   ID.AddInteger(ST->getRawSubclassData());
7558   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7559   void *IP = nullptr;
7560   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7561     return SDValue(E, 0);
7562 
7563   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7564                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7565                                    ST->getMemOperand());
7566   createOperands(N, Ops);
7567 
7568   CSEMap.InsertNode(N, IP);
7569   InsertNode(N);
7570   SDValue V(N, 0);
7571   NewSDValueDbgMsg(V, "Creating new node: ", this);
7572   return V;
7573 }
7574 
7575 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7576                                     SDValue Base, SDValue Offset, SDValue Mask,
7577                                     SDValue PassThru, EVT MemVT,
7578                                     MachineMemOperand *MMO,
7579                                     ISD::MemIndexedMode AM,
7580                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7581   bool Indexed = AM != ISD::UNINDEXED;
7582   assert((Indexed || Offset.isUndef()) &&
7583          "Unindexed masked load with an offset!");
7584   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
7585                          : getVTList(VT, MVT::Other);
7586   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
7587   FoldingSetNodeID ID;
7588   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
7589   ID.AddInteger(MemVT.getRawBits());
7590   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
7591       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
7592   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7593   void *IP = nullptr;
7594   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7595     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
7596     return SDValue(E, 0);
7597   }
7598   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7599                                         AM, ExtTy, isExpanding, MemVT, MMO);
7600   createOperands(N, Ops);
7601 
7602   CSEMap.InsertNode(N, IP);
7603   InsertNode(N);
7604   SDValue V(N, 0);
7605   NewSDValueDbgMsg(V, "Creating new node: ", this);
7606   return V;
7607 }
7608 
7609 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
7610                                            SDValue Base, SDValue Offset,
7611                                            ISD::MemIndexedMode AM) {
7612   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
7613   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
7614   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
7615                        Offset, LD->getMask(), LD->getPassThru(),
7616                        LD->getMemoryVT(), LD->getMemOperand(), AM,
7617                        LD->getExtensionType(), LD->isExpandingLoad());
7618 }
7619 
7620 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
7621                                      SDValue Val, SDValue Base, SDValue Offset,
7622                                      SDValue Mask, EVT MemVT,
7623                                      MachineMemOperand *MMO,
7624                                      ISD::MemIndexedMode AM, bool IsTruncating,
7625                                      bool IsCompressing) {
7626   assert(Chain.getValueType() == MVT::Other &&
7627         "Invalid chain type");
7628   bool Indexed = AM != ISD::UNINDEXED;
7629   assert((Indexed || Offset.isUndef()) &&
7630          "Unindexed masked store with an offset!");
7631   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
7632                          : getVTList(MVT::Other);
7633   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
7634   FoldingSetNodeID ID;
7635   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
7636   ID.AddInteger(MemVT.getRawBits());
7637   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
7638       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7639   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7640   void *IP = nullptr;
7641   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7642     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
7643     return SDValue(E, 0);
7644   }
7645   auto *N =
7646       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7647                                    IsTruncating, IsCompressing, MemVT, MMO);
7648   createOperands(N, Ops);
7649 
7650   CSEMap.InsertNode(N, IP);
7651   InsertNode(N);
7652   SDValue V(N, 0);
7653   NewSDValueDbgMsg(V, "Creating new node: ", this);
7654   return V;
7655 }
7656 
7657 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
7658                                             SDValue Base, SDValue Offset,
7659                                             ISD::MemIndexedMode AM) {
7660   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
7661   assert(ST->getOffset().isUndef() &&
7662          "Masked store is already a indexed store!");
7663   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
7664                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
7665                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
7666 }
7667 
7668 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
7669                                       ArrayRef<SDValue> Ops,
7670                                       MachineMemOperand *MMO,
7671                                       ISD::MemIndexType IndexType,
7672                                       ISD::LoadExtType ExtTy) {
7673   assert(Ops.size() == 6 && "Incompatible number of operands");
7674 
7675   FoldingSetNodeID ID;
7676   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7677   ID.AddInteger(MemVT.getRawBits());
7678   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7679       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
7680   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7681   void *IP = nullptr;
7682   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7683     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7684     return SDValue(E, 0);
7685   }
7686 
7687   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
7688   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7689                                           VTs, MemVT, MMO, IndexType, ExtTy);
7690   createOperands(N, Ops);
7691 
7692   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7693          "Incompatible type of the PassThru value in MaskedGatherSDNode");
7694   assert(N->getMask().getValueType().getVectorElementCount() ==
7695              N->getValueType(0).getVectorElementCount() &&
7696          "Vector width mismatch between mask and data");
7697   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7698              N->getValueType(0).getVectorElementCount().isScalable() &&
7699          "Scalable flags of index and data do not match");
7700   assert(ElementCount::isKnownGE(
7701              N->getIndex().getValueType().getVectorElementCount(),
7702              N->getValueType(0).getVectorElementCount()) &&
7703          "Vector width mismatch between index and data");
7704   assert(isa<ConstantSDNode>(N->getScale()) &&
7705          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7706          "Scale should be a constant power of 2");
7707 
7708   CSEMap.InsertNode(N, IP);
7709   InsertNode(N);
7710   SDValue V(N, 0);
7711   NewSDValueDbgMsg(V, "Creating new node: ", this);
7712   return V;
7713 }
7714 
7715 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
7716                                        ArrayRef<SDValue> Ops,
7717                                        MachineMemOperand *MMO,
7718                                        ISD::MemIndexType IndexType,
7719                                        bool IsTrunc) {
7720   assert(Ops.size() == 6 && "Incompatible number of operands");
7721 
7722   FoldingSetNodeID ID;
7723   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7724   ID.AddInteger(MemVT.getRawBits());
7725   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7726       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
7727   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7728   void *IP = nullptr;
7729   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7730     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7731     return SDValue(E, 0);
7732   }
7733 
7734   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
7735   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7736                                            VTs, MemVT, MMO, IndexType, IsTrunc);
7737   createOperands(N, Ops);
7738 
7739   assert(N->getMask().getValueType().getVectorElementCount() ==
7740              N->getValue().getValueType().getVectorElementCount() &&
7741          "Vector width mismatch between mask and data");
7742   assert(
7743       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7744           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7745       "Scalable flags of index and data do not match");
7746   assert(ElementCount::isKnownGE(
7747              N->getIndex().getValueType().getVectorElementCount(),
7748              N->getValue().getValueType().getVectorElementCount()) &&
7749          "Vector width mismatch between index and data");
7750   assert(isa<ConstantSDNode>(N->getScale()) &&
7751          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7752          "Scale should be a constant power of 2");
7753 
7754   CSEMap.InsertNode(N, IP);
7755   InsertNode(N);
7756   SDValue V(N, 0);
7757   NewSDValueDbgMsg(V, "Creating new node: ", this);
7758   return V;
7759 }
7760 
7761 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7762   // select undef, T, F --> T (if T is a constant), otherwise F
7763   // select, ?, undef, F --> F
7764   // select, ?, T, undef --> T
7765   if (Cond.isUndef())
7766     return isConstantValueOfAnyType(T) ? T : F;
7767   if (T.isUndef())
7768     return F;
7769   if (F.isUndef())
7770     return T;
7771 
7772   // select true, T, F --> T
7773   // select false, T, F --> F
7774   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7775     return CondC->isNullValue() ? F : T;
7776 
7777   // TODO: This should simplify VSELECT with constant condition using something
7778   // like this (but check boolean contents to be complete?):
7779   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7780   //    return T;
7781   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7782   //    return F;
7783 
7784   // select ?, T, T --> T
7785   if (T == F)
7786     return T;
7787 
7788   return SDValue();
7789 }
7790 
7791 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7792   // shift undef, Y --> 0 (can always assume that the undef value is 0)
7793   if (X.isUndef())
7794     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7795   // shift X, undef --> undef (because it may shift by the bitwidth)
7796   if (Y.isUndef())
7797     return getUNDEF(X.getValueType());
7798 
7799   // shift 0, Y --> 0
7800   // shift X, 0 --> X
7801   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7802     return X;
7803 
7804   // shift X, C >= bitwidth(X) --> undef
7805   // All vector elements must be too big (or undef) to avoid partial undefs.
7806   auto isShiftTooBig = [X](ConstantSDNode *Val) {
7807     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7808   };
7809   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7810     return getUNDEF(X.getValueType());
7811 
7812   return SDValue();
7813 }
7814 
7815 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
7816                                       SDNodeFlags Flags) {
7817   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
7818   // (an undef operand can be chosen to be Nan/Inf), then the result of this
7819   // operation is poison. That result can be relaxed to undef.
7820   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
7821   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7822   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
7823                 (YC && YC->getValueAPF().isNaN());
7824   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
7825                 (YC && YC->getValueAPF().isInfinity());
7826 
7827   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
7828     return getUNDEF(X.getValueType());
7829 
7830   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
7831     return getUNDEF(X.getValueType());
7832 
7833   if (!YC)
7834     return SDValue();
7835 
7836   // X + -0.0 --> X
7837   if (Opcode == ISD::FADD)
7838     if (YC->getValueAPF().isNegZero())
7839       return X;
7840 
7841   // X - +0.0 --> X
7842   if (Opcode == ISD::FSUB)
7843     if (YC->getValueAPF().isPosZero())
7844       return X;
7845 
7846   // X * 1.0 --> X
7847   // X / 1.0 --> X
7848   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7849     if (YC->getValueAPF().isExactlyValue(1.0))
7850       return X;
7851 
7852   // X * 0.0 --> 0.0
7853   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
7854     if (YC->getValueAPF().isZero())
7855       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
7856 
7857   return SDValue();
7858 }
7859 
7860 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7861                                SDValue Ptr, SDValue SV, unsigned Align) {
7862   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7863   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7864 }
7865 
7866 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7867                               ArrayRef<SDUse> Ops) {
7868   switch (Ops.size()) {
7869   case 0: return getNode(Opcode, DL, VT);
7870   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7871   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7872   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7873   default: break;
7874   }
7875 
7876   // Copy from an SDUse array into an SDValue array for use with
7877   // the regular getNode logic.
7878   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7879   return getNode(Opcode, DL, VT, NewOps);
7880 }
7881 
7882 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7883                               ArrayRef<SDValue> Ops) {
7884   SDNodeFlags Flags;
7885   if (Inserter)
7886     Flags = Inserter->getFlags();
7887   return getNode(Opcode, DL, VT, Ops, Flags);
7888 }
7889 
7890 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7891                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7892   unsigned NumOps = Ops.size();
7893   switch (NumOps) {
7894   case 0: return getNode(Opcode, DL, VT);
7895   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7896   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7897   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7898   default: break;
7899   }
7900 
7901 #ifndef NDEBUG
7902   for (auto &Op : Ops)
7903     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7904            "Operand is DELETED_NODE!");
7905 #endif
7906 
7907   switch (Opcode) {
7908   default: break;
7909   case ISD::BUILD_VECTOR:
7910     // Attempt to simplify BUILD_VECTOR.
7911     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7912       return V;
7913     break;
7914   case ISD::CONCAT_VECTORS:
7915     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7916       return V;
7917     break;
7918   case ISD::SELECT_CC:
7919     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7920     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7921            "LHS and RHS of condition must have same type!");
7922     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7923            "True and False arms of SelectCC must have same type!");
7924     assert(Ops[2].getValueType() == VT &&
7925            "select_cc node must be of same type as true and false value!");
7926     break;
7927   case ISD::BR_CC:
7928     assert(NumOps == 5 && "BR_CC takes 5 operands!");
7929     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7930            "LHS/RHS of comparison should match types!");
7931     break;
7932   }
7933 
7934   // Memoize nodes.
7935   SDNode *N;
7936   SDVTList VTs = getVTList(VT);
7937 
7938   if (VT != MVT::Glue) {
7939     FoldingSetNodeID ID;
7940     AddNodeIDNode(ID, Opcode, VTs, Ops);
7941     void *IP = nullptr;
7942 
7943     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7944       return SDValue(E, 0);
7945 
7946     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7947     createOperands(N, Ops);
7948 
7949     CSEMap.InsertNode(N, IP);
7950   } else {
7951     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7952     createOperands(N, Ops);
7953   }
7954 
7955   N->setFlags(Flags);
7956   InsertNode(N);
7957   SDValue V(N, 0);
7958   NewSDValueDbgMsg(V, "Creating new node: ", this);
7959   return V;
7960 }
7961 
7962 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7963                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7964   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7965 }
7966 
7967 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7968                               ArrayRef<SDValue> Ops) {
7969   SDNodeFlags Flags;
7970   if (Inserter)
7971     Flags = Inserter->getFlags();
7972   return getNode(Opcode, DL, VTList, Ops, Flags);
7973 }
7974 
7975 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7976                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7977   if (VTList.NumVTs == 1)
7978     return getNode(Opcode, DL, VTList.VTs[0], Ops);
7979 
7980 #ifndef NDEBUG
7981   for (auto &Op : Ops)
7982     assert(Op.getOpcode() != ISD::DELETED_NODE &&
7983            "Operand is DELETED_NODE!");
7984 #endif
7985 
7986   switch (Opcode) {
7987   case ISD::STRICT_FP_EXTEND:
7988     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
7989            "Invalid STRICT_FP_EXTEND!");
7990     assert(VTList.VTs[0].isFloatingPoint() &&
7991            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
7992     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7993            "STRICT_FP_EXTEND result type should be vector iff the operand "
7994            "type is vector!");
7995     assert((!VTList.VTs[0].isVector() ||
7996             VTList.VTs[0].getVectorNumElements() ==
7997             Ops[1].getValueType().getVectorNumElements()) &&
7998            "Vector element count mismatch!");
7999     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8000            "Invalid fpext node, dst <= src!");
8001     break;
8002   case ISD::STRICT_FP_ROUND:
8003     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8004     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8005            "STRICT_FP_ROUND result type should be vector iff the operand "
8006            "type is vector!");
8007     assert((!VTList.VTs[0].isVector() ||
8008             VTList.VTs[0].getVectorNumElements() ==
8009             Ops[1].getValueType().getVectorNumElements()) &&
8010            "Vector element count mismatch!");
8011     assert(VTList.VTs[0].isFloatingPoint() &&
8012            Ops[1].getValueType().isFloatingPoint() &&
8013            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8014            isa<ConstantSDNode>(Ops[2]) &&
8015            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8016             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8017            "Invalid STRICT_FP_ROUND!");
8018     break;
8019 #if 0
8020   // FIXME: figure out how to safely handle things like
8021   // int foo(int x) { return 1 << (x & 255); }
8022   // int bar() { return foo(256); }
8023   case ISD::SRA_PARTS:
8024   case ISD::SRL_PARTS:
8025   case ISD::SHL_PARTS:
8026     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8027         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8028       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8029     else if (N3.getOpcode() == ISD::AND)
8030       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8031         // If the and is only masking out bits that cannot effect the shift,
8032         // eliminate the and.
8033         unsigned NumBits = VT.getScalarSizeInBits()*2;
8034         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8035           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8036       }
8037     break;
8038 #endif
8039   }
8040 
8041   // Memoize the node unless it returns a flag.
8042   SDNode *N;
8043   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8044     FoldingSetNodeID ID;
8045     AddNodeIDNode(ID, Opcode, VTList, Ops);
8046     void *IP = nullptr;
8047     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8048       return SDValue(E, 0);
8049 
8050     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8051     createOperands(N, Ops);
8052     CSEMap.InsertNode(N, IP);
8053   } else {
8054     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8055     createOperands(N, Ops);
8056   }
8057 
8058   N->setFlags(Flags);
8059   InsertNode(N);
8060   SDValue V(N, 0);
8061   NewSDValueDbgMsg(V, "Creating new node: ", this);
8062   return V;
8063 }
8064 
8065 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8066                               SDVTList VTList) {
8067   return getNode(Opcode, DL, VTList, None);
8068 }
8069 
8070 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8071                               SDValue N1) {
8072   SDValue Ops[] = { N1 };
8073   return getNode(Opcode, DL, VTList, Ops);
8074 }
8075 
8076 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8077                               SDValue N1, SDValue N2) {
8078   SDValue Ops[] = { N1, N2 };
8079   return getNode(Opcode, DL, VTList, Ops);
8080 }
8081 
8082 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8083                               SDValue N1, SDValue N2, SDValue N3) {
8084   SDValue Ops[] = { N1, N2, N3 };
8085   return getNode(Opcode, DL, VTList, Ops);
8086 }
8087 
8088 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8089                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8090   SDValue Ops[] = { N1, N2, N3, N4 };
8091   return getNode(Opcode, DL, VTList, Ops);
8092 }
8093 
8094 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8095                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8096                               SDValue N5) {
8097   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8098   return getNode(Opcode, DL, VTList, Ops);
8099 }
8100 
8101 SDVTList SelectionDAG::getVTList(EVT VT) {
8102   return makeVTList(SDNode::getValueTypeList(VT), 1);
8103 }
8104 
8105 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8106   FoldingSetNodeID ID;
8107   ID.AddInteger(2U);
8108   ID.AddInteger(VT1.getRawBits());
8109   ID.AddInteger(VT2.getRawBits());
8110 
8111   void *IP = nullptr;
8112   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8113   if (!Result) {
8114     EVT *Array = Allocator.Allocate<EVT>(2);
8115     Array[0] = VT1;
8116     Array[1] = VT2;
8117     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8118     VTListMap.InsertNode(Result, IP);
8119   }
8120   return Result->getSDVTList();
8121 }
8122 
8123 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8124   FoldingSetNodeID ID;
8125   ID.AddInteger(3U);
8126   ID.AddInteger(VT1.getRawBits());
8127   ID.AddInteger(VT2.getRawBits());
8128   ID.AddInteger(VT3.getRawBits());
8129 
8130   void *IP = nullptr;
8131   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8132   if (!Result) {
8133     EVT *Array = Allocator.Allocate<EVT>(3);
8134     Array[0] = VT1;
8135     Array[1] = VT2;
8136     Array[2] = VT3;
8137     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8138     VTListMap.InsertNode(Result, IP);
8139   }
8140   return Result->getSDVTList();
8141 }
8142 
8143 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8144   FoldingSetNodeID ID;
8145   ID.AddInteger(4U);
8146   ID.AddInteger(VT1.getRawBits());
8147   ID.AddInteger(VT2.getRawBits());
8148   ID.AddInteger(VT3.getRawBits());
8149   ID.AddInteger(VT4.getRawBits());
8150 
8151   void *IP = nullptr;
8152   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8153   if (!Result) {
8154     EVT *Array = Allocator.Allocate<EVT>(4);
8155     Array[0] = VT1;
8156     Array[1] = VT2;
8157     Array[2] = VT3;
8158     Array[3] = VT4;
8159     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8160     VTListMap.InsertNode(Result, IP);
8161   }
8162   return Result->getSDVTList();
8163 }
8164 
8165 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8166   unsigned NumVTs = VTs.size();
8167   FoldingSetNodeID ID;
8168   ID.AddInteger(NumVTs);
8169   for (unsigned index = 0; index < NumVTs; index++) {
8170     ID.AddInteger(VTs[index].getRawBits());
8171   }
8172 
8173   void *IP = nullptr;
8174   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8175   if (!Result) {
8176     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8177     llvm::copy(VTs, Array);
8178     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8179     VTListMap.InsertNode(Result, IP);
8180   }
8181   return Result->getSDVTList();
8182 }
8183 
8184 
8185 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8186 /// specified operands.  If the resultant node already exists in the DAG,
8187 /// this does not modify the specified node, instead it returns the node that
8188 /// already exists.  If the resultant node does not exist in the DAG, the
8189 /// input node is returned.  As a degenerate case, if you specify the same
8190 /// input operands as the node already has, the input node is returned.
8191 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8192   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8193 
8194   // Check to see if there is no change.
8195   if (Op == N->getOperand(0)) return N;
8196 
8197   // See if the modified node already exists.
8198   void *InsertPos = nullptr;
8199   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8200     return Existing;
8201 
8202   // Nope it doesn't.  Remove the node from its current place in the maps.
8203   if (InsertPos)
8204     if (!RemoveNodeFromCSEMaps(N))
8205       InsertPos = nullptr;
8206 
8207   // Now we update the operands.
8208   N->OperandList[0].set(Op);
8209 
8210   updateDivergence(N);
8211   // If this gets put into a CSE map, add it.
8212   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8213   return N;
8214 }
8215 
8216 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8217   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8218 
8219   // Check to see if there is no change.
8220   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8221     return N;   // No operands changed, just return the input node.
8222 
8223   // See if the modified node already exists.
8224   void *InsertPos = nullptr;
8225   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8226     return Existing;
8227 
8228   // Nope it doesn't.  Remove the node from its current place in the maps.
8229   if (InsertPos)
8230     if (!RemoveNodeFromCSEMaps(N))
8231       InsertPos = nullptr;
8232 
8233   // Now we update the operands.
8234   if (N->OperandList[0] != Op1)
8235     N->OperandList[0].set(Op1);
8236   if (N->OperandList[1] != Op2)
8237     N->OperandList[1].set(Op2);
8238 
8239   updateDivergence(N);
8240   // If this gets put into a CSE map, add it.
8241   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8242   return N;
8243 }
8244 
8245 SDNode *SelectionDAG::
8246 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8247   SDValue Ops[] = { Op1, Op2, Op3 };
8248   return UpdateNodeOperands(N, Ops);
8249 }
8250 
8251 SDNode *SelectionDAG::
8252 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8253                    SDValue Op3, SDValue Op4) {
8254   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8255   return UpdateNodeOperands(N, Ops);
8256 }
8257 
8258 SDNode *SelectionDAG::
8259 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8260                    SDValue Op3, SDValue Op4, SDValue Op5) {
8261   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8262   return UpdateNodeOperands(N, Ops);
8263 }
8264 
8265 SDNode *SelectionDAG::
8266 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8267   unsigned NumOps = Ops.size();
8268   assert(N->getNumOperands() == NumOps &&
8269          "Update with wrong number of operands");
8270 
8271   // If no operands changed just return the input node.
8272   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8273     return N;
8274 
8275   // See if the modified node already exists.
8276   void *InsertPos = nullptr;
8277   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8278     return Existing;
8279 
8280   // Nope it doesn't.  Remove the node from its current place in the maps.
8281   if (InsertPos)
8282     if (!RemoveNodeFromCSEMaps(N))
8283       InsertPos = nullptr;
8284 
8285   // Now we update the operands.
8286   for (unsigned i = 0; i != NumOps; ++i)
8287     if (N->OperandList[i] != Ops[i])
8288       N->OperandList[i].set(Ops[i]);
8289 
8290   updateDivergence(N);
8291   // If this gets put into a CSE map, add it.
8292   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8293   return N;
8294 }
8295 
8296 /// DropOperands - Release the operands and set this node to have
8297 /// zero operands.
8298 void SDNode::DropOperands() {
8299   // Unlike the code in MorphNodeTo that does this, we don't need to
8300   // watch for dead nodes here.
8301   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8302     SDUse &Use = *I++;
8303     Use.set(SDValue());
8304   }
8305 }
8306 
8307 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8308                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8309   if (NewMemRefs.empty()) {
8310     N->clearMemRefs();
8311     return;
8312   }
8313 
8314   // Check if we can avoid allocating by storing a single reference directly.
8315   if (NewMemRefs.size() == 1) {
8316     N->MemRefs = NewMemRefs[0];
8317     N->NumMemRefs = 1;
8318     return;
8319   }
8320 
8321   MachineMemOperand **MemRefsBuffer =
8322       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8323   llvm::copy(NewMemRefs, MemRefsBuffer);
8324   N->MemRefs = MemRefsBuffer;
8325   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8326 }
8327 
8328 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8329 /// machine opcode.
8330 ///
8331 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8332                                    EVT VT) {
8333   SDVTList VTs = getVTList(VT);
8334   return SelectNodeTo(N, MachineOpc, VTs, None);
8335 }
8336 
8337 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8338                                    EVT VT, SDValue Op1) {
8339   SDVTList VTs = getVTList(VT);
8340   SDValue Ops[] = { Op1 };
8341   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8342 }
8343 
8344 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8345                                    EVT VT, SDValue Op1,
8346                                    SDValue Op2) {
8347   SDVTList VTs = getVTList(VT);
8348   SDValue Ops[] = { Op1, Op2 };
8349   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8350 }
8351 
8352 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8353                                    EVT VT, SDValue Op1,
8354                                    SDValue Op2, SDValue Op3) {
8355   SDVTList VTs = getVTList(VT);
8356   SDValue Ops[] = { Op1, Op2, Op3 };
8357   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8358 }
8359 
8360 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8361                                    EVT VT, ArrayRef<SDValue> Ops) {
8362   SDVTList VTs = getVTList(VT);
8363   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8364 }
8365 
8366 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8367                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8368   SDVTList VTs = getVTList(VT1, VT2);
8369   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8370 }
8371 
8372 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8373                                    EVT VT1, EVT VT2) {
8374   SDVTList VTs = getVTList(VT1, VT2);
8375   return SelectNodeTo(N, MachineOpc, VTs, None);
8376 }
8377 
8378 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8379                                    EVT VT1, EVT VT2, EVT VT3,
8380                                    ArrayRef<SDValue> Ops) {
8381   SDVTList VTs = getVTList(VT1, VT2, VT3);
8382   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8383 }
8384 
8385 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8386                                    EVT VT1, EVT VT2,
8387                                    SDValue Op1, SDValue Op2) {
8388   SDVTList VTs = getVTList(VT1, VT2);
8389   SDValue Ops[] = { Op1, Op2 };
8390   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8391 }
8392 
8393 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8394                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8395   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8396   // Reset the NodeID to -1.
8397   New->setNodeId(-1);
8398   if (New != N) {
8399     ReplaceAllUsesWith(N, New);
8400     RemoveDeadNode(N);
8401   }
8402   return New;
8403 }
8404 
8405 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8406 /// the line number information on the merged node since it is not possible to
8407 /// preserve the information that operation is associated with multiple lines.
8408 /// This will make the debugger working better at -O0, were there is a higher
8409 /// probability having other instructions associated with that line.
8410 ///
8411 /// For IROrder, we keep the smaller of the two
8412 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8413   DebugLoc NLoc = N->getDebugLoc();
8414   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8415     N->setDebugLoc(DebugLoc());
8416   }
8417   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8418   N->setIROrder(Order);
8419   return N;
8420 }
8421 
8422 /// MorphNodeTo - This *mutates* the specified node to have the specified
8423 /// return type, opcode, and operands.
8424 ///
8425 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8426 /// node of the specified opcode and operands, it returns that node instead of
8427 /// the current one.  Note that the SDLoc need not be the same.
8428 ///
8429 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8430 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8431 /// node, and because it doesn't require CSE recalculation for any of
8432 /// the node's users.
8433 ///
8434 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8435 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8436 /// the legalizer which maintain worklists that would need to be updated when
8437 /// deleting things.
8438 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8439                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8440   // If an identical node already exists, use it.
8441   void *IP = nullptr;
8442   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8443     FoldingSetNodeID ID;
8444     AddNodeIDNode(ID, Opc, VTs, Ops);
8445     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8446       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8447   }
8448 
8449   if (!RemoveNodeFromCSEMaps(N))
8450     IP = nullptr;
8451 
8452   // Start the morphing.
8453   N->NodeType = Opc;
8454   N->ValueList = VTs.VTs;
8455   N->NumValues = VTs.NumVTs;
8456 
8457   // Clear the operands list, updating used nodes to remove this from their
8458   // use list.  Keep track of any operands that become dead as a result.
8459   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8460   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8461     SDUse &Use = *I++;
8462     SDNode *Used = Use.getNode();
8463     Use.set(SDValue());
8464     if (Used->use_empty())
8465       DeadNodeSet.insert(Used);
8466   }
8467 
8468   // For MachineNode, initialize the memory references information.
8469   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8470     MN->clearMemRefs();
8471 
8472   // Swap for an appropriately sized array from the recycler.
8473   removeOperands(N);
8474   createOperands(N, Ops);
8475 
8476   // Delete any nodes that are still dead after adding the uses for the
8477   // new operands.
8478   if (!DeadNodeSet.empty()) {
8479     SmallVector<SDNode *, 16> DeadNodes;
8480     for (SDNode *N : DeadNodeSet)
8481       if (N->use_empty())
8482         DeadNodes.push_back(N);
8483     RemoveDeadNodes(DeadNodes);
8484   }
8485 
8486   if (IP)
8487     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8488   return N;
8489 }
8490 
8491 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8492   unsigned OrigOpc = Node->getOpcode();
8493   unsigned NewOpc;
8494   switch (OrigOpc) {
8495   default:
8496     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8497 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8498   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8499 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8500   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8501 #include "llvm/IR/ConstrainedOps.def"
8502   }
8503 
8504   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8505 
8506   // We're taking this node out of the chain, so we need to re-link things.
8507   SDValue InputChain = Node->getOperand(0);
8508   SDValue OutputChain = SDValue(Node, 1);
8509   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8510 
8511   SmallVector<SDValue, 3> Ops;
8512   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8513     Ops.push_back(Node->getOperand(i));
8514 
8515   SDVTList VTs = getVTList(Node->getValueType(0));
8516   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8517 
8518   // MorphNodeTo can operate in two ways: if an existing node with the
8519   // specified operands exists, it can just return it.  Otherwise, it
8520   // updates the node in place to have the requested operands.
8521   if (Res == Node) {
8522     // If we updated the node in place, reset the node ID.  To the isel,
8523     // this should be just like a newly allocated machine node.
8524     Res->setNodeId(-1);
8525   } else {
8526     ReplaceAllUsesWith(Node, Res);
8527     RemoveDeadNode(Node);
8528   }
8529 
8530   return Res;
8531 }
8532 
8533 /// getMachineNode - These are used for target selectors to create a new node
8534 /// with specified return type(s), MachineInstr opcode, and operands.
8535 ///
8536 /// Note that getMachineNode returns the resultant node.  If there is already a
8537 /// node of the specified opcode and operands, it returns that node instead of
8538 /// the current one.
8539 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8540                                             EVT VT) {
8541   SDVTList VTs = getVTList(VT);
8542   return getMachineNode(Opcode, dl, VTs, None);
8543 }
8544 
8545 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8546                                             EVT VT, SDValue Op1) {
8547   SDVTList VTs = getVTList(VT);
8548   SDValue Ops[] = { Op1 };
8549   return getMachineNode(Opcode, dl, VTs, Ops);
8550 }
8551 
8552 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8553                                             EVT VT, SDValue Op1, SDValue Op2) {
8554   SDVTList VTs = getVTList(VT);
8555   SDValue Ops[] = { Op1, Op2 };
8556   return getMachineNode(Opcode, dl, VTs, Ops);
8557 }
8558 
8559 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8560                                             EVT VT, SDValue Op1, SDValue Op2,
8561                                             SDValue Op3) {
8562   SDVTList VTs = getVTList(VT);
8563   SDValue Ops[] = { Op1, Op2, Op3 };
8564   return getMachineNode(Opcode, dl, VTs, Ops);
8565 }
8566 
8567 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8568                                             EVT VT, ArrayRef<SDValue> Ops) {
8569   SDVTList VTs = getVTList(VT);
8570   return getMachineNode(Opcode, dl, VTs, Ops);
8571 }
8572 
8573 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8574                                             EVT VT1, EVT VT2, SDValue Op1,
8575                                             SDValue Op2) {
8576   SDVTList VTs = getVTList(VT1, VT2);
8577   SDValue Ops[] = { Op1, Op2 };
8578   return getMachineNode(Opcode, dl, VTs, Ops);
8579 }
8580 
8581 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8582                                             EVT VT1, EVT VT2, SDValue Op1,
8583                                             SDValue Op2, SDValue Op3) {
8584   SDVTList VTs = getVTList(VT1, VT2);
8585   SDValue Ops[] = { Op1, Op2, Op3 };
8586   return getMachineNode(Opcode, dl, VTs, Ops);
8587 }
8588 
8589 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8590                                             EVT VT1, EVT VT2,
8591                                             ArrayRef<SDValue> Ops) {
8592   SDVTList VTs = getVTList(VT1, VT2);
8593   return getMachineNode(Opcode, dl, VTs, Ops);
8594 }
8595 
8596 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8597                                             EVT VT1, EVT VT2, EVT VT3,
8598                                             SDValue Op1, SDValue Op2) {
8599   SDVTList VTs = getVTList(VT1, VT2, VT3);
8600   SDValue Ops[] = { Op1, Op2 };
8601   return getMachineNode(Opcode, dl, VTs, Ops);
8602 }
8603 
8604 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8605                                             EVT VT1, EVT VT2, EVT VT3,
8606                                             SDValue Op1, SDValue Op2,
8607                                             SDValue Op3) {
8608   SDVTList VTs = getVTList(VT1, VT2, VT3);
8609   SDValue Ops[] = { Op1, Op2, Op3 };
8610   return getMachineNode(Opcode, dl, VTs, Ops);
8611 }
8612 
8613 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8614                                             EVT VT1, EVT VT2, EVT VT3,
8615                                             ArrayRef<SDValue> Ops) {
8616   SDVTList VTs = getVTList(VT1, VT2, VT3);
8617   return getMachineNode(Opcode, dl, VTs, Ops);
8618 }
8619 
8620 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8621                                             ArrayRef<EVT> ResultTys,
8622                                             ArrayRef<SDValue> Ops) {
8623   SDVTList VTs = getVTList(ResultTys);
8624   return getMachineNode(Opcode, dl, VTs, Ops);
8625 }
8626 
8627 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
8628                                             SDVTList VTs,
8629                                             ArrayRef<SDValue> Ops) {
8630   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
8631   MachineSDNode *N;
8632   void *IP = nullptr;
8633 
8634   if (DoCSE) {
8635     FoldingSetNodeID ID;
8636     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
8637     IP = nullptr;
8638     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8639       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
8640     }
8641   }
8642 
8643   // Allocate a new MachineSDNode.
8644   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8645   createOperands(N, Ops);
8646 
8647   if (DoCSE)
8648     CSEMap.InsertNode(N, IP);
8649 
8650   InsertNode(N);
8651   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
8652   return N;
8653 }
8654 
8655 /// getTargetExtractSubreg - A convenience function for creating
8656 /// TargetOpcode::EXTRACT_SUBREG nodes.
8657 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8658                                              SDValue Operand) {
8659   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8660   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
8661                                   VT, Operand, SRIdxVal);
8662   return SDValue(Subreg, 0);
8663 }
8664 
8665 /// getTargetInsertSubreg - A convenience function for creating
8666 /// TargetOpcode::INSERT_SUBREG nodes.
8667 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8668                                             SDValue Operand, SDValue Subreg) {
8669   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8670   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
8671                                   VT, Operand, Subreg, SRIdxVal);
8672   return SDValue(Result, 0);
8673 }
8674 
8675 /// getNodeIfExists - Get the specified node if it's already available, or
8676 /// else return NULL.
8677 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8678                                       ArrayRef<SDValue> Ops) {
8679   SDNodeFlags Flags;
8680   if (Inserter)
8681     Flags = Inserter->getFlags();
8682   return getNodeIfExists(Opcode, VTList, Ops, Flags);
8683 }
8684 
8685 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8686                                       ArrayRef<SDValue> Ops,
8687                                       const SDNodeFlags Flags) {
8688   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8689     FoldingSetNodeID ID;
8690     AddNodeIDNode(ID, Opcode, VTList, Ops);
8691     void *IP = nullptr;
8692     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
8693       E->intersectFlagsWith(Flags);
8694       return E;
8695     }
8696   }
8697   return nullptr;
8698 }
8699 
8700 /// doesNodeExist - Check if a node exists without modifying its flags.
8701 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
8702                                  ArrayRef<SDValue> Ops) {
8703   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8704     FoldingSetNodeID ID;
8705     AddNodeIDNode(ID, Opcode, VTList, Ops);
8706     void *IP = nullptr;
8707     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
8708       return true;
8709   }
8710   return false;
8711 }
8712 
8713 /// getDbgValue - Creates a SDDbgValue node.
8714 ///
8715 /// SDNode
8716 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
8717                                       SDNode *N, unsigned R, bool IsIndirect,
8718                                       const DebugLoc &DL, unsigned O) {
8719   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8720          "Expected inlined-at fields to agree");
8721   return new (DbgInfo->getAlloc())
8722       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
8723                  {}, IsIndirect, DL, O,
8724                  /*IsVariadic=*/false);
8725 }
8726 
8727 /// Constant
8728 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
8729                                               DIExpression *Expr,
8730                                               const Value *C,
8731                                               const DebugLoc &DL, unsigned O) {
8732   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8733          "Expected inlined-at fields to agree");
8734   return new (DbgInfo->getAlloc())
8735       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
8736                  /*IsIndirect=*/false, DL, O,
8737                  /*IsVariadic=*/false);
8738 }
8739 
8740 /// FrameIndex
8741 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8742                                                 DIExpression *Expr, unsigned FI,
8743                                                 bool IsIndirect,
8744                                                 const DebugLoc &DL,
8745                                                 unsigned O) {
8746   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8747          "Expected inlined-at fields to agree");
8748   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
8749 }
8750 
8751 /// FrameIndex with dependencies
8752 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8753                                                 DIExpression *Expr, unsigned FI,
8754                                                 ArrayRef<SDNode *> Dependencies,
8755                                                 bool IsIndirect,
8756                                                 const DebugLoc &DL,
8757                                                 unsigned O) {
8758   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8759          "Expected inlined-at fields to agree");
8760   return new (DbgInfo->getAlloc())
8761       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
8762                  Dependencies, IsIndirect, DL, O,
8763                  /*IsVariadic=*/false);
8764 }
8765 
8766 /// VReg
8767 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
8768                                           unsigned VReg, bool IsIndirect,
8769                                           const DebugLoc &DL, unsigned O) {
8770   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8771          "Expected inlined-at fields to agree");
8772   return new (DbgInfo->getAlloc())
8773       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
8774                  {}, IsIndirect, DL, O,
8775                  /*IsVariadic=*/false);
8776 }
8777 
8778 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
8779                                           ArrayRef<SDDbgOperand> Locs,
8780                                           ArrayRef<SDNode *> Dependencies,
8781                                           bool IsIndirect, const DebugLoc &DL,
8782                                           unsigned O, bool IsVariadic) {
8783   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8784          "Expected inlined-at fields to agree");
8785   return new (DbgInfo->getAlloc())
8786       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
8787                  DL, O, IsVariadic);
8788 }
8789 
8790 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8791                                      unsigned OffsetInBits, unsigned SizeInBits,
8792                                      bool InvalidateDbg) {
8793   SDNode *FromNode = From.getNode();
8794   SDNode *ToNode = To.getNode();
8795   assert(FromNode && ToNode && "Can't modify dbg values");
8796 
8797   // PR35338
8798   // TODO: assert(From != To && "Redundant dbg value transfer");
8799   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8800   if (From == To || FromNode == ToNode)
8801     return;
8802 
8803   if (!FromNode->getHasDebugValue())
8804     return;
8805 
8806   SDDbgOperand FromLocOp =
8807       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
8808   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
8809 
8810   SmallVector<SDDbgValue *, 2> ClonedDVs;
8811   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8812     if (Dbg->isInvalidated())
8813       continue;
8814 
8815     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8816 
8817     // Create a new location ops vector that is equal to the old vector, but
8818     // with each instance of FromLocOp replaced with ToLocOp.
8819     bool Changed = false;
8820     auto NewLocOps = Dbg->copyLocationOps();
8821     std::replace_if(
8822         NewLocOps.begin(), NewLocOps.end(),
8823         [&Changed, FromLocOp](const SDDbgOperand &Op) {
8824           bool Match = Op == FromLocOp;
8825           Changed |= Match;
8826           return Match;
8827         },
8828         ToLocOp);
8829     // Ignore this SDDbgValue if we didn't find a matching location.
8830     if (!Changed)
8831       continue;
8832 
8833     DIVariable *Var = Dbg->getVariable();
8834     auto *Expr = Dbg->getExpression();
8835     // If a fragment is requested, update the expression.
8836     if (SizeInBits) {
8837       // When splitting a larger (e.g., sign-extended) value whose
8838       // lower bits are described with an SDDbgValue, do not attempt
8839       // to transfer the SDDbgValue to the upper bits.
8840       if (auto FI = Expr->getFragmentInfo())
8841         if (OffsetInBits + SizeInBits > FI->SizeInBits)
8842           continue;
8843       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8844                                                              SizeInBits);
8845       if (!Fragment)
8846         continue;
8847       Expr = *Fragment;
8848     }
8849 
8850     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
8851     // Clone the SDDbgValue and move it to To.
8852     SDDbgValue *Clone = getDbgValueList(
8853         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
8854         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
8855         Dbg->isVariadic());
8856     ClonedDVs.push_back(Clone);
8857 
8858     if (InvalidateDbg) {
8859       // Invalidate value and indicate the SDDbgValue should not be emitted.
8860       Dbg->setIsInvalidated();
8861       Dbg->setIsEmitted();
8862     }
8863   }
8864 
8865   for (SDDbgValue *Dbg : ClonedDVs) {
8866     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
8867            "Transferred DbgValues should depend on the new SDNode");
8868     AddDbgValue(Dbg, false);
8869   }
8870 }
8871 
8872 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8873   if (!N.getHasDebugValue())
8874     return;
8875 
8876   SmallVector<SDDbgValue *, 2> ClonedDVs;
8877   for (auto DV : GetDbgValues(&N)) {
8878     if (DV->isInvalidated())
8879       continue;
8880     switch (N.getOpcode()) {
8881     default:
8882       break;
8883     case ISD::ADD:
8884       SDValue N0 = N.getOperand(0);
8885       SDValue N1 = N.getOperand(1);
8886       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8887           isConstantIntBuildVectorOrConstantInt(N1)) {
8888         uint64_t Offset = N.getConstantOperandVal(1);
8889 
8890         // Rewrite an ADD constant node into a DIExpression. Since we are
8891         // performing arithmetic to compute the variable's *value* in the
8892         // DIExpression, we need to mark the expression with a
8893         // DW_OP_stack_value.
8894         auto *DIExpr = DV->getExpression();
8895         auto NewLocOps = DV->copyLocationOps();
8896         bool Changed = false;
8897         for (size_t i = 0; i < NewLocOps.size(); ++i) {
8898           // We're not given a ResNo to compare against because the whole
8899           // node is going away. We know that any ISD::ADD only has one
8900           // result, so we can assume any node match is using the result.
8901           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
8902               NewLocOps[i].getSDNode() != &N)
8903             continue;
8904           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
8905           SmallVector<uint64_t, 3> ExprOps;
8906           DIExpression::appendOffset(ExprOps, Offset);
8907           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
8908           Changed = true;
8909         }
8910         (void)Changed;
8911         assert(Changed && "Salvage target doesn't use N");
8912 
8913         auto AdditionalDependencies = DV->getAdditionalDependencies();
8914         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
8915                                             NewLocOps, AdditionalDependencies,
8916                                             DV->isIndirect(), DV->getDebugLoc(),
8917                                             DV->getOrder(), DV->isVariadic());
8918         ClonedDVs.push_back(Clone);
8919         DV->setIsInvalidated();
8920         DV->setIsEmitted();
8921         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8922                    N0.getNode()->dumprFull(this);
8923                    dbgs() << " into " << *DIExpr << '\n');
8924       }
8925     }
8926   }
8927 
8928   for (SDDbgValue *Dbg : ClonedDVs) {
8929     assert(!Dbg->getSDNodes().empty() &&
8930            "Salvaged DbgValue should depend on a new SDNode");
8931     AddDbgValue(Dbg, false);
8932   }
8933 }
8934 
8935 /// Creates a SDDbgLabel node.
8936 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8937                                       const DebugLoc &DL, unsigned O) {
8938   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8939          "Expected inlined-at fields to agree");
8940   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8941 }
8942 
8943 namespace {
8944 
8945 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8946 /// pointed to by a use iterator is deleted, increment the use iterator
8947 /// so that it doesn't dangle.
8948 ///
8949 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8950   SDNode::use_iterator &UI;
8951   SDNode::use_iterator &UE;
8952 
8953   void NodeDeleted(SDNode *N, SDNode *E) override {
8954     // Increment the iterator as needed.
8955     while (UI != UE && N == *UI)
8956       ++UI;
8957   }
8958 
8959 public:
8960   RAUWUpdateListener(SelectionDAG &d,
8961                      SDNode::use_iterator &ui,
8962                      SDNode::use_iterator &ue)
8963     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8964 };
8965 
8966 } // end anonymous namespace
8967 
8968 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8969 /// This can cause recursive merging of nodes in the DAG.
8970 ///
8971 /// This version assumes From has a single result value.
8972 ///
8973 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8974   SDNode *From = FromN.getNode();
8975   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8976          "Cannot replace with this method!");
8977   assert(From != To.getNode() && "Cannot replace uses of with self");
8978 
8979   // Preserve Debug Values
8980   transferDbgValues(FromN, To);
8981 
8982   // Iterate over all the existing uses of From. New uses will be added
8983   // to the beginning of the use list, which we avoid visiting.
8984   // This specifically avoids visiting uses of From that arise while the
8985   // replacement is happening, because any such uses would be the result
8986   // of CSE: If an existing node looks like From after one of its operands
8987   // is replaced by To, we don't want to replace of all its users with To
8988   // too. See PR3018 for more info.
8989   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8990   RAUWUpdateListener Listener(*this, UI, UE);
8991   while (UI != UE) {
8992     SDNode *User = *UI;
8993 
8994     // This node is about to morph, remove its old self from the CSE maps.
8995     RemoveNodeFromCSEMaps(User);
8996 
8997     // A user can appear in a use list multiple times, and when this
8998     // happens the uses are usually next to each other in the list.
8999     // To help reduce the number of CSE recomputations, process all
9000     // the uses of this user that we can find this way.
9001     do {
9002       SDUse &Use = UI.getUse();
9003       ++UI;
9004       Use.set(To);
9005       if (To->isDivergent() != From->isDivergent())
9006         updateDivergence(User);
9007     } while (UI != UE && *UI == User);
9008     // Now that we have modified User, add it back to the CSE maps.  If it
9009     // already exists there, recursively merge the results together.
9010     AddModifiedNodeToCSEMaps(User);
9011   }
9012 
9013   // If we just RAUW'd the root, take note.
9014   if (FromN == getRoot())
9015     setRoot(To);
9016 }
9017 
9018 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9019 /// This can cause recursive merging of nodes in the DAG.
9020 ///
9021 /// This version assumes that for each value of From, there is a
9022 /// corresponding value in To in the same position with the same type.
9023 ///
9024 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9025 #ifndef NDEBUG
9026   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9027     assert((!From->hasAnyUseOfValue(i) ||
9028             From->getValueType(i) == To->getValueType(i)) &&
9029            "Cannot use this version of ReplaceAllUsesWith!");
9030 #endif
9031 
9032   // Handle the trivial case.
9033   if (From == To)
9034     return;
9035 
9036   // Preserve Debug Info. Only do this if there's a use.
9037   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9038     if (From->hasAnyUseOfValue(i)) {
9039       assert((i < To->getNumValues()) && "Invalid To location");
9040       transferDbgValues(SDValue(From, i), SDValue(To, i));
9041     }
9042 
9043   // Iterate over just the existing users of From. See the comments in
9044   // the ReplaceAllUsesWith above.
9045   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9046   RAUWUpdateListener Listener(*this, UI, UE);
9047   while (UI != UE) {
9048     SDNode *User = *UI;
9049 
9050     // This node is about to morph, remove its old self from the CSE maps.
9051     RemoveNodeFromCSEMaps(User);
9052 
9053     // A user can appear in a use list multiple times, and when this
9054     // happens the uses are usually next to each other in the list.
9055     // To help reduce the number of CSE recomputations, process all
9056     // the uses of this user that we can find this way.
9057     do {
9058       SDUse &Use = UI.getUse();
9059       ++UI;
9060       Use.setNode(To);
9061       if (To->isDivergent() != From->isDivergent())
9062         updateDivergence(User);
9063     } while (UI != UE && *UI == User);
9064 
9065     // Now that we have modified User, add it back to the CSE maps.  If it
9066     // already exists there, recursively merge the results together.
9067     AddModifiedNodeToCSEMaps(User);
9068   }
9069 
9070   // If we just RAUW'd the root, take note.
9071   if (From == getRoot().getNode())
9072     setRoot(SDValue(To, getRoot().getResNo()));
9073 }
9074 
9075 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9076 /// This can cause recursive merging of nodes in the DAG.
9077 ///
9078 /// This version can replace From with any result values.  To must match the
9079 /// number and types of values returned by From.
9080 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9081   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9082     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9083 
9084   // Preserve Debug Info.
9085   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9086     transferDbgValues(SDValue(From, i), To[i]);
9087 
9088   // Iterate over just the existing users of From. See the comments in
9089   // the ReplaceAllUsesWith above.
9090   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9091   RAUWUpdateListener Listener(*this, UI, UE);
9092   while (UI != UE) {
9093     SDNode *User = *UI;
9094 
9095     // This node is about to morph, remove its old self from the CSE maps.
9096     RemoveNodeFromCSEMaps(User);
9097 
9098     // A user can appear in a use list multiple times, and when this happens the
9099     // uses are usually next to each other in the list.  To help reduce the
9100     // number of CSE and divergence recomputations, process all the uses of this
9101     // user that we can find this way.
9102     bool To_IsDivergent = false;
9103     do {
9104       SDUse &Use = UI.getUse();
9105       const SDValue &ToOp = To[Use.getResNo()];
9106       ++UI;
9107       Use.set(ToOp);
9108       To_IsDivergent |= ToOp->isDivergent();
9109     } while (UI != UE && *UI == User);
9110 
9111     if (To_IsDivergent != From->isDivergent())
9112       updateDivergence(User);
9113 
9114     // Now that we have modified User, add it back to the CSE maps.  If it
9115     // already exists there, recursively merge the results together.
9116     AddModifiedNodeToCSEMaps(User);
9117   }
9118 
9119   // If we just RAUW'd the root, take note.
9120   if (From == getRoot().getNode())
9121     setRoot(SDValue(To[getRoot().getResNo()]));
9122 }
9123 
9124 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9125 /// uses of other values produced by From.getNode() alone.  The Deleted
9126 /// vector is handled the same way as for ReplaceAllUsesWith.
9127 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9128   // Handle the really simple, really trivial case efficiently.
9129   if (From == To) return;
9130 
9131   // Handle the simple, trivial, case efficiently.
9132   if (From.getNode()->getNumValues() == 1) {
9133     ReplaceAllUsesWith(From, To);
9134     return;
9135   }
9136 
9137   // Preserve Debug Info.
9138   transferDbgValues(From, To);
9139 
9140   // Iterate over just the existing users of From. See the comments in
9141   // the ReplaceAllUsesWith above.
9142   SDNode::use_iterator UI = From.getNode()->use_begin(),
9143                        UE = From.getNode()->use_end();
9144   RAUWUpdateListener Listener(*this, UI, UE);
9145   while (UI != UE) {
9146     SDNode *User = *UI;
9147     bool UserRemovedFromCSEMaps = false;
9148 
9149     // A user can appear in a use list multiple times, and when this
9150     // happens the uses are usually next to each other in the list.
9151     // To help reduce the number of CSE recomputations, process all
9152     // the uses of this user that we can find this way.
9153     do {
9154       SDUse &Use = UI.getUse();
9155 
9156       // Skip uses of different values from the same node.
9157       if (Use.getResNo() != From.getResNo()) {
9158         ++UI;
9159         continue;
9160       }
9161 
9162       // If this node hasn't been modified yet, it's still in the CSE maps,
9163       // so remove its old self from the CSE maps.
9164       if (!UserRemovedFromCSEMaps) {
9165         RemoveNodeFromCSEMaps(User);
9166         UserRemovedFromCSEMaps = true;
9167       }
9168 
9169       ++UI;
9170       Use.set(To);
9171       if (To->isDivergent() != From->isDivergent())
9172         updateDivergence(User);
9173     } while (UI != UE && *UI == User);
9174     // We are iterating over all uses of the From node, so if a use
9175     // doesn't use the specific value, no changes are made.
9176     if (!UserRemovedFromCSEMaps)
9177       continue;
9178 
9179     // Now that we have modified User, add it back to the CSE maps.  If it
9180     // already exists there, recursively merge the results together.
9181     AddModifiedNodeToCSEMaps(User);
9182   }
9183 
9184   // If we just RAUW'd the root, take note.
9185   if (From == getRoot())
9186     setRoot(To);
9187 }
9188 
9189 namespace {
9190 
9191   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9192   /// to record information about a use.
9193   struct UseMemo {
9194     SDNode *User;
9195     unsigned Index;
9196     SDUse *Use;
9197   };
9198 
9199   /// operator< - Sort Memos by User.
9200   bool operator<(const UseMemo &L, const UseMemo &R) {
9201     return (intptr_t)L.User < (intptr_t)R.User;
9202   }
9203 
9204 } // end anonymous namespace
9205 
9206 bool SelectionDAG::calculateDivergence(SDNode *N) {
9207   if (TLI->isSDNodeAlwaysUniform(N)) {
9208     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9209            "Conflicting divergence information!");
9210     return false;
9211   }
9212   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9213     return true;
9214   for (auto &Op : N->ops()) {
9215     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9216       return true;
9217   }
9218   return false;
9219 }
9220 
9221 void SelectionDAG::updateDivergence(SDNode *N) {
9222   SmallVector<SDNode *, 16> Worklist(1, N);
9223   do {
9224     N = Worklist.pop_back_val();
9225     bool IsDivergent = calculateDivergence(N);
9226     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9227       N->SDNodeBits.IsDivergent = IsDivergent;
9228       llvm::append_range(Worklist, N->uses());
9229     }
9230   } while (!Worklist.empty());
9231 }
9232 
9233 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9234   DenseMap<SDNode *, unsigned> Degree;
9235   Order.reserve(AllNodes.size());
9236   for (auto &N : allnodes()) {
9237     unsigned NOps = N.getNumOperands();
9238     Degree[&N] = NOps;
9239     if (0 == NOps)
9240       Order.push_back(&N);
9241   }
9242   for (size_t I = 0; I != Order.size(); ++I) {
9243     SDNode *N = Order[I];
9244     for (auto U : N->uses()) {
9245       unsigned &UnsortedOps = Degree[U];
9246       if (0 == --UnsortedOps)
9247         Order.push_back(U);
9248     }
9249   }
9250 }
9251 
9252 #ifndef NDEBUG
9253 void SelectionDAG::VerifyDAGDiverence() {
9254   std::vector<SDNode *> TopoOrder;
9255   CreateTopologicalOrder(TopoOrder);
9256   for (auto *N : TopoOrder) {
9257     assert(calculateDivergence(N) == N->isDivergent() &&
9258            "Divergence bit inconsistency detected");
9259   }
9260 }
9261 #endif
9262 
9263 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9264 /// uses of other values produced by From.getNode() alone.  The same value
9265 /// may appear in both the From and To list.  The Deleted vector is
9266 /// handled the same way as for ReplaceAllUsesWith.
9267 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9268                                               const SDValue *To,
9269                                               unsigned Num){
9270   // Handle the simple, trivial case efficiently.
9271   if (Num == 1)
9272     return ReplaceAllUsesOfValueWith(*From, *To);
9273 
9274   transferDbgValues(*From, *To);
9275 
9276   // Read up all the uses and make records of them. This helps
9277   // processing new uses that are introduced during the
9278   // replacement process.
9279   SmallVector<UseMemo, 4> Uses;
9280   for (unsigned i = 0; i != Num; ++i) {
9281     unsigned FromResNo = From[i].getResNo();
9282     SDNode *FromNode = From[i].getNode();
9283     for (SDNode::use_iterator UI = FromNode->use_begin(),
9284          E = FromNode->use_end(); UI != E; ++UI) {
9285       SDUse &Use = UI.getUse();
9286       if (Use.getResNo() == FromResNo) {
9287         UseMemo Memo = { *UI, i, &Use };
9288         Uses.push_back(Memo);
9289       }
9290     }
9291   }
9292 
9293   // Sort the uses, so that all the uses from a given User are together.
9294   llvm::sort(Uses);
9295 
9296   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9297        UseIndex != UseIndexEnd; ) {
9298     // We know that this user uses some value of From.  If it is the right
9299     // value, update it.
9300     SDNode *User = Uses[UseIndex].User;
9301 
9302     // This node is about to morph, remove its old self from the CSE maps.
9303     RemoveNodeFromCSEMaps(User);
9304 
9305     // The Uses array is sorted, so all the uses for a given User
9306     // are next to each other in the list.
9307     // To help reduce the number of CSE recomputations, process all
9308     // the uses of this user that we can find this way.
9309     do {
9310       unsigned i = Uses[UseIndex].Index;
9311       SDUse &Use = *Uses[UseIndex].Use;
9312       ++UseIndex;
9313 
9314       Use.set(To[i]);
9315     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9316 
9317     // Now that we have modified User, add it back to the CSE maps.  If it
9318     // already exists there, recursively merge the results together.
9319     AddModifiedNodeToCSEMaps(User);
9320   }
9321 }
9322 
9323 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9324 /// based on their topological order. It returns the maximum id and a vector
9325 /// of the SDNodes* in assigned order by reference.
9326 unsigned SelectionDAG::AssignTopologicalOrder() {
9327   unsigned DAGSize = 0;
9328 
9329   // SortedPos tracks the progress of the algorithm. Nodes before it are
9330   // sorted, nodes after it are unsorted. When the algorithm completes
9331   // it is at the end of the list.
9332   allnodes_iterator SortedPos = allnodes_begin();
9333 
9334   // Visit all the nodes. Move nodes with no operands to the front of
9335   // the list immediately. Annotate nodes that do have operands with their
9336   // operand count. Before we do this, the Node Id fields of the nodes
9337   // may contain arbitrary values. After, the Node Id fields for nodes
9338   // before SortedPos will contain the topological sort index, and the
9339   // Node Id fields for nodes At SortedPos and after will contain the
9340   // count of outstanding operands.
9341   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
9342     SDNode *N = &*I++;
9343     checkForCycles(N, this);
9344     unsigned Degree = N->getNumOperands();
9345     if (Degree == 0) {
9346       // A node with no uses, add it to the result array immediately.
9347       N->setNodeId(DAGSize++);
9348       allnodes_iterator Q(N);
9349       if (Q != SortedPos)
9350         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9351       assert(SortedPos != AllNodes.end() && "Overran node list");
9352       ++SortedPos;
9353     } else {
9354       // Temporarily use the Node Id as scratch space for the degree count.
9355       N->setNodeId(Degree);
9356     }
9357   }
9358 
9359   // Visit all the nodes. As we iterate, move nodes into sorted order,
9360   // such that by the time the end is reached all nodes will be sorted.
9361   for (SDNode &Node : allnodes()) {
9362     SDNode *N = &Node;
9363     checkForCycles(N, this);
9364     // N is in sorted position, so all its uses have one less operand
9365     // that needs to be sorted.
9366     for (SDNode *P : N->uses()) {
9367       unsigned Degree = P->getNodeId();
9368       assert(Degree != 0 && "Invalid node degree");
9369       --Degree;
9370       if (Degree == 0) {
9371         // All of P's operands are sorted, so P may sorted now.
9372         P->setNodeId(DAGSize++);
9373         if (P->getIterator() != SortedPos)
9374           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9375         assert(SortedPos != AllNodes.end() && "Overran node list");
9376         ++SortedPos;
9377       } else {
9378         // Update P's outstanding operand count.
9379         P->setNodeId(Degree);
9380       }
9381     }
9382     if (Node.getIterator() == SortedPos) {
9383 #ifndef NDEBUG
9384       allnodes_iterator I(N);
9385       SDNode *S = &*++I;
9386       dbgs() << "Overran sorted position:\n";
9387       S->dumprFull(this); dbgs() << "\n";
9388       dbgs() << "Checking if this is due to cycles\n";
9389       checkForCycles(this, true);
9390 #endif
9391       llvm_unreachable(nullptr);
9392     }
9393   }
9394 
9395   assert(SortedPos == AllNodes.end() &&
9396          "Topological sort incomplete!");
9397   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9398          "First node in topological sort is not the entry token!");
9399   assert(AllNodes.front().getNodeId() == 0 &&
9400          "First node in topological sort has non-zero id!");
9401   assert(AllNodes.front().getNumOperands() == 0 &&
9402          "First node in topological sort has operands!");
9403   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9404          "Last node in topologic sort has unexpected id!");
9405   assert(AllNodes.back().use_empty() &&
9406          "Last node in topologic sort has users!");
9407   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9408   return DAGSize;
9409 }
9410 
9411 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9412 /// value is produced by SD.
9413 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9414   for (SDNode *SD : DB->getSDNodes()) {
9415     if (!SD)
9416       continue;
9417     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9418     SD->setHasDebugValue(true);
9419   }
9420   DbgInfo->add(DB, isParameter);
9421 }
9422 
9423 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9424 
9425 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9426                                                    SDValue NewMemOpChain) {
9427   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9428   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9429   // The new memory operation must have the same position as the old load in
9430   // terms of memory dependency. Create a TokenFactor for the old load and new
9431   // memory operation and update uses of the old load's output chain to use that
9432   // TokenFactor.
9433   if (OldChain == NewMemOpChain || OldChain.use_empty())
9434     return NewMemOpChain;
9435 
9436   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9437                                 OldChain, NewMemOpChain);
9438   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9439   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9440   return TokenFactor;
9441 }
9442 
9443 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9444                                                    SDValue NewMemOp) {
9445   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9446   SDValue OldChain = SDValue(OldLoad, 1);
9447   SDValue NewMemOpChain = NewMemOp.getValue(1);
9448   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9449 }
9450 
9451 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9452                                                      Function **OutFunction) {
9453   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9454 
9455   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9456   auto *Module = MF->getFunction().getParent();
9457   auto *Function = Module->getFunction(Symbol);
9458 
9459   if (OutFunction != nullptr)
9460       *OutFunction = Function;
9461 
9462   if (Function != nullptr) {
9463     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9464     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9465   }
9466 
9467   std::string ErrorStr;
9468   raw_string_ostream ErrorFormatter(ErrorStr);
9469 
9470   ErrorFormatter << "Undefined external symbol ";
9471   ErrorFormatter << '"' << Symbol << '"';
9472   ErrorFormatter.flush();
9473 
9474   report_fatal_error(ErrorStr);
9475 }
9476 
9477 //===----------------------------------------------------------------------===//
9478 //                              SDNode Class
9479 //===----------------------------------------------------------------------===//
9480 
9481 bool llvm::isNullConstant(SDValue V) {
9482   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9483   return Const != nullptr && Const->isNullValue();
9484 }
9485 
9486 bool llvm::isNullFPConstant(SDValue V) {
9487   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9488   return Const != nullptr && Const->isZero() && !Const->isNegative();
9489 }
9490 
9491 bool llvm::isAllOnesConstant(SDValue V) {
9492   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9493   return Const != nullptr && Const->isAllOnesValue();
9494 }
9495 
9496 bool llvm::isOneConstant(SDValue V) {
9497   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9498   return Const != nullptr && Const->isOne();
9499 }
9500 
9501 SDValue llvm::peekThroughBitcasts(SDValue V) {
9502   while (V.getOpcode() == ISD::BITCAST)
9503     V = V.getOperand(0);
9504   return V;
9505 }
9506 
9507 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9508   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9509     V = V.getOperand(0);
9510   return V;
9511 }
9512 
9513 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9514   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9515     V = V.getOperand(0);
9516   return V;
9517 }
9518 
9519 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9520   if (V.getOpcode() != ISD::XOR)
9521     return false;
9522   V = peekThroughBitcasts(V.getOperand(1));
9523   unsigned NumBits = V.getScalarValueSizeInBits();
9524   ConstantSDNode *C =
9525       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9526   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9527 }
9528 
9529 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9530                                           bool AllowTruncation) {
9531   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9532     return CN;
9533 
9534   // SplatVectors can truncate their operands. Ignore that case here unless
9535   // AllowTruncation is set.
9536   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9537     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9538     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9539       EVT CVT = CN->getValueType(0);
9540       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9541       if (AllowTruncation || CVT == VecEltVT)
9542         return CN;
9543     }
9544   }
9545 
9546   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9547     BitVector UndefElements;
9548     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9549 
9550     // BuildVectors can truncate their operands. Ignore that case here unless
9551     // AllowTruncation is set.
9552     if (CN && (UndefElements.none() || AllowUndefs)) {
9553       EVT CVT = CN->getValueType(0);
9554       EVT NSVT = N.getValueType().getScalarType();
9555       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9556       if (AllowTruncation || (CVT == NSVT))
9557         return CN;
9558     }
9559   }
9560 
9561   return nullptr;
9562 }
9563 
9564 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9565                                           bool AllowUndefs,
9566                                           bool AllowTruncation) {
9567   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9568     return CN;
9569 
9570   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9571     BitVector UndefElements;
9572     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9573 
9574     // BuildVectors can truncate their operands. Ignore that case here unless
9575     // AllowTruncation is set.
9576     if (CN && (UndefElements.none() || AllowUndefs)) {
9577       EVT CVT = CN->getValueType(0);
9578       EVT NSVT = N.getValueType().getScalarType();
9579       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9580       if (AllowTruncation || (CVT == NSVT))
9581         return CN;
9582     }
9583   }
9584 
9585   return nullptr;
9586 }
9587 
9588 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
9589   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9590     return CN;
9591 
9592   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9593     BitVector UndefElements;
9594     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
9595     if (CN && (UndefElements.none() || AllowUndefs))
9596       return CN;
9597   }
9598 
9599   if (N.getOpcode() == ISD::SPLAT_VECTOR)
9600     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
9601       return CN;
9602 
9603   return nullptr;
9604 }
9605 
9606 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
9607                                               const APInt &DemandedElts,
9608                                               bool AllowUndefs) {
9609   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9610     return CN;
9611 
9612   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9613     BitVector UndefElements;
9614     ConstantFPSDNode *CN =
9615         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
9616     if (CN && (UndefElements.none() || AllowUndefs))
9617       return CN;
9618   }
9619 
9620   return nullptr;
9621 }
9622 
9623 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
9624   // TODO: may want to use peekThroughBitcast() here.
9625   ConstantSDNode *C =
9626       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
9627   return C && C->isNullValue();
9628 }
9629 
9630 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
9631   // TODO: may want to use peekThroughBitcast() here.
9632   unsigned BitWidth = N.getScalarValueSizeInBits();
9633   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9634   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
9635 }
9636 
9637 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
9638   N = peekThroughBitcasts(N);
9639   unsigned BitWidth = N.getScalarValueSizeInBits();
9640   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9641   return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
9642 }
9643 
9644 HandleSDNode::~HandleSDNode() {
9645   DropOperands();
9646 }
9647 
9648 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
9649                                          const DebugLoc &DL,
9650                                          const GlobalValue *GA, EVT VT,
9651                                          int64_t o, unsigned TF)
9652     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
9653   TheGlobal = GA;
9654 }
9655 
9656 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
9657                                          EVT VT, unsigned SrcAS,
9658                                          unsigned DestAS)
9659     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
9660       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
9661 
9662 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
9663                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
9664     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
9665   MemSDNodeBits.IsVolatile = MMO->isVolatile();
9666   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
9667   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
9668   MemSDNodeBits.IsInvariant = MMO->isInvariant();
9669 
9670   // We check here that the size of the memory operand fits within the size of
9671   // the MMO. This is because the MMO might indicate only a possible address
9672   // range instead of specifying the affected memory addresses precisely.
9673   // TODO: Make MachineMemOperands aware of scalable vectors.
9674   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
9675          "Size mismatch!");
9676 }
9677 
9678 /// Profile - Gather unique data for the node.
9679 ///
9680 void SDNode::Profile(FoldingSetNodeID &ID) const {
9681   AddNodeIDNode(ID, this);
9682 }
9683 
9684 namespace {
9685 
9686   struct EVTArray {
9687     std::vector<EVT> VTs;
9688 
9689     EVTArray() {
9690       VTs.reserve(MVT::VALUETYPE_SIZE);
9691       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
9692         VTs.push_back(MVT((MVT::SimpleValueType)i));
9693     }
9694   };
9695 
9696 } // end anonymous namespace
9697 
9698 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
9699 static ManagedStatic<EVTArray> SimpleVTArray;
9700 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
9701 
9702 /// getValueTypeList - Return a pointer to the specified value type.
9703 ///
9704 const EVT *SDNode::getValueTypeList(EVT VT) {
9705   if (VT.isExtended()) {
9706     sys::SmartScopedLock<true> Lock(*VTMutex);
9707     return &(*EVTs->insert(VT).first);
9708   }
9709   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
9710   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
9711 }
9712 
9713 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
9714 /// indicated value.  This method ignores uses of other values defined by this
9715 /// operation.
9716 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
9717   assert(Value < getNumValues() && "Bad value!");
9718 
9719   // TODO: Only iterate over uses of a given value of the node
9720   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
9721     if (UI.getUse().getResNo() == Value) {
9722       if (NUses == 0)
9723         return false;
9724       --NUses;
9725     }
9726   }
9727 
9728   // Found exactly the right number of uses?
9729   return NUses == 0;
9730 }
9731 
9732 /// hasAnyUseOfValue - Return true if there are any use of the indicated
9733 /// value. This method ignores uses of other values defined by this operation.
9734 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
9735   assert(Value < getNumValues() && "Bad value!");
9736 
9737   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
9738     if (UI.getUse().getResNo() == Value)
9739       return true;
9740 
9741   return false;
9742 }
9743 
9744 /// isOnlyUserOf - Return true if this node is the only use of N.
9745 bool SDNode::isOnlyUserOf(const SDNode *N) const {
9746   bool Seen = false;
9747   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9748     SDNode *User = *I;
9749     if (User == this)
9750       Seen = true;
9751     else
9752       return false;
9753   }
9754 
9755   return Seen;
9756 }
9757 
9758 /// Return true if the only users of N are contained in Nodes.
9759 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
9760   bool Seen = false;
9761   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9762     SDNode *User = *I;
9763     if (llvm::is_contained(Nodes, User))
9764       Seen = true;
9765     else
9766       return false;
9767   }
9768 
9769   return Seen;
9770 }
9771 
9772 /// isOperand - Return true if this node is an operand of N.
9773 bool SDValue::isOperandOf(const SDNode *N) const {
9774   return is_contained(N->op_values(), *this);
9775 }
9776 
9777 bool SDNode::isOperandOf(const SDNode *N) const {
9778   return any_of(N->op_values(),
9779                 [this](SDValue Op) { return this == Op.getNode(); });
9780 }
9781 
9782 /// reachesChainWithoutSideEffects - Return true if this operand (which must
9783 /// be a chain) reaches the specified operand without crossing any
9784 /// side-effecting instructions on any chain path.  In practice, this looks
9785 /// through token factors and non-volatile loads.  In order to remain efficient,
9786 /// this only looks a couple of nodes in, it does not do an exhaustive search.
9787 ///
9788 /// Note that we only need to examine chains when we're searching for
9789 /// side-effects; SelectionDAG requires that all side-effects are represented
9790 /// by chains, even if another operand would force a specific ordering. This
9791 /// constraint is necessary to allow transformations like splitting loads.
9792 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
9793                                              unsigned Depth) const {
9794   if (*this == Dest) return true;
9795 
9796   // Don't search too deeply, we just want to be able to see through
9797   // TokenFactor's etc.
9798   if (Depth == 0) return false;
9799 
9800   // If this is a token factor, all inputs to the TF happen in parallel.
9801   if (getOpcode() == ISD::TokenFactor) {
9802     // First, try a shallow search.
9803     if (is_contained((*this)->ops(), Dest)) {
9804       // We found the chain we want as an operand of this TokenFactor.
9805       // Essentially, we reach the chain without side-effects if we could
9806       // serialize the TokenFactor into a simple chain of operations with
9807       // Dest as the last operation. This is automatically true if the
9808       // chain has one use: there are no other ordering constraints.
9809       // If the chain has more than one use, we give up: some other
9810       // use of Dest might force a side-effect between Dest and the current
9811       // node.
9812       if (Dest.hasOneUse())
9813         return true;
9814     }
9815     // Next, try a deep search: check whether every operand of the TokenFactor
9816     // reaches Dest.
9817     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
9818       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
9819     });
9820   }
9821 
9822   // Loads don't have side effects, look through them.
9823   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
9824     if (Ld->isUnordered())
9825       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
9826   }
9827   return false;
9828 }
9829 
9830 bool SDNode::hasPredecessor(const SDNode *N) const {
9831   SmallPtrSet<const SDNode *, 32> Visited;
9832   SmallVector<const SDNode *, 16> Worklist;
9833   Worklist.push_back(this);
9834   return hasPredecessorHelper(N, Visited, Worklist);
9835 }
9836 
9837 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
9838   this->Flags.intersectWith(Flags);
9839 }
9840 
9841 SDValue
9842 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
9843                                   ArrayRef<ISD::NodeType> CandidateBinOps,
9844                                   bool AllowPartials) {
9845   // The pattern must end in an extract from index 0.
9846   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9847       !isNullConstant(Extract->getOperand(1)))
9848     return SDValue();
9849 
9850   // Match against one of the candidate binary ops.
9851   SDValue Op = Extract->getOperand(0);
9852   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9853         return Op.getOpcode() == unsigned(BinOp);
9854       }))
9855     return SDValue();
9856 
9857   // Floating-point reductions may require relaxed constraints on the final step
9858   // of the reduction because they may reorder intermediate operations.
9859   unsigned CandidateBinOp = Op.getOpcode();
9860   if (Op.getValueType().isFloatingPoint()) {
9861     SDNodeFlags Flags = Op->getFlags();
9862     switch (CandidateBinOp) {
9863     case ISD::FADD:
9864       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
9865         return SDValue();
9866       break;
9867     default:
9868       llvm_unreachable("Unhandled FP opcode for binop reduction");
9869     }
9870   }
9871 
9872   // Matching failed - attempt to see if we did enough stages that a partial
9873   // reduction from a subvector is possible.
9874   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
9875     if (!AllowPartials || !Op)
9876       return SDValue();
9877     EVT OpVT = Op.getValueType();
9878     EVT OpSVT = OpVT.getScalarType();
9879     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
9880     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
9881       return SDValue();
9882     BinOp = (ISD::NodeType)CandidateBinOp;
9883     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
9884                    getVectorIdxConstant(0, SDLoc(Op)));
9885   };
9886 
9887   // At each stage, we're looking for something that looks like:
9888   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9889   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9890   //                               i32 undef, i32 undef, i32 undef, i32 undef>
9891   // %a = binop <8 x i32> %op, %s
9892   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9893   // we expect something like:
9894   // <4,5,6,7,u,u,u,u>
9895   // <2,3,u,u,u,u,u,u>
9896   // <1,u,u,u,u,u,u,u>
9897   // While a partial reduction match would be:
9898   // <2,3,u,u,u,u,u,u>
9899   // <1,u,u,u,u,u,u,u>
9900   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9901   SDValue PrevOp;
9902   for (unsigned i = 0; i < Stages; ++i) {
9903     unsigned MaskEnd = (1 << i);
9904 
9905     if (Op.getOpcode() != CandidateBinOp)
9906       return PartialReduction(PrevOp, MaskEnd);
9907 
9908     SDValue Op0 = Op.getOperand(0);
9909     SDValue Op1 = Op.getOperand(1);
9910 
9911     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9912     if (Shuffle) {
9913       Op = Op1;
9914     } else {
9915       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9916       Op = Op0;
9917     }
9918 
9919     // The first operand of the shuffle should be the same as the other operand
9920     // of the binop.
9921     if (!Shuffle || Shuffle->getOperand(0) != Op)
9922       return PartialReduction(PrevOp, MaskEnd);
9923 
9924     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9925     for (int Index = 0; Index < (int)MaskEnd; ++Index)
9926       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
9927         return PartialReduction(PrevOp, MaskEnd);
9928 
9929     PrevOp = Op;
9930   }
9931 
9932   // Handle subvector reductions, which tend to appear after the shuffle
9933   // reduction stages.
9934   while (Op.getOpcode() == CandidateBinOp) {
9935     unsigned NumElts = Op.getValueType().getVectorNumElements();
9936     SDValue Op0 = Op.getOperand(0);
9937     SDValue Op1 = Op.getOperand(1);
9938     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9939         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9940         Op0.getOperand(0) != Op1.getOperand(0))
9941       break;
9942     SDValue Src = Op0.getOperand(0);
9943     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
9944     if (NumSrcElts != (2 * NumElts))
9945       break;
9946     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
9947           Op1.getConstantOperandAPInt(1) == NumElts) &&
9948         !(Op1.getConstantOperandAPInt(1) == 0 &&
9949           Op0.getConstantOperandAPInt(1) == NumElts))
9950       break;
9951     Op = Src;
9952   }
9953 
9954   BinOp = (ISD::NodeType)CandidateBinOp;
9955   return Op;
9956 }
9957 
9958 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9959   assert(N->getNumValues() == 1 &&
9960          "Can't unroll a vector with multiple results!");
9961 
9962   EVT VT = N->getValueType(0);
9963   unsigned NE = VT.getVectorNumElements();
9964   EVT EltVT = VT.getVectorElementType();
9965   SDLoc dl(N);
9966 
9967   SmallVector<SDValue, 8> Scalars;
9968   SmallVector<SDValue, 4> Operands(N->getNumOperands());
9969 
9970   // If ResNE is 0, fully unroll the vector op.
9971   if (ResNE == 0)
9972     ResNE = NE;
9973   else if (NE > ResNE)
9974     NE = ResNE;
9975 
9976   unsigned i;
9977   for (i= 0; i != NE; ++i) {
9978     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9979       SDValue Operand = N->getOperand(j);
9980       EVT OperandVT = Operand.getValueType();
9981       if (OperandVT.isVector()) {
9982         // A vector operand; extract a single element.
9983         EVT OperandEltVT = OperandVT.getVectorElementType();
9984         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
9985                               Operand, getVectorIdxConstant(i, dl));
9986       } else {
9987         // A scalar operand; just use it as is.
9988         Operands[j] = Operand;
9989       }
9990     }
9991 
9992     switch (N->getOpcode()) {
9993     default: {
9994       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9995                                 N->getFlags()));
9996       break;
9997     }
9998     case ISD::VSELECT:
9999       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10000       break;
10001     case ISD::SHL:
10002     case ISD::SRA:
10003     case ISD::SRL:
10004     case ISD::ROTL:
10005     case ISD::ROTR:
10006       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10007                                getShiftAmountOperand(Operands[0].getValueType(),
10008                                                      Operands[1])));
10009       break;
10010     case ISD::SIGN_EXTEND_INREG: {
10011       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10012       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10013                                 Operands[0],
10014                                 getValueType(ExtVT)));
10015     }
10016     }
10017   }
10018 
10019   for (; i < ResNE; ++i)
10020     Scalars.push_back(getUNDEF(EltVT));
10021 
10022   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10023   return getBuildVector(VecVT, dl, Scalars);
10024 }
10025 
10026 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10027     SDNode *N, unsigned ResNE) {
10028   unsigned Opcode = N->getOpcode();
10029   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10030           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10031           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10032          "Expected an overflow opcode");
10033 
10034   EVT ResVT = N->getValueType(0);
10035   EVT OvVT = N->getValueType(1);
10036   EVT ResEltVT = ResVT.getVectorElementType();
10037   EVT OvEltVT = OvVT.getVectorElementType();
10038   SDLoc dl(N);
10039 
10040   // If ResNE is 0, fully unroll the vector op.
10041   unsigned NE = ResVT.getVectorNumElements();
10042   if (ResNE == 0)
10043     ResNE = NE;
10044   else if (NE > ResNE)
10045     NE = ResNE;
10046 
10047   SmallVector<SDValue, 8> LHSScalars;
10048   SmallVector<SDValue, 8> RHSScalars;
10049   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10050   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10051 
10052   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10053   SDVTList VTs = getVTList(ResEltVT, SVT);
10054   SmallVector<SDValue, 8> ResScalars;
10055   SmallVector<SDValue, 8> OvScalars;
10056   for (unsigned i = 0; i < NE; ++i) {
10057     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10058     SDValue Ov =
10059         getSelect(dl, OvEltVT, Res.getValue(1),
10060                   getBoolConstant(true, dl, OvEltVT, ResVT),
10061                   getConstant(0, dl, OvEltVT));
10062 
10063     ResScalars.push_back(Res);
10064     OvScalars.push_back(Ov);
10065   }
10066 
10067   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10068   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10069 
10070   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10071   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10072   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10073                         getBuildVector(NewOvVT, dl, OvScalars));
10074 }
10075 
10076 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10077                                                   LoadSDNode *Base,
10078                                                   unsigned Bytes,
10079                                                   int Dist) const {
10080   if (LD->isVolatile() || Base->isVolatile())
10081     return false;
10082   // TODO: probably too restrictive for atomics, revisit
10083   if (!LD->isSimple())
10084     return false;
10085   if (LD->isIndexed() || Base->isIndexed())
10086     return false;
10087   if (LD->getChain() != Base->getChain())
10088     return false;
10089   EVT VT = LD->getValueType(0);
10090   if (VT.getSizeInBits() / 8 != Bytes)
10091     return false;
10092 
10093   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10094   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10095 
10096   int64_t Offset = 0;
10097   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10098     return (Dist * Bytes == Offset);
10099   return false;
10100 }
10101 
10102 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10103 /// if it cannot be inferred.
10104 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10105   // If this is a GlobalAddress + cst, return the alignment.
10106   const GlobalValue *GV = nullptr;
10107   int64_t GVOffset = 0;
10108   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10109     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10110     KnownBits Known(PtrWidth);
10111     llvm::computeKnownBits(GV, Known, getDataLayout());
10112     unsigned AlignBits = Known.countMinTrailingZeros();
10113     if (AlignBits)
10114       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10115   }
10116 
10117   // If this is a direct reference to a stack slot, use information about the
10118   // stack slot's alignment.
10119   int FrameIdx = INT_MIN;
10120   int64_t FrameOffset = 0;
10121   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10122     FrameIdx = FI->getIndex();
10123   } else if (isBaseWithConstantOffset(Ptr) &&
10124              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10125     // Handle FI+Cst
10126     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10127     FrameOffset = Ptr.getConstantOperandVal(1);
10128   }
10129 
10130   if (FrameIdx != INT_MIN) {
10131     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10132     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10133   }
10134 
10135   return None;
10136 }
10137 
10138 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10139 /// which is split (or expanded) into two not necessarily identical pieces.
10140 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10141   // Currently all types are split in half.
10142   EVT LoVT, HiVT;
10143   if (!VT.isVector())
10144     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10145   else
10146     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10147 
10148   return std::make_pair(LoVT, HiVT);
10149 }
10150 
10151 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10152 /// type, dependent on an enveloping VT that has been split into two identical
10153 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10154 std::pair<EVT, EVT>
10155 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10156                                        bool *HiIsEmpty) const {
10157   EVT EltTp = VT.getVectorElementType();
10158   // Examples:
10159   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10160   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10161   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10162   //   etc.
10163   ElementCount VTNumElts = VT.getVectorElementCount();
10164   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10165   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10166          "Mixing fixed width and scalable vectors when enveloping a type");
10167   EVT LoVT, HiVT;
10168   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10169     LoVT = EnvVT;
10170     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10171     *HiIsEmpty = false;
10172   } else {
10173     // Flag that hi type has zero storage size, but return split envelop type
10174     // (this would be easier if vector types with zero elements were allowed).
10175     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10176     HiVT = EnvVT;
10177     *HiIsEmpty = true;
10178   }
10179   return std::make_pair(LoVT, HiVT);
10180 }
10181 
10182 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10183 /// low/high part.
10184 std::pair<SDValue, SDValue>
10185 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10186                           const EVT &HiVT) {
10187   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10188          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10189          "Splitting vector with an invalid mixture of fixed and scalable "
10190          "vector types");
10191   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10192              N.getValueType().getVectorMinNumElements() &&
10193          "More vector elements requested than available!");
10194   SDValue Lo, Hi;
10195   Lo =
10196       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10197   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10198   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10199   // IDX with the runtime scaling factor of the result vector type. For
10200   // fixed-width result vectors, that runtime scaling factor is 1.
10201   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10202                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10203   return std::make_pair(Lo, Hi);
10204 }
10205 
10206 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10207 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10208   EVT VT = N.getValueType();
10209   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10210                                 NextPowerOf2(VT.getVectorNumElements()));
10211   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10212                  getVectorIdxConstant(0, DL));
10213 }
10214 
10215 void SelectionDAG::ExtractVectorElements(SDValue Op,
10216                                          SmallVectorImpl<SDValue> &Args,
10217                                          unsigned Start, unsigned Count,
10218                                          EVT EltVT) {
10219   EVT VT = Op.getValueType();
10220   if (Count == 0)
10221     Count = VT.getVectorNumElements();
10222   if (EltVT == EVT())
10223     EltVT = VT.getVectorElementType();
10224   SDLoc SL(Op);
10225   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10226     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10227                            getVectorIdxConstant(i, SL)));
10228   }
10229 }
10230 
10231 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10232 unsigned GlobalAddressSDNode::getAddressSpace() const {
10233   return getGlobal()->getType()->getAddressSpace();
10234 }
10235 
10236 Type *ConstantPoolSDNode::getType() const {
10237   if (isMachineConstantPoolEntry())
10238     return Val.MachineCPVal->getType();
10239   return Val.ConstVal->getType();
10240 }
10241 
10242 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10243                                         unsigned &SplatBitSize,
10244                                         bool &HasAnyUndefs,
10245                                         unsigned MinSplatBits,
10246                                         bool IsBigEndian) const {
10247   EVT VT = getValueType(0);
10248   assert(VT.isVector() && "Expected a vector type");
10249   unsigned VecWidth = VT.getSizeInBits();
10250   if (MinSplatBits > VecWidth)
10251     return false;
10252 
10253   // FIXME: The widths are based on this node's type, but build vectors can
10254   // truncate their operands.
10255   SplatValue = APInt(VecWidth, 0);
10256   SplatUndef = APInt(VecWidth, 0);
10257 
10258   // Get the bits. Bits with undefined values (when the corresponding element
10259   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10260   // in SplatValue. If any of the values are not constant, give up and return
10261   // false.
10262   unsigned int NumOps = getNumOperands();
10263   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10264   unsigned EltWidth = VT.getScalarSizeInBits();
10265 
10266   for (unsigned j = 0; j < NumOps; ++j) {
10267     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10268     SDValue OpVal = getOperand(i);
10269     unsigned BitPos = j * EltWidth;
10270 
10271     if (OpVal.isUndef())
10272       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10273     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10274       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10275     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10276       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10277     else
10278       return false;
10279   }
10280 
10281   // The build_vector is all constants or undefs. Find the smallest element
10282   // size that splats the vector.
10283   HasAnyUndefs = (SplatUndef != 0);
10284 
10285   // FIXME: This does not work for vectors with elements less than 8 bits.
10286   while (VecWidth > 8) {
10287     unsigned HalfSize = VecWidth / 2;
10288     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10289     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10290     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10291     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10292 
10293     // If the two halves do not match (ignoring undef bits), stop here.
10294     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10295         MinSplatBits > HalfSize)
10296       break;
10297 
10298     SplatValue = HighValue | LowValue;
10299     SplatUndef = HighUndef & LowUndef;
10300 
10301     VecWidth = HalfSize;
10302   }
10303 
10304   SplatBitSize = VecWidth;
10305   return true;
10306 }
10307 
10308 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10309                                          BitVector *UndefElements) const {
10310   unsigned NumOps = getNumOperands();
10311   if (UndefElements) {
10312     UndefElements->clear();
10313     UndefElements->resize(NumOps);
10314   }
10315   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10316   if (!DemandedElts)
10317     return SDValue();
10318   SDValue Splatted;
10319   for (unsigned i = 0; i != NumOps; ++i) {
10320     if (!DemandedElts[i])
10321       continue;
10322     SDValue Op = getOperand(i);
10323     if (Op.isUndef()) {
10324       if (UndefElements)
10325         (*UndefElements)[i] = true;
10326     } else if (!Splatted) {
10327       Splatted = Op;
10328     } else if (Splatted != Op) {
10329       return SDValue();
10330     }
10331   }
10332 
10333   if (!Splatted) {
10334     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10335     assert(getOperand(FirstDemandedIdx).isUndef() &&
10336            "Can only have a splat without a constant for all undefs.");
10337     return getOperand(FirstDemandedIdx);
10338   }
10339 
10340   return Splatted;
10341 }
10342 
10343 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10344   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10345   return getSplatValue(DemandedElts, UndefElements);
10346 }
10347 
10348 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10349                                             SmallVectorImpl<SDValue> &Sequence,
10350                                             BitVector *UndefElements) const {
10351   unsigned NumOps = getNumOperands();
10352   Sequence.clear();
10353   if (UndefElements) {
10354     UndefElements->clear();
10355     UndefElements->resize(NumOps);
10356   }
10357   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10358   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10359     return false;
10360 
10361   // Set the undefs even if we don't find a sequence (like getSplatValue).
10362   if (UndefElements)
10363     for (unsigned I = 0; I != NumOps; ++I)
10364       if (DemandedElts[I] && getOperand(I).isUndef())
10365         (*UndefElements)[I] = true;
10366 
10367   // Iteratively widen the sequence length looking for repetitions.
10368   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10369     Sequence.append(SeqLen, SDValue());
10370     for (unsigned I = 0; I != NumOps; ++I) {
10371       if (!DemandedElts[I])
10372         continue;
10373       SDValue &SeqOp = Sequence[I % SeqLen];
10374       SDValue Op = getOperand(I);
10375       if (Op.isUndef()) {
10376         if (!SeqOp)
10377           SeqOp = Op;
10378         continue;
10379       }
10380       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10381         Sequence.clear();
10382         break;
10383       }
10384       SeqOp = Op;
10385     }
10386     if (!Sequence.empty())
10387       return true;
10388   }
10389 
10390   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10391   return false;
10392 }
10393 
10394 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10395                                             BitVector *UndefElements) const {
10396   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10397   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10398 }
10399 
10400 ConstantSDNode *
10401 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10402                                         BitVector *UndefElements) const {
10403   return dyn_cast_or_null<ConstantSDNode>(
10404       getSplatValue(DemandedElts, UndefElements));
10405 }
10406 
10407 ConstantSDNode *
10408 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10409   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10410 }
10411 
10412 ConstantFPSDNode *
10413 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10414                                           BitVector *UndefElements) const {
10415   return dyn_cast_or_null<ConstantFPSDNode>(
10416       getSplatValue(DemandedElts, UndefElements));
10417 }
10418 
10419 ConstantFPSDNode *
10420 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10421   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10422 }
10423 
10424 int32_t
10425 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10426                                                    uint32_t BitWidth) const {
10427   if (ConstantFPSDNode *CN =
10428           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10429     bool IsExact;
10430     APSInt IntVal(BitWidth);
10431     const APFloat &APF = CN->getValueAPF();
10432     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10433             APFloat::opOK ||
10434         !IsExact)
10435       return -1;
10436 
10437     return IntVal.exactLogBase2();
10438   }
10439   return -1;
10440 }
10441 
10442 bool BuildVectorSDNode::isConstant() const {
10443   for (const SDValue &Op : op_values()) {
10444     unsigned Opc = Op.getOpcode();
10445     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10446       return false;
10447   }
10448   return true;
10449 }
10450 
10451 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10452   // Find the first non-undef value in the shuffle mask.
10453   unsigned i, e;
10454   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10455     /* search */;
10456 
10457   // If all elements are undefined, this shuffle can be considered a splat
10458   // (although it should eventually get simplified away completely).
10459   if (i == e)
10460     return true;
10461 
10462   // Make sure all remaining elements are either undef or the same as the first
10463   // non-undef value.
10464   for (int Idx = Mask[i]; i != e; ++i)
10465     if (Mask[i] >= 0 && Mask[i] != Idx)
10466       return false;
10467   return true;
10468 }
10469 
10470 // Returns the SDNode if it is a constant integer BuildVector
10471 // or constant integer.
10472 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10473   if (isa<ConstantSDNode>(N))
10474     return N.getNode();
10475   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10476     return N.getNode();
10477   // Treat a GlobalAddress supporting constant offset folding as a
10478   // constant integer.
10479   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10480     if (GA->getOpcode() == ISD::GlobalAddress &&
10481         TLI->isOffsetFoldingLegal(GA))
10482       return GA;
10483   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10484       isa<ConstantSDNode>(N.getOperand(0)))
10485     return N.getNode();
10486   return nullptr;
10487 }
10488 
10489 // Returns the SDNode if it is a constant float BuildVector
10490 // or constant float.
10491 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10492   if (isa<ConstantFPSDNode>(N))
10493     return N.getNode();
10494 
10495   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10496     return N.getNode();
10497 
10498   return nullptr;
10499 }
10500 
10501 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10502   assert(!Node->OperandList && "Node already has operands");
10503   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
10504          "too many operands to fit into SDNode");
10505   SDUse *Ops = OperandRecycler.allocate(
10506       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10507 
10508   bool IsDivergent = false;
10509   for (unsigned I = 0; I != Vals.size(); ++I) {
10510     Ops[I].setUser(Node);
10511     Ops[I].setInitial(Vals[I]);
10512     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10513       IsDivergent |= Ops[I].getNode()->isDivergent();
10514   }
10515   Node->NumOperands = Vals.size();
10516   Node->OperandList = Ops;
10517   if (!TLI->isSDNodeAlwaysUniform(Node)) {
10518     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10519     Node->SDNodeBits.IsDivergent = IsDivergent;
10520   }
10521   checkForCycles(Node);
10522 }
10523 
10524 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10525                                      SmallVectorImpl<SDValue> &Vals) {
10526   size_t Limit = SDNode::getMaxNumOperands();
10527   while (Vals.size() > Limit) {
10528     unsigned SliceIdx = Vals.size() - Limit;
10529     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
10530     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
10531     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
10532     Vals.emplace_back(NewTF);
10533   }
10534   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
10535 }
10536 
10537 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
10538                                         EVT VT, SDNodeFlags Flags) {
10539   switch (Opcode) {
10540   default:
10541     return SDValue();
10542   case ISD::ADD:
10543   case ISD::OR:
10544   case ISD::XOR:
10545   case ISD::UMAX:
10546     return getConstant(0, DL, VT);
10547   case ISD::MUL:
10548     return getConstant(1, DL, VT);
10549   case ISD::AND:
10550   case ISD::UMIN:
10551     return getAllOnesConstant(DL, VT);
10552   case ISD::SMAX:
10553     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
10554   case ISD::SMIN:
10555     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
10556   case ISD::FADD:
10557     return getConstantFP(-0.0, DL, VT);
10558   case ISD::FMUL:
10559     return getConstantFP(1.0, DL, VT);
10560   case ISD::FMINNUM:
10561   case ISD::FMAXNUM: {
10562     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
10563     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
10564     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
10565                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
10566                         APFloat::getLargest(Semantics);
10567     if (Opcode == ISD::FMAXNUM)
10568       NeutralAF.changeSign();
10569 
10570     return getConstantFP(NeutralAF, DL, VT);
10571   }
10572   }
10573 }
10574 
10575 #ifndef NDEBUG
10576 static void checkForCyclesHelper(const SDNode *N,
10577                                  SmallPtrSetImpl<const SDNode*> &Visited,
10578                                  SmallPtrSetImpl<const SDNode*> &Checked,
10579                                  const llvm::SelectionDAG *DAG) {
10580   // If this node has already been checked, don't check it again.
10581   if (Checked.count(N))
10582     return;
10583 
10584   // If a node has already been visited on this depth-first walk, reject it as
10585   // a cycle.
10586   if (!Visited.insert(N).second) {
10587     errs() << "Detected cycle in SelectionDAG\n";
10588     dbgs() << "Offending node:\n";
10589     N->dumprFull(DAG); dbgs() << "\n";
10590     abort();
10591   }
10592 
10593   for (const SDValue &Op : N->op_values())
10594     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
10595 
10596   Checked.insert(N);
10597   Visited.erase(N);
10598 }
10599 #endif
10600 
10601 void llvm::checkForCycles(const llvm::SDNode *N,
10602                           const llvm::SelectionDAG *DAG,
10603                           bool force) {
10604 #ifndef NDEBUG
10605   bool check = force;
10606 #ifdef EXPENSIVE_CHECKS
10607   check = true;
10608 #endif  // EXPENSIVE_CHECKS
10609   if (check) {
10610     assert(N && "Checking nonexistent SDNode");
10611     SmallPtrSet<const SDNode*, 32> visited;
10612     SmallPtrSet<const SDNode*, 32> checked;
10613     checkForCyclesHelper(N, visited, checked, DAG);
10614   }
10615 #endif  // !NDEBUG
10616 }
10617 
10618 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
10619   checkForCycles(DAG->getRoot().getNode(), DAG, force);
10620 }
10621