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