efb2fff456467de6ec1d2eb475af589bcf517042
[platform/upstream/llvm.git] / llvm / lib / CodeGen / SelectionDAG / SelectionDAG.cpp
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/AliasAnalysis.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/CodeGen/Analysis.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/Support/Casting.h"
58 #include "llvm/Support/CodeGen.h"
59 #include "llvm/Support/Compiler.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/KnownBits.h"
63 #include "llvm/Support/MachineValueType.h"
64 #include "llvm/Support/MathExtras.h"
65 #include "llvm/Support/Mutex.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include "llvm/Target/TargetOptions.h"
69 #include "llvm/Transforms/Utils/SizeOpts.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cstdint>
73 #include <cstdlib>
74 #include <limits>
75 #include <set>
76 #include <string>
77 #include <utility>
78 #include <vector>
79
80 using namespace llvm;
81
82 /// makeVTList - Return an instance of the SDVTList struct initialized with the
83 /// specified members.
84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
85   SDVTList Res = {VTs, NumVTs};
86   return Res;
87 }
88
89 // Default null implementations of the callbacks.
90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
93
94 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
95
96 #define DEBUG_TYPE "selectiondag"
97
98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
99        cl::Hidden, cl::init(true),
100        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
101
102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
103        cl::desc("Number limit for gluing ld/st of memcpy."),
104        cl::Hidden, cl::init(0));
105
106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
107   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
108 }
109
110 //===----------------------------------------------------------------------===//
111 //                              ConstantFPSDNode Class
112 //===----------------------------------------------------------------------===//
113
114 /// isExactlyValue - We don't rely on operator== working on double values, as
115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
116 /// As such, this method can be used to do an exact bit-for-bit comparison of
117 /// two floating point values.
118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
119   return getValueAPF().bitwiseIsEqual(V);
120 }
121
122 bool ConstantFPSDNode::isValueValidForType(EVT VT,
123                                            const APFloat& Val) {
124   assert(VT.isFloatingPoint() && "Can only convert between FP types");
125
126   // convert modifies in place, so make a copy.
127   APFloat Val2 = APFloat(Val);
128   bool losesInfo;
129   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
130                       APFloat::rmNearestTiesToEven,
131                       &losesInfo);
132   return !losesInfo;
133 }
134
135 //===----------------------------------------------------------------------===//
136 //                              ISD Namespace
137 //===----------------------------------------------------------------------===//
138
139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
140   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
141     unsigned EltSize =
142         N->getValueType(0).getVectorElementType().getSizeInBits();
143     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
144       SplatVal = Op0->getAPIntValue().trunc(EltSize);
145       return true;
146     }
147     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
148       SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize);
149       return true;
150     }
151   }
152
153   auto *BV = dyn_cast<BuildVectorSDNode>(N);
154   if (!BV)
155     return false;
156
157   APInt SplatUndef;
158   unsigned SplatBitSize;
159   bool HasUndefs;
160   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
161   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
162                              EltSize) &&
163          EltSize == SplatBitSize;
164 }
165
166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
167 // specializations of the more general isConstantSplatVector()?
168
169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
170   // Look through a bit convert.
171   while (N->getOpcode() == ISD::BITCAST)
172     N = N->getOperand(0).getNode();
173
174   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
175     APInt SplatVal;
176     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
177   }
178
179   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
180
181   unsigned i = 0, e = N->getNumOperands();
182
183   // Skip over all of the undef values.
184   while (i != e && N->getOperand(i).isUndef())
185     ++i;
186
187   // Do not accept an all-undef vector.
188   if (i == e) return false;
189
190   // Do not accept build_vectors that aren't all constants or which have non-~0
191   // elements. We have to be a bit careful here, as the type of the constant
192   // may not be the same as the type of the vector elements due to type
193   // legalization (the elements are promoted to a legal type for the target and
194   // a vector of a type may be legal when the base element type is not).
195   // We only want to check enough bits to cover the vector elements, because
196   // we care if the resultant vector is all ones, not whether the individual
197   // constants are.
198   SDValue NotZero = N->getOperand(i);
199   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
200   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
201     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
202       return false;
203   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
204     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
205       return false;
206   } else
207     return false;
208
209   // Okay, we have at least one ~0 value, check to see if the rest match or are
210   // undefs. Even with the above element type twiddling, this should be OK, as
211   // the same type legalization should have applied to all the elements.
212   for (++i; i != e; ++i)
213     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
214       return false;
215   return true;
216 }
217
218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
219   // Look through a bit convert.
220   while (N->getOpcode() == ISD::BITCAST)
221     N = N->getOperand(0).getNode();
222
223   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
224     APInt SplatVal;
225     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
226   }
227
228   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
229
230   bool IsAllUndef = true;
231   for (const SDValue &Op : N->op_values()) {
232     if (Op.isUndef())
233       continue;
234     IsAllUndef = false;
235     // Do not accept build_vectors that aren't all constants or which have non-0
236     // elements. We have to be a bit careful here, as the type of the constant
237     // may not be the same as the type of the vector elements due to type
238     // legalization (the elements are promoted to a legal type for the target
239     // and a vector of a type may be legal when the base element type is not).
240     // We only want to check enough bits to cover the vector elements, because
241     // we care if the resultant vector is all zeros, not whether the individual
242     // constants are.
243     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
244     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
245       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
246         return false;
247     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
248       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
249         return false;
250     } else
251       return false;
252   }
253
254   // Do not accept an all-undef vector.
255   if (IsAllUndef)
256     return false;
257   return true;
258 }
259
260 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
261   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
262 }
263
264 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
265   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
266 }
267
268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
269   if (N->getOpcode() != ISD::BUILD_VECTOR)
270     return false;
271
272   for (const SDValue &Op : N->op_values()) {
273     if (Op.isUndef())
274       continue;
275     if (!isa<ConstantSDNode>(Op))
276       return false;
277   }
278   return true;
279 }
280
281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
282   if (N->getOpcode() != ISD::BUILD_VECTOR)
283     return false;
284
285   for (const SDValue &Op : N->op_values()) {
286     if (Op.isUndef())
287       continue;
288     if (!isa<ConstantFPSDNode>(Op))
289       return false;
290   }
291   return true;
292 }
293
294 bool ISD::allOperandsUndef(const SDNode *N) {
295   // Return false if the node has no operands.
296   // This is "logically inconsistent" with the definition of "all" but
297   // is probably the desired behavior.
298   if (N->getNumOperands() == 0)
299     return false;
300   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
301 }
302
303 bool ISD::matchUnaryPredicate(SDValue Op,
304                               std::function<bool(ConstantSDNode *)> Match,
305                               bool AllowUndefs) {
306   // FIXME: Add support for scalar UNDEF cases?
307   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
308     return Match(Cst);
309
310   // FIXME: Add support for vector UNDEF cases?
311   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
312       ISD::SPLAT_VECTOR != Op.getOpcode())
313     return false;
314
315   EVT SVT = Op.getValueType().getScalarType();
316   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
317     if (AllowUndefs && Op.getOperand(i).isUndef()) {
318       if (!Match(nullptr))
319         return false;
320       continue;
321     }
322
323     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
324     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
325       return false;
326   }
327   return true;
328 }
329
330 bool ISD::matchBinaryPredicate(
331     SDValue LHS, SDValue RHS,
332     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
333     bool AllowUndefs, bool AllowTypeMismatch) {
334   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
335     return false;
336
337   // TODO: Add support for scalar UNDEF cases?
338   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
339     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
340       return Match(LHSCst, RHSCst);
341
342   // TODO: Add support for vector UNDEF cases?
343   if (LHS.getOpcode() != RHS.getOpcode() ||
344       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
345        LHS.getOpcode() != ISD::SPLAT_VECTOR))
346     return false;
347
348   EVT SVT = LHS.getValueType().getScalarType();
349   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
350     SDValue LHSOp = LHS.getOperand(i);
351     SDValue RHSOp = RHS.getOperand(i);
352     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
353     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
354     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
355     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
356     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
357       return false;
358     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
359                                LHSOp.getValueType() != RHSOp.getValueType()))
360       return false;
361     if (!Match(LHSCst, RHSCst))
362       return false;
363   }
364   return true;
365 }
366
367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
368   switch (VecReduceOpcode) {
369   default:
370     llvm_unreachable("Expected VECREDUCE opcode");
371   case ISD::VECREDUCE_FADD:
372   case ISD::VECREDUCE_SEQ_FADD:
373   case ISD::VP_REDUCE_FADD:
374   case ISD::VP_REDUCE_SEQ_FADD:
375     return ISD::FADD;
376   case ISD::VECREDUCE_FMUL:
377   case ISD::VECREDUCE_SEQ_FMUL:
378   case ISD::VP_REDUCE_FMUL:
379   case ISD::VP_REDUCE_SEQ_FMUL:
380     return ISD::FMUL;
381   case ISD::VECREDUCE_ADD:
382   case ISD::VP_REDUCE_ADD:
383     return ISD::ADD;
384   case ISD::VECREDUCE_MUL:
385   case ISD::VP_REDUCE_MUL:
386     return ISD::MUL;
387   case ISD::VECREDUCE_AND:
388   case ISD::VP_REDUCE_AND:
389     return ISD::AND;
390   case ISD::VECREDUCE_OR:
391   case ISD::VP_REDUCE_OR:
392     return ISD::OR;
393   case ISD::VECREDUCE_XOR:
394   case ISD::VP_REDUCE_XOR:
395     return ISD::XOR;
396   case ISD::VECREDUCE_SMAX:
397   case ISD::VP_REDUCE_SMAX:
398     return ISD::SMAX;
399   case ISD::VECREDUCE_SMIN:
400   case ISD::VP_REDUCE_SMIN:
401     return ISD::SMIN;
402   case ISD::VECREDUCE_UMAX:
403   case ISD::VP_REDUCE_UMAX:
404     return ISD::UMAX;
405   case ISD::VECREDUCE_UMIN:
406   case ISD::VP_REDUCE_UMIN:
407     return ISD::UMIN;
408   case ISD::VECREDUCE_FMAX:
409   case ISD::VP_REDUCE_FMAX:
410     return ISD::FMAXNUM;
411   case ISD::VECREDUCE_FMIN:
412   case ISD::VP_REDUCE_FMIN:
413     return ISD::FMINNUM;
414   }
415 }
416
417 bool ISD::isVPOpcode(unsigned Opcode) {
418   switch (Opcode) {
419   default:
420     return false;
421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
422   case ISD::VPSD:                                                              \
423     return true;
424 #include "llvm/IR/VPIntrinsics.def"
425   }
426 }
427
428 bool ISD::isVPBinaryOp(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     break;
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_BINARYOP return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437   return false;
438 }
439
440 bool ISD::isVPReduction(unsigned Opcode) {
441   switch (Opcode) {
442   default:
443     break;
444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
446 #define END_REGISTER_VP_SDNODE(VPSD) break;
447 #include "llvm/IR/VPIntrinsics.def"
448   }
449   return false;
450 }
451
452 /// The operand position of the vector mask.
453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
454   switch (Opcode) {
455   default:
456     return None;
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
458   case ISD::VPSD:                                                              \
459     return MASKPOS;
460 #include "llvm/IR/VPIntrinsics.def"
461   }
462 }
463
464 /// The operand position of the explicit vector length parameter.
465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
466   switch (Opcode) {
467   default:
468     return None;
469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
470   case ISD::VPSD:                                                              \
471     return EVLPOS;
472 #include "llvm/IR/VPIntrinsics.def"
473   }
474 }
475
476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
477   switch (ExtType) {
478   case ISD::EXTLOAD:
479     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
480   case ISD::SEXTLOAD:
481     return ISD::SIGN_EXTEND;
482   case ISD::ZEXTLOAD:
483     return ISD::ZERO_EXTEND;
484   default:
485     break;
486   }
487
488   llvm_unreachable("Invalid LoadExtType");
489 }
490
491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
492   // To perform this operation, we just need to swap the L and G bits of the
493   // operation.
494   unsigned OldL = (Operation >> 2) & 1;
495   unsigned OldG = (Operation >> 1) & 1;
496   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
497                        (OldL << 1) |       // New G bit
498                        (OldG << 2));       // New L bit.
499 }
500
501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
502   unsigned Operation = Op;
503   if (isIntegerLike)
504     Operation ^= 7;   // Flip L, G, E bits, but not U.
505   else
506     Operation ^= 15;  // Flip all of the condition bits.
507
508   if (Operation > ISD::SETTRUE2)
509     Operation &= ~8;  // Don't let N and U bits get set.
510
511   return ISD::CondCode(Operation);
512 }
513
514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
515   return getSetCCInverseImpl(Op, Type.isInteger());
516 }
517
518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
519                                                bool isIntegerLike) {
520   return getSetCCInverseImpl(Op, isIntegerLike);
521 }
522
523 /// For an integer comparison, return 1 if the comparison is a signed operation
524 /// and 2 if the result is an unsigned comparison. Return zero if the operation
525 /// does not depend on the sign of the input (setne and seteq).
526 static int isSignedOp(ISD::CondCode Opcode) {
527   switch (Opcode) {
528   default: llvm_unreachable("Illegal integer setcc operation!");
529   case ISD::SETEQ:
530   case ISD::SETNE: return 0;
531   case ISD::SETLT:
532   case ISD::SETLE:
533   case ISD::SETGT:
534   case ISD::SETGE: return 1;
535   case ISD::SETULT:
536   case ISD::SETULE:
537   case ISD::SETUGT:
538   case ISD::SETUGE: return 2;
539   }
540 }
541
542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
543                                        EVT Type) {
544   bool IsInteger = Type.isInteger();
545   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
546     // Cannot fold a signed integer setcc with an unsigned integer setcc.
547     return ISD::SETCC_INVALID;
548
549   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
550
551   // If the N and U bits get set, then the resultant comparison DOES suddenly
552   // care about orderedness, and it is true when ordered.
553   if (Op > ISD::SETTRUE2)
554     Op &= ~16;     // Clear the U bit if the N bit is set.
555
556   // Canonicalize illegal integer setcc's.
557   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
558     Op = ISD::SETNE;
559
560   return ISD::CondCode(Op);
561 }
562
563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
564                                         EVT Type) {
565   bool IsInteger = Type.isInteger();
566   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
567     // Cannot fold a signed setcc with an unsigned setcc.
568     return ISD::SETCC_INVALID;
569
570   // Combine all of the condition bits.
571   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
572
573   // Canonicalize illegal integer setcc's.
574   if (IsInteger) {
575     switch (Result) {
576     default: break;
577     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
578     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
579     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
580     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
581     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
582     }
583   }
584
585   return Result;
586 }
587
588 //===----------------------------------------------------------------------===//
589 //                           SDNode Profile Support
590 //===----------------------------------------------------------------------===//
591
592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
594   ID.AddInteger(OpC);
595 }
596
597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
598 /// solely with their pointer.
599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
600   ID.AddPointer(VTList.VTs);
601 }
602
603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
604 static void AddNodeIDOperands(FoldingSetNodeID &ID,
605                               ArrayRef<SDValue> Ops) {
606   for (const auto &Op : Ops) {
607     ID.AddPointer(Op.getNode());
608     ID.AddInteger(Op.getResNo());
609   }
610 }
611
612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
613 static void AddNodeIDOperands(FoldingSetNodeID &ID,
614                               ArrayRef<SDUse> Ops) {
615   for (const auto &Op : Ops) {
616     ID.AddPointer(Op.getNode());
617     ID.AddInteger(Op.getResNo());
618   }
619 }
620
621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
622                           SDVTList VTList, ArrayRef<SDValue> OpList) {
623   AddNodeIDOpcode(ID, OpC);
624   AddNodeIDValueTypes(ID, VTList);
625   AddNodeIDOperands(ID, OpList);
626 }
627
628 /// If this is an SDNode with special info, add this info to the NodeID data.
629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
630   switch (N->getOpcode()) {
631   case ISD::TargetExternalSymbol:
632   case ISD::ExternalSymbol:
633   case ISD::MCSymbol:
634     llvm_unreachable("Should only be used on nodes with operands");
635   default: break;  // Normal nodes don't need extra info.
636   case ISD::TargetConstant:
637   case ISD::Constant: {
638     const ConstantSDNode *C = cast<ConstantSDNode>(N);
639     ID.AddPointer(C->getConstantIntValue());
640     ID.AddBoolean(C->isOpaque());
641     break;
642   }
643   case ISD::TargetConstantFP:
644   case ISD::ConstantFP:
645     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
646     break;
647   case ISD::TargetGlobalAddress:
648   case ISD::GlobalAddress:
649   case ISD::TargetGlobalTLSAddress:
650   case ISD::GlobalTLSAddress: {
651     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
652     ID.AddPointer(GA->getGlobal());
653     ID.AddInteger(GA->getOffset());
654     ID.AddInteger(GA->getTargetFlags());
655     break;
656   }
657   case ISD::BasicBlock:
658     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
659     break;
660   case ISD::Register:
661     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
662     break;
663   case ISD::RegisterMask:
664     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
665     break;
666   case ISD::SRCVALUE:
667     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
668     break;
669   case ISD::FrameIndex:
670   case ISD::TargetFrameIndex:
671     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
672     break;
673   case ISD::LIFETIME_START:
674   case ISD::LIFETIME_END:
675     if (cast<LifetimeSDNode>(N)->hasOffset()) {
676       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
677       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
678     }
679     break;
680   case ISD::PSEUDO_PROBE:
681     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
682     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
683     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
684     break;
685   case ISD::JumpTable:
686   case ISD::TargetJumpTable:
687     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
688     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
689     break;
690   case ISD::ConstantPool:
691   case ISD::TargetConstantPool: {
692     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
693     ID.AddInteger(CP->getAlign().value());
694     ID.AddInteger(CP->getOffset());
695     if (CP->isMachineConstantPoolEntry())
696       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
697     else
698       ID.AddPointer(CP->getConstVal());
699     ID.AddInteger(CP->getTargetFlags());
700     break;
701   }
702   case ISD::TargetIndex: {
703     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
704     ID.AddInteger(TI->getIndex());
705     ID.AddInteger(TI->getOffset());
706     ID.AddInteger(TI->getTargetFlags());
707     break;
708   }
709   case ISD::LOAD: {
710     const LoadSDNode *LD = cast<LoadSDNode>(N);
711     ID.AddInteger(LD->getMemoryVT().getRawBits());
712     ID.AddInteger(LD->getRawSubclassData());
713     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
714     ID.AddInteger(LD->getMemOperand()->getFlags());
715     break;
716   }
717   case ISD::STORE: {
718     const StoreSDNode *ST = cast<StoreSDNode>(N);
719     ID.AddInteger(ST->getMemoryVT().getRawBits());
720     ID.AddInteger(ST->getRawSubclassData());
721     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
722     ID.AddInteger(ST->getMemOperand()->getFlags());
723     break;
724   }
725   case ISD::VP_LOAD: {
726     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
727     ID.AddInteger(ELD->getMemoryVT().getRawBits());
728     ID.AddInteger(ELD->getRawSubclassData());
729     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
730     ID.AddInteger(ELD->getMemOperand()->getFlags());
731     break;
732   }
733   case ISD::VP_STORE: {
734     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735     ID.AddInteger(EST->getMemoryVT().getRawBits());
736     ID.AddInteger(EST->getRawSubclassData());
737     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738     ID.AddInteger(EST->getMemOperand()->getFlags());
739     break;
740   }
741   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
742     const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
743     ID.AddInteger(SLD->getMemoryVT().getRawBits());
744     ID.AddInteger(SLD->getRawSubclassData());
745     ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
746     break;
747   }
748   case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
749     const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
750     ID.AddInteger(SST->getMemoryVT().getRawBits());
751     ID.AddInteger(SST->getRawSubclassData());
752     ID.AddInteger(SST->getPointerInfo().getAddrSpace());
753     break;
754   }
755   case ISD::VP_GATHER: {
756     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
757     ID.AddInteger(EG->getMemoryVT().getRawBits());
758     ID.AddInteger(EG->getRawSubclassData());
759     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
760     ID.AddInteger(EG->getMemOperand()->getFlags());
761     break;
762   }
763   case ISD::VP_SCATTER: {
764     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
765     ID.AddInteger(ES->getMemoryVT().getRawBits());
766     ID.AddInteger(ES->getRawSubclassData());
767     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
768     ID.AddInteger(ES->getMemOperand()->getFlags());
769     break;
770   }
771   case ISD::MLOAD: {
772     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
773     ID.AddInteger(MLD->getMemoryVT().getRawBits());
774     ID.AddInteger(MLD->getRawSubclassData());
775     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
776     ID.AddInteger(MLD->getMemOperand()->getFlags());
777     break;
778   }
779   case ISD::MSTORE: {
780     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
781     ID.AddInteger(MST->getMemoryVT().getRawBits());
782     ID.AddInteger(MST->getRawSubclassData());
783     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
784     ID.AddInteger(MST->getMemOperand()->getFlags());
785     break;
786   }
787   case ISD::MGATHER: {
788     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
789     ID.AddInteger(MG->getMemoryVT().getRawBits());
790     ID.AddInteger(MG->getRawSubclassData());
791     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
792     ID.AddInteger(MG->getMemOperand()->getFlags());
793     break;
794   }
795   case ISD::MSCATTER: {
796     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
797     ID.AddInteger(MS->getMemoryVT().getRawBits());
798     ID.AddInteger(MS->getRawSubclassData());
799     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
800     ID.AddInteger(MS->getMemOperand()->getFlags());
801     break;
802   }
803   case ISD::ATOMIC_CMP_SWAP:
804   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
805   case ISD::ATOMIC_SWAP:
806   case ISD::ATOMIC_LOAD_ADD:
807   case ISD::ATOMIC_LOAD_SUB:
808   case ISD::ATOMIC_LOAD_AND:
809   case ISD::ATOMIC_LOAD_CLR:
810   case ISD::ATOMIC_LOAD_OR:
811   case ISD::ATOMIC_LOAD_XOR:
812   case ISD::ATOMIC_LOAD_NAND:
813   case ISD::ATOMIC_LOAD_MIN:
814   case ISD::ATOMIC_LOAD_MAX:
815   case ISD::ATOMIC_LOAD_UMIN:
816   case ISD::ATOMIC_LOAD_UMAX:
817   case ISD::ATOMIC_LOAD:
818   case ISD::ATOMIC_STORE: {
819     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
820     ID.AddInteger(AT->getMemoryVT().getRawBits());
821     ID.AddInteger(AT->getRawSubclassData());
822     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
823     ID.AddInteger(AT->getMemOperand()->getFlags());
824     break;
825   }
826   case ISD::PREFETCH: {
827     const MemSDNode *PF = cast<MemSDNode>(N);
828     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
829     ID.AddInteger(PF->getMemOperand()->getFlags());
830     break;
831   }
832   case ISD::VECTOR_SHUFFLE: {
833     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
834     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
835          i != e; ++i)
836       ID.AddInteger(SVN->getMaskElt(i));
837     break;
838   }
839   case ISD::TargetBlockAddress:
840   case ISD::BlockAddress: {
841     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
842     ID.AddPointer(BA->getBlockAddress());
843     ID.AddInteger(BA->getOffset());
844     ID.AddInteger(BA->getTargetFlags());
845     break;
846   }
847   case ISD::AssertAlign:
848     ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
849     break;
850   } // end switch (N->getOpcode())
851
852   // Target specific memory nodes could also have address spaces and flags
853   // to check.
854   if (N->isTargetMemoryOpcode()) {
855     const MemSDNode *MN = cast<MemSDNode>(N);
856     ID.AddInteger(MN->getPointerInfo().getAddrSpace());
857     ID.AddInteger(MN->getMemOperand()->getFlags());
858   }
859 }
860
861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
862 /// data.
863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
864   AddNodeIDOpcode(ID, N->getOpcode());
865   // Add the return value info.
866   AddNodeIDValueTypes(ID, N->getVTList());
867   // Add the operand info.
868   AddNodeIDOperands(ID, N->ops());
869
870   // Handle SDNode leafs with special info.
871   AddNodeIDCustom(ID, N);
872 }
873
874 //===----------------------------------------------------------------------===//
875 //                              SelectionDAG Class
876 //===----------------------------------------------------------------------===//
877
878 /// doNotCSE - Return true if CSE should not be performed for this node.
879 static bool doNotCSE(SDNode *N) {
880   if (N->getValueType(0) == MVT::Glue)
881     return true; // Never CSE anything that produces a flag.
882
883   switch (N->getOpcode()) {
884   default: break;
885   case ISD::HANDLENODE:
886   case ISD::EH_LABEL:
887     return true;   // Never CSE these nodes.
888   }
889
890   // Check that remaining values produced are not flags.
891   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
892     if (N->getValueType(i) == MVT::Glue)
893       return true; // Never CSE anything that produces a flag.
894
895   return false;
896 }
897
898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
899 /// SelectionDAG.
900 void SelectionDAG::RemoveDeadNodes() {
901   // Create a dummy node (which is not added to allnodes), that adds a reference
902   // to the root node, preventing it from being deleted.
903   HandleSDNode Dummy(getRoot());
904
905   SmallVector<SDNode*, 128> DeadNodes;
906
907   // Add all obviously-dead nodes to the DeadNodes worklist.
908   for (SDNode &Node : allnodes())
909     if (Node.use_empty())
910       DeadNodes.push_back(&Node);
911
912   RemoveDeadNodes(DeadNodes);
913
914   // If the root changed (e.g. it was a dead load, update the root).
915   setRoot(Dummy.getValue());
916 }
917
918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
919 /// given list, and any nodes that become unreachable as a result.
920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
921
922   // Process the worklist, deleting the nodes and adding their uses to the
923   // worklist.
924   while (!DeadNodes.empty()) {
925     SDNode *N = DeadNodes.pop_back_val();
926     // Skip to next node if we've already managed to delete the node. This could
927     // happen if replacing a node causes a node previously added to the node to
928     // be deleted.
929     if (N->getOpcode() == ISD::DELETED_NODE)
930       continue;
931
932     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
933       DUL->NodeDeleted(N, nullptr);
934
935     // Take the node out of the appropriate CSE map.
936     RemoveNodeFromCSEMaps(N);
937
938     // Next, brutally remove the operand list.  This is safe to do, as there are
939     // no cycles in the graph.
940     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
941       SDUse &Use = *I++;
942       SDNode *Operand = Use.getNode();
943       Use.set(SDValue());
944
945       // Now that we removed this operand, see if there are no uses of it left.
946       if (Operand->use_empty())
947         DeadNodes.push_back(Operand);
948     }
949
950     DeallocateNode(N);
951   }
952 }
953
954 void SelectionDAG::RemoveDeadNode(SDNode *N){
955   SmallVector<SDNode*, 16> DeadNodes(1, N);
956
957   // Create a dummy node that adds a reference to the root node, preventing
958   // it from being deleted.  (This matters if the root is an operand of the
959   // dead node.)
960   HandleSDNode Dummy(getRoot());
961
962   RemoveDeadNodes(DeadNodes);
963 }
964
965 void SelectionDAG::DeleteNode(SDNode *N) {
966   // First take this out of the appropriate CSE map.
967   RemoveNodeFromCSEMaps(N);
968
969   // Finally, remove uses due to operands of this node, remove from the
970   // AllNodes list, and delete the node.
971   DeleteNodeNotInCSEMaps(N);
972 }
973
974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
975   assert(N->getIterator() != AllNodes.begin() &&
976          "Cannot delete the entry node!");
977   assert(N->use_empty() && "Cannot delete a node that is not dead!");
978
979   // Drop all of the operands and decrement used node's use counts.
980   N->DropOperands();
981
982   DeallocateNode(N);
983 }
984
985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
986   assert(!(V->isVariadic() && isParameter));
987   if (isParameter)
988     ByvalParmDbgValues.push_back(V);
989   else
990     DbgValues.push_back(V);
991   for (const SDNode *Node : V->getSDNodes())
992     if (Node)
993       DbgValMap[Node].push_back(V);
994 }
995
996 void SDDbgInfo::erase(const SDNode *Node) {
997   DbgValMapType::iterator I = DbgValMap.find(Node);
998   if (I == DbgValMap.end())
999     return;
1000   for (auto &Val: I->second)
1001     Val->setIsInvalidated();
1002   DbgValMap.erase(I);
1003 }
1004
1005 void SelectionDAG::DeallocateNode(SDNode *N) {
1006   // If we have operands, deallocate them.
1007   removeOperands(N);
1008
1009   NodeAllocator.Deallocate(AllNodes.remove(N));
1010
1011   // Set the opcode to DELETED_NODE to help catch bugs when node
1012   // memory is reallocated.
1013   // FIXME: There are places in SDag that have grown a dependency on the opcode
1014   // value in the released node.
1015   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1016   N->NodeType = ISD::DELETED_NODE;
1017
1018   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1019   // them and forget about that node.
1020   DbgInfo->erase(N);
1021 }
1022
1023 #ifndef NDEBUG
1024 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
1025 static void VerifySDNode(SDNode *N) {
1026   switch (N->getOpcode()) {
1027   default:
1028     break;
1029   case ISD::BUILD_PAIR: {
1030     EVT VT = N->getValueType(0);
1031     assert(N->getNumValues() == 1 && "Too many results!");
1032     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1033            "Wrong return type!");
1034     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1035     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1036            "Mismatched operand types!");
1037     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1038            "Wrong operand type!");
1039     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1040            "Wrong return type size");
1041     break;
1042   }
1043   case ISD::BUILD_VECTOR: {
1044     assert(N->getNumValues() == 1 && "Too many results!");
1045     assert(N->getValueType(0).isVector() && "Wrong return type!");
1046     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1047            "Wrong number of operands!");
1048     EVT EltVT = N->getValueType(0).getVectorElementType();
1049     for (const SDUse &Op : N->ops()) {
1050       assert((Op.getValueType() == EltVT ||
1051               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1052                EltVT.bitsLE(Op.getValueType()))) &&
1053              "Wrong operand type!");
1054       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1055              "Operands must all have the same type");
1056     }
1057     break;
1058   }
1059   }
1060 }
1061 #endif // NDEBUG
1062
1063 /// Insert a newly allocated node into the DAG.
1064 ///
1065 /// Handles insertion into the all nodes list and CSE map, as well as
1066 /// verification and other common operations when a new node is allocated.
1067 void SelectionDAG::InsertNode(SDNode *N) {
1068   AllNodes.push_back(N);
1069 #ifndef NDEBUG
1070   N->PersistentId = NextPersistentId++;
1071   VerifySDNode(N);
1072 #endif
1073   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1074     DUL->NodeInserted(N);
1075 }
1076
1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1078 /// correspond to it.  This is useful when we're about to delete or repurpose
1079 /// the node.  We don't want future request for structurally identical nodes
1080 /// to return N anymore.
1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1082   bool Erased = false;
1083   switch (N->getOpcode()) {
1084   case ISD::HANDLENODE: return false;  // noop.
1085   case ISD::CONDCODE:
1086     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1087            "Cond code doesn't exist!");
1088     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1089     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1090     break;
1091   case ISD::ExternalSymbol:
1092     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1093     break;
1094   case ISD::TargetExternalSymbol: {
1095     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1096     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1097         ESN->getSymbol(), ESN->getTargetFlags()));
1098     break;
1099   }
1100   case ISD::MCSymbol: {
1101     auto *MCSN = cast<MCSymbolSDNode>(N);
1102     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1103     break;
1104   }
1105   case ISD::VALUETYPE: {
1106     EVT VT = cast<VTSDNode>(N)->getVT();
1107     if (VT.isExtended()) {
1108       Erased = ExtendedValueTypeNodes.erase(VT);
1109     } else {
1110       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1111       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1112     }
1113     break;
1114   }
1115   default:
1116     // Remove it from the CSE Map.
1117     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1118     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1119     Erased = CSEMap.RemoveNode(N);
1120     break;
1121   }
1122 #ifndef NDEBUG
1123   // Verify that the node was actually in one of the CSE maps, unless it has a
1124   // flag result (which cannot be CSE'd) or is one of the special cases that are
1125   // not subject to CSE.
1126   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1127       !N->isMachineOpcode() && !doNotCSE(N)) {
1128     N->dump(this);
1129     dbgs() << "\n";
1130     llvm_unreachable("Node is not in map!");
1131   }
1132 #endif
1133   return Erased;
1134 }
1135
1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1138 /// node already exists, in which case transfer all its users to the existing
1139 /// node. This transfer can potentially trigger recursive merging.
1140 void
1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1142   // For node types that aren't CSE'd, just act as if no identical node
1143   // already exists.
1144   if (!doNotCSE(N)) {
1145     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1146     if (Existing != N) {
1147       // If there was already an existing matching node, use ReplaceAllUsesWith
1148       // to replace the dead one with the existing one.  This can cause
1149       // recursive merging of other unrelated nodes down the line.
1150       ReplaceAllUsesWith(N, Existing);
1151
1152       // N is now dead. Inform the listeners and delete it.
1153       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1154         DUL->NodeDeleted(N, Existing);
1155       DeleteNodeNotInCSEMaps(N);
1156       return;
1157     }
1158   }
1159
1160   // If the node doesn't already exist, we updated it.  Inform listeners.
1161   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1162     DUL->NodeUpdated(N);
1163 }
1164
1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1166 /// were replaced with those specified.  If this node is never memoized,
1167 /// return null, otherwise return a pointer to the slot it would take.  If a
1168 /// node already exists with these operands, the slot will be non-null.
1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1170                                            void *&InsertPos) {
1171   if (doNotCSE(N))
1172     return nullptr;
1173
1174   SDValue Ops[] = { Op };
1175   FoldingSetNodeID ID;
1176   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1177   AddNodeIDCustom(ID, N);
1178   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1179   if (Node)
1180     Node->intersectFlagsWith(N->getFlags());
1181   return Node;
1182 }
1183
1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1185 /// were replaced with those specified.  If this node is never memoized,
1186 /// return null, otherwise return a pointer to the slot it would take.  If a
1187 /// node already exists with these operands, the slot will be non-null.
1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1189                                            SDValue Op1, SDValue Op2,
1190                                            void *&InsertPos) {
1191   if (doNotCSE(N))
1192     return nullptr;
1193
1194   SDValue Ops[] = { Op1, Op2 };
1195   FoldingSetNodeID ID;
1196   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1197   AddNodeIDCustom(ID, N);
1198   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1199   if (Node)
1200     Node->intersectFlagsWith(N->getFlags());
1201   return Node;
1202 }
1203
1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1205 /// were replaced with those specified.  If this node is never memoized,
1206 /// return null, otherwise return a pointer to the slot it would take.  If a
1207 /// node already exists with these operands, the slot will be non-null.
1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1209                                            void *&InsertPos) {
1210   if (doNotCSE(N))
1211     return nullptr;
1212
1213   FoldingSetNodeID ID;
1214   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1215   AddNodeIDCustom(ID, N);
1216   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1217   if (Node)
1218     Node->intersectFlagsWith(N->getFlags());
1219   return Node;
1220 }
1221
1222 Align SelectionDAG::getEVTAlign(EVT VT) const {
1223   Type *Ty = VT == MVT::iPTR ?
1224                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1225                    VT.getTypeForEVT(*getContext());
1226
1227   return getDataLayout().getABITypeAlign(Ty);
1228 }
1229
1230 // EntryNode could meaningfully have debug info if we can find it...
1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1232     : TM(tm), OptLevel(OL),
1233       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1234       Root(getEntryNode()) {
1235   InsertNode(&EntryNode);
1236   DbgInfo = new SDDbgInfo();
1237 }
1238
1239 void SelectionDAG::init(MachineFunction &NewMF,
1240                         OptimizationRemarkEmitter &NewORE,
1241                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1242                         LegacyDivergenceAnalysis * Divergence,
1243                         ProfileSummaryInfo *PSIin,
1244                         BlockFrequencyInfo *BFIin) {
1245   MF = &NewMF;
1246   SDAGISelPass = PassPtr;
1247   ORE = &NewORE;
1248   TLI = getSubtarget().getTargetLowering();
1249   TSI = getSubtarget().getSelectionDAGInfo();
1250   LibInfo = LibraryInfo;
1251   Context = &MF->getFunction().getContext();
1252   DA = Divergence;
1253   PSI = PSIin;
1254   BFI = BFIin;
1255 }
1256
1257 SelectionDAG::~SelectionDAG() {
1258   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1259   allnodes_clear();
1260   OperandRecycler.clear(OperandAllocator);
1261   delete DbgInfo;
1262 }
1263
1264 bool SelectionDAG::shouldOptForSize() const {
1265   return MF->getFunction().hasOptSize() ||
1266       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1267 }
1268
1269 void SelectionDAG::allnodes_clear() {
1270   assert(&*AllNodes.begin() == &EntryNode);
1271   AllNodes.remove(AllNodes.begin());
1272   while (!AllNodes.empty())
1273     DeallocateNode(&AllNodes.front());
1274 #ifndef NDEBUG
1275   NextPersistentId = 0;
1276 #endif
1277 }
1278
1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1280                                           void *&InsertPos) {
1281   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1282   if (N) {
1283     switch (N->getOpcode()) {
1284     default: break;
1285     case ISD::Constant:
1286     case ISD::ConstantFP:
1287       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1288                        "debug location.  Use another overload.");
1289     }
1290   }
1291   return N;
1292 }
1293
1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1295                                           const SDLoc &DL, void *&InsertPos) {
1296   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1297   if (N) {
1298     switch (N->getOpcode()) {
1299     case ISD::Constant:
1300     case ISD::ConstantFP:
1301       // Erase debug location from the node if the node is used at several
1302       // different places. Do not propagate one location to all uses as it
1303       // will cause a worse single stepping debugging experience.
1304       if (N->getDebugLoc() != DL.getDebugLoc())
1305         N->setDebugLoc(DebugLoc());
1306       break;
1307     default:
1308       // When the node's point of use is located earlier in the instruction
1309       // sequence than its prior point of use, update its debug info to the
1310       // earlier location.
1311       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1312         N->setDebugLoc(DL.getDebugLoc());
1313       break;
1314     }
1315   }
1316   return N;
1317 }
1318
1319 void SelectionDAG::clear() {
1320   allnodes_clear();
1321   OperandRecycler.clear(OperandAllocator);
1322   OperandAllocator.Reset();
1323   CSEMap.clear();
1324
1325   ExtendedValueTypeNodes.clear();
1326   ExternalSymbols.clear();
1327   TargetExternalSymbols.clear();
1328   MCSymbols.clear();
1329   SDCallSiteDbgInfo.clear();
1330   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1331             static_cast<CondCodeSDNode*>(nullptr));
1332   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1333             static_cast<SDNode*>(nullptr));
1334
1335   EntryNode.UseList = nullptr;
1336   InsertNode(&EntryNode);
1337   Root = getEntryNode();
1338   DbgInfo->clear();
1339 }
1340
1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1342   return VT.bitsGT(Op.getValueType())
1343              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1344              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1345 }
1346
1347 std::pair<SDValue, SDValue>
1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1349                                        const SDLoc &DL, EVT VT) {
1350   assert(!VT.bitsEq(Op.getValueType()) &&
1351          "Strict no-op FP extend/round not allowed.");
1352   SDValue Res =
1353       VT.bitsGT(Op.getValueType())
1354           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1355           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1356                     {Chain, Op, getIntPtrConstant(0, DL)});
1357
1358   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1359 }
1360
1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362   return VT.bitsGT(Op.getValueType()) ?
1363     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1364     getNode(ISD::TRUNCATE, DL, VT, Op);
1365 }
1366
1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1368   return VT.bitsGT(Op.getValueType()) ?
1369     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1370     getNode(ISD::TRUNCATE, DL, VT, Op);
1371 }
1372
1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1374   return VT.bitsGT(Op.getValueType()) ?
1375     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1376     getNode(ISD::TRUNCATE, DL, VT, Op);
1377 }
1378
1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1380                                         EVT OpVT) {
1381   if (VT.bitsLE(Op.getValueType()))
1382     return getNode(ISD::TRUNCATE, SL, VT, Op);
1383
1384   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1385   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1386 }
1387
1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1389   EVT OpVT = Op.getValueType();
1390   assert(VT.isInteger() && OpVT.isInteger() &&
1391          "Cannot getZeroExtendInReg FP types");
1392   assert(VT.isVector() == OpVT.isVector() &&
1393          "getZeroExtendInReg type should be vector iff the operand "
1394          "type is vector!");
1395   assert((!VT.isVector() ||
1396           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1397          "Vector element counts must match in getZeroExtendInReg");
1398   assert(VT.bitsLE(OpVT) && "Not extending!");
1399   if (OpVT == VT)
1400     return Op;
1401   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1402                                    VT.getScalarSizeInBits());
1403   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1404 }
1405
1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1407   // Only unsigned pointer semantics are supported right now. In the future this
1408   // might delegate to TLI to check pointer signedness.
1409   return getZExtOrTrunc(Op, DL, VT);
1410 }
1411
1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1413   // Only unsigned pointer semantics are supported right now. In the future this
1414   // might delegate to TLI to check pointer signedness.
1415   return getZeroExtendInReg(Op, DL, VT);
1416 }
1417
1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1420   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1421 }
1422
1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1424   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1425   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1426 }
1427
1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
1429                                       SDValue Mask, SDValue EVL, EVT VT) {
1430   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1431   return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1432 }
1433
1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1435                                       EVT OpVT) {
1436   if (!V)
1437     return getConstant(0, DL, VT);
1438
1439   switch (TLI->getBooleanContents(OpVT)) {
1440   case TargetLowering::ZeroOrOneBooleanContent:
1441   case TargetLowering::UndefinedBooleanContent:
1442     return getConstant(1, DL, VT);
1443   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1444     return getAllOnesConstant(DL, VT);
1445   }
1446   llvm_unreachable("Unexpected boolean content enum!");
1447 }
1448
1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1450                                   bool isT, bool isO) {
1451   EVT EltVT = VT.getScalarType();
1452   assert((EltVT.getSizeInBits() >= 64 ||
1453           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1454          "getConstant with a uint64_t value that doesn't fit in the type!");
1455   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1456 }
1457
1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1459                                   bool isT, bool isO) {
1460   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1461 }
1462
1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1464                                   EVT VT, bool isT, bool isO) {
1465   assert(VT.isInteger() && "Cannot create FP integer constant!");
1466
1467   EVT EltVT = VT.getScalarType();
1468   const ConstantInt *Elt = &Val;
1469
1470   // In some cases the vector type is legal but the element type is illegal and
1471   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1472   // inserted value (the type does not need to match the vector element type).
1473   // Any extra bits introduced will be truncated away.
1474   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1475                            TargetLowering::TypePromoteInteger) {
1476     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1477     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1478     Elt = ConstantInt::get(*getContext(), NewVal);
1479   }
1480   // In other cases the element type is illegal and needs to be expanded, for
1481   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1482   // the value into n parts and use a vector type with n-times the elements.
1483   // Then bitcast to the type requested.
1484   // Legalizing constants too early makes the DAGCombiner's job harder so we
1485   // only legalize if the DAG tells us we must produce legal types.
1486   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1487            TLI->getTypeAction(*getContext(), EltVT) ==
1488                TargetLowering::TypeExpandInteger) {
1489     const APInt &NewVal = Elt->getValue();
1490     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1491     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1492
1493     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1494     if (VT.isScalableVector()) {
1495       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1496              "Can only handle an even split!");
1497       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1498
1499       SmallVector<SDValue, 2> ScalarParts;
1500       for (unsigned i = 0; i != Parts; ++i)
1501         ScalarParts.push_back(getConstant(
1502             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1503             ViaEltVT, isT, isO));
1504
1505       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1506     }
1507
1508     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1509     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1510
1511     // Check the temporary vector is the correct size. If this fails then
1512     // getTypeToTransformTo() probably returned a type whose size (in bits)
1513     // isn't a power-of-2 factor of the requested type size.
1514     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1515
1516     SmallVector<SDValue, 2> EltParts;
1517     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1518       EltParts.push_back(getConstant(
1519           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1520           ViaEltVT, isT, isO));
1521
1522     // EltParts is currently in little endian order. If we actually want
1523     // big-endian order then reverse it now.
1524     if (getDataLayout().isBigEndian())
1525       std::reverse(EltParts.begin(), EltParts.end());
1526
1527     // The elements must be reversed when the element order is different
1528     // to the endianness of the elements (because the BITCAST is itself a
1529     // vector shuffle in this situation). However, we do not need any code to
1530     // perform this reversal because getConstant() is producing a vector
1531     // splat.
1532     // This situation occurs in MIPS MSA.
1533
1534     SmallVector<SDValue, 8> Ops;
1535     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1536       llvm::append_range(Ops, EltParts);
1537
1538     SDValue V =
1539         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1540     return V;
1541   }
1542
1543   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1544          "APInt size does not match type size!");
1545   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1546   FoldingSetNodeID ID;
1547   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1548   ID.AddPointer(Elt);
1549   ID.AddBoolean(isO);
1550   void *IP = nullptr;
1551   SDNode *N = nullptr;
1552   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1553     if (!VT.isVector())
1554       return SDValue(N, 0);
1555
1556   if (!N) {
1557     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1558     CSEMap.InsertNode(N, IP);
1559     InsertNode(N);
1560     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1561   }
1562
1563   SDValue Result(N, 0);
1564   if (VT.isScalableVector())
1565     Result = getSplatVector(VT, DL, Result);
1566   else if (VT.isVector())
1567     Result = getSplatBuildVector(VT, DL, Result);
1568
1569   return Result;
1570 }
1571
1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1573                                         bool isTarget) {
1574   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1575 }
1576
1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1578                                              const SDLoc &DL, bool LegalTypes) {
1579   assert(VT.isInteger() && "Shift amount is not an integer type!");
1580   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1581   return getConstant(Val, DL, ShiftVT);
1582 }
1583
1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1585                                            bool isTarget) {
1586   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1587 }
1588
1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1590                                     bool isTarget) {
1591   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1592 }
1593
1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1595                                     EVT VT, bool isTarget) {
1596   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1597
1598   EVT EltVT = VT.getScalarType();
1599
1600   // Do the map lookup using the actual bit pattern for the floating point
1601   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1602   // we don't have issues with SNANs.
1603   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1604   FoldingSetNodeID ID;
1605   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1606   ID.AddPointer(&V);
1607   void *IP = nullptr;
1608   SDNode *N = nullptr;
1609   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1610     if (!VT.isVector())
1611       return SDValue(N, 0);
1612
1613   if (!N) {
1614     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1615     CSEMap.InsertNode(N, IP);
1616     InsertNode(N);
1617   }
1618
1619   SDValue Result(N, 0);
1620   if (VT.isScalableVector())
1621     Result = getSplatVector(VT, DL, Result);
1622   else if (VT.isVector())
1623     Result = getSplatBuildVector(VT, DL, Result);
1624   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1625   return Result;
1626 }
1627
1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1629                                     bool isTarget) {
1630   EVT EltVT = VT.getScalarType();
1631   if (EltVT == MVT::f32)
1632     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1633   if (EltVT == MVT::f64)
1634     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1635   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1636       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1637     bool Ignored;
1638     APFloat APF = APFloat(Val);
1639     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1640                 &Ignored);
1641     return getConstantFP(APF, DL, VT, isTarget);
1642   }
1643   llvm_unreachable("Unsupported type in getConstantFP");
1644 }
1645
1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1647                                        EVT VT, int64_t Offset, bool isTargetGA,
1648                                        unsigned TargetFlags) {
1649   assert((TargetFlags == 0 || isTargetGA) &&
1650          "Cannot set target flags on target-independent globals");
1651
1652   // Truncate (with sign-extension) the offset value to the pointer size.
1653   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1654   if (BitWidth < 64)
1655     Offset = SignExtend64(Offset, BitWidth);
1656
1657   unsigned Opc;
1658   if (GV->isThreadLocal())
1659     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1660   else
1661     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1662
1663   FoldingSetNodeID ID;
1664   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1665   ID.AddPointer(GV);
1666   ID.AddInteger(Offset);
1667   ID.AddInteger(TargetFlags);
1668   void *IP = nullptr;
1669   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1670     return SDValue(E, 0);
1671
1672   auto *N = newSDNode<GlobalAddressSDNode>(
1673       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1674   CSEMap.InsertNode(N, IP);
1675     InsertNode(N);
1676   return SDValue(N, 0);
1677 }
1678
1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1680   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1681   FoldingSetNodeID ID;
1682   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1683   ID.AddInteger(FI);
1684   void *IP = nullptr;
1685   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1686     return SDValue(E, 0);
1687
1688   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1689   CSEMap.InsertNode(N, IP);
1690   InsertNode(N);
1691   return SDValue(N, 0);
1692 }
1693
1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1695                                    unsigned TargetFlags) {
1696   assert((TargetFlags == 0 || isTarget) &&
1697          "Cannot set target flags on target-independent jump tables");
1698   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1699   FoldingSetNodeID ID;
1700   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1701   ID.AddInteger(JTI);
1702   ID.AddInteger(TargetFlags);
1703   void *IP = nullptr;
1704   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1705     return SDValue(E, 0);
1706
1707   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1708   CSEMap.InsertNode(N, IP);
1709   InsertNode(N);
1710   return SDValue(N, 0);
1711 }
1712
1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1714                                       MaybeAlign Alignment, int Offset,
1715                                       bool isTarget, unsigned TargetFlags) {
1716   assert((TargetFlags == 0 || isTarget) &&
1717          "Cannot set target flags on target-independent globals");
1718   if (!Alignment)
1719     Alignment = shouldOptForSize()
1720                     ? getDataLayout().getABITypeAlign(C->getType())
1721                     : getDataLayout().getPrefTypeAlign(C->getType());
1722   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1723   FoldingSetNodeID ID;
1724   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1725   ID.AddInteger(Alignment->value());
1726   ID.AddInteger(Offset);
1727   ID.AddPointer(C);
1728   ID.AddInteger(TargetFlags);
1729   void *IP = nullptr;
1730   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1731     return SDValue(E, 0);
1732
1733   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1734                                           TargetFlags);
1735   CSEMap.InsertNode(N, IP);
1736   InsertNode(N);
1737   SDValue V = SDValue(N, 0);
1738   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1739   return V;
1740 }
1741
1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1743                                       MaybeAlign Alignment, int Offset,
1744                                       bool isTarget, unsigned TargetFlags) {
1745   assert((TargetFlags == 0 || isTarget) &&
1746          "Cannot set target flags on target-independent globals");
1747   if (!Alignment)
1748     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1749   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1750   FoldingSetNodeID ID;
1751   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1752   ID.AddInteger(Alignment->value());
1753   ID.AddInteger(Offset);
1754   C->addSelectionDAGCSEId(ID);
1755   ID.AddInteger(TargetFlags);
1756   void *IP = nullptr;
1757   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1758     return SDValue(E, 0);
1759
1760   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1761                                           TargetFlags);
1762   CSEMap.InsertNode(N, IP);
1763   InsertNode(N);
1764   return SDValue(N, 0);
1765 }
1766
1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1768                                      unsigned TargetFlags) {
1769   FoldingSetNodeID ID;
1770   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1771   ID.AddInteger(Index);
1772   ID.AddInteger(Offset);
1773   ID.AddInteger(TargetFlags);
1774   void *IP = nullptr;
1775   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1776     return SDValue(E, 0);
1777
1778   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1779   CSEMap.InsertNode(N, IP);
1780   InsertNode(N);
1781   return SDValue(N, 0);
1782 }
1783
1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1785   FoldingSetNodeID ID;
1786   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1787   ID.AddPointer(MBB);
1788   void *IP = nullptr;
1789   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1790     return SDValue(E, 0);
1791
1792   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1793   CSEMap.InsertNode(N, IP);
1794   InsertNode(N);
1795   return SDValue(N, 0);
1796 }
1797
1798 SDValue SelectionDAG::getValueType(EVT VT) {
1799   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1800       ValueTypeNodes.size())
1801     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1802
1803   SDNode *&N = VT.isExtended() ?
1804     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1805
1806   if (N) return SDValue(N, 0);
1807   N = newSDNode<VTSDNode>(VT);
1808   InsertNode(N);
1809   return SDValue(N, 0);
1810 }
1811
1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1813   SDNode *&N = ExternalSymbols[Sym];
1814   if (N) return SDValue(N, 0);
1815   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1816   InsertNode(N);
1817   return SDValue(N, 0);
1818 }
1819
1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1821   SDNode *&N = MCSymbols[Sym];
1822   if (N)
1823     return SDValue(N, 0);
1824   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1825   InsertNode(N);
1826   return SDValue(N, 0);
1827 }
1828
1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1830                                               unsigned TargetFlags) {
1831   SDNode *&N =
1832       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1833   if (N) return SDValue(N, 0);
1834   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1835   InsertNode(N);
1836   return SDValue(N, 0);
1837 }
1838
1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1840   if ((unsigned)Cond >= CondCodeNodes.size())
1841     CondCodeNodes.resize(Cond+1);
1842
1843   if (!CondCodeNodes[Cond]) {
1844     auto *N = newSDNode<CondCodeSDNode>(Cond);
1845     CondCodeNodes[Cond] = N;
1846     InsertNode(N);
1847   }
1848
1849   return SDValue(CondCodeNodes[Cond], 0);
1850 }
1851
1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1853   APInt One(ResVT.getScalarSizeInBits(), 1);
1854   return getStepVector(DL, ResVT, One);
1855 }
1856
1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1858   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1859   if (ResVT.isScalableVector())
1860     return getNode(
1861         ISD::STEP_VECTOR, DL, ResVT,
1862         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1863
1864   SmallVector<SDValue, 16> OpsStepConstants;
1865   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1866     OpsStepConstants.push_back(
1867         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1868   return getBuildVector(ResVT, DL, OpsStepConstants);
1869 }
1870
1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1874   std::swap(N1, N2);
1875   ShuffleVectorSDNode::commuteMask(M);
1876 }
1877
1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1879                                        SDValue N2, ArrayRef<int> Mask) {
1880   assert(VT.getVectorNumElements() == Mask.size() &&
1881          "Must have the same number of vector elements as mask elements!");
1882   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1883          "Invalid VECTOR_SHUFFLE");
1884
1885   // Canonicalize shuffle undef, undef -> undef
1886   if (N1.isUndef() && N2.isUndef())
1887     return getUNDEF(VT);
1888
1889   // Validate that all indices in Mask are within the range of the elements
1890   // input to the shuffle.
1891   int NElts = Mask.size();
1892   assert(llvm::all_of(Mask,
1893                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1894          "Index out of range");
1895
1896   // Copy the mask so we can do any needed cleanup.
1897   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1898
1899   // Canonicalize shuffle v, v -> v, undef
1900   if (N1 == N2) {
1901     N2 = getUNDEF(VT);
1902     for (int i = 0; i != NElts; ++i)
1903       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1904   }
1905
1906   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1907   if (N1.isUndef())
1908     commuteShuffle(N1, N2, MaskVec);
1909
1910   if (TLI->hasVectorBlend()) {
1911     // If shuffling a splat, try to blend the splat instead. We do this here so
1912     // that even when this arises during lowering we don't have to re-handle it.
1913     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1914       BitVector UndefElements;
1915       SDValue Splat = BV->getSplatValue(&UndefElements);
1916       if (!Splat)
1917         return;
1918
1919       for (int i = 0; i < NElts; ++i) {
1920         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1921           continue;
1922
1923         // If this input comes from undef, mark it as such.
1924         if (UndefElements[MaskVec[i] - Offset]) {
1925           MaskVec[i] = -1;
1926           continue;
1927         }
1928
1929         // If we can blend a non-undef lane, use that instead.
1930         if (!UndefElements[i])
1931           MaskVec[i] = i + Offset;
1932       }
1933     };
1934     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1935       BlendSplat(N1BV, 0);
1936     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1937       BlendSplat(N2BV, NElts);
1938   }
1939
1940   // Canonicalize all index into lhs, -> shuffle lhs, undef
1941   // Canonicalize all index into rhs, -> shuffle rhs, undef
1942   bool AllLHS = true, AllRHS = true;
1943   bool N2Undef = N2.isUndef();
1944   for (int i = 0; i != NElts; ++i) {
1945     if (MaskVec[i] >= NElts) {
1946       if (N2Undef)
1947         MaskVec[i] = -1;
1948       else
1949         AllLHS = false;
1950     } else if (MaskVec[i] >= 0) {
1951       AllRHS = false;
1952     }
1953   }
1954   if (AllLHS && AllRHS)
1955     return getUNDEF(VT);
1956   if (AllLHS && !N2Undef)
1957     N2 = getUNDEF(VT);
1958   if (AllRHS) {
1959     N1 = getUNDEF(VT);
1960     commuteShuffle(N1, N2, MaskVec);
1961   }
1962   // Reset our undef status after accounting for the mask.
1963   N2Undef = N2.isUndef();
1964   // Re-check whether both sides ended up undef.
1965   if (N1.isUndef() && N2Undef)
1966     return getUNDEF(VT);
1967
1968   // If Identity shuffle return that node.
1969   bool Identity = true, AllSame = true;
1970   for (int i = 0; i != NElts; ++i) {
1971     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1972     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1973   }
1974   if (Identity && NElts)
1975     return N1;
1976
1977   // Shuffling a constant splat doesn't change the result.
1978   if (N2Undef) {
1979     SDValue V = N1;
1980
1981     // Look through any bitcasts. We check that these don't change the number
1982     // (and size) of elements and just changes their types.
1983     while (V.getOpcode() == ISD::BITCAST)
1984       V = V->getOperand(0);
1985
1986     // A splat should always show up as a build vector node.
1987     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1988       BitVector UndefElements;
1989       SDValue Splat = BV->getSplatValue(&UndefElements);
1990       // If this is a splat of an undef, shuffling it is also undef.
1991       if (Splat && Splat.isUndef())
1992         return getUNDEF(VT);
1993
1994       bool SameNumElts =
1995           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1996
1997       // We only have a splat which can skip shuffles if there is a splatted
1998       // value and no undef lanes rearranged by the shuffle.
1999       if (Splat && UndefElements.none()) {
2000         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2001         // number of elements match or the value splatted is a zero constant.
2002         if (SameNumElts)
2003           return N1;
2004         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
2005           if (C->isZero())
2006             return N1;
2007       }
2008
2009       // If the shuffle itself creates a splat, build the vector directly.
2010       if (AllSame && SameNumElts) {
2011         EVT BuildVT = BV->getValueType(0);
2012         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2013         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2014
2015         // We may have jumped through bitcasts, so the type of the
2016         // BUILD_VECTOR may not match the type of the shuffle.
2017         if (BuildVT != VT)
2018           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2019         return NewBV;
2020       }
2021     }
2022   }
2023
2024   FoldingSetNodeID ID;
2025   SDValue Ops[2] = { N1, N2 };
2026   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2027   for (int i = 0; i != NElts; ++i)
2028     ID.AddInteger(MaskVec[i]);
2029
2030   void* IP = nullptr;
2031   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2032     return SDValue(E, 0);
2033
2034   // Allocate the mask array for the node out of the BumpPtrAllocator, since
2035   // SDNode doesn't have access to it.  This memory will be "leaked" when
2036   // the node is deallocated, but recovered when the NodeAllocator is released.
2037   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2038   llvm::copy(MaskVec, MaskAlloc);
2039
2040   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2041                                            dl.getDebugLoc(), MaskAlloc);
2042   createOperands(N, Ops);
2043
2044   CSEMap.InsertNode(N, IP);
2045   InsertNode(N);
2046   SDValue V = SDValue(N, 0);
2047   NewSDValueDbgMsg(V, "Creating new node: ", this);
2048   return V;
2049 }
2050
2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2052   EVT VT = SV.getValueType(0);
2053   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2054   ShuffleVectorSDNode::commuteMask(MaskVec);
2055
2056   SDValue Op0 = SV.getOperand(0);
2057   SDValue Op1 = SV.getOperand(1);
2058   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2059 }
2060
2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2062   FoldingSetNodeID ID;
2063   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2064   ID.AddInteger(RegNo);
2065   void *IP = nullptr;
2066   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067     return SDValue(E, 0);
2068
2069   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2070   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2071   CSEMap.InsertNode(N, IP);
2072   InsertNode(N);
2073   return SDValue(N, 0);
2074 }
2075
2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2077   FoldingSetNodeID ID;
2078   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2079   ID.AddPointer(RegMask);
2080   void *IP = nullptr;
2081   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2082     return SDValue(E, 0);
2083
2084   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2085   CSEMap.InsertNode(N, IP);
2086   InsertNode(N);
2087   return SDValue(N, 0);
2088 }
2089
2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2091                                  MCSymbol *Label) {
2092   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2093 }
2094
2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2096                                    SDValue Root, MCSymbol *Label) {
2097   FoldingSetNodeID ID;
2098   SDValue Ops[] = { Root };
2099   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2100   ID.AddPointer(Label);
2101   void *IP = nullptr;
2102   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2103     return SDValue(E, 0);
2104
2105   auto *N =
2106       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2107   createOperands(N, Ops);
2108
2109   CSEMap.InsertNode(N, IP);
2110   InsertNode(N);
2111   return SDValue(N, 0);
2112 }
2113
2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2115                                       int64_t Offset, bool isTarget,
2116                                       unsigned TargetFlags) {
2117   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2118
2119   FoldingSetNodeID ID;
2120   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2121   ID.AddPointer(BA);
2122   ID.AddInteger(Offset);
2123   ID.AddInteger(TargetFlags);
2124   void *IP = nullptr;
2125   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2126     return SDValue(E, 0);
2127
2128   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2129   CSEMap.InsertNode(N, IP);
2130   InsertNode(N);
2131   return SDValue(N, 0);
2132 }
2133
2134 SDValue SelectionDAG::getSrcValue(const Value *V) {
2135   FoldingSetNodeID ID;
2136   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2137   ID.AddPointer(V);
2138
2139   void *IP = nullptr;
2140   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2141     return SDValue(E, 0);
2142
2143   auto *N = newSDNode<SrcValueSDNode>(V);
2144   CSEMap.InsertNode(N, IP);
2145   InsertNode(N);
2146   return SDValue(N, 0);
2147 }
2148
2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2150   FoldingSetNodeID ID;
2151   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2152   ID.AddPointer(MD);
2153
2154   void *IP = nullptr;
2155   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2156     return SDValue(E, 0);
2157
2158   auto *N = newSDNode<MDNodeSDNode>(MD);
2159   CSEMap.InsertNode(N, IP);
2160   InsertNode(N);
2161   return SDValue(N, 0);
2162 }
2163
2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2165   if (VT == V.getValueType())
2166     return V;
2167
2168   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2169 }
2170
2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2172                                        unsigned SrcAS, unsigned DestAS) {
2173   SDValue Ops[] = {Ptr};
2174   FoldingSetNodeID ID;
2175   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2176   ID.AddInteger(SrcAS);
2177   ID.AddInteger(DestAS);
2178
2179   void *IP = nullptr;
2180   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2181     return SDValue(E, 0);
2182
2183   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2184                                            VT, SrcAS, DestAS);
2185   createOperands(N, Ops);
2186
2187   CSEMap.InsertNode(N, IP);
2188   InsertNode(N);
2189   return SDValue(N, 0);
2190 }
2191
2192 SDValue SelectionDAG::getFreeze(SDValue V) {
2193   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2194 }
2195
2196 /// getShiftAmountOperand - Return the specified value casted to
2197 /// the target's desired shift amount type.
2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2199   EVT OpTy = Op.getValueType();
2200   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2201   if (OpTy == ShTy || OpTy.isVector()) return Op;
2202
2203   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2204 }
2205
2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2207   SDLoc dl(Node);
2208   const TargetLowering &TLI = getTargetLoweringInfo();
2209   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2210   EVT VT = Node->getValueType(0);
2211   SDValue Tmp1 = Node->getOperand(0);
2212   SDValue Tmp2 = Node->getOperand(1);
2213   const MaybeAlign MA(Node->getConstantOperandVal(3));
2214
2215   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2216                                Tmp2, MachinePointerInfo(V));
2217   SDValue VAList = VAListLoad;
2218
2219   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2220     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2221                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2222
2223     VAList =
2224         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2225                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2226   }
2227
2228   // Increment the pointer, VAList, to the next vaarg
2229   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2230                  getConstant(getDataLayout().getTypeAllocSize(
2231                                                VT.getTypeForEVT(*getContext())),
2232                              dl, VAList.getValueType()));
2233   // Store the incremented VAList to the legalized pointer
2234   Tmp1 =
2235       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2236   // Load the actual argument out of the pointer VAList
2237   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2238 }
2239
2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2241   SDLoc dl(Node);
2242   const TargetLowering &TLI = getTargetLoweringInfo();
2243   // This defaults to loading a pointer from the input and storing it to the
2244   // output, returning the chain.
2245   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2246   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2247   SDValue Tmp1 =
2248       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2249               Node->getOperand(2), MachinePointerInfo(VS));
2250   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2251                   MachinePointerInfo(VD));
2252 }
2253
2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2255   const DataLayout &DL = getDataLayout();
2256   Type *Ty = VT.getTypeForEVT(*getContext());
2257   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2258
2259   if (TLI->isTypeLegal(VT) || !VT.isVector())
2260     return RedAlign;
2261
2262   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2263   const Align StackAlign = TFI->getStackAlign();
2264
2265   // See if we can choose a smaller ABI alignment in cases where it's an
2266   // illegal vector type that will get broken down.
2267   if (RedAlign > StackAlign) {
2268     EVT IntermediateVT;
2269     MVT RegisterVT;
2270     unsigned NumIntermediates;
2271     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2272                                 NumIntermediates, RegisterVT);
2273     Ty = IntermediateVT.getTypeForEVT(*getContext());
2274     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2275     if (RedAlign2 < RedAlign)
2276       RedAlign = RedAlign2;
2277   }
2278
2279   return RedAlign;
2280 }
2281
2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2283   MachineFrameInfo &MFI = MF->getFrameInfo();
2284   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2285   int StackID = 0;
2286   if (Bytes.isScalable())
2287     StackID = TFI->getStackIDForScalableVectors();
2288   // The stack id gives an indication of whether the object is scalable or
2289   // not, so it's safe to pass in the minimum size here.
2290   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2291                                        false, nullptr, StackID);
2292   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2293 }
2294
2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2296   Type *Ty = VT.getTypeForEVT(*getContext());
2297   Align StackAlign =
2298       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2299   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2300 }
2301
2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2303   TypeSize VT1Size = VT1.getStoreSize();
2304   TypeSize VT2Size = VT2.getStoreSize();
2305   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2306          "Don't know how to choose the maximum size when creating a stack "
2307          "temporary");
2308   TypeSize Bytes =
2309       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2310
2311   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2312   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2313   const DataLayout &DL = getDataLayout();
2314   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2315   return CreateStackTemporary(Bytes, Align);
2316 }
2317
2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2319                                 ISD::CondCode Cond, const SDLoc &dl) {
2320   EVT OpVT = N1.getValueType();
2321
2322   // These setcc operations always fold.
2323   switch (Cond) {
2324   default: break;
2325   case ISD::SETFALSE:
2326   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2327   case ISD::SETTRUE:
2328   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2329
2330   case ISD::SETOEQ:
2331   case ISD::SETOGT:
2332   case ISD::SETOGE:
2333   case ISD::SETOLT:
2334   case ISD::SETOLE:
2335   case ISD::SETONE:
2336   case ISD::SETO:
2337   case ISD::SETUO:
2338   case ISD::SETUEQ:
2339   case ISD::SETUNE:
2340     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2341     break;
2342   }
2343
2344   if (OpVT.isInteger()) {
2345     // For EQ and NE, we can always pick a value for the undef to make the
2346     // predicate pass or fail, so we can return undef.
2347     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2348     // icmp eq/ne X, undef -> undef.
2349     if ((N1.isUndef() || N2.isUndef()) &&
2350         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2351       return getUNDEF(VT);
2352
2353     // If both operands are undef, we can return undef for int comparison.
2354     // icmp undef, undef -> undef.
2355     if (N1.isUndef() && N2.isUndef())
2356       return getUNDEF(VT);
2357
2358     // icmp X, X -> true/false
2359     // icmp X, undef -> true/false because undef could be X.
2360     if (N1 == N2)
2361       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2362   }
2363
2364   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2365     const APInt &C2 = N2C->getAPIntValue();
2366     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2367       const APInt &C1 = N1C->getAPIntValue();
2368
2369       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2370                              dl, VT, OpVT);
2371     }
2372   }
2373
2374   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2375   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2376
2377   if (N1CFP && N2CFP) {
2378     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2379     switch (Cond) {
2380     default: break;
2381     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2382                         return getUNDEF(VT);
2383                       LLVM_FALLTHROUGH;
2384     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2385                                              OpVT);
2386     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2387                         return getUNDEF(VT);
2388                       LLVM_FALLTHROUGH;
2389     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390                                              R==APFloat::cmpLessThan, dl, VT,
2391                                              OpVT);
2392     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2393                         return getUNDEF(VT);
2394                       LLVM_FALLTHROUGH;
2395     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2396                                              OpVT);
2397     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2398                         return getUNDEF(VT);
2399                       LLVM_FALLTHROUGH;
2400     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2401                                              VT, OpVT);
2402     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2403                         return getUNDEF(VT);
2404                       LLVM_FALLTHROUGH;
2405     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2406                                              R==APFloat::cmpEqual, dl, VT,
2407                                              OpVT);
2408     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2409                         return getUNDEF(VT);
2410                       LLVM_FALLTHROUGH;
2411     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2412                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2413     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2414                                              OpVT);
2415     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2416                                              OpVT);
2417     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2418                                              R==APFloat::cmpEqual, dl, VT,
2419                                              OpVT);
2420     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2421                                              OpVT);
2422     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2423                                              R==APFloat::cmpLessThan, dl, VT,
2424                                              OpVT);
2425     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2426                                              R==APFloat::cmpUnordered, dl, VT,
2427                                              OpVT);
2428     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2429                                              VT, OpVT);
2430     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2431                                              OpVT);
2432     }
2433   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2434     // Ensure that the constant occurs on the RHS.
2435     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2436     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2437       return SDValue();
2438     return getSetCC(dl, VT, N2, N1, SwappedCond);
2439   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2440              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2441     // If an operand is known to be a nan (or undef that could be a nan), we can
2442     // fold it.
2443     // Choosing NaN for the undef will always make unordered comparison succeed
2444     // and ordered comparison fails.
2445     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2446     switch (ISD::getUnorderedFlavor(Cond)) {
2447     default:
2448       llvm_unreachable("Unknown flavor!");
2449     case 0: // Known false.
2450       return getBoolConstant(false, dl, VT, OpVT);
2451     case 1: // Known true.
2452       return getBoolConstant(true, dl, VT, OpVT);
2453     case 2: // Undefined.
2454       return getUNDEF(VT);
2455     }
2456   }
2457
2458   // Could not fold it.
2459   return SDValue();
2460 }
2461
2462 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2463 /// use this predicate to simplify operations downstream.
2464 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2465   unsigned BitWidth = Op.getScalarValueSizeInBits();
2466   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2467 }
2468
2469 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2470 /// this predicate to simplify operations downstream.  Mask is known to be zero
2471 /// for bits that V cannot have.
2472 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2473                                      unsigned Depth) const {
2474   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2475 }
2476
2477 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2478 /// DemandedElts.  We use this predicate to simplify operations downstream.
2479 /// Mask is known to be zero for bits that V cannot have.
2480 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2481                                      const APInt &DemandedElts,
2482                                      unsigned Depth) const {
2483   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2484 }
2485
2486 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2487 /// DemandedElts.  We use this predicate to simplify operations downstream.
2488 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts,
2489                                       unsigned Depth /* = 0 */) const {
2490   return computeKnownBits(V, DemandedElts, Depth).isZero();
2491 }
2492
2493 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2494 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2495                                         unsigned Depth) const {
2496   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2497 }
2498
2499 /// isSplatValue - Return true if the vector V has the same value
2500 /// across all DemandedElts. For scalable vectors it does not make
2501 /// sense to specify which elements are demanded or undefined, therefore
2502 /// they are simply ignored.
2503 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2504                                 APInt &UndefElts, unsigned Depth) const {
2505   unsigned Opcode = V.getOpcode();
2506   EVT VT = V.getValueType();
2507   assert(VT.isVector() && "Vector type expected");
2508
2509   if (!VT.isScalableVector() && !DemandedElts)
2510     return false; // No demanded elts, better to assume we don't know anything.
2511
2512   if (Depth >= MaxRecursionDepth)
2513     return false; // Limit search depth.
2514
2515   // Deal with some common cases here that work for both fixed and scalable
2516   // vector types.
2517   switch (Opcode) {
2518   case ISD::SPLAT_VECTOR:
2519     UndefElts = V.getOperand(0).isUndef()
2520                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2521                     : APInt(DemandedElts.getBitWidth(), 0);
2522     return true;
2523   case ISD::ADD:
2524   case ISD::SUB:
2525   case ISD::AND:
2526   case ISD::XOR:
2527   case ISD::OR: {
2528     APInt UndefLHS, UndefRHS;
2529     SDValue LHS = V.getOperand(0);
2530     SDValue RHS = V.getOperand(1);
2531     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2532         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2533       UndefElts = UndefLHS | UndefRHS;
2534       return true;
2535     }
2536     return false;
2537   }
2538   case ISD::ABS:
2539   case ISD::TRUNCATE:
2540   case ISD::SIGN_EXTEND:
2541   case ISD::ZERO_EXTEND:
2542     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2543   default:
2544     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2545         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2546       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2547     break;
2548 }
2549
2550   // We don't support other cases than those above for scalable vectors at
2551   // the moment.
2552   if (VT.isScalableVector())
2553     return false;
2554
2555   unsigned NumElts = VT.getVectorNumElements();
2556   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2557   UndefElts = APInt::getZero(NumElts);
2558
2559   switch (Opcode) {
2560   case ISD::BUILD_VECTOR: {
2561     SDValue Scl;
2562     for (unsigned i = 0; i != NumElts; ++i) {
2563       SDValue Op = V.getOperand(i);
2564       if (Op.isUndef()) {
2565         UndefElts.setBit(i);
2566         continue;
2567       }
2568       if (!DemandedElts[i])
2569         continue;
2570       if (Scl && Scl != Op)
2571         return false;
2572       Scl = Op;
2573     }
2574     return true;
2575   }
2576   case ISD::VECTOR_SHUFFLE: {
2577     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2578     APInt DemandedLHS = APInt::getNullValue(NumElts);
2579     APInt DemandedRHS = APInt::getNullValue(NumElts);
2580     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2581     for (int i = 0; i != (int)NumElts; ++i) {
2582       int M = Mask[i];
2583       if (M < 0) {
2584         UndefElts.setBit(i);
2585         continue;
2586       }
2587       if (!DemandedElts[i])
2588         continue;
2589       if (M < (int)NumElts)
2590         DemandedLHS.setBit(M);
2591       else
2592         DemandedRHS.setBit(M - NumElts);
2593     }
2594
2595     // If we aren't demanding either op, assume there's no splat.
2596     // If we are demanding both ops, assume there's no splat.
2597     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2598         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2599       return false;
2600
2601     // See if the demanded elts of the source op is a splat or we only demand
2602     // one element, which should always be a splat.
2603     // TODO: Handle source ops splats with undefs.
2604     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2605       APInt SrcUndefs;
2606       return (SrcElts.countPopulation() == 1) ||
2607              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2608               (SrcElts & SrcUndefs).isZero());
2609     };
2610     if (!DemandedLHS.isZero())
2611       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2612     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2613   }
2614   case ISD::EXTRACT_SUBVECTOR: {
2615     // Offset the demanded elts by the subvector index.
2616     SDValue Src = V.getOperand(0);
2617     // We don't support scalable vectors at the moment.
2618     if (Src.getValueType().isScalableVector())
2619       return false;
2620     uint64_t Idx = V.getConstantOperandVal(1);
2621     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2622     APInt UndefSrcElts;
2623     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2624     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2625       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2626       return true;
2627     }
2628     break;
2629   }
2630   case ISD::ANY_EXTEND_VECTOR_INREG:
2631   case ISD::SIGN_EXTEND_VECTOR_INREG:
2632   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2633     // Widen the demanded elts by the src element count.
2634     SDValue Src = V.getOperand(0);
2635     // We don't support scalable vectors at the moment.
2636     if (Src.getValueType().isScalableVector())
2637       return false;
2638     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2639     APInt UndefSrcElts;
2640     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
2641     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2642       UndefElts = UndefSrcElts.trunc(NumElts);
2643       return true;
2644     }
2645     break;
2646   }
2647   case ISD::BITCAST: {
2648     SDValue Src = V.getOperand(0);
2649     EVT SrcVT = Src.getValueType();
2650     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2651     unsigned BitWidth = VT.getScalarSizeInBits();
2652
2653     // Ignore bitcasts from unsupported types.
2654     // TODO: Add fp support?
2655     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2656       break;
2657
2658     // Bitcast 'small element' vector to 'large element' vector.
2659     if ((BitWidth % SrcBitWidth) == 0) {
2660       // See if each sub element is a splat.
2661       unsigned Scale = BitWidth / SrcBitWidth;
2662       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2663       APInt ScaledDemandedElts =
2664           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2665       for (unsigned I = 0; I != Scale; ++I) {
2666         APInt SubUndefElts;
2667         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2668         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2669         SubDemandedElts &= ScaledDemandedElts;
2670         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2671           return false;
2672         // TODO: Add support for merging sub undef elements.
2673         if (!SubUndefElts.isZero())
2674           return false;
2675       }
2676       return true;
2677     }
2678     break;
2679   }
2680   }
2681
2682   return false;
2683 }
2684
2685 /// Helper wrapper to main isSplatValue function.
2686 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2687   EVT VT = V.getValueType();
2688   assert(VT.isVector() && "Vector type expected");
2689
2690   APInt UndefElts;
2691   APInt DemandedElts;
2692
2693   // For now we don't support this with scalable vectors.
2694   if (!VT.isScalableVector())
2695     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2696   return isSplatValue(V, DemandedElts, UndefElts) &&
2697          (AllowUndefs || !UndefElts);
2698 }
2699
2700 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2701   V = peekThroughExtractSubvectors(V);
2702
2703   EVT VT = V.getValueType();
2704   unsigned Opcode = V.getOpcode();
2705   switch (Opcode) {
2706   default: {
2707     APInt UndefElts;
2708     APInt DemandedElts;
2709
2710     if (!VT.isScalableVector())
2711       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2712
2713     if (isSplatValue(V, DemandedElts, UndefElts)) {
2714       if (VT.isScalableVector()) {
2715         // DemandedElts and UndefElts are ignored for scalable vectors, since
2716         // the only supported cases are SPLAT_VECTOR nodes.
2717         SplatIdx = 0;
2718       } else {
2719         // Handle case where all demanded elements are UNDEF.
2720         if (DemandedElts.isSubsetOf(UndefElts)) {
2721           SplatIdx = 0;
2722           return getUNDEF(VT);
2723         }
2724         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2725       }
2726       return V;
2727     }
2728     break;
2729   }
2730   case ISD::SPLAT_VECTOR:
2731     SplatIdx = 0;
2732     return V;
2733   case ISD::VECTOR_SHUFFLE: {
2734     if (VT.isScalableVector())
2735       return SDValue();
2736
2737     // Check if this is a shuffle node doing a splat.
2738     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2739     // getTargetVShiftNode currently struggles without the splat source.
2740     auto *SVN = cast<ShuffleVectorSDNode>(V);
2741     if (!SVN->isSplat())
2742       break;
2743     int Idx = SVN->getSplatIndex();
2744     int NumElts = V.getValueType().getVectorNumElements();
2745     SplatIdx = Idx % NumElts;
2746     return V.getOperand(Idx / NumElts);
2747   }
2748   }
2749
2750   return SDValue();
2751 }
2752
2753 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2754   int SplatIdx;
2755   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2756     EVT SVT = SrcVector.getValueType().getScalarType();
2757     EVT LegalSVT = SVT;
2758     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2759       if (!SVT.isInteger())
2760         return SDValue();
2761       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2762       if (LegalSVT.bitsLT(SVT))
2763         return SDValue();
2764     }
2765     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2766                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2767   }
2768   return SDValue();
2769 }
2770
2771 const APInt *
2772 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2773                                           const APInt &DemandedElts) const {
2774   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2775           V.getOpcode() == ISD::SRA) &&
2776          "Unknown shift node");
2777   unsigned BitWidth = V.getScalarValueSizeInBits();
2778   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2779     // Shifting more than the bitwidth is not valid.
2780     const APInt &ShAmt = SA->getAPIntValue();
2781     if (ShAmt.ult(BitWidth))
2782       return &ShAmt;
2783   }
2784   return nullptr;
2785 }
2786
2787 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2788     SDValue V, const APInt &DemandedElts) const {
2789   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2790           V.getOpcode() == ISD::SRA) &&
2791          "Unknown shift node");
2792   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2793     return ValidAmt;
2794   unsigned BitWidth = V.getScalarValueSizeInBits();
2795   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2796   if (!BV)
2797     return nullptr;
2798   const APInt *MinShAmt = nullptr;
2799   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2800     if (!DemandedElts[i])
2801       continue;
2802     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2803     if (!SA)
2804       return nullptr;
2805     // Shifting more than the bitwidth is not valid.
2806     const APInt &ShAmt = SA->getAPIntValue();
2807     if (ShAmt.uge(BitWidth))
2808       return nullptr;
2809     if (MinShAmt && MinShAmt->ule(ShAmt))
2810       continue;
2811     MinShAmt = &ShAmt;
2812   }
2813   return MinShAmt;
2814 }
2815
2816 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2817     SDValue V, const APInt &DemandedElts) const {
2818   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2819           V.getOpcode() == ISD::SRA) &&
2820          "Unknown shift node");
2821   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2822     return ValidAmt;
2823   unsigned BitWidth = V.getScalarValueSizeInBits();
2824   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2825   if (!BV)
2826     return nullptr;
2827   const APInt *MaxShAmt = nullptr;
2828   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2829     if (!DemandedElts[i])
2830       continue;
2831     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2832     if (!SA)
2833       return nullptr;
2834     // Shifting more than the bitwidth is not valid.
2835     const APInt &ShAmt = SA->getAPIntValue();
2836     if (ShAmt.uge(BitWidth))
2837       return nullptr;
2838     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2839       continue;
2840     MaxShAmt = &ShAmt;
2841   }
2842   return MaxShAmt;
2843 }
2844
2845 /// Determine which bits of Op are known to be either zero or one and return
2846 /// them in Known. For vectors, the known bits are those that are shared by
2847 /// every vector element.
2848 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2849   EVT VT = Op.getValueType();
2850
2851   // TOOD: Until we have a plan for how to represent demanded elements for
2852   // scalable vectors, we can just bail out for now.
2853   if (Op.getValueType().isScalableVector()) {
2854     unsigned BitWidth = Op.getScalarValueSizeInBits();
2855     return KnownBits(BitWidth);
2856   }
2857
2858   APInt DemandedElts = VT.isVector()
2859                            ? APInt::getAllOnes(VT.getVectorNumElements())
2860                            : APInt(1, 1);
2861   return computeKnownBits(Op, DemandedElts, Depth);
2862 }
2863
2864 /// Determine which bits of Op are known to be either zero or one and return
2865 /// them in Known. The DemandedElts argument allows us to only collect the known
2866 /// bits that are shared by the requested vector elements.
2867 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2868                                          unsigned Depth) const {
2869   unsigned BitWidth = Op.getScalarValueSizeInBits();
2870
2871   KnownBits Known(BitWidth);   // Don't know anything.
2872
2873   // TOOD: Until we have a plan for how to represent demanded elements for
2874   // scalable vectors, we can just bail out for now.
2875   if (Op.getValueType().isScalableVector())
2876     return Known;
2877
2878   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2879     // We know all of the bits for a constant!
2880     return KnownBits::makeConstant(C->getAPIntValue());
2881   }
2882   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2883     // We know all of the bits for a constant fp!
2884     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2885   }
2886
2887   if (Depth >= MaxRecursionDepth)
2888     return Known;  // Limit search depth.
2889
2890   KnownBits Known2;
2891   unsigned NumElts = DemandedElts.getBitWidth();
2892   assert((!Op.getValueType().isVector() ||
2893           NumElts == Op.getValueType().getVectorNumElements()) &&
2894          "Unexpected vector size");
2895
2896   if (!DemandedElts)
2897     return Known;  // No demanded elts, better to assume we don't know anything.
2898
2899   unsigned Opcode = Op.getOpcode();
2900   switch (Opcode) {
2901   case ISD::MERGE_VALUES:
2902     return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
2903                             Depth + 1);
2904   case ISD::BUILD_VECTOR:
2905     // Collect the known bits that are shared by every demanded vector element.
2906     Known.Zero.setAllBits(); Known.One.setAllBits();
2907     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2908       if (!DemandedElts[i])
2909         continue;
2910
2911       SDValue SrcOp = Op.getOperand(i);
2912       Known2 = computeKnownBits(SrcOp, Depth + 1);
2913
2914       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2915       if (SrcOp.getValueSizeInBits() != BitWidth) {
2916         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2917                "Expected BUILD_VECTOR implicit truncation");
2918         Known2 = Known2.trunc(BitWidth);
2919       }
2920
2921       // Known bits are the values that are shared by every demanded element.
2922       Known = KnownBits::commonBits(Known, Known2);
2923
2924       // If we don't know any bits, early out.
2925       if (Known.isUnknown())
2926         break;
2927     }
2928     break;
2929   case ISD::VECTOR_SHUFFLE: {
2930     // Collect the known bits that are shared by every vector element referenced
2931     // by the shuffle.
2932     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2933     Known.Zero.setAllBits(); Known.One.setAllBits();
2934     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2935     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2936     for (unsigned i = 0; i != NumElts; ++i) {
2937       if (!DemandedElts[i])
2938         continue;
2939
2940       int M = SVN->getMaskElt(i);
2941       if (M < 0) {
2942         // For UNDEF elements, we don't know anything about the common state of
2943         // the shuffle result.
2944         Known.resetAll();
2945         DemandedLHS.clearAllBits();
2946         DemandedRHS.clearAllBits();
2947         break;
2948       }
2949
2950       if ((unsigned)M < NumElts)
2951         DemandedLHS.setBit((unsigned)M % NumElts);
2952       else
2953         DemandedRHS.setBit((unsigned)M % NumElts);
2954     }
2955     // Known bits are the values that are shared by every demanded element.
2956     if (!!DemandedLHS) {
2957       SDValue LHS = Op.getOperand(0);
2958       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2959       Known = KnownBits::commonBits(Known, Known2);
2960     }
2961     // If we don't know any bits, early out.
2962     if (Known.isUnknown())
2963       break;
2964     if (!!DemandedRHS) {
2965       SDValue RHS = Op.getOperand(1);
2966       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2967       Known = KnownBits::commonBits(Known, Known2);
2968     }
2969     break;
2970   }
2971   case ISD::CONCAT_VECTORS: {
2972     // Split DemandedElts and test each of the demanded subvectors.
2973     Known.Zero.setAllBits(); Known.One.setAllBits();
2974     EVT SubVectorVT = Op.getOperand(0).getValueType();
2975     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2976     unsigned NumSubVectors = Op.getNumOperands();
2977     for (unsigned i = 0; i != NumSubVectors; ++i) {
2978       APInt DemandedSub =
2979           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2980       if (!!DemandedSub) {
2981         SDValue Sub = Op.getOperand(i);
2982         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2983         Known = KnownBits::commonBits(Known, Known2);
2984       }
2985       // If we don't know any bits, early out.
2986       if (Known.isUnknown())
2987         break;
2988     }
2989     break;
2990   }
2991   case ISD::INSERT_SUBVECTOR: {
2992     // Demand any elements from the subvector and the remainder from the src its
2993     // inserted into.
2994     SDValue Src = Op.getOperand(0);
2995     SDValue Sub = Op.getOperand(1);
2996     uint64_t Idx = Op.getConstantOperandVal(2);
2997     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2998     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2999     APInt DemandedSrcElts = DemandedElts;
3000     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3001
3002     Known.One.setAllBits();
3003     Known.Zero.setAllBits();
3004     if (!!DemandedSubElts) {
3005       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3006       if (Known.isUnknown())
3007         break; // early-out.
3008     }
3009     if (!!DemandedSrcElts) {
3010       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3011       Known = KnownBits::commonBits(Known, Known2);
3012     }
3013     break;
3014   }
3015   case ISD::EXTRACT_SUBVECTOR: {
3016     // Offset the demanded elts by the subvector index.
3017     SDValue Src = Op.getOperand(0);
3018     // Bail until we can represent demanded elements for scalable vectors.
3019     if (Src.getValueType().isScalableVector())
3020       break;
3021     uint64_t Idx = Op.getConstantOperandVal(1);
3022     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3023     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3024     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3025     break;
3026   }
3027   case ISD::SCALAR_TO_VECTOR: {
3028     // We know about scalar_to_vector as much as we know about it source,
3029     // which becomes the first element of otherwise unknown vector.
3030     if (DemandedElts != 1)
3031       break;
3032
3033     SDValue N0 = Op.getOperand(0);
3034     Known = computeKnownBits(N0, Depth + 1);
3035     if (N0.getValueSizeInBits() != BitWidth)
3036       Known = Known.trunc(BitWidth);
3037
3038     break;
3039   }
3040   case ISD::BITCAST: {
3041     SDValue N0 = Op.getOperand(0);
3042     EVT SubVT = N0.getValueType();
3043     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3044
3045     // Ignore bitcasts from unsupported types.
3046     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3047       break;
3048
3049     // Fast handling of 'identity' bitcasts.
3050     if (BitWidth == SubBitWidth) {
3051       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3052       break;
3053     }
3054
3055     bool IsLE = getDataLayout().isLittleEndian();
3056
3057     // Bitcast 'small element' vector to 'large element' scalar/vector.
3058     if ((BitWidth % SubBitWidth) == 0) {
3059       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3060
3061       // Collect known bits for the (larger) output by collecting the known
3062       // bits from each set of sub elements and shift these into place.
3063       // We need to separately call computeKnownBits for each set of
3064       // sub elements as the knownbits for each is likely to be different.
3065       unsigned SubScale = BitWidth / SubBitWidth;
3066       APInt SubDemandedElts(NumElts * SubScale, 0);
3067       for (unsigned i = 0; i != NumElts; ++i)
3068         if (DemandedElts[i])
3069           SubDemandedElts.setBit(i * SubScale);
3070
3071       for (unsigned i = 0; i != SubScale; ++i) {
3072         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3073                          Depth + 1);
3074         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3075         Known.insertBits(Known2, SubBitWidth * Shifts);
3076       }
3077     }
3078
3079     // Bitcast 'large element' scalar/vector to 'small element' vector.
3080     if ((SubBitWidth % BitWidth) == 0) {
3081       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3082
3083       // Collect known bits for the (smaller) output by collecting the known
3084       // bits from the overlapping larger input elements and extracting the
3085       // sub sections we actually care about.
3086       unsigned SubScale = SubBitWidth / BitWidth;
3087       APInt SubDemandedElts =
3088           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3089       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3090
3091       Known.Zero.setAllBits(); Known.One.setAllBits();
3092       for (unsigned i = 0; i != NumElts; ++i)
3093         if (DemandedElts[i]) {
3094           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3095           unsigned Offset = (Shifts % SubScale) * BitWidth;
3096           Known = KnownBits::commonBits(Known,
3097                                         Known2.extractBits(BitWidth, Offset));
3098           // If we don't know any bits, early out.
3099           if (Known.isUnknown())
3100             break;
3101         }
3102     }
3103     break;
3104   }
3105   case ISD::AND:
3106     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3107     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3108
3109     Known &= Known2;
3110     break;
3111   case ISD::OR:
3112     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3113     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3114
3115     Known |= Known2;
3116     break;
3117   case ISD::XOR:
3118     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3119     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3120
3121     Known ^= Known2;
3122     break;
3123   case ISD::MUL: {
3124     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3125     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3126     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3127     // TODO: SelfMultiply can be poison, but not undef.
3128     if (SelfMultiply)
3129       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3130           Op.getOperand(0), DemandedElts, false, Depth + 1);
3131     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3132
3133     // If the multiplication is known not to overflow, the product of a number
3134     // with itself is non-negative. Only do this if we didn't already computed
3135     // the opposite value for the sign bit.
3136     if (Op->getFlags().hasNoSignedWrap() &&
3137         Op.getOperand(0) == Op.getOperand(1) &&
3138         !Known.isNegative())
3139       Known.makeNonNegative();
3140     break;
3141   }
3142   case ISD::MULHU: {
3143     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3144     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3145     Known = KnownBits::mulhu(Known, Known2);
3146     break;
3147   }
3148   case ISD::MULHS: {
3149     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3150     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3151     Known = KnownBits::mulhs(Known, Known2);
3152     break;
3153   }
3154   case ISD::UMUL_LOHI: {
3155     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3156     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3157     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3158     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3159     if (Op.getResNo() == 0)
3160       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3161     else
3162       Known = KnownBits::mulhu(Known, Known2);
3163     break;
3164   }
3165   case ISD::SMUL_LOHI: {
3166     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3167     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3168     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3169     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3170     if (Op.getResNo() == 0)
3171       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3172     else
3173       Known = KnownBits::mulhs(Known, Known2);
3174     break;
3175   }
3176   case ISD::AVGCEILU: {
3177     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3178     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3179     Known = Known.zext(BitWidth + 1);
3180     Known2 = Known2.zext(BitWidth + 1);
3181     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3182     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3183     Known = Known.extractBits(BitWidth, 1);
3184     break;
3185   }
3186   case ISD::SELECT:
3187   case ISD::VSELECT:
3188     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3189     // If we don't know any bits, early out.
3190     if (Known.isUnknown())
3191       break;
3192     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3193
3194     // Only known if known in both the LHS and RHS.
3195     Known = KnownBits::commonBits(Known, Known2);
3196     break;
3197   case ISD::SELECT_CC:
3198     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3199     // If we don't know any bits, early out.
3200     if (Known.isUnknown())
3201       break;
3202     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3203
3204     // Only known if known in both the LHS and RHS.
3205     Known = KnownBits::commonBits(Known, Known2);
3206     break;
3207   case ISD::SMULO:
3208   case ISD::UMULO:
3209     if (Op.getResNo() != 1)
3210       break;
3211     // The boolean result conforms to getBooleanContents.
3212     // If we know the result of a setcc has the top bits zero, use this info.
3213     // We know that we have an integer-based boolean since these operations
3214     // are only available for integer.
3215     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3216             TargetLowering::ZeroOrOneBooleanContent &&
3217         BitWidth > 1)
3218       Known.Zero.setBitsFrom(1);
3219     break;
3220   case ISD::SETCC:
3221   case ISD::SETCCCARRY:
3222   case ISD::STRICT_FSETCC:
3223   case ISD::STRICT_FSETCCS: {
3224     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3225     // If we know the result of a setcc has the top bits zero, use this info.
3226     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3227             TargetLowering::ZeroOrOneBooleanContent &&
3228         BitWidth > 1)
3229       Known.Zero.setBitsFrom(1);
3230     break;
3231   }
3232   case ISD::SHL:
3233     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3234     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3235     Known = KnownBits::shl(Known, Known2);
3236
3237     // Minimum shift low bits are known zero.
3238     if (const APInt *ShMinAmt =
3239             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3240       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3241     break;
3242   case ISD::SRL:
3243     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3244     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3245     Known = KnownBits::lshr(Known, Known2);
3246
3247     // Minimum shift high bits are known zero.
3248     if (const APInt *ShMinAmt =
3249             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3250       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3251     break;
3252   case ISD::SRA:
3253     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3254     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3255     Known = KnownBits::ashr(Known, Known2);
3256     // TODO: Add minimum shift high known sign bits.
3257     break;
3258   case ISD::FSHL:
3259   case ISD::FSHR:
3260     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3261       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3262
3263       // For fshl, 0-shift returns the 1st arg.
3264       // For fshr, 0-shift returns the 2nd arg.
3265       if (Amt == 0) {
3266         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3267                                  DemandedElts, Depth + 1);
3268         break;
3269       }
3270
3271       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3272       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3273       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3274       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3275       if (Opcode == ISD::FSHL) {
3276         Known.One <<= Amt;
3277         Known.Zero <<= Amt;
3278         Known2.One.lshrInPlace(BitWidth - Amt);
3279         Known2.Zero.lshrInPlace(BitWidth - Amt);
3280       } else {
3281         Known.One <<= BitWidth - Amt;
3282         Known.Zero <<= BitWidth - Amt;
3283         Known2.One.lshrInPlace(Amt);
3284         Known2.Zero.lshrInPlace(Amt);
3285       }
3286       Known.One |= Known2.One;
3287       Known.Zero |= Known2.Zero;
3288     }
3289     break;
3290   case ISD::SHL_PARTS:
3291   case ISD::SRA_PARTS:
3292   case ISD::SRL_PARTS: {
3293     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3294
3295     // Collect lo/hi source values and concatenate.
3296     unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3297     unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3298     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3299     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3300     Known = Known2.concat(Known);
3301
3302     // Collect shift amount.
3303     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3304
3305     if (Opcode == ISD::SHL_PARTS)
3306       Known = KnownBits::shl(Known, Known2);
3307     else if (Opcode == ISD::SRA_PARTS)
3308       Known = KnownBits::ashr(Known, Known2);
3309     else // if (Opcode == ISD::SRL_PARTS)
3310       Known = KnownBits::lshr(Known, Known2);
3311
3312     // TODO: Minimum shift low/high bits are known zero.
3313
3314     if (Op.getResNo() == 0)
3315       Known = Known.extractBits(LoBits, 0);
3316     else
3317       Known = Known.extractBits(HiBits, LoBits);
3318     break;
3319   }
3320   case ISD::SIGN_EXTEND_INREG: {
3321     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3322     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3323     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3324     break;
3325   }
3326   case ISD::CTTZ:
3327   case ISD::CTTZ_ZERO_UNDEF: {
3328     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3329     // If we have a known 1, its position is our upper bound.
3330     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3331     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3332     Known.Zero.setBitsFrom(LowBits);
3333     break;
3334   }
3335   case ISD::CTLZ:
3336   case ISD::CTLZ_ZERO_UNDEF: {
3337     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3338     // If we have a known 1, its position is our upper bound.
3339     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3340     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3341     Known.Zero.setBitsFrom(LowBits);
3342     break;
3343   }
3344   case ISD::CTPOP: {
3345     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3346     // If we know some of the bits are zero, they can't be one.
3347     unsigned PossibleOnes = Known2.countMaxPopulation();
3348     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3349     break;
3350   }
3351   case ISD::PARITY: {
3352     // Parity returns 0 everywhere but the LSB.
3353     Known.Zero.setBitsFrom(1);
3354     break;
3355   }
3356   case ISD::LOAD: {
3357     LoadSDNode *LD = cast<LoadSDNode>(Op);
3358     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3359     if (ISD::isNON_EXTLoad(LD) && Cst) {
3360       // Determine any common known bits from the loaded constant pool value.
3361       Type *CstTy = Cst->getType();
3362       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3363         // If its a vector splat, then we can (quickly) reuse the scalar path.
3364         // NOTE: We assume all elements match and none are UNDEF.
3365         if (CstTy->isVectorTy()) {
3366           if (const Constant *Splat = Cst->getSplatValue()) {
3367             Cst = Splat;
3368             CstTy = Cst->getType();
3369           }
3370         }
3371         // TODO - do we need to handle different bitwidths?
3372         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3373           // Iterate across all vector elements finding common known bits.
3374           Known.One.setAllBits();
3375           Known.Zero.setAllBits();
3376           for (unsigned i = 0; i != NumElts; ++i) {
3377             if (!DemandedElts[i])
3378               continue;
3379             if (Constant *Elt = Cst->getAggregateElement(i)) {
3380               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3381                 const APInt &Value = CInt->getValue();
3382                 Known.One &= Value;
3383                 Known.Zero &= ~Value;
3384                 continue;
3385               }
3386               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3387                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3388                 Known.One &= Value;
3389                 Known.Zero &= ~Value;
3390                 continue;
3391               }
3392             }
3393             Known.One.clearAllBits();
3394             Known.Zero.clearAllBits();
3395             break;
3396           }
3397         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3398           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3399             Known = KnownBits::makeConstant(CInt->getValue());
3400           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3401             Known =
3402                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3403           }
3404         }
3405       }
3406     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3407       // If this is a ZEXTLoad and we are looking at the loaded value.
3408       EVT VT = LD->getMemoryVT();
3409       unsigned MemBits = VT.getScalarSizeInBits();
3410       Known.Zero.setBitsFrom(MemBits);
3411     } else if (const MDNode *Ranges = LD->getRanges()) {
3412       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3413         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3414     }
3415     break;
3416   }
3417   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3418     EVT InVT = Op.getOperand(0).getValueType();
3419     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3420     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3421     Known = Known.zext(BitWidth);
3422     break;
3423   }
3424   case ISD::ZERO_EXTEND: {
3425     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3426     Known = Known.zext(BitWidth);
3427     break;
3428   }
3429   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3430     EVT InVT = Op.getOperand(0).getValueType();
3431     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3432     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3433     // If the sign bit is known to be zero or one, then sext will extend
3434     // it to the top bits, else it will just zext.
3435     Known = Known.sext(BitWidth);
3436     break;
3437   }
3438   case ISD::SIGN_EXTEND: {
3439     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3440     // If the sign bit is known to be zero or one, then sext will extend
3441     // it to the top bits, else it will just zext.
3442     Known = Known.sext(BitWidth);
3443     break;
3444   }
3445   case ISD::ANY_EXTEND_VECTOR_INREG: {
3446     EVT InVT = Op.getOperand(0).getValueType();
3447     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3448     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3449     Known = Known.anyext(BitWidth);
3450     break;
3451   }
3452   case ISD::ANY_EXTEND: {
3453     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3454     Known = Known.anyext(BitWidth);
3455     break;
3456   }
3457   case ISD::TRUNCATE: {
3458     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3459     Known = Known.trunc(BitWidth);
3460     break;
3461   }
3462   case ISD::AssertZext: {
3463     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3464     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3465     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3466     Known.Zero |= (~InMask);
3467     Known.One  &= (~Known.Zero);
3468     break;
3469   }
3470   case ISD::AssertAlign: {
3471     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3472     assert(LogOfAlign != 0);
3473
3474     // TODO: Should use maximum with source
3475     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3476     // well as clearing one bits.
3477     Known.Zero.setLowBits(LogOfAlign);
3478     Known.One.clearLowBits(LogOfAlign);
3479     break;
3480   }
3481   case ISD::FGETSIGN:
3482     // All bits are zero except the low bit.
3483     Known.Zero.setBitsFrom(1);
3484     break;
3485   case ISD::USUBO:
3486   case ISD::SSUBO:
3487   case ISD::SUBCARRY:
3488   case ISD::SSUBO_CARRY:
3489     if (Op.getResNo() == 1) {
3490       // If we know the result of a setcc has the top bits zero, use this info.
3491       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3492               TargetLowering::ZeroOrOneBooleanContent &&
3493           BitWidth > 1)
3494         Known.Zero.setBitsFrom(1);
3495       break;
3496     }
3497     LLVM_FALLTHROUGH;
3498   case ISD::SUB:
3499   case ISD::SUBC: {
3500     assert(Op.getResNo() == 0 &&
3501            "We only compute knownbits for the difference here.");
3502
3503     // TODO: Compute influence of the carry operand.
3504     if (Opcode == ISD::SUBCARRY || Opcode == ISD::SSUBO_CARRY)
3505       break;
3506
3507     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3508     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3509     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3510                                         Known, Known2);
3511     break;
3512   }
3513   case ISD::UADDO:
3514   case ISD::SADDO:
3515   case ISD::ADDCARRY:
3516   case ISD::SADDO_CARRY:
3517     if (Op.getResNo() == 1) {
3518       // If we know the result of a setcc has the top bits zero, use this info.
3519       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3520               TargetLowering::ZeroOrOneBooleanContent &&
3521           BitWidth > 1)
3522         Known.Zero.setBitsFrom(1);
3523       break;
3524     }
3525     LLVM_FALLTHROUGH;
3526   case ISD::ADD:
3527   case ISD::ADDC:
3528   case ISD::ADDE: {
3529     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3530
3531     // With ADDE and ADDCARRY, a carry bit may be added in.
3532     KnownBits Carry(1);
3533     if (Opcode == ISD::ADDE)
3534       // Can't track carry from glue, set carry to unknown.
3535       Carry.resetAll();
3536     else if (Opcode == ISD::ADDCARRY || Opcode == ISD::SADDO_CARRY)
3537       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3538       // the trouble (how often will we find a known carry bit). And I haven't
3539       // tested this very much yet, but something like this might work:
3540       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3541       //   Carry = Carry.zextOrTrunc(1, false);
3542       Carry.resetAll();
3543     else
3544       Carry.setAllZero();
3545
3546     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3547     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3548     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3549     break;
3550   }
3551   case ISD::UDIV: {
3552     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3553     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3554     Known = KnownBits::udiv(Known, Known2);
3555     break;
3556   }
3557   case ISD::SREM: {
3558     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3559     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3560     Known = KnownBits::srem(Known, Known2);
3561     break;
3562   }
3563   case ISD::UREM: {
3564     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3565     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3566     Known = KnownBits::urem(Known, Known2);
3567     break;
3568   }
3569   case ISD::EXTRACT_ELEMENT: {
3570     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3571     const unsigned Index = Op.getConstantOperandVal(1);
3572     const unsigned EltBitWidth = Op.getValueSizeInBits();
3573
3574     // Remove low part of known bits mask
3575     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3576     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3577
3578     // Remove high part of known bit mask
3579     Known = Known.trunc(EltBitWidth);
3580     break;
3581   }
3582   case ISD::EXTRACT_VECTOR_ELT: {
3583     SDValue InVec = Op.getOperand(0);
3584     SDValue EltNo = Op.getOperand(1);
3585     EVT VecVT = InVec.getValueType();
3586     // computeKnownBits not yet implemented for scalable vectors.
3587     if (VecVT.isScalableVector())
3588       break;
3589     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3590     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3591
3592     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3593     // anything about the extended bits.
3594     if (BitWidth > EltBitWidth)
3595       Known = Known.trunc(EltBitWidth);
3596
3597     // If we know the element index, just demand that vector element, else for
3598     // an unknown element index, ignore DemandedElts and demand them all.
3599     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3600     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3601     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3602       DemandedSrcElts =
3603           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3604
3605     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3606     if (BitWidth > EltBitWidth)
3607       Known = Known.anyext(BitWidth);
3608     break;
3609   }
3610   case ISD::INSERT_VECTOR_ELT: {
3611     // If we know the element index, split the demand between the
3612     // source vector and the inserted element, otherwise assume we need
3613     // the original demanded vector elements and the value.
3614     SDValue InVec = Op.getOperand(0);
3615     SDValue InVal = Op.getOperand(1);
3616     SDValue EltNo = Op.getOperand(2);
3617     bool DemandedVal = true;
3618     APInt DemandedVecElts = DemandedElts;
3619     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3620     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3621       unsigned EltIdx = CEltNo->getZExtValue();
3622       DemandedVal = !!DemandedElts[EltIdx];
3623       DemandedVecElts.clearBit(EltIdx);
3624     }
3625     Known.One.setAllBits();
3626     Known.Zero.setAllBits();
3627     if (DemandedVal) {
3628       Known2 = computeKnownBits(InVal, Depth + 1);
3629       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3630     }
3631     if (!!DemandedVecElts) {
3632       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3633       Known = KnownBits::commonBits(Known, Known2);
3634     }
3635     break;
3636   }
3637   case ISD::BITREVERSE: {
3638     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3639     Known = Known2.reverseBits();
3640     break;
3641   }
3642   case ISD::BSWAP: {
3643     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3644     Known = Known2.byteSwap();
3645     break;
3646   }
3647   case ISD::ABS: {
3648     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3649     Known = Known2.abs();
3650     break;
3651   }
3652   case ISD::USUBSAT: {
3653     // The result of usubsat will never be larger than the LHS.
3654     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3655     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3656     break;
3657   }
3658   case ISD::UMIN: {
3659     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3660     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3661     Known = KnownBits::umin(Known, Known2);
3662     break;
3663   }
3664   case ISD::UMAX: {
3665     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3666     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3667     Known = KnownBits::umax(Known, Known2);
3668     break;
3669   }
3670   case ISD::SMIN:
3671   case ISD::SMAX: {
3672     // If we have a clamp pattern, we know that the number of sign bits will be
3673     // the minimum of the clamp min/max range.
3674     bool IsMax = (Opcode == ISD::SMAX);
3675     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3676     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3677       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3678         CstHigh =
3679             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3680     if (CstLow && CstHigh) {
3681       if (!IsMax)
3682         std::swap(CstLow, CstHigh);
3683
3684       const APInt &ValueLow = CstLow->getAPIntValue();
3685       const APInt &ValueHigh = CstHigh->getAPIntValue();
3686       if (ValueLow.sle(ValueHigh)) {
3687         unsigned LowSignBits = ValueLow.getNumSignBits();
3688         unsigned HighSignBits = ValueHigh.getNumSignBits();
3689         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3690         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3691           Known.One.setHighBits(MinSignBits);
3692           break;
3693         }
3694         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3695           Known.Zero.setHighBits(MinSignBits);
3696           break;
3697         }
3698       }
3699     }
3700
3701     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3702     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3703     if (IsMax)
3704       Known = KnownBits::smax(Known, Known2);
3705     else
3706       Known = KnownBits::smin(Known, Known2);
3707
3708     // For SMAX, if CstLow is non-negative we know the result will be
3709     // non-negative and thus all sign bits are 0.
3710     // TODO: There's an equivalent of this for smin with negative constant for
3711     // known ones.
3712     if (IsMax && CstLow) {
3713       const APInt &ValueLow = CstLow->getAPIntValue();
3714       if (ValueLow.isNonNegative()) {
3715         unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3716         Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3717       }
3718     }
3719
3720     break;
3721   }
3722   case ISD::FP_TO_UINT_SAT: {
3723     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3724     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3725     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3726     break;
3727   }
3728   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3729     if (Op.getResNo() == 1) {
3730       // The boolean result conforms to getBooleanContents.
3731       // If we know the result of a setcc has the top bits zero, use this info.
3732       // We know that we have an integer-based boolean since these operations
3733       // are only available for integer.
3734       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3735               TargetLowering::ZeroOrOneBooleanContent &&
3736           BitWidth > 1)
3737         Known.Zero.setBitsFrom(1);
3738       break;
3739     }
3740     LLVM_FALLTHROUGH;
3741   case ISD::ATOMIC_CMP_SWAP:
3742   case ISD::ATOMIC_SWAP:
3743   case ISD::ATOMIC_LOAD_ADD:
3744   case ISD::ATOMIC_LOAD_SUB:
3745   case ISD::ATOMIC_LOAD_AND:
3746   case ISD::ATOMIC_LOAD_CLR:
3747   case ISD::ATOMIC_LOAD_OR:
3748   case ISD::ATOMIC_LOAD_XOR:
3749   case ISD::ATOMIC_LOAD_NAND:
3750   case ISD::ATOMIC_LOAD_MIN:
3751   case ISD::ATOMIC_LOAD_MAX:
3752   case ISD::ATOMIC_LOAD_UMIN:
3753   case ISD::ATOMIC_LOAD_UMAX:
3754   case ISD::ATOMIC_LOAD: {
3755     unsigned MemBits =
3756         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3757     // If we are looking at the loaded value.
3758     if (Op.getResNo() == 0) {
3759       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3760         Known.Zero.setBitsFrom(MemBits);
3761     }
3762     break;
3763   }
3764   case ISD::FrameIndex:
3765   case ISD::TargetFrameIndex:
3766     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3767                                        Known, getMachineFunction());
3768     break;
3769
3770   default:
3771     if (Opcode < ISD::BUILTIN_OP_END)
3772       break;
3773     LLVM_FALLTHROUGH;
3774   case ISD::INTRINSIC_WO_CHAIN:
3775   case ISD::INTRINSIC_W_CHAIN:
3776   case ISD::INTRINSIC_VOID:
3777     // Allow the target to implement this method for its nodes.
3778     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3779     break;
3780   }
3781
3782   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3783   return Known;
3784 }
3785
3786 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3787                                                              SDValue N1) const {
3788   // X + 0 never overflow
3789   if (isNullConstant(N1))
3790     return OFK_Never;
3791
3792   KnownBits N1Known = computeKnownBits(N1);
3793   if (N1Known.Zero.getBoolValue()) {
3794     KnownBits N0Known = computeKnownBits(N0);
3795
3796     bool overflow;
3797     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3798     if (!overflow)
3799       return OFK_Never;
3800   }
3801
3802   // mulhi + 1 never overflow
3803   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3804       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3805     return OFK_Never;
3806
3807   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3808     KnownBits N0Known = computeKnownBits(N0);
3809
3810     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3811       return OFK_Never;
3812   }
3813
3814   return OFK_Sometime;
3815 }
3816
3817 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3818   EVT OpVT = Val.getValueType();
3819   unsigned BitWidth = OpVT.getScalarSizeInBits();
3820
3821   // Is the constant a known power of 2?
3822   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3823     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3824
3825   // A left-shift of a constant one will have exactly one bit set because
3826   // shifting the bit off the end is undefined.
3827   if (Val.getOpcode() == ISD::SHL) {
3828     auto *C = isConstOrConstSplat(Val.getOperand(0));
3829     if (C && C->getAPIntValue() == 1)
3830       return true;
3831   }
3832
3833   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3834   // one bit set.
3835   if (Val.getOpcode() == ISD::SRL) {
3836     auto *C = isConstOrConstSplat(Val.getOperand(0));
3837     if (C && C->getAPIntValue().isSignMask())
3838       return true;
3839   }
3840
3841   // Are all operands of a build vector constant powers of two?
3842   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3843     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3844           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3845             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3846           return false;
3847         }))
3848       return true;
3849
3850   // Is the operand of a splat vector a constant power of two?
3851   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3852     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3853       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3854         return true;
3855
3856   // vscale(power-of-two) is a power-of-two for some targets
3857   if (Val.getOpcode() == ISD::VSCALE &&
3858       getTargetLoweringInfo().isVScaleKnownToBeAPowerOfTwo() &&
3859       isKnownToBeAPowerOfTwo(Val.getOperand(0)))
3860     return true;
3861
3862   // More could be done here, though the above checks are enough
3863   // to handle some common cases.
3864
3865   // Fall back to computeKnownBits to catch other known cases.
3866   KnownBits Known = computeKnownBits(Val);
3867   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3868 }
3869
3870 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3871   EVT VT = Op.getValueType();
3872
3873   // TODO: Assume we don't know anything for now.
3874   if (VT.isScalableVector())
3875     return 1;
3876
3877   APInt DemandedElts = VT.isVector()
3878                            ? APInt::getAllOnes(VT.getVectorNumElements())
3879                            : APInt(1, 1);
3880   return ComputeNumSignBits(Op, DemandedElts, Depth);
3881 }
3882
3883 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3884                                           unsigned Depth) const {
3885   EVT VT = Op.getValueType();
3886   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3887   unsigned VTBits = VT.getScalarSizeInBits();
3888   unsigned NumElts = DemandedElts.getBitWidth();
3889   unsigned Tmp, Tmp2;
3890   unsigned FirstAnswer = 1;
3891
3892   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3893     const APInt &Val = C->getAPIntValue();
3894     return Val.getNumSignBits();
3895   }
3896
3897   if (Depth >= MaxRecursionDepth)
3898     return 1;  // Limit search depth.
3899
3900   if (!DemandedElts || VT.isScalableVector())
3901     return 1;  // No demanded elts, better to assume we don't know anything.
3902
3903   unsigned Opcode = Op.getOpcode();
3904   switch (Opcode) {
3905   default: break;
3906   case ISD::AssertSext:
3907     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3908     return VTBits-Tmp+1;
3909   case ISD::AssertZext:
3910     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3911     return VTBits-Tmp;
3912   case ISD::MERGE_VALUES:
3913     return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
3914                               Depth + 1);
3915   case ISD::BUILD_VECTOR:
3916     Tmp = VTBits;
3917     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3918       if (!DemandedElts[i])
3919         continue;
3920
3921       SDValue SrcOp = Op.getOperand(i);
3922       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3923
3924       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3925       if (SrcOp.getValueSizeInBits() != VTBits) {
3926         assert(SrcOp.getValueSizeInBits() > VTBits &&
3927                "Expected BUILD_VECTOR implicit truncation");
3928         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3929         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3930       }
3931       Tmp = std::min(Tmp, Tmp2);
3932     }
3933     return Tmp;
3934
3935   case ISD::VECTOR_SHUFFLE: {
3936     // Collect the minimum number of sign bits that are shared by every vector
3937     // element referenced by the shuffle.
3938     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3939     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3940     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3941     for (unsigned i = 0; i != NumElts; ++i) {
3942       int M = SVN->getMaskElt(i);
3943       if (!DemandedElts[i])
3944         continue;
3945       // For UNDEF elements, we don't know anything about the common state of
3946       // the shuffle result.
3947       if (M < 0)
3948         return 1;
3949       if ((unsigned)M < NumElts)
3950         DemandedLHS.setBit((unsigned)M % NumElts);
3951       else
3952         DemandedRHS.setBit((unsigned)M % NumElts);
3953     }
3954     Tmp = std::numeric_limits<unsigned>::max();
3955     if (!!DemandedLHS)
3956       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3957     if (!!DemandedRHS) {
3958       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3959       Tmp = std::min(Tmp, Tmp2);
3960     }
3961     // If we don't know anything, early out and try computeKnownBits fall-back.
3962     if (Tmp == 1)
3963       break;
3964     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3965     return Tmp;
3966   }
3967
3968   case ISD::BITCAST: {
3969     SDValue N0 = Op.getOperand(0);
3970     EVT SrcVT = N0.getValueType();
3971     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3972
3973     // Ignore bitcasts from unsupported types..
3974     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3975       break;
3976
3977     // Fast handling of 'identity' bitcasts.
3978     if (VTBits == SrcBits)
3979       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3980
3981     bool IsLE = getDataLayout().isLittleEndian();
3982
3983     // Bitcast 'large element' scalar/vector to 'small element' vector.
3984     if ((SrcBits % VTBits) == 0) {
3985       assert(VT.isVector() && "Expected bitcast to vector");
3986
3987       unsigned Scale = SrcBits / VTBits;
3988       APInt SrcDemandedElts =
3989           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3990
3991       // Fast case - sign splat can be simply split across the small elements.
3992       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3993       if (Tmp == SrcBits)
3994         return VTBits;
3995
3996       // Slow case - determine how far the sign extends into each sub-element.
3997       Tmp2 = VTBits;
3998       for (unsigned i = 0; i != NumElts; ++i)
3999         if (DemandedElts[i]) {
4000           unsigned SubOffset = i % Scale;
4001           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
4002           SubOffset = SubOffset * VTBits;
4003           if (Tmp <= SubOffset)
4004             return 1;
4005           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
4006         }
4007       return Tmp2;
4008     }
4009     break;
4010   }
4011
4012   case ISD::FP_TO_SINT_SAT:
4013     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4014     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4015     return VTBits - Tmp + 1;
4016   case ISD::SIGN_EXTEND:
4017     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4018     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4019   case ISD::SIGN_EXTEND_INREG:
4020     // Max of the input and what this extends.
4021     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4022     Tmp = VTBits-Tmp+1;
4023     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4024     return std::max(Tmp, Tmp2);
4025   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4026     SDValue Src = Op.getOperand(0);
4027     EVT SrcVT = Src.getValueType();
4028     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4029     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4030     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4031   }
4032   case ISD::SRA:
4033     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4034     // SRA X, C -> adds C sign bits.
4035     if (const APInt *ShAmt =
4036             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4037       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4038     return Tmp;
4039   case ISD::SHL:
4040     if (const APInt *ShAmt =
4041             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4042       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4043       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4044       if (ShAmt->ult(Tmp))
4045         return Tmp - ShAmt->getZExtValue();
4046     }
4047     break;
4048   case ISD::AND:
4049   case ISD::OR:
4050   case ISD::XOR:    // NOT is handled here.
4051     // Logical binary ops preserve the number of sign bits at the worst.
4052     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4053     if (Tmp != 1) {
4054       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4055       FirstAnswer = std::min(Tmp, Tmp2);
4056       // We computed what we know about the sign bits as our first
4057       // answer. Now proceed to the generic code that uses
4058       // computeKnownBits, and pick whichever answer is better.
4059     }
4060     break;
4061
4062   case ISD::SELECT:
4063   case ISD::VSELECT:
4064     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4065     if (Tmp == 1) return 1;  // Early out.
4066     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4067     return std::min(Tmp, Tmp2);
4068   case ISD::SELECT_CC:
4069     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4070     if (Tmp == 1) return 1;  // Early out.
4071     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4072     return std::min(Tmp, Tmp2);
4073
4074   case ISD::SMIN:
4075   case ISD::SMAX: {
4076     // If we have a clamp pattern, we know that the number of sign bits will be
4077     // the minimum of the clamp min/max range.
4078     bool IsMax = (Opcode == ISD::SMAX);
4079     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4080     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4081       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4082         CstHigh =
4083             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4084     if (CstLow && CstHigh) {
4085       if (!IsMax)
4086         std::swap(CstLow, CstHigh);
4087       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4088         Tmp = CstLow->getAPIntValue().getNumSignBits();
4089         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4090         return std::min(Tmp, Tmp2);
4091       }
4092     }
4093
4094     // Fallback - just get the minimum number of sign bits of the operands.
4095     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4096     if (Tmp == 1)
4097       return 1;  // Early out.
4098     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4099     return std::min(Tmp, Tmp2);
4100   }
4101   case ISD::UMIN:
4102   case ISD::UMAX:
4103     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4104     if (Tmp == 1)
4105       return 1;  // Early out.
4106     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4107     return std::min(Tmp, Tmp2);
4108   case ISD::SADDO:
4109   case ISD::UADDO:
4110   case ISD::SADDO_CARRY:
4111   case ISD::ADDCARRY:
4112   case ISD::SSUBO:
4113   case ISD::USUBO:
4114   case ISD::SSUBO_CARRY:
4115   case ISD::SUBCARRY:
4116   case ISD::SMULO:
4117   case ISD::UMULO:
4118     if (Op.getResNo() != 1)
4119       break;
4120     // The boolean result conforms to getBooleanContents.  Fall through.
4121     // If setcc returns 0/-1, all bits are sign bits.
4122     // We know that we have an integer-based boolean since these operations
4123     // are only available for integer.
4124     if (TLI->getBooleanContents(VT.isVector(), false) ==
4125         TargetLowering::ZeroOrNegativeOneBooleanContent)
4126       return VTBits;
4127     break;
4128   case ISD::SETCC:
4129   case ISD::SETCCCARRY:
4130   case ISD::STRICT_FSETCC:
4131   case ISD::STRICT_FSETCCS: {
4132     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4133     // If setcc returns 0/-1, all bits are sign bits.
4134     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4135         TargetLowering::ZeroOrNegativeOneBooleanContent)
4136       return VTBits;
4137     break;
4138   }
4139   case ISD::ROTL:
4140   case ISD::ROTR:
4141     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4142
4143     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4144     if (Tmp == VTBits)
4145       return VTBits;
4146
4147     if (ConstantSDNode *C =
4148             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4149       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4150
4151       // Handle rotate right by N like a rotate left by 32-N.
4152       if (Opcode == ISD::ROTR)
4153         RotAmt = (VTBits - RotAmt) % VTBits;
4154
4155       // If we aren't rotating out all of the known-in sign bits, return the
4156       // number that are left.  This handles rotl(sext(x), 1) for example.
4157       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4158     }
4159     break;
4160   case ISD::ADD:
4161   case ISD::ADDC:
4162     // Add can have at most one carry bit.  Thus we know that the output
4163     // is, at worst, one more bit than the inputs.
4164     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4165     if (Tmp == 1) return 1; // Early out.
4166
4167     // Special case decrementing a value (ADD X, -1):
4168     if (ConstantSDNode *CRHS =
4169             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4170       if (CRHS->isAllOnes()) {
4171         KnownBits Known =
4172             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4173
4174         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4175         // sign bits set.
4176         if ((Known.Zero | 1).isAllOnes())
4177           return VTBits;
4178
4179         // If we are subtracting one from a positive number, there is no carry
4180         // out of the result.
4181         if (Known.isNonNegative())
4182           return Tmp;
4183       }
4184
4185     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4186     if (Tmp2 == 1) return 1; // Early out.
4187     return std::min(Tmp, Tmp2) - 1;
4188   case ISD::SUB:
4189     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4190     if (Tmp2 == 1) return 1; // Early out.
4191
4192     // Handle NEG.
4193     if (ConstantSDNode *CLHS =
4194             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4195       if (CLHS->isZero()) {
4196         KnownBits Known =
4197             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4198         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4199         // sign bits set.
4200         if ((Known.Zero | 1).isAllOnes())
4201           return VTBits;
4202
4203         // If the input is known to be positive (the sign bit is known clear),
4204         // the output of the NEG has the same number of sign bits as the input.
4205         if (Known.isNonNegative())
4206           return Tmp2;
4207
4208         // Otherwise, we treat this like a SUB.
4209       }
4210
4211     // Sub can have at most one carry bit.  Thus we know that the output
4212     // is, at worst, one more bit than the inputs.
4213     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4214     if (Tmp == 1) return 1; // Early out.
4215     return std::min(Tmp, Tmp2) - 1;
4216   case ISD::MUL: {
4217     // The output of the Mul can be at most twice the valid bits in the inputs.
4218     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4219     if (SignBitsOp0 == 1)
4220       break;
4221     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4222     if (SignBitsOp1 == 1)
4223       break;
4224     unsigned OutValidBits =
4225         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4226     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4227   }
4228   case ISD::SREM:
4229     // The sign bit is the LHS's sign bit, except when the result of the
4230     // remainder is zero. The magnitude of the result should be less than or
4231     // equal to the magnitude of the LHS. Therefore, the result should have
4232     // at least as many sign bits as the left hand side.
4233     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4234   case ISD::TRUNCATE: {
4235     // Check if the sign bits of source go down as far as the truncated value.
4236     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4237     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4238     if (NumSrcSignBits > (NumSrcBits - VTBits))
4239       return NumSrcSignBits - (NumSrcBits - VTBits);
4240     break;
4241   }
4242   case ISD::EXTRACT_ELEMENT: {
4243     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4244     const int BitWidth = Op.getValueSizeInBits();
4245     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4246
4247     // Get reverse index (starting from 1), Op1 value indexes elements from
4248     // little end. Sign starts at big end.
4249     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4250
4251     // If the sign portion ends in our element the subtraction gives correct
4252     // result. Otherwise it gives either negative or > bitwidth result
4253     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4254   }
4255   case ISD::INSERT_VECTOR_ELT: {
4256     // If we know the element index, split the demand between the
4257     // source vector and the inserted element, otherwise assume we need
4258     // the original demanded vector elements and the value.
4259     SDValue InVec = Op.getOperand(0);
4260     SDValue InVal = Op.getOperand(1);
4261     SDValue EltNo = Op.getOperand(2);
4262     bool DemandedVal = true;
4263     APInt DemandedVecElts = DemandedElts;
4264     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4265     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4266       unsigned EltIdx = CEltNo->getZExtValue();
4267       DemandedVal = !!DemandedElts[EltIdx];
4268       DemandedVecElts.clearBit(EltIdx);
4269     }
4270     Tmp = std::numeric_limits<unsigned>::max();
4271     if (DemandedVal) {
4272       // TODO - handle implicit truncation of inserted elements.
4273       if (InVal.getScalarValueSizeInBits() != VTBits)
4274         break;
4275       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4276       Tmp = std::min(Tmp, Tmp2);
4277     }
4278     if (!!DemandedVecElts) {
4279       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4280       Tmp = std::min(Tmp, Tmp2);
4281     }
4282     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4283     return Tmp;
4284   }
4285   case ISD::EXTRACT_VECTOR_ELT: {
4286     SDValue InVec = Op.getOperand(0);
4287     SDValue EltNo = Op.getOperand(1);
4288     EVT VecVT = InVec.getValueType();
4289     // ComputeNumSignBits not yet implemented for scalable vectors.
4290     if (VecVT.isScalableVector())
4291       break;
4292     const unsigned BitWidth = Op.getValueSizeInBits();
4293     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4294     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4295
4296     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4297     // anything about sign bits. But if the sizes match we can derive knowledge
4298     // about sign bits from the vector operand.
4299     if (BitWidth != EltBitWidth)
4300       break;
4301
4302     // If we know the element index, just demand that vector element, else for
4303     // an unknown element index, ignore DemandedElts and demand them all.
4304     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4305     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4306     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4307       DemandedSrcElts =
4308           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4309
4310     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4311   }
4312   case ISD::EXTRACT_SUBVECTOR: {
4313     // Offset the demanded elts by the subvector index.
4314     SDValue Src = Op.getOperand(0);
4315     // Bail until we can represent demanded elements for scalable vectors.
4316     if (Src.getValueType().isScalableVector())
4317       break;
4318     uint64_t Idx = Op.getConstantOperandVal(1);
4319     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4320     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4321     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4322   }
4323   case ISD::CONCAT_VECTORS: {
4324     // Determine the minimum number of sign bits across all demanded
4325     // elts of the input vectors. Early out if the result is already 1.
4326     Tmp = std::numeric_limits<unsigned>::max();
4327     EVT SubVectorVT = Op.getOperand(0).getValueType();
4328     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4329     unsigned NumSubVectors = Op.getNumOperands();
4330     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4331       APInt DemandedSub =
4332           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4333       if (!DemandedSub)
4334         continue;
4335       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4336       Tmp = std::min(Tmp, Tmp2);
4337     }
4338     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4339     return Tmp;
4340   }
4341   case ISD::INSERT_SUBVECTOR: {
4342     // Demand any elements from the subvector and the remainder from the src its
4343     // inserted into.
4344     SDValue Src = Op.getOperand(0);
4345     SDValue Sub = Op.getOperand(1);
4346     uint64_t Idx = Op.getConstantOperandVal(2);
4347     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4348     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4349     APInt DemandedSrcElts = DemandedElts;
4350     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4351
4352     Tmp = std::numeric_limits<unsigned>::max();
4353     if (!!DemandedSubElts) {
4354       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4355       if (Tmp == 1)
4356         return 1; // early-out
4357     }
4358     if (!!DemandedSrcElts) {
4359       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4360       Tmp = std::min(Tmp, Tmp2);
4361     }
4362     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4363     return Tmp;
4364   }
4365   case ISD::ATOMIC_CMP_SWAP:
4366   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4367   case ISD::ATOMIC_SWAP:
4368   case ISD::ATOMIC_LOAD_ADD:
4369   case ISD::ATOMIC_LOAD_SUB:
4370   case ISD::ATOMIC_LOAD_AND:
4371   case ISD::ATOMIC_LOAD_CLR:
4372   case ISD::ATOMIC_LOAD_OR:
4373   case ISD::ATOMIC_LOAD_XOR:
4374   case ISD::ATOMIC_LOAD_NAND:
4375   case ISD::ATOMIC_LOAD_MIN:
4376   case ISD::ATOMIC_LOAD_MAX:
4377   case ISD::ATOMIC_LOAD_UMIN:
4378   case ISD::ATOMIC_LOAD_UMAX:
4379   case ISD::ATOMIC_LOAD: {
4380     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4381     // If we are looking at the loaded value.
4382     if (Op.getResNo() == 0) {
4383       if (Tmp == VTBits)
4384         return 1; // early-out
4385       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4386         return VTBits - Tmp + 1;
4387       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4388         return VTBits - Tmp;
4389     }
4390     break;
4391   }
4392   }
4393
4394   // If we are looking at the loaded value of the SDNode.
4395   if (Op.getResNo() == 0) {
4396     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4397     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4398       unsigned ExtType = LD->getExtensionType();
4399       switch (ExtType) {
4400       default: break;
4401       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4402         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4403         return VTBits - Tmp + 1;
4404       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4405         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4406         return VTBits - Tmp;
4407       case ISD::NON_EXTLOAD:
4408         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4409           // We only need to handle vectors - computeKnownBits should handle
4410           // scalar cases.
4411           Type *CstTy = Cst->getType();
4412           if (CstTy->isVectorTy() &&
4413               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4414               VTBits == CstTy->getScalarSizeInBits()) {
4415             Tmp = VTBits;
4416             for (unsigned i = 0; i != NumElts; ++i) {
4417               if (!DemandedElts[i])
4418                 continue;
4419               if (Constant *Elt = Cst->getAggregateElement(i)) {
4420                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4421                   const APInt &Value = CInt->getValue();
4422                   Tmp = std::min(Tmp, Value.getNumSignBits());
4423                   continue;
4424                 }
4425                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4426                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4427                   Tmp = std::min(Tmp, Value.getNumSignBits());
4428                   continue;
4429                 }
4430               }
4431               // Unknown type. Conservatively assume no bits match sign bit.
4432               return 1;
4433             }
4434             return Tmp;
4435           }
4436         }
4437         break;
4438       }
4439     }
4440   }
4441
4442   // Allow the target to implement this method for its nodes.
4443   if (Opcode >= ISD::BUILTIN_OP_END ||
4444       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4445       Opcode == ISD::INTRINSIC_W_CHAIN ||
4446       Opcode == ISD::INTRINSIC_VOID) {
4447     unsigned NumBits =
4448         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4449     if (NumBits > 1)
4450       FirstAnswer = std::max(FirstAnswer, NumBits);
4451   }
4452
4453   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4454   // use this information.
4455   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4456   return std::max(FirstAnswer, Known.countMinSignBits());
4457 }
4458
4459 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4460                                                  unsigned Depth) const {
4461   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4462   return Op.getScalarValueSizeInBits() - SignBits + 1;
4463 }
4464
4465 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4466                                                  const APInt &DemandedElts,
4467                                                  unsigned Depth) const {
4468   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4469   return Op.getScalarValueSizeInBits() - SignBits + 1;
4470 }
4471
4472 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4473                                                     unsigned Depth) const {
4474   // Early out for FREEZE.
4475   if (Op.getOpcode() == ISD::FREEZE)
4476     return true;
4477
4478   // TODO: Assume we don't know anything for now.
4479   EVT VT = Op.getValueType();
4480   if (VT.isScalableVector())
4481     return false;
4482
4483   APInt DemandedElts = VT.isVector()
4484                            ? APInt::getAllOnes(VT.getVectorNumElements())
4485                            : APInt(1, 1);
4486   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4487 }
4488
4489 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4490                                                     const APInt &DemandedElts,
4491                                                     bool PoisonOnly,
4492                                                     unsigned Depth) const {
4493   unsigned Opcode = Op.getOpcode();
4494
4495   // Early out for FREEZE.
4496   if (Opcode == ISD::FREEZE)
4497     return true;
4498
4499   if (Depth >= MaxRecursionDepth)
4500     return false; // Limit search depth.
4501
4502   if (isIntOrFPConstant(Op))
4503     return true;
4504
4505   switch (Opcode) {
4506   case ISD::UNDEF:
4507     return PoisonOnly;
4508
4509   case ISD::BUILD_VECTOR:
4510     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4511     // this shouldn't affect the result.
4512     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4513       if (!DemandedElts[i])
4514         continue;
4515       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4516                                             Depth + 1))
4517         return false;
4518     }
4519     return true;
4520
4521   // TODO: Search for noundef attributes from library functions.
4522
4523   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4524
4525   default:
4526     // Allow the target to implement this method for its nodes.
4527     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4528         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4529       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4530           Op, DemandedElts, *this, PoisonOnly, Depth);
4531     break;
4532   }
4533
4534   return false;
4535 }
4536
4537 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4538   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4539       !isa<ConstantSDNode>(Op.getOperand(1)))
4540     return false;
4541
4542   if (Op.getOpcode() == ISD::OR &&
4543       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4544     return false;
4545
4546   return true;
4547 }
4548
4549 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4550   // If we're told that NaNs won't happen, assume they won't.
4551   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4552     return true;
4553
4554   if (Depth >= MaxRecursionDepth)
4555     return false; // Limit search depth.
4556
4557   // TODO: Handle vectors.
4558   // If the value is a constant, we can obviously see if it is a NaN or not.
4559   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4560     return !C->getValueAPF().isNaN() ||
4561            (SNaN && !C->getValueAPF().isSignaling());
4562   }
4563
4564   unsigned Opcode = Op.getOpcode();
4565   switch (Opcode) {
4566   case ISD::FADD:
4567   case ISD::FSUB:
4568   case ISD::FMUL:
4569   case ISD::FDIV:
4570   case ISD::FREM:
4571   case ISD::FSIN:
4572   case ISD::FCOS: {
4573     if (SNaN)
4574       return true;
4575     // TODO: Need isKnownNeverInfinity
4576     return false;
4577   }
4578   case ISD::FCANONICALIZE:
4579   case ISD::FEXP:
4580   case ISD::FEXP2:
4581   case ISD::FTRUNC:
4582   case ISD::FFLOOR:
4583   case ISD::FCEIL:
4584   case ISD::FROUND:
4585   case ISD::FROUNDEVEN:
4586   case ISD::FRINT:
4587   case ISD::FNEARBYINT: {
4588     if (SNaN)
4589       return true;
4590     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4591   }
4592   case ISD::FABS:
4593   case ISD::FNEG:
4594   case ISD::FCOPYSIGN: {
4595     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4596   }
4597   case ISD::SELECT:
4598     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4599            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4600   case ISD::FP_EXTEND:
4601   case ISD::FP_ROUND: {
4602     if (SNaN)
4603       return true;
4604     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4605   }
4606   case ISD::SINT_TO_FP:
4607   case ISD::UINT_TO_FP:
4608     return true;
4609   case ISD::FMA:
4610   case ISD::FMAD: {
4611     if (SNaN)
4612       return true;
4613     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4614            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4615            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4616   }
4617   case ISD::FSQRT: // Need is known positive
4618   case ISD::FLOG:
4619   case ISD::FLOG2:
4620   case ISD::FLOG10:
4621   case ISD::FPOWI:
4622   case ISD::FPOW: {
4623     if (SNaN)
4624       return true;
4625     // TODO: Refine on operand
4626     return false;
4627   }
4628   case ISD::FMINNUM:
4629   case ISD::FMAXNUM: {
4630     // Only one needs to be known not-nan, since it will be returned if the
4631     // other ends up being one.
4632     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4633            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4634   }
4635   case ISD::FMINNUM_IEEE:
4636   case ISD::FMAXNUM_IEEE: {
4637     if (SNaN)
4638       return true;
4639     // This can return a NaN if either operand is an sNaN, or if both operands
4640     // are NaN.
4641     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4642             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4643            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4644             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4645   }
4646   case ISD::FMINIMUM:
4647   case ISD::FMAXIMUM: {
4648     // TODO: Does this quiet or return the origina NaN as-is?
4649     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4650            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4651   }
4652   case ISD::EXTRACT_VECTOR_ELT: {
4653     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4654   }
4655   default:
4656     if (Opcode >= ISD::BUILTIN_OP_END ||
4657         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4658         Opcode == ISD::INTRINSIC_W_CHAIN ||
4659         Opcode == ISD::INTRINSIC_VOID) {
4660       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4661     }
4662
4663     return false;
4664   }
4665 }
4666
4667 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4668   assert(Op.getValueType().isFloatingPoint() &&
4669          "Floating point type expected");
4670
4671   // If the value is a constant, we can obviously see if it is a zero or not.
4672   // TODO: Add BuildVector support.
4673   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4674     return !C->isZero();
4675   return false;
4676 }
4677
4678 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4679   assert(!Op.getValueType().isFloatingPoint() &&
4680          "Floating point types unsupported - use isKnownNeverZeroFloat");
4681
4682   // If the value is a constant, we can obviously see if it is a zero or not.
4683   if (ISD::matchUnaryPredicate(Op,
4684                                [](ConstantSDNode *C) { return !C->isZero(); }))
4685     return true;
4686
4687   // TODO: Recognize more cases here.
4688   switch (Op.getOpcode()) {
4689   default: break;
4690   case ISD::OR:
4691     if (isKnownNeverZero(Op.getOperand(1)) ||
4692         isKnownNeverZero(Op.getOperand(0)))
4693       return true;
4694     break;
4695   }
4696
4697   return false;
4698 }
4699
4700 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4701   // Check the obvious case.
4702   if (A == B) return true;
4703
4704   // For for negative and positive zero.
4705   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4706     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4707       if (CA->isZero() && CB->isZero()) return true;
4708
4709   // Otherwise they may not be equal.
4710   return false;
4711 }
4712
4713 // Only bits set in Mask must be negated, other bits may be arbitrary.
4714 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4715   if (isBitwiseNot(V, AllowUndefs))
4716     return V.getOperand(0);
4717
4718   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4719   // bits in the non-extended part.
4720   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4721   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4722     return SDValue();
4723   SDValue ExtArg = V.getOperand(0);
4724   if (ExtArg.getScalarValueSizeInBits() >=
4725           MaskC->getAPIntValue().getActiveBits() &&
4726       isBitwiseNot(ExtArg, AllowUndefs) &&
4727       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4728       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4729     return ExtArg.getOperand(0).getOperand(0);
4730   return SDValue();
4731 }
4732
4733 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4734   // Match masked merge pattern (X & ~M) op (Y & M)
4735   // Including degenerate case (X & ~M) op M
4736   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4737                                       SDValue Other) {
4738     if (SDValue NotOperand =
4739             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4740       if (Other == NotOperand)
4741         return true;
4742       if (Other->getOpcode() == ISD::AND)
4743         return NotOperand == Other->getOperand(0) ||
4744                NotOperand == Other->getOperand(1);
4745     }
4746     return false;
4747   };
4748   if (A->getOpcode() == ISD::AND)
4749     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4750            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4751   return false;
4752 }
4753
4754 // FIXME: unify with llvm::haveNoCommonBitsSet.
4755 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4756   assert(A.getValueType() == B.getValueType() &&
4757          "Values must have the same type");
4758   if (haveNoCommonBitsSetCommutative(A, B) ||
4759       haveNoCommonBitsSetCommutative(B, A))
4760     return true;
4761   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4762                                         computeKnownBits(B));
4763 }
4764
4765 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4766                                SelectionDAG &DAG) {
4767   if (cast<ConstantSDNode>(Step)->isZero())
4768     return DAG.getConstant(0, DL, VT);
4769
4770   return SDValue();
4771 }
4772
4773 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4774                                 ArrayRef<SDValue> Ops,
4775                                 SelectionDAG &DAG) {
4776   int NumOps = Ops.size();
4777   assert(NumOps != 0 && "Can't build an empty vector!");
4778   assert(!VT.isScalableVector() &&
4779          "BUILD_VECTOR cannot be used with scalable types");
4780   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4781          "Incorrect element count in BUILD_VECTOR!");
4782
4783   // BUILD_VECTOR of UNDEFs is UNDEF.
4784   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4785     return DAG.getUNDEF(VT);
4786
4787   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4788   SDValue IdentitySrc;
4789   bool IsIdentity = true;
4790   for (int i = 0; i != NumOps; ++i) {
4791     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4792         Ops[i].getOperand(0).getValueType() != VT ||
4793         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4794         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4795         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4796       IsIdentity = false;
4797       break;
4798     }
4799     IdentitySrc = Ops[i].getOperand(0);
4800   }
4801   if (IsIdentity)
4802     return IdentitySrc;
4803
4804   return SDValue();
4805 }
4806
4807 /// Try to simplify vector concatenation to an input value, undef, or build
4808 /// vector.
4809 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4810                                   ArrayRef<SDValue> Ops,
4811                                   SelectionDAG &DAG) {
4812   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4813   assert(llvm::all_of(Ops,
4814                       [Ops](SDValue Op) {
4815                         return Ops[0].getValueType() == Op.getValueType();
4816                       }) &&
4817          "Concatenation of vectors with inconsistent value types!");
4818   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4819              VT.getVectorElementCount() &&
4820          "Incorrect element count in vector concatenation!");
4821
4822   if (Ops.size() == 1)
4823     return Ops[0];
4824
4825   // Concat of UNDEFs is UNDEF.
4826   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4827     return DAG.getUNDEF(VT);
4828
4829   // Scan the operands and look for extract operations from a single source
4830   // that correspond to insertion at the same location via this concatenation:
4831   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4832   SDValue IdentitySrc;
4833   bool IsIdentity = true;
4834   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4835     SDValue Op = Ops[i];
4836     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4837     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4838         Op.getOperand(0).getValueType() != VT ||
4839         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4840         Op.getConstantOperandVal(1) != IdentityIndex) {
4841       IsIdentity = false;
4842       break;
4843     }
4844     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4845            "Unexpected identity source vector for concat of extracts");
4846     IdentitySrc = Op.getOperand(0);
4847   }
4848   if (IsIdentity) {
4849     assert(IdentitySrc && "Failed to set source vector of extracts");
4850     return IdentitySrc;
4851   }
4852
4853   // The code below this point is only designed to work for fixed width
4854   // vectors, so we bail out for now.
4855   if (VT.isScalableVector())
4856     return SDValue();
4857
4858   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4859   // simplified to one big BUILD_VECTOR.
4860   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4861   EVT SVT = VT.getScalarType();
4862   SmallVector<SDValue, 16> Elts;
4863   for (SDValue Op : Ops) {
4864     EVT OpVT = Op.getValueType();
4865     if (Op.isUndef())
4866       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4867     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4868       Elts.append(Op->op_begin(), Op->op_end());
4869     else
4870       return SDValue();
4871   }
4872
4873   // BUILD_VECTOR requires all inputs to be of the same type, find the
4874   // maximum type and extend them all.
4875   for (SDValue Op : Elts)
4876     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4877
4878   if (SVT.bitsGT(VT.getScalarType())) {
4879     for (SDValue &Op : Elts) {
4880       if (Op.isUndef())
4881         Op = DAG.getUNDEF(SVT);
4882       else
4883         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4884                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4885                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4886     }
4887   }
4888
4889   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4890   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4891   return V;
4892 }
4893
4894 /// Gets or creates the specified node.
4895 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4896   FoldingSetNodeID ID;
4897   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4898   void *IP = nullptr;
4899   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4900     return SDValue(E, 0);
4901
4902   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4903                               getVTList(VT));
4904   CSEMap.InsertNode(N, IP);
4905
4906   InsertNode(N);
4907   SDValue V = SDValue(N, 0);
4908   NewSDValueDbgMsg(V, "Creating new node: ", this);
4909   return V;
4910 }
4911
4912 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4913                               SDValue Operand) {
4914   SDNodeFlags Flags;
4915   if (Inserter)
4916     Flags = Inserter->getFlags();
4917   return getNode(Opcode, DL, VT, Operand, Flags);
4918 }
4919
4920 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4921                               SDValue Operand, const SDNodeFlags Flags) {
4922   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4923          "Operand is DELETED_NODE!");
4924   // Constant fold unary operations with an integer constant operand. Even
4925   // opaque constant will be folded, because the folding of unary operations
4926   // doesn't create new constants with different values. Nevertheless, the
4927   // opaque flag is preserved during folding to prevent future folding with
4928   // other constants.
4929   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4930     const APInt &Val = C->getAPIntValue();
4931     switch (Opcode) {
4932     default: break;
4933     case ISD::SIGN_EXTEND:
4934       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4935                          C->isTargetOpcode(), C->isOpaque());
4936     case ISD::TRUNCATE:
4937       if (C->isOpaque())
4938         break;
4939       LLVM_FALLTHROUGH;
4940     case ISD::ZERO_EXTEND:
4941       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4942                          C->isTargetOpcode(), C->isOpaque());
4943     case ISD::ANY_EXTEND:
4944       // Some targets like RISCV prefer to sign extend some types.
4945       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4946         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4947                            C->isTargetOpcode(), C->isOpaque());
4948       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4949                          C->isTargetOpcode(), C->isOpaque());
4950     case ISD::UINT_TO_FP:
4951     case ISD::SINT_TO_FP: {
4952       APFloat apf(EVTToAPFloatSemantics(VT),
4953                   APInt::getZero(VT.getSizeInBits()));
4954       (void)apf.convertFromAPInt(Val,
4955                                  Opcode==ISD::SINT_TO_FP,
4956                                  APFloat::rmNearestTiesToEven);
4957       return getConstantFP(apf, DL, VT);
4958     }
4959     case ISD::BITCAST:
4960       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4961         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4962       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4963         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4964       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4965         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4966       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4967         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4968       break;
4969     case ISD::ABS:
4970       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4971                          C->isOpaque());
4972     case ISD::BITREVERSE:
4973       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4974                          C->isOpaque());
4975     case ISD::BSWAP:
4976       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4977                          C->isOpaque());
4978     case ISD::CTPOP:
4979       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4980                          C->isOpaque());
4981     case ISD::CTLZ:
4982     case ISD::CTLZ_ZERO_UNDEF:
4983       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4984                          C->isOpaque());
4985     case ISD::CTTZ:
4986     case ISD::CTTZ_ZERO_UNDEF:
4987       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4988                          C->isOpaque());
4989     case ISD::FP16_TO_FP:
4990     case ISD::BF16_TO_FP: {
4991       bool Ignored;
4992       APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
4993                                             : APFloat::BFloat(),
4994                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4995
4996       // This can return overflow, underflow, or inexact; we don't care.
4997       // FIXME need to be more flexible about rounding mode.
4998       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4999                         APFloat::rmNearestTiesToEven, &Ignored);
5000       return getConstantFP(FPV, DL, VT);
5001     }
5002     case ISD::STEP_VECTOR: {
5003       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
5004         return V;
5005       break;
5006     }
5007     }
5008   }
5009
5010   // Constant fold unary operations with a floating point constant operand.
5011   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
5012     APFloat V = C->getValueAPF();    // make copy
5013     switch (Opcode) {
5014     case ISD::FNEG:
5015       V.changeSign();
5016       return getConstantFP(V, DL, VT);
5017     case ISD::FABS:
5018       V.clearSign();
5019       return getConstantFP(V, DL, VT);
5020     case ISD::FCEIL: {
5021       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5022       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5023         return getConstantFP(V, DL, VT);
5024       break;
5025     }
5026     case ISD::FTRUNC: {
5027       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5028       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5029         return getConstantFP(V, DL, VT);
5030       break;
5031     }
5032     case ISD::FFLOOR: {
5033       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5034       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5035         return getConstantFP(V, DL, VT);
5036       break;
5037     }
5038     case ISD::FP_EXTEND: {
5039       bool ignored;
5040       // This can return overflow, underflow, or inexact; we don't care.
5041       // FIXME need to be more flexible about rounding mode.
5042       (void)V.convert(EVTToAPFloatSemantics(VT),
5043                       APFloat::rmNearestTiesToEven, &ignored);
5044       return getConstantFP(V, DL, VT);
5045     }
5046     case ISD::FP_TO_SINT:
5047     case ISD::FP_TO_UINT: {
5048       bool ignored;
5049       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5050       // FIXME need to be more flexible about rounding mode.
5051       APFloat::opStatus s =
5052           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5053       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5054         break;
5055       return getConstant(IntVal, DL, VT);
5056     }
5057     case ISD::BITCAST:
5058       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5059         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5060       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5061         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5062       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5063         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5064       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5065         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5066       break;
5067     case ISD::FP_TO_FP16:
5068     case ISD::FP_TO_BF16: {
5069       bool Ignored;
5070       // This can return overflow, underflow, or inexact; we don't care.
5071       // FIXME need to be more flexible about rounding mode.
5072       (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
5073                                                 : APFloat::BFloat(),
5074                       APFloat::rmNearestTiesToEven, &Ignored);
5075       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5076     }
5077     }
5078   }
5079
5080   // Constant fold unary operations with a vector integer or float operand.
5081   switch (Opcode) {
5082   default:
5083     // FIXME: Entirely reasonable to perform folding of other unary
5084     // operations here as the need arises.
5085     break;
5086   case ISD::FNEG:
5087   case ISD::FABS:
5088   case ISD::FCEIL:
5089   case ISD::FTRUNC:
5090   case ISD::FFLOOR:
5091   case ISD::FP_EXTEND:
5092   case ISD::FP_TO_SINT:
5093   case ISD::FP_TO_UINT:
5094   case ISD::TRUNCATE:
5095   case ISD::ANY_EXTEND:
5096   case ISD::ZERO_EXTEND:
5097   case ISD::SIGN_EXTEND:
5098   case ISD::UINT_TO_FP:
5099   case ISD::SINT_TO_FP:
5100   case ISD::ABS:
5101   case ISD::BITREVERSE:
5102   case ISD::BSWAP:
5103   case ISD::CTLZ:
5104   case ISD::CTLZ_ZERO_UNDEF:
5105   case ISD::CTTZ:
5106   case ISD::CTTZ_ZERO_UNDEF:
5107   case ISD::CTPOP: {
5108     SDValue Ops = {Operand};
5109     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5110       return Fold;
5111   }
5112   }
5113
5114   unsigned OpOpcode = Operand.getNode()->getOpcode();
5115   switch (Opcode) {
5116   case ISD::STEP_VECTOR:
5117     assert(VT.isScalableVector() &&
5118            "STEP_VECTOR can only be used with scalable types");
5119     assert(OpOpcode == ISD::TargetConstant &&
5120            VT.getVectorElementType() == Operand.getValueType() &&
5121            "Unexpected step operand");
5122     break;
5123   case ISD::FREEZE:
5124     assert(VT == Operand.getValueType() && "Unexpected VT!");
5125     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5126       return Operand;
5127     break;
5128   case ISD::TokenFactor:
5129   case ISD::MERGE_VALUES:
5130   case ISD::CONCAT_VECTORS:
5131     return Operand;         // Factor, merge or concat of one node?  No need.
5132   case ISD::BUILD_VECTOR: {
5133     // Attempt to simplify BUILD_VECTOR.
5134     SDValue Ops[] = {Operand};
5135     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5136       return V;
5137     break;
5138   }
5139   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5140   case ISD::FP_EXTEND:
5141     assert(VT.isFloatingPoint() &&
5142            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5143     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5144     assert((!VT.isVector() ||
5145             VT.getVectorElementCount() ==
5146             Operand.getValueType().getVectorElementCount()) &&
5147            "Vector element count mismatch!");
5148     assert(Operand.getValueType().bitsLT(VT) &&
5149            "Invalid fpext node, dst < src!");
5150     if (Operand.isUndef())
5151       return getUNDEF(VT);
5152     break;
5153   case ISD::FP_TO_SINT:
5154   case ISD::FP_TO_UINT:
5155     if (Operand.isUndef())
5156       return getUNDEF(VT);
5157     break;
5158   case ISD::SINT_TO_FP:
5159   case ISD::UINT_TO_FP:
5160     // [us]itofp(undef) = 0, because the result value is bounded.
5161     if (Operand.isUndef())
5162       return getConstantFP(0.0, DL, VT);
5163     break;
5164   case ISD::SIGN_EXTEND:
5165     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5166            "Invalid SIGN_EXTEND!");
5167     assert(VT.isVector() == Operand.getValueType().isVector() &&
5168            "SIGN_EXTEND result type type should be vector iff the operand "
5169            "type is vector!");
5170     if (Operand.getValueType() == VT) return Operand;   // noop extension
5171     assert((!VT.isVector() ||
5172             VT.getVectorElementCount() ==
5173                 Operand.getValueType().getVectorElementCount()) &&
5174            "Vector element count mismatch!");
5175     assert(Operand.getValueType().bitsLT(VT) &&
5176            "Invalid sext node, dst < src!");
5177     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5178       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5179     if (OpOpcode == ISD::UNDEF)
5180       // sext(undef) = 0, because the top bits will all be the same.
5181       return getConstant(0, DL, VT);
5182     break;
5183   case ISD::ZERO_EXTEND:
5184     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5185            "Invalid ZERO_EXTEND!");
5186     assert(VT.isVector() == Operand.getValueType().isVector() &&
5187            "ZERO_EXTEND result type type should be vector iff the operand "
5188            "type is vector!");
5189     if (Operand.getValueType() == VT) return Operand;   // noop extension
5190     assert((!VT.isVector() ||
5191             VT.getVectorElementCount() ==
5192                 Operand.getValueType().getVectorElementCount()) &&
5193            "Vector element count mismatch!");
5194     assert(Operand.getValueType().bitsLT(VT) &&
5195            "Invalid zext node, dst < src!");
5196     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5197       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5198     if (OpOpcode == ISD::UNDEF)
5199       // zext(undef) = 0, because the top bits will be zero.
5200       return getConstant(0, DL, VT);
5201     break;
5202   case ISD::ANY_EXTEND:
5203     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5204            "Invalid ANY_EXTEND!");
5205     assert(VT.isVector() == Operand.getValueType().isVector() &&
5206            "ANY_EXTEND result type type should be vector iff the operand "
5207            "type is vector!");
5208     if (Operand.getValueType() == VT) return Operand;   // noop extension
5209     assert((!VT.isVector() ||
5210             VT.getVectorElementCount() ==
5211                 Operand.getValueType().getVectorElementCount()) &&
5212            "Vector element count mismatch!");
5213     assert(Operand.getValueType().bitsLT(VT) &&
5214            "Invalid anyext node, dst < src!");
5215
5216     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5217         OpOpcode == ISD::ANY_EXTEND)
5218       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5219       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5220     if (OpOpcode == ISD::UNDEF)
5221       return getUNDEF(VT);
5222
5223     // (ext (trunc x)) -> x
5224     if (OpOpcode == ISD::TRUNCATE) {
5225       SDValue OpOp = Operand.getOperand(0);
5226       if (OpOp.getValueType() == VT) {
5227         transferDbgValues(Operand, OpOp);
5228         return OpOp;
5229       }
5230     }
5231     break;
5232   case ISD::TRUNCATE:
5233     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5234            "Invalid TRUNCATE!");
5235     assert(VT.isVector() == Operand.getValueType().isVector() &&
5236            "TRUNCATE result type type should be vector iff the operand "
5237            "type is vector!");
5238     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5239     assert((!VT.isVector() ||
5240             VT.getVectorElementCount() ==
5241                 Operand.getValueType().getVectorElementCount()) &&
5242            "Vector element count mismatch!");
5243     assert(Operand.getValueType().bitsGT(VT) &&
5244            "Invalid truncate node, src < dst!");
5245     if (OpOpcode == ISD::TRUNCATE)
5246       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5247     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5248         OpOpcode == ISD::ANY_EXTEND) {
5249       // If the source is smaller than the dest, we still need an extend.
5250       if (Operand.getOperand(0).getValueType().getScalarType()
5251             .bitsLT(VT.getScalarType()))
5252         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5253       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5254         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5255       return Operand.getOperand(0);
5256     }
5257     if (OpOpcode == ISD::UNDEF)
5258       return getUNDEF(VT);
5259     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5260       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5261     break;
5262   case ISD::ANY_EXTEND_VECTOR_INREG:
5263   case ISD::ZERO_EXTEND_VECTOR_INREG:
5264   case ISD::SIGN_EXTEND_VECTOR_INREG:
5265     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5266     assert(Operand.getValueType().bitsLE(VT) &&
5267            "The input must be the same size or smaller than the result.");
5268     assert(VT.getVectorMinNumElements() <
5269                Operand.getValueType().getVectorMinNumElements() &&
5270            "The destination vector type must have fewer lanes than the input.");
5271     break;
5272   case ISD::ABS:
5273     assert(VT.isInteger() && VT == Operand.getValueType() &&
5274            "Invalid ABS!");
5275     if (OpOpcode == ISD::UNDEF)
5276       return getConstant(0, DL, VT);
5277     break;
5278   case ISD::BSWAP:
5279     assert(VT.isInteger() && VT == Operand.getValueType() &&
5280            "Invalid BSWAP!");
5281     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5282            "BSWAP types must be a multiple of 16 bits!");
5283     if (OpOpcode == ISD::UNDEF)
5284       return getUNDEF(VT);
5285     // bswap(bswap(X)) -> X.
5286     if (OpOpcode == ISD::BSWAP)
5287       return Operand.getOperand(0);
5288     break;
5289   case ISD::BITREVERSE:
5290     assert(VT.isInteger() && VT == Operand.getValueType() &&
5291            "Invalid BITREVERSE!");
5292     if (OpOpcode == ISD::UNDEF)
5293       return getUNDEF(VT);
5294     break;
5295   case ISD::BITCAST:
5296     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5297            "Cannot BITCAST between types of different sizes!");
5298     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5299     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5300       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5301     if (OpOpcode == ISD::UNDEF)
5302       return getUNDEF(VT);
5303     break;
5304   case ISD::SCALAR_TO_VECTOR:
5305     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5306            (VT.getVectorElementType() == Operand.getValueType() ||
5307             (VT.getVectorElementType().isInteger() &&
5308              Operand.getValueType().isInteger() &&
5309              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5310            "Illegal SCALAR_TO_VECTOR node!");
5311     if (OpOpcode == ISD::UNDEF)
5312       return getUNDEF(VT);
5313     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5314     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5315         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5316         Operand.getConstantOperandVal(1) == 0 &&
5317         Operand.getOperand(0).getValueType() == VT)
5318       return Operand.getOperand(0);
5319     break;
5320   case ISD::FNEG:
5321     // Negation of an unknown bag of bits is still completely undefined.
5322     if (OpOpcode == ISD::UNDEF)
5323       return getUNDEF(VT);
5324
5325     if (OpOpcode == ISD::FNEG)  // --X -> X
5326       return Operand.getOperand(0);
5327     break;
5328   case ISD::FABS:
5329     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5330       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5331     break;
5332   case ISD::VSCALE:
5333     assert(VT == Operand.getValueType() && "Unexpected VT!");
5334     break;
5335   case ISD::CTPOP:
5336     if (Operand.getValueType().getScalarType() == MVT::i1)
5337       return Operand;
5338     break;
5339   case ISD::CTLZ:
5340   case ISD::CTTZ:
5341     if (Operand.getValueType().getScalarType() == MVT::i1)
5342       return getNOT(DL, Operand, Operand.getValueType());
5343     break;
5344   case ISD::VECREDUCE_ADD:
5345     if (Operand.getValueType().getScalarType() == MVT::i1)
5346       return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
5347     break;
5348   case ISD::VECREDUCE_SMIN:
5349   case ISD::VECREDUCE_UMAX:
5350     if (Operand.getValueType().getScalarType() == MVT::i1)
5351       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5352     break;
5353   case ISD::VECREDUCE_SMAX:
5354   case ISD::VECREDUCE_UMIN:
5355     if (Operand.getValueType().getScalarType() == MVT::i1)
5356       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5357     break;
5358   }
5359
5360   SDNode *N;
5361   SDVTList VTs = getVTList(VT);
5362   SDValue Ops[] = {Operand};
5363   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5364     FoldingSetNodeID ID;
5365     AddNodeIDNode(ID, Opcode, VTs, Ops);
5366     void *IP = nullptr;
5367     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5368       E->intersectFlagsWith(Flags);
5369       return SDValue(E, 0);
5370     }
5371
5372     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5373     N->setFlags(Flags);
5374     createOperands(N, Ops);
5375     CSEMap.InsertNode(N, IP);
5376   } else {
5377     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5378     createOperands(N, Ops);
5379   }
5380
5381   InsertNode(N);
5382   SDValue V = SDValue(N, 0);
5383   NewSDValueDbgMsg(V, "Creating new node: ", this);
5384   return V;
5385 }
5386
5387 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5388                                        const APInt &C2) {
5389   switch (Opcode) {
5390   case ISD::ADD:  return C1 + C2;
5391   case ISD::SUB:  return C1 - C2;
5392   case ISD::MUL:  return C1 * C2;
5393   case ISD::AND:  return C1 & C2;
5394   case ISD::OR:   return C1 | C2;
5395   case ISD::XOR:  return C1 ^ C2;
5396   case ISD::SHL:  return C1 << C2;
5397   case ISD::SRL:  return C1.lshr(C2);
5398   case ISD::SRA:  return C1.ashr(C2);
5399   case ISD::ROTL: return C1.rotl(C2);
5400   case ISD::ROTR: return C1.rotr(C2);
5401   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5402   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5403   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5404   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5405   case ISD::SADDSAT: return C1.sadd_sat(C2);
5406   case ISD::UADDSAT: return C1.uadd_sat(C2);
5407   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5408   case ISD::USUBSAT: return C1.usub_sat(C2);
5409   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5410   case ISD::USHLSAT: return C1.ushl_sat(C2);
5411   case ISD::UDIV:
5412     if (!C2.getBoolValue())
5413       break;
5414     return C1.udiv(C2);
5415   case ISD::UREM:
5416     if (!C2.getBoolValue())
5417       break;
5418     return C1.urem(C2);
5419   case ISD::SDIV:
5420     if (!C2.getBoolValue())
5421       break;
5422     return C1.sdiv(C2);
5423   case ISD::SREM:
5424     if (!C2.getBoolValue())
5425       break;
5426     return C1.srem(C2);
5427   case ISD::MULHS: {
5428     unsigned FullWidth = C1.getBitWidth() * 2;
5429     APInt C1Ext = C1.sext(FullWidth);
5430     APInt C2Ext = C2.sext(FullWidth);
5431     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5432   }
5433   case ISD::MULHU: {
5434     unsigned FullWidth = C1.getBitWidth() * 2;
5435     APInt C1Ext = C1.zext(FullWidth);
5436     APInt C2Ext = C2.zext(FullWidth);
5437     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5438   }
5439   case ISD::AVGFLOORS: {
5440     unsigned FullWidth = C1.getBitWidth() + 1;
5441     APInt C1Ext = C1.sext(FullWidth);
5442     APInt C2Ext = C2.sext(FullWidth);
5443     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5444   }
5445   case ISD::AVGFLOORU: {
5446     unsigned FullWidth = C1.getBitWidth() + 1;
5447     APInt C1Ext = C1.zext(FullWidth);
5448     APInt C2Ext = C2.zext(FullWidth);
5449     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5450   }
5451   case ISD::AVGCEILS: {
5452     unsigned FullWidth = C1.getBitWidth() + 1;
5453     APInt C1Ext = C1.sext(FullWidth);
5454     APInt C2Ext = C2.sext(FullWidth);
5455     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5456   }
5457   case ISD::AVGCEILU: {
5458     unsigned FullWidth = C1.getBitWidth() + 1;
5459     APInt C1Ext = C1.zext(FullWidth);
5460     APInt C2Ext = C2.zext(FullWidth);
5461     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5462   }
5463   }
5464   return llvm::None;
5465 }
5466
5467 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5468                                        const GlobalAddressSDNode *GA,
5469                                        const SDNode *N2) {
5470   if (GA->getOpcode() != ISD::GlobalAddress)
5471     return SDValue();
5472   if (!TLI->isOffsetFoldingLegal(GA))
5473     return SDValue();
5474   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5475   if (!C2)
5476     return SDValue();
5477   int64_t Offset = C2->getSExtValue();
5478   switch (Opcode) {
5479   case ISD::ADD: break;
5480   case ISD::SUB: Offset = -uint64_t(Offset); break;
5481   default: return SDValue();
5482   }
5483   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5484                           GA->getOffset() + uint64_t(Offset));
5485 }
5486
5487 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5488   switch (Opcode) {
5489   case ISD::SDIV:
5490   case ISD::UDIV:
5491   case ISD::SREM:
5492   case ISD::UREM: {
5493     // If a divisor is zero/undef or any element of a divisor vector is
5494     // zero/undef, the whole op is undef.
5495     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5496     SDValue Divisor = Ops[1];
5497     if (Divisor.isUndef() || isNullConstant(Divisor))
5498       return true;
5499
5500     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5501            llvm::any_of(Divisor->op_values(),
5502                         [](SDValue V) { return V.isUndef() ||
5503                                         isNullConstant(V); });
5504     // TODO: Handle signed overflow.
5505   }
5506   // TODO: Handle oversized shifts.
5507   default:
5508     return false;
5509   }
5510 }
5511
5512 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5513                                              EVT VT, ArrayRef<SDValue> Ops) {
5514   // If the opcode is a target-specific ISD node, there's nothing we can
5515   // do here and the operand rules may not line up with the below, so
5516   // bail early.
5517   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5518   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5519   // foldCONCAT_VECTORS in getNode before this is called.
5520   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5521     return SDValue();
5522
5523   unsigned NumOps = Ops.size();
5524   if (NumOps == 0)
5525     return SDValue();
5526
5527   if (isUndef(Opcode, Ops))
5528     return getUNDEF(VT);
5529
5530   // Handle binops special cases.
5531   if (NumOps == 2) {
5532     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5533       return CFP;
5534
5535     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5536       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5537         if (C1->isOpaque() || C2->isOpaque())
5538           return SDValue();
5539
5540         Optional<APInt> FoldAttempt =
5541             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5542         if (!FoldAttempt)
5543           return SDValue();
5544
5545         SDValue Folded = getConstant(*FoldAttempt, DL, VT);
5546         assert((!Folded || !VT.isVector()) &&
5547                "Can't fold vectors ops with scalar operands");
5548         return Folded;
5549       }
5550     }
5551
5552     // fold (add Sym, c) -> Sym+c
5553     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5554       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5555     if (TLI->isCommutativeBinOp(Opcode))
5556       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5557         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5558   }
5559
5560   // This is for vector folding only from here on.
5561   if (!VT.isVector())
5562     return SDValue();
5563
5564   ElementCount NumElts = VT.getVectorElementCount();
5565
5566   // See if we can fold through bitcasted integer ops.
5567   // TODO: Can we handle undef elements?
5568   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5569       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5570       Ops[0].getOpcode() == ISD::BITCAST &&
5571       Ops[1].getOpcode() == ISD::BITCAST) {
5572     SDValue N1 = peekThroughBitcasts(Ops[0]);
5573     SDValue N2 = peekThroughBitcasts(Ops[1]);
5574     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5575     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5576     EVT BVVT = N1.getValueType();
5577     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5578       bool IsLE = getDataLayout().isLittleEndian();
5579       unsigned EltBits = VT.getScalarSizeInBits();
5580       SmallVector<APInt> RawBits1, RawBits2;
5581       BitVector UndefElts1, UndefElts2;
5582       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5583           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5584           UndefElts1.none() && UndefElts2.none()) {
5585         SmallVector<APInt> RawBits;
5586         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5587           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5588           if (!Fold)
5589             break;
5590           RawBits.push_back(*Fold);
5591         }
5592         if (RawBits.size() == NumElts.getFixedValue()) {
5593           // We have constant folded, but we need to cast this again back to
5594           // the original (possibly legalized) type.
5595           SmallVector<APInt> DstBits;
5596           BitVector DstUndefs;
5597           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5598                                            DstBits, RawBits, DstUndefs,
5599                                            BitVector(RawBits.size(), false));
5600           EVT BVEltVT = BV1->getOperand(0).getValueType();
5601           unsigned BVEltBits = BVEltVT.getSizeInBits();
5602           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5603           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5604             if (DstUndefs[I])
5605               continue;
5606             Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
5607           }
5608           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5609         }
5610       }
5611     }
5612   }
5613
5614   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5615   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5616   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5617       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5618     APInt RHSVal;
5619     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5620       APInt NewStep = Opcode == ISD::MUL
5621                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5622                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5623       return getStepVector(DL, VT, NewStep);
5624     }
5625   }
5626
5627   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5628     return !Op.getValueType().isVector() ||
5629            Op.getValueType().getVectorElementCount() == NumElts;
5630   };
5631
5632   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5633     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5634            Op.getOpcode() == ISD::BUILD_VECTOR ||
5635            Op.getOpcode() == ISD::SPLAT_VECTOR;
5636   };
5637
5638   // All operands must be vector types with the same number of elements as
5639   // the result type and must be either UNDEF or a build/splat vector
5640   // or UNDEF scalars.
5641   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5642       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5643     return SDValue();
5644
5645   // If we are comparing vectors, then the result needs to be a i1 boolean that
5646   // is then extended back to the legal result type depending on how booleans
5647   // are represented.
5648   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5649   ISD::NodeType ExtendCode =
5650       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5651           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5652           : ISD::SIGN_EXTEND;
5653
5654   // Find legal integer scalar type for constant promotion and
5655   // ensure that its scalar size is at least as large as source.
5656   EVT LegalSVT = VT.getScalarType();
5657   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5658     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5659     if (LegalSVT.bitsLT(VT.getScalarType()))
5660       return SDValue();
5661   }
5662
5663   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5664   // only have one operand to check. For fixed-length vector types we may have
5665   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5666   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5667
5668   // Constant fold each scalar lane separately.
5669   SmallVector<SDValue, 4> ScalarResults;
5670   for (unsigned I = 0; I != NumVectorElts; I++) {
5671     SmallVector<SDValue, 4> ScalarOps;
5672     for (SDValue Op : Ops) {
5673       EVT InSVT = Op.getValueType().getScalarType();
5674       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5675           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5676         if (Op.isUndef())
5677           ScalarOps.push_back(getUNDEF(InSVT));
5678         else
5679           ScalarOps.push_back(Op);
5680         continue;
5681       }
5682
5683       SDValue ScalarOp =
5684           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5685       EVT ScalarVT = ScalarOp.getValueType();
5686
5687       // Build vector (integer) scalar operands may need implicit
5688       // truncation - do this before constant folding.
5689       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5690         // Don't create illegally-typed nodes unless they're constants or undef
5691         // - if we fail to constant fold we can't guarantee the (dead) nodes
5692         // we're creating will be cleaned up before being visited for
5693         // legalization.
5694         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5695             !isa<ConstantSDNode>(ScalarOp) &&
5696             TLI->getTypeAction(*getContext(), InSVT) !=
5697                 TargetLowering::TypeLegal)
5698           return SDValue();
5699         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5700       }
5701
5702       ScalarOps.push_back(ScalarOp);
5703     }
5704
5705     // Constant fold the scalar operands.
5706     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5707
5708     // Legalize the (integer) scalar constant if necessary.
5709     if (LegalSVT != SVT)
5710       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5711
5712     // Scalar folding only succeeded if the result is a constant or UNDEF.
5713     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5714         ScalarResult.getOpcode() != ISD::ConstantFP)
5715       return SDValue();
5716     ScalarResults.push_back(ScalarResult);
5717   }
5718
5719   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5720                                    : getBuildVector(VT, DL, ScalarResults);
5721   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5722   return V;
5723 }
5724
5725 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5726                                          EVT VT, SDValue N1, SDValue N2) {
5727   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5728   //       should. That will require dealing with a potentially non-default
5729   //       rounding mode, checking the "opStatus" return value from the APFloat
5730   //       math calculations, and possibly other variations.
5731   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5732   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5733   if (N1CFP && N2CFP) {
5734     APFloat C1 = N1CFP->getValueAPF(); // make copy
5735     const APFloat &C2 = N2CFP->getValueAPF();
5736     switch (Opcode) {
5737     case ISD::FADD:
5738       C1.add(C2, APFloat::rmNearestTiesToEven);
5739       return getConstantFP(C1, DL, VT);
5740     case ISD::FSUB:
5741       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5742       return getConstantFP(C1, DL, VT);
5743     case ISD::FMUL:
5744       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5745       return getConstantFP(C1, DL, VT);
5746     case ISD::FDIV:
5747       C1.divide(C2, APFloat::rmNearestTiesToEven);
5748       return getConstantFP(C1, DL, VT);
5749     case ISD::FREM:
5750       C1.mod(C2);
5751       return getConstantFP(C1, DL, VT);
5752     case ISD::FCOPYSIGN:
5753       C1.copySign(C2);
5754       return getConstantFP(C1, DL, VT);
5755     case ISD::FMINNUM:
5756       return getConstantFP(minnum(C1, C2), DL, VT);
5757     case ISD::FMAXNUM:
5758       return getConstantFP(maxnum(C1, C2), DL, VT);
5759     case ISD::FMINIMUM:
5760       return getConstantFP(minimum(C1, C2), DL, VT);
5761     case ISD::FMAXIMUM:
5762       return getConstantFP(maximum(C1, C2), DL, VT);
5763     default: break;
5764     }
5765   }
5766   if (N1CFP && Opcode == ISD::FP_ROUND) {
5767     APFloat C1 = N1CFP->getValueAPF();    // make copy
5768     bool Unused;
5769     // This can return overflow, underflow, or inexact; we don't care.
5770     // FIXME need to be more flexible about rounding mode.
5771     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5772                       &Unused);
5773     return getConstantFP(C1, DL, VT);
5774   }
5775
5776   switch (Opcode) {
5777   case ISD::FSUB:
5778     // -0.0 - undef --> undef (consistent with "fneg undef")
5779     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5780       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5781         return getUNDEF(VT);
5782     LLVM_FALLTHROUGH;
5783
5784   case ISD::FADD:
5785   case ISD::FMUL:
5786   case ISD::FDIV:
5787   case ISD::FREM:
5788     // If both operands are undef, the result is undef. If 1 operand is undef,
5789     // the result is NaN. This should match the behavior of the IR optimizer.
5790     if (N1.isUndef() && N2.isUndef())
5791       return getUNDEF(VT);
5792     if (N1.isUndef() || N2.isUndef())
5793       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5794   }
5795   return SDValue();
5796 }
5797
5798 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5799   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5800
5801   // There's no need to assert on a byte-aligned pointer. All pointers are at
5802   // least byte aligned.
5803   if (A == Align(1))
5804     return Val;
5805
5806   FoldingSetNodeID ID;
5807   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5808   ID.AddInteger(A.value());
5809
5810   void *IP = nullptr;
5811   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5812     return SDValue(E, 0);
5813
5814   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5815                                          Val.getValueType(), A);
5816   createOperands(N, {Val});
5817
5818   CSEMap.InsertNode(N, IP);
5819   InsertNode(N);
5820
5821   SDValue V(N, 0);
5822   NewSDValueDbgMsg(V, "Creating new node: ", this);
5823   return V;
5824 }
5825
5826 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5827                               SDValue N1, SDValue N2) {
5828   SDNodeFlags Flags;
5829   if (Inserter)
5830     Flags = Inserter->getFlags();
5831   return getNode(Opcode, DL, VT, N1, N2, Flags);
5832 }
5833
5834 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5835                                                 SDValue &N2) const {
5836   if (!TLI->isCommutativeBinOp(Opcode))
5837     return;
5838
5839   // Canonicalize:
5840   //   binop(const, nonconst) -> binop(nonconst, const)
5841   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5842   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5843   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5844   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5845   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5846     std::swap(N1, N2);
5847
5848   // Canonicalize:
5849   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5850   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5851            N2.getOpcode() == ISD::STEP_VECTOR)
5852     std::swap(N1, N2);
5853 }
5854
5855 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5856                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5857   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5858          N2.getOpcode() != ISD::DELETED_NODE &&
5859          "Operand is DELETED_NODE!");
5860
5861   canonicalizeCommutativeBinop(Opcode, N1, N2);
5862
5863   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5864   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5865
5866   // Don't allow undefs in vector splats - we might be returning N2 when folding
5867   // to zero etc.
5868   ConstantSDNode *N2CV =
5869       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5870
5871   switch (Opcode) {
5872   default: break;
5873   case ISD::TokenFactor:
5874     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5875            N2.getValueType() == MVT::Other && "Invalid token factor!");
5876     // Fold trivial token factors.
5877     if (N1.getOpcode() == ISD::EntryToken) return N2;
5878     if (N2.getOpcode() == ISD::EntryToken) return N1;
5879     if (N1 == N2) return N1;
5880     break;
5881   case ISD::BUILD_VECTOR: {
5882     // Attempt to simplify BUILD_VECTOR.
5883     SDValue Ops[] = {N1, N2};
5884     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5885       return V;
5886     break;
5887   }
5888   case ISD::CONCAT_VECTORS: {
5889     SDValue Ops[] = {N1, N2};
5890     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5891       return V;
5892     break;
5893   }
5894   case ISD::AND:
5895     assert(VT.isInteger() && "This operator does not apply to FP types!");
5896     assert(N1.getValueType() == N2.getValueType() &&
5897            N1.getValueType() == VT && "Binary operator types must match!");
5898     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5899     // worth handling here.
5900     if (N2CV && N2CV->isZero())
5901       return N2;
5902     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5903       return N1;
5904     break;
5905   case ISD::OR:
5906   case ISD::XOR:
5907   case ISD::ADD:
5908   case ISD::SUB:
5909     assert(VT.isInteger() && "This operator does not apply to FP types!");
5910     assert(N1.getValueType() == N2.getValueType() &&
5911            N1.getValueType() == VT && "Binary operator types must match!");
5912     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5913     // it's worth handling here.
5914     if (N2CV && N2CV->isZero())
5915       return N1;
5916     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5917         VT.getVectorElementType() == MVT::i1)
5918       return getNode(ISD::XOR, DL, VT, N1, N2);
5919     break;
5920   case ISD::MUL:
5921     assert(VT.isInteger() && "This operator does not apply to FP types!");
5922     assert(N1.getValueType() == N2.getValueType() &&
5923            N1.getValueType() == VT && "Binary operator types must match!");
5924     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5925       return getNode(ISD::AND, DL, VT, N1, N2);
5926     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5927       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5928       const APInt &N2CImm = N2C->getAPIntValue();
5929       return getVScale(DL, VT, MulImm * N2CImm);
5930     }
5931     break;
5932   case ISD::UDIV:
5933   case ISD::UREM:
5934   case ISD::MULHU:
5935   case ISD::MULHS:
5936   case ISD::SDIV:
5937   case ISD::SREM:
5938   case ISD::SADDSAT:
5939   case ISD::SSUBSAT:
5940   case ISD::UADDSAT:
5941   case ISD::USUBSAT:
5942     assert(VT.isInteger() && "This operator does not apply to FP types!");
5943     assert(N1.getValueType() == N2.getValueType() &&
5944            N1.getValueType() == VT && "Binary operator types must match!");
5945     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5946       // fold (add_sat x, y) -> (or x, y) for bool types.
5947       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5948         return getNode(ISD::OR, DL, VT, N1, N2);
5949       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5950       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5951         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5952     }
5953     break;
5954   case ISD::SMIN:
5955   case ISD::UMAX:
5956     assert(VT.isInteger() && "This operator does not apply to FP types!");
5957     assert(N1.getValueType() == N2.getValueType() &&
5958            N1.getValueType() == VT && "Binary operator types must match!");
5959     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5960       return getNode(ISD::OR, DL, VT, N1, N2);
5961     break;
5962   case ISD::SMAX:
5963   case ISD::UMIN:
5964     assert(VT.isInteger() && "This operator does not apply to FP types!");
5965     assert(N1.getValueType() == N2.getValueType() &&
5966            N1.getValueType() == VT && "Binary operator types must match!");
5967     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5968       return getNode(ISD::AND, DL, VT, N1, N2);
5969     break;
5970   case ISD::FADD:
5971   case ISD::FSUB:
5972   case ISD::FMUL:
5973   case ISD::FDIV:
5974   case ISD::FREM:
5975     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5976     assert(N1.getValueType() == N2.getValueType() &&
5977            N1.getValueType() == VT && "Binary operator types must match!");
5978     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5979       return V;
5980     break;
5981   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5982     assert(N1.getValueType() == VT &&
5983            N1.getValueType().isFloatingPoint() &&
5984            N2.getValueType().isFloatingPoint() &&
5985            "Invalid FCOPYSIGN!");
5986     break;
5987   case ISD::SHL:
5988     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5989       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5990       const APInt &ShiftImm = N2C->getAPIntValue();
5991       return getVScale(DL, VT, MulImm << ShiftImm);
5992     }
5993     LLVM_FALLTHROUGH;
5994   case ISD::SRA:
5995   case ISD::SRL:
5996     if (SDValue V = simplifyShift(N1, N2))
5997       return V;
5998     LLVM_FALLTHROUGH;
5999   case ISD::ROTL:
6000   case ISD::ROTR:
6001     assert(VT == N1.getValueType() &&
6002            "Shift operators return type must be the same as their first arg");
6003     assert(VT.isInteger() && N2.getValueType().isInteger() &&
6004            "Shifts only work on integers");
6005     assert((!VT.isVector() || VT == N2.getValueType()) &&
6006            "Vector shift amounts must be in the same as their first arg");
6007     // Verify that the shift amount VT is big enough to hold valid shift
6008     // amounts.  This catches things like trying to shift an i1024 value by an
6009     // i8, which is easy to fall into in generic code that uses
6010     // TLI.getShiftAmount().
6011     assert(N2.getValueType().getScalarSizeInBits() >=
6012                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
6013            "Invalid use of small shift amount with oversized value!");
6014
6015     // Always fold shifts of i1 values so the code generator doesn't need to
6016     // handle them.  Since we know the size of the shift has to be less than the
6017     // size of the value, the shift/rotate count is guaranteed to be zero.
6018     if (VT == MVT::i1)
6019       return N1;
6020     if (N2CV && N2CV->isZero())
6021       return N1;
6022     break;
6023   case ISD::FP_ROUND:
6024     assert(VT.isFloatingPoint() &&
6025            N1.getValueType().isFloatingPoint() &&
6026            VT.bitsLE(N1.getValueType()) &&
6027            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6028            "Invalid FP_ROUND!");
6029     if (N1.getValueType() == VT) return N1;  // noop conversion.
6030     break;
6031   case ISD::AssertSext:
6032   case ISD::AssertZext: {
6033     EVT EVT = cast<VTSDNode>(N2)->getVT();
6034     assert(VT == N1.getValueType() && "Not an inreg extend!");
6035     assert(VT.isInteger() && EVT.isInteger() &&
6036            "Cannot *_EXTEND_INREG FP types");
6037     assert(!EVT.isVector() &&
6038            "AssertSExt/AssertZExt type should be the vector element type "
6039            "rather than the vector type!");
6040     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6041     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6042     break;
6043   }
6044   case ISD::SIGN_EXTEND_INREG: {
6045     EVT EVT = cast<VTSDNode>(N2)->getVT();
6046     assert(VT == N1.getValueType() && "Not an inreg extend!");
6047     assert(VT.isInteger() && EVT.isInteger() &&
6048            "Cannot *_EXTEND_INREG FP types");
6049     assert(EVT.isVector() == VT.isVector() &&
6050            "SIGN_EXTEND_INREG type should be vector iff the operand "
6051            "type is vector!");
6052     assert((!EVT.isVector() ||
6053             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6054            "Vector element counts must match in SIGN_EXTEND_INREG");
6055     assert(EVT.bitsLE(VT) && "Not extending!");
6056     if (EVT == VT) return N1;  // Not actually extending
6057
6058     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6059       unsigned FromBits = EVT.getScalarSizeInBits();
6060       Val <<= Val.getBitWidth() - FromBits;
6061       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6062       return getConstant(Val, DL, ConstantVT);
6063     };
6064
6065     if (N1C) {
6066       const APInt &Val = N1C->getAPIntValue();
6067       return SignExtendInReg(Val, VT);
6068     }
6069
6070     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6071       SmallVector<SDValue, 8> Ops;
6072       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6073       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6074         SDValue Op = N1.getOperand(i);
6075         if (Op.isUndef()) {
6076           Ops.push_back(getUNDEF(OpVT));
6077           continue;
6078         }
6079         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6080         APInt Val = C->getAPIntValue();
6081         Ops.push_back(SignExtendInReg(Val, OpVT));
6082       }
6083       return getBuildVector(VT, DL, Ops);
6084     }
6085     break;
6086   }
6087   case ISD::FP_TO_SINT_SAT:
6088   case ISD::FP_TO_UINT_SAT: {
6089     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6090            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6091     assert(N1.getValueType().isVector() == VT.isVector() &&
6092            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6093            "vector!");
6094     assert((!VT.isVector() || VT.getVectorElementCount() ==
6095                                   N1.getValueType().getVectorElementCount()) &&
6096            "Vector element counts must match in FP_TO_*INT_SAT");
6097     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6098            "Type to saturate to must be a scalar.");
6099     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6100            "Not extending!");
6101     break;
6102   }
6103   case ISD::EXTRACT_VECTOR_ELT:
6104     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6105            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6106              element type of the vector.");
6107
6108     // Extract from an undefined value or using an undefined index is undefined.
6109     if (N1.isUndef() || N2.isUndef())
6110       return getUNDEF(VT);
6111
6112     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6113     // vectors. For scalable vectors we will provide appropriate support for
6114     // dealing with arbitrary indices.
6115     if (N2C && N1.getValueType().isFixedLengthVector() &&
6116         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6117       return getUNDEF(VT);
6118
6119     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6120     // expanding copies of large vectors from registers. This only works for
6121     // fixed length vectors, since we need to know the exact number of
6122     // elements.
6123     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6124         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6125       unsigned Factor =
6126         N1.getOperand(0).getValueType().getVectorNumElements();
6127       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6128                      N1.getOperand(N2C->getZExtValue() / Factor),
6129                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6130     }
6131
6132     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6133     // lowering is expanding large vector constants.
6134     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6135                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6136       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6137               N1.getValueType().isFixedLengthVector()) &&
6138              "BUILD_VECTOR used for scalable vectors");
6139       unsigned Index =
6140           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6141       SDValue Elt = N1.getOperand(Index);
6142
6143       if (VT != Elt.getValueType())
6144         // If the vector element type is not legal, the BUILD_VECTOR operands
6145         // are promoted and implicitly truncated, and the result implicitly
6146         // extended. Make that explicit here.
6147         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6148
6149       return Elt;
6150     }
6151
6152     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6153     // operations are lowered to scalars.
6154     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6155       // If the indices are the same, return the inserted element else
6156       // if the indices are known different, extract the element from
6157       // the original vector.
6158       SDValue N1Op2 = N1.getOperand(2);
6159       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6160
6161       if (N1Op2C && N2C) {
6162         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6163           if (VT == N1.getOperand(1).getValueType())
6164             return N1.getOperand(1);
6165           if (VT.isFloatingPoint()) {
6166             assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits());
6167             return getFPExtendOrRound(N1.getOperand(1), DL, VT);
6168           }
6169           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6170         }
6171         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6172       }
6173     }
6174
6175     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6176     // when vector types are scalarized and v1iX is legal.
6177     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6178     // Here we are completely ignoring the extract element index (N2),
6179     // which is fine for fixed width vectors, since any index other than 0
6180     // is undefined anyway. However, this cannot be ignored for scalable
6181     // vectors - in theory we could support this, but we don't want to do this
6182     // without a profitability check.
6183     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6184         N1.getValueType().isFixedLengthVector() &&
6185         N1.getValueType().getVectorNumElements() == 1) {
6186       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6187                      N1.getOperand(1));
6188     }
6189     break;
6190   case ISD::EXTRACT_ELEMENT:
6191     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6192     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6193            (N1.getValueType().isInteger() == VT.isInteger()) &&
6194            N1.getValueType() != VT &&
6195            "Wrong types for EXTRACT_ELEMENT!");
6196
6197     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6198     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6199     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6200     if (N1.getOpcode() == ISD::BUILD_PAIR)
6201       return N1.getOperand(N2C->getZExtValue());
6202
6203     // EXTRACT_ELEMENT of a constant int is also very common.
6204     if (N1C) {
6205       unsigned ElementSize = VT.getSizeInBits();
6206       unsigned Shift = ElementSize * N2C->getZExtValue();
6207       const APInt &Val = N1C->getAPIntValue();
6208       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6209     }
6210     break;
6211   case ISD::EXTRACT_SUBVECTOR: {
6212     EVT N1VT = N1.getValueType();
6213     assert(VT.isVector() && N1VT.isVector() &&
6214            "Extract subvector VTs must be vectors!");
6215     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6216            "Extract subvector VTs must have the same element type!");
6217     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6218            "Cannot extract a scalable vector from a fixed length vector!");
6219     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6220             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6221            "Extract subvector must be from larger vector to smaller vector!");
6222     assert(N2C && "Extract subvector index must be a constant");
6223     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6224             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6225                 N1VT.getVectorMinNumElements()) &&
6226            "Extract subvector overflow!");
6227     assert(N2C->getAPIntValue().getBitWidth() ==
6228                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6229            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6230
6231     // Trivial extraction.
6232     if (VT == N1VT)
6233       return N1;
6234
6235     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6236     if (N1.isUndef())
6237       return getUNDEF(VT);
6238
6239     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6240     // the concat have the same type as the extract.
6241     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6242         VT == N1.getOperand(0).getValueType()) {
6243       unsigned Factor = VT.getVectorMinNumElements();
6244       return N1.getOperand(N2C->getZExtValue() / Factor);
6245     }
6246
6247     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6248     // during shuffle legalization.
6249     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6250         VT == N1.getOperand(1).getValueType())
6251       return N1.getOperand(1);
6252     break;
6253   }
6254   }
6255
6256   // Perform trivial constant folding.
6257   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6258     return SV;
6259
6260   // Canonicalize an UNDEF to the RHS, even over a constant.
6261   if (N1.isUndef()) {
6262     if (TLI->isCommutativeBinOp(Opcode)) {
6263       std::swap(N1, N2);
6264     } else {
6265       switch (Opcode) {
6266       case ISD::SUB:
6267         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6268       case ISD::SIGN_EXTEND_INREG:
6269       case ISD::UDIV:
6270       case ISD::SDIV:
6271       case ISD::UREM:
6272       case ISD::SREM:
6273       case ISD::SSUBSAT:
6274       case ISD::USUBSAT:
6275         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6276       }
6277     }
6278   }
6279
6280   // Fold a bunch of operators when the RHS is undef.
6281   if (N2.isUndef()) {
6282     switch (Opcode) {
6283     case ISD::XOR:
6284       if (N1.isUndef())
6285         // Handle undef ^ undef -> 0 special case. This is a common
6286         // idiom (misuse).
6287         return getConstant(0, DL, VT);
6288       LLVM_FALLTHROUGH;
6289     case ISD::ADD:
6290     case ISD::SUB:
6291     case ISD::UDIV:
6292     case ISD::SDIV:
6293     case ISD::UREM:
6294     case ISD::SREM:
6295       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6296     case ISD::MUL:
6297     case ISD::AND:
6298     case ISD::SSUBSAT:
6299     case ISD::USUBSAT:
6300       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6301     case ISD::OR:
6302     case ISD::SADDSAT:
6303     case ISD::UADDSAT:
6304       return getAllOnesConstant(DL, VT);
6305     }
6306   }
6307
6308   // Memoize this node if possible.
6309   SDNode *N;
6310   SDVTList VTs = getVTList(VT);
6311   SDValue Ops[] = {N1, N2};
6312   if (VT != MVT::Glue) {
6313     FoldingSetNodeID ID;
6314     AddNodeIDNode(ID, Opcode, VTs, Ops);
6315     void *IP = nullptr;
6316     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6317       E->intersectFlagsWith(Flags);
6318       return SDValue(E, 0);
6319     }
6320
6321     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6322     N->setFlags(Flags);
6323     createOperands(N, Ops);
6324     CSEMap.InsertNode(N, IP);
6325   } else {
6326     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6327     createOperands(N, Ops);
6328   }
6329
6330   InsertNode(N);
6331   SDValue V = SDValue(N, 0);
6332   NewSDValueDbgMsg(V, "Creating new node: ", this);
6333   return V;
6334 }
6335
6336 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6337                               SDValue N1, SDValue N2, SDValue N3) {
6338   SDNodeFlags Flags;
6339   if (Inserter)
6340     Flags = Inserter->getFlags();
6341   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6342 }
6343
6344 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6345                               SDValue N1, SDValue N2, SDValue N3,
6346                               const SDNodeFlags Flags) {
6347   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6348          N2.getOpcode() != ISD::DELETED_NODE &&
6349          N3.getOpcode() != ISD::DELETED_NODE &&
6350          "Operand is DELETED_NODE!");
6351   // Perform various simplifications.
6352   switch (Opcode) {
6353   case ISD::FMA: {
6354     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6355     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6356            N3.getValueType() == VT && "FMA types must match!");
6357     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6358     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6359     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6360     if (N1CFP && N2CFP && N3CFP) {
6361       APFloat  V1 = N1CFP->getValueAPF();
6362       const APFloat &V2 = N2CFP->getValueAPF();
6363       const APFloat &V3 = N3CFP->getValueAPF();
6364       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6365       return getConstantFP(V1, DL, VT);
6366     }
6367     break;
6368   }
6369   case ISD::BUILD_VECTOR: {
6370     // Attempt to simplify BUILD_VECTOR.
6371     SDValue Ops[] = {N1, N2, N3};
6372     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6373       return V;
6374     break;
6375   }
6376   case ISD::CONCAT_VECTORS: {
6377     SDValue Ops[] = {N1, N2, N3};
6378     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6379       return V;
6380     break;
6381   }
6382   case ISD::SETCC: {
6383     assert(VT.isInteger() && "SETCC result type must be an integer!");
6384     assert(N1.getValueType() == N2.getValueType() &&
6385            "SETCC operands must have the same type!");
6386     assert(VT.isVector() == N1.getValueType().isVector() &&
6387            "SETCC type should be vector iff the operand type is vector!");
6388     assert((!VT.isVector() || VT.getVectorElementCount() ==
6389                                   N1.getValueType().getVectorElementCount()) &&
6390            "SETCC vector element counts must match!");
6391     // Use FoldSetCC to simplify SETCC's.
6392     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6393       return V;
6394     // Vector constant folding.
6395     SDValue Ops[] = {N1, N2, N3};
6396     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6397       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6398       return V;
6399     }
6400     break;
6401   }
6402   case ISD::SELECT:
6403   case ISD::VSELECT:
6404     if (SDValue V = simplifySelect(N1, N2, N3))
6405       return V;
6406     break;
6407   case ISD::VECTOR_SHUFFLE:
6408     llvm_unreachable("should use getVectorShuffle constructor!");
6409   case ISD::VECTOR_SPLICE: {
6410     if (cast<ConstantSDNode>(N3)->isNullValue())
6411       return N1;
6412     break;
6413   }
6414   case ISD::INSERT_VECTOR_ELT: {
6415     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6416     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6417     // for scalable vectors where we will generate appropriate code to
6418     // deal with out-of-bounds cases correctly.
6419     if (N3C && N1.getValueType().isFixedLengthVector() &&
6420         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6421       return getUNDEF(VT);
6422
6423     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6424     if (N3.isUndef())
6425       return getUNDEF(VT);
6426
6427     // If the inserted element is an UNDEF, just use the input vector.
6428     if (N2.isUndef())
6429       return N1;
6430
6431     break;
6432   }
6433   case ISD::INSERT_SUBVECTOR: {
6434     // Inserting undef into undef is still undef.
6435     if (N1.isUndef() && N2.isUndef())
6436       return getUNDEF(VT);
6437
6438     EVT N2VT = N2.getValueType();
6439     assert(VT == N1.getValueType() &&
6440            "Dest and insert subvector source types must match!");
6441     assert(VT.isVector() && N2VT.isVector() &&
6442            "Insert subvector VTs must be vectors!");
6443     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6444            "Cannot insert a scalable vector into a fixed length vector!");
6445     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6446             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6447            "Insert subvector must be from smaller vector to larger vector!");
6448     assert(isa<ConstantSDNode>(N3) &&
6449            "Insert subvector index must be constant");
6450     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6451             (N2VT.getVectorMinNumElements() +
6452              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6453                 VT.getVectorMinNumElements()) &&
6454            "Insert subvector overflow!");
6455     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6456                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6457            "Constant index for INSERT_SUBVECTOR has an invalid size");
6458
6459     // Trivial insertion.
6460     if (VT == N2VT)
6461       return N2;
6462
6463     // If this is an insert of an extracted vector into an undef vector, we
6464     // can just use the input to the extract.
6465     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6466         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6467       return N2.getOperand(0);
6468     break;
6469   }
6470   case ISD::BITCAST:
6471     // Fold bit_convert nodes from a type to themselves.
6472     if (N1.getValueType() == VT)
6473       return N1;
6474     break;
6475   }
6476
6477   // Memoize node if it doesn't produce a flag.
6478   SDNode *N;
6479   SDVTList VTs = getVTList(VT);
6480   SDValue Ops[] = {N1, N2, N3};
6481   if (VT != MVT::Glue) {
6482     FoldingSetNodeID ID;
6483     AddNodeIDNode(ID, Opcode, VTs, Ops);
6484     void *IP = nullptr;
6485     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6486       E->intersectFlagsWith(Flags);
6487       return SDValue(E, 0);
6488     }
6489
6490     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6491     N->setFlags(Flags);
6492     createOperands(N, Ops);
6493     CSEMap.InsertNode(N, IP);
6494   } else {
6495     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6496     createOperands(N, Ops);
6497   }
6498
6499   InsertNode(N);
6500   SDValue V = SDValue(N, 0);
6501   NewSDValueDbgMsg(V, "Creating new node: ", this);
6502   return V;
6503 }
6504
6505 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6506                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6507   SDValue Ops[] = { N1, N2, N3, N4 };
6508   return getNode(Opcode, DL, VT, Ops);
6509 }
6510
6511 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6512                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6513                               SDValue N5) {
6514   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6515   return getNode(Opcode, DL, VT, Ops);
6516 }
6517
6518 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6519 /// the incoming stack arguments to be loaded from the stack.
6520 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6521   SmallVector<SDValue, 8> ArgChains;
6522
6523   // Include the original chain at the beginning of the list. When this is
6524   // used by target LowerCall hooks, this helps legalize find the
6525   // CALLSEQ_BEGIN node.
6526   ArgChains.push_back(Chain);
6527
6528   // Add a chain value for each stack argument.
6529   for (SDNode *U : getEntryNode().getNode()->uses())
6530     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6531       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6532         if (FI->getIndex() < 0)
6533           ArgChains.push_back(SDValue(L, 1));
6534
6535   // Build a tokenfactor for all the chains.
6536   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6537 }
6538
6539 /// getMemsetValue - Vectorized representation of the memset value
6540 /// operand.
6541 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6542                               const SDLoc &dl) {
6543   assert(!Value.isUndef());
6544
6545   unsigned NumBits = VT.getScalarSizeInBits();
6546   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6547     assert(C->getAPIntValue().getBitWidth() == 8);
6548     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6549     if (VT.isInteger()) {
6550       bool IsOpaque = VT.getSizeInBits() > 64 ||
6551           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6552       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6553     }
6554     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6555                              VT);
6556   }
6557
6558   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6559   EVT IntVT = VT.getScalarType();
6560   if (!IntVT.isInteger())
6561     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6562
6563   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6564   if (NumBits > 8) {
6565     // Use a multiplication with 0x010101... to extend the input to the
6566     // required length.
6567     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6568     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6569                         DAG.getConstant(Magic, dl, IntVT));
6570   }
6571
6572   if (VT != Value.getValueType() && !VT.isInteger())
6573     Value = DAG.getBitcast(VT.getScalarType(), Value);
6574   if (VT != Value.getValueType())
6575     Value = DAG.getSplatBuildVector(VT, dl, Value);
6576
6577   return Value;
6578 }
6579
6580 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6581 /// used when a memcpy is turned into a memset when the source is a constant
6582 /// string ptr.
6583 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6584                                   const TargetLowering &TLI,
6585                                   const ConstantDataArraySlice &Slice) {
6586   // Handle vector with all elements zero.
6587   if (Slice.Array == nullptr) {
6588     if (VT.isInteger())
6589       return DAG.getConstant(0, dl, VT);
6590     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6591       return DAG.getConstantFP(0.0, dl, VT);
6592     if (VT.isVector()) {
6593       unsigned NumElts = VT.getVectorNumElements();
6594       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6595       return DAG.getNode(ISD::BITCAST, dl, VT,
6596                          DAG.getConstant(0, dl,
6597                                          EVT::getVectorVT(*DAG.getContext(),
6598                                                           EltVT, NumElts)));
6599     }
6600     llvm_unreachable("Expected type!");
6601   }
6602
6603   assert(!VT.isVector() && "Can't handle vector type here!");
6604   unsigned NumVTBits = VT.getSizeInBits();
6605   unsigned NumVTBytes = NumVTBits / 8;
6606   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6607
6608   APInt Val(NumVTBits, 0);
6609   if (DAG.getDataLayout().isLittleEndian()) {
6610     for (unsigned i = 0; i != NumBytes; ++i)
6611       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6612   } else {
6613     for (unsigned i = 0; i != NumBytes; ++i)
6614       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6615   }
6616
6617   // If the "cost" of materializing the integer immediate is less than the cost
6618   // of a load, then it is cost effective to turn the load into the immediate.
6619   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6620   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6621     return DAG.getConstant(Val, dl, VT);
6622   return SDValue();
6623 }
6624
6625 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6626                                            const SDLoc &DL,
6627                                            const SDNodeFlags Flags) {
6628   EVT VT = Base.getValueType();
6629   SDValue Index;
6630
6631   if (Offset.isScalable())
6632     Index = getVScale(DL, Base.getValueType(),
6633                       APInt(Base.getValueSizeInBits().getFixedSize(),
6634                             Offset.getKnownMinSize()));
6635   else
6636     Index = getConstant(Offset.getFixedSize(), DL, VT);
6637
6638   return getMemBasePlusOffset(Base, Index, DL, Flags);
6639 }
6640
6641 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6642                                            const SDLoc &DL,
6643                                            const SDNodeFlags Flags) {
6644   assert(Offset.getValueType().isInteger());
6645   EVT BasePtrVT = Ptr.getValueType();
6646   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6647 }
6648
6649 /// Returns true if memcpy source is constant data.
6650 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6651   uint64_t SrcDelta = 0;
6652   GlobalAddressSDNode *G = nullptr;
6653   if (Src.getOpcode() == ISD::GlobalAddress)
6654     G = cast<GlobalAddressSDNode>(Src);
6655   else if (Src.getOpcode() == ISD::ADD &&
6656            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6657            Src.getOperand(1).getOpcode() == ISD::Constant) {
6658     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6659     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6660   }
6661   if (!G)
6662     return false;
6663
6664   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6665                                   SrcDelta + G->getOffset());
6666 }
6667
6668 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6669                                       SelectionDAG &DAG) {
6670   // On Darwin, -Os means optimize for size without hurting performance, so
6671   // only really optimize for size when -Oz (MinSize) is used.
6672   if (MF.getTarget().getTargetTriple().isOSDarwin())
6673     return MF.getFunction().hasMinSize();
6674   return DAG.shouldOptForSize();
6675 }
6676
6677 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6678                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6679                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6680                           SmallVector<SDValue, 16> &OutStoreChains) {
6681   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6682   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6683   SmallVector<SDValue, 16> GluedLoadChains;
6684   for (unsigned i = From; i < To; ++i) {
6685     OutChains.push_back(OutLoadChains[i]);
6686     GluedLoadChains.push_back(OutLoadChains[i]);
6687   }
6688
6689   // Chain for all loads.
6690   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6691                                   GluedLoadChains);
6692
6693   for (unsigned i = From; i < To; ++i) {
6694     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6695     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6696                                   ST->getBasePtr(), ST->getMemoryVT(),
6697                                   ST->getMemOperand());
6698     OutChains.push_back(NewStore);
6699   }
6700 }
6701
6702 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6703                                        SDValue Chain, SDValue Dst, SDValue Src,
6704                                        uint64_t Size, Align Alignment,
6705                                        bool isVol, bool AlwaysInline,
6706                                        MachinePointerInfo DstPtrInfo,
6707                                        MachinePointerInfo SrcPtrInfo,
6708                                        const AAMDNodes &AAInfo, AAResults *AA) {
6709   // Turn a memcpy of undef to nop.
6710   // FIXME: We need to honor volatile even is Src is undef.
6711   if (Src.isUndef())
6712     return Chain;
6713
6714   // Expand memcpy to a series of load and store ops if the size operand falls
6715   // below a certain threshold.
6716   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6717   // rather than maybe a humongous number of loads and stores.
6718   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6719   const DataLayout &DL = DAG.getDataLayout();
6720   LLVMContext &C = *DAG.getContext();
6721   std::vector<EVT> MemOps;
6722   bool DstAlignCanChange = false;
6723   MachineFunction &MF = DAG.getMachineFunction();
6724   MachineFrameInfo &MFI = MF.getFrameInfo();
6725   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6726   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6727   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6728     DstAlignCanChange = true;
6729   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6730   if (!SrcAlign || Alignment > *SrcAlign)
6731     SrcAlign = Alignment;
6732   assert(SrcAlign && "SrcAlign must be set");
6733   ConstantDataArraySlice Slice;
6734   // If marked as volatile, perform a copy even when marked as constant.
6735   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6736   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6737   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6738   const MemOp Op = isZeroConstant
6739                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6740                                     /*IsZeroMemset*/ true, isVol)
6741                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6742                                      *SrcAlign, isVol, CopyFromConstant);
6743   if (!TLI.findOptimalMemOpLowering(
6744           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6745           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6746     return SDValue();
6747
6748   if (DstAlignCanChange) {
6749     Type *Ty = MemOps[0].getTypeForEVT(C);
6750     Align NewAlign = DL.getABITypeAlign(Ty);
6751
6752     // Don't promote to an alignment that would require dynamic stack
6753     // realignment.
6754     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6755     if (!TRI->hasStackRealignment(MF))
6756       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6757         NewAlign = NewAlign.previous();
6758
6759     if (NewAlign > Alignment) {
6760       // Give the stack frame object a larger alignment if needed.
6761       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6762         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6763       Alignment = NewAlign;
6764     }
6765   }
6766
6767   // Prepare AAInfo for loads/stores after lowering this memcpy.
6768   AAMDNodes NewAAInfo = AAInfo;
6769   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6770
6771   const Value *SrcVal = SrcPtrInfo.V.dyn_cast<const Value *>();
6772   bool isConstant =
6773       AA && SrcVal &&
6774       AA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
6775
6776   MachineMemOperand::Flags MMOFlags =
6777       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6778   SmallVector<SDValue, 16> OutLoadChains;
6779   SmallVector<SDValue, 16> OutStoreChains;
6780   SmallVector<SDValue, 32> OutChains;
6781   unsigned NumMemOps = MemOps.size();
6782   uint64_t SrcOff = 0, DstOff = 0;
6783   for (unsigned i = 0; i != NumMemOps; ++i) {
6784     EVT VT = MemOps[i];
6785     unsigned VTSize = VT.getSizeInBits() / 8;
6786     SDValue Value, Store;
6787
6788     if (VTSize > Size) {
6789       // Issuing an unaligned load / store pair  that overlaps with the previous
6790       // pair. Adjust the offset accordingly.
6791       assert(i == NumMemOps-1 && i != 0);
6792       SrcOff -= VTSize - Size;
6793       DstOff -= VTSize - Size;
6794     }
6795
6796     if (CopyFromConstant &&
6797         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6798       // It's unlikely a store of a vector immediate can be done in a single
6799       // instruction. It would require a load from a constantpool first.
6800       // We only handle zero vectors here.
6801       // FIXME: Handle other cases where store of vector immediate is done in
6802       // a single instruction.
6803       ConstantDataArraySlice SubSlice;
6804       if (SrcOff < Slice.Length) {
6805         SubSlice = Slice;
6806         SubSlice.move(SrcOff);
6807       } else {
6808         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6809         SubSlice.Array = nullptr;
6810         SubSlice.Offset = 0;
6811         SubSlice.Length = VTSize;
6812       }
6813       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6814       if (Value.getNode()) {
6815         Store = DAG.getStore(
6816             Chain, dl, Value,
6817             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6818             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6819         OutChains.push_back(Store);
6820       }
6821     }
6822
6823     if (!Store.getNode()) {
6824       // The type might not be legal for the target.  This should only happen
6825       // if the type is smaller than a legal type, as on PPC, so the right
6826       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6827       // to Load/Store if NVT==VT.
6828       // FIXME does the case above also need this?
6829       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6830       assert(NVT.bitsGE(VT));
6831
6832       bool isDereferenceable =
6833         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6834       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6835       if (isDereferenceable)
6836         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6837       if (isConstant)
6838         SrcMMOFlags |= MachineMemOperand::MOInvariant;
6839
6840       Value = DAG.getExtLoad(
6841           ISD::EXTLOAD, dl, NVT, Chain,
6842           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6843           SrcPtrInfo.getWithOffset(SrcOff), VT,
6844           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6845       OutLoadChains.push_back(Value.getValue(1));
6846
6847       Store = DAG.getTruncStore(
6848           Chain, dl, Value,
6849           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6850           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6851       OutStoreChains.push_back(Store);
6852     }
6853     SrcOff += VTSize;
6854     DstOff += VTSize;
6855     Size -= VTSize;
6856   }
6857
6858   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6859                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6860   unsigned NumLdStInMemcpy = OutStoreChains.size();
6861
6862   if (NumLdStInMemcpy) {
6863     // It may be that memcpy might be converted to memset if it's memcpy
6864     // of constants. In such a case, we won't have loads and stores, but
6865     // just stores. In the absence of loads, there is nothing to gang up.
6866     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6867       // If target does not care, just leave as it.
6868       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6869         OutChains.push_back(OutLoadChains[i]);
6870         OutChains.push_back(OutStoreChains[i]);
6871       }
6872     } else {
6873       // Ld/St less than/equal limit set by target.
6874       if (NumLdStInMemcpy <= GluedLdStLimit) {
6875           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6876                                         NumLdStInMemcpy, OutLoadChains,
6877                                         OutStoreChains);
6878       } else {
6879         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6880         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6881         unsigned GlueIter = 0;
6882
6883         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6884           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6885           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6886
6887           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6888                                        OutLoadChains, OutStoreChains);
6889           GlueIter += GluedLdStLimit;
6890         }
6891
6892         // Residual ld/st.
6893         if (RemainingLdStInMemcpy) {
6894           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6895                                         RemainingLdStInMemcpy, OutLoadChains,
6896                                         OutStoreChains);
6897         }
6898       }
6899     }
6900   }
6901   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6902 }
6903
6904 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6905                                         SDValue Chain, SDValue Dst, SDValue Src,
6906                                         uint64_t Size, Align Alignment,
6907                                         bool isVol, bool AlwaysInline,
6908                                         MachinePointerInfo DstPtrInfo,
6909                                         MachinePointerInfo SrcPtrInfo,
6910                                         const AAMDNodes &AAInfo) {
6911   // Turn a memmove of undef to nop.
6912   // FIXME: We need to honor volatile even is Src is undef.
6913   if (Src.isUndef())
6914     return Chain;
6915
6916   // Expand memmove to a series of load and store ops if the size operand falls
6917   // below a certain threshold.
6918   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6919   const DataLayout &DL = DAG.getDataLayout();
6920   LLVMContext &C = *DAG.getContext();
6921   std::vector<EVT> MemOps;
6922   bool DstAlignCanChange = false;
6923   MachineFunction &MF = DAG.getMachineFunction();
6924   MachineFrameInfo &MFI = MF.getFrameInfo();
6925   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6926   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6927   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6928     DstAlignCanChange = true;
6929   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6930   if (!SrcAlign || Alignment > *SrcAlign)
6931     SrcAlign = Alignment;
6932   assert(SrcAlign && "SrcAlign must be set");
6933   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6934   if (!TLI.findOptimalMemOpLowering(
6935           MemOps, Limit,
6936           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6937                       /*IsVolatile*/ true),
6938           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6939           MF.getFunction().getAttributes()))
6940     return SDValue();
6941
6942   if (DstAlignCanChange) {
6943     Type *Ty = MemOps[0].getTypeForEVT(C);
6944     Align NewAlign = DL.getABITypeAlign(Ty);
6945     if (NewAlign > Alignment) {
6946       // Give the stack frame object a larger alignment if needed.
6947       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6948         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6949       Alignment = NewAlign;
6950     }
6951   }
6952
6953   // Prepare AAInfo for loads/stores after lowering this memmove.
6954   AAMDNodes NewAAInfo = AAInfo;
6955   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6956
6957   MachineMemOperand::Flags MMOFlags =
6958       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6959   uint64_t SrcOff = 0, DstOff = 0;
6960   SmallVector<SDValue, 8> LoadValues;
6961   SmallVector<SDValue, 8> LoadChains;
6962   SmallVector<SDValue, 8> OutChains;
6963   unsigned NumMemOps = MemOps.size();
6964   for (unsigned i = 0; i < NumMemOps; i++) {
6965     EVT VT = MemOps[i];
6966     unsigned VTSize = VT.getSizeInBits() / 8;
6967     SDValue Value;
6968
6969     bool isDereferenceable =
6970       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6971     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6972     if (isDereferenceable)
6973       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6974
6975     Value = DAG.getLoad(
6976         VT, dl, Chain,
6977         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6978         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6979     LoadValues.push_back(Value);
6980     LoadChains.push_back(Value.getValue(1));
6981     SrcOff += VTSize;
6982   }
6983   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6984   OutChains.clear();
6985   for (unsigned i = 0; i < NumMemOps; i++) {
6986     EVT VT = MemOps[i];
6987     unsigned VTSize = VT.getSizeInBits() / 8;
6988     SDValue Store;
6989
6990     Store = DAG.getStore(
6991         Chain, dl, LoadValues[i],
6992         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6993         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6994     OutChains.push_back(Store);
6995     DstOff += VTSize;
6996   }
6997
6998   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6999 }
7000
7001 /// Lower the call to 'memset' intrinsic function into a series of store
7002 /// operations.
7003 ///
7004 /// \param DAG Selection DAG where lowered code is placed.
7005 /// \param dl Link to corresponding IR location.
7006 /// \param Chain Control flow dependency.
7007 /// \param Dst Pointer to destination memory location.
7008 /// \param Src Value of byte to write into the memory.
7009 /// \param Size Number of bytes to write.
7010 /// \param Alignment Alignment of the destination in bytes.
7011 /// \param isVol True if destination is volatile.
7012 /// \param AlwaysInline Makes sure no function call is generated.
7013 /// \param DstPtrInfo IR information on the memory pointer.
7014 /// \returns New head in the control flow, if lowering was successful, empty
7015 /// SDValue otherwise.
7016 ///
7017 /// The function tries to replace 'llvm.memset' intrinsic with several store
7018 /// operations and value calculation code. This is usually profitable for small
7019 /// memory size or when the semantic requires inlining.
7020 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
7021                                SDValue Chain, SDValue Dst, SDValue Src,
7022                                uint64_t Size, Align Alignment, bool isVol,
7023                                bool AlwaysInline, MachinePointerInfo DstPtrInfo,
7024                                const AAMDNodes &AAInfo) {
7025   // Turn a memset of undef to nop.
7026   // FIXME: We need to honor volatile even is Src is undef.
7027   if (Src.isUndef())
7028     return Chain;
7029
7030   // Expand memset to a series of load/store ops if the size operand
7031   // falls below a certain threshold.
7032   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7033   std::vector<EVT> MemOps;
7034   bool DstAlignCanChange = false;
7035   MachineFunction &MF = DAG.getMachineFunction();
7036   MachineFrameInfo &MFI = MF.getFrameInfo();
7037   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7038   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7039   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7040     DstAlignCanChange = true;
7041   bool IsZeroVal =
7042       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
7043   unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
7044
7045   if (!TLI.findOptimalMemOpLowering(
7046           MemOps, Limit,
7047           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7048           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7049     return SDValue();
7050
7051   if (DstAlignCanChange) {
7052     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7053     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7054     if (NewAlign > Alignment) {
7055       // Give the stack frame object a larger alignment if needed.
7056       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7057         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7058       Alignment = NewAlign;
7059     }
7060   }
7061
7062   SmallVector<SDValue, 8> OutChains;
7063   uint64_t DstOff = 0;
7064   unsigned NumMemOps = MemOps.size();
7065
7066   // Find the largest store and generate the bit pattern for it.
7067   EVT LargestVT = MemOps[0];
7068   for (unsigned i = 1; i < NumMemOps; i++)
7069     if (MemOps[i].bitsGT(LargestVT))
7070       LargestVT = MemOps[i];
7071   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7072
7073   // Prepare AAInfo for loads/stores after lowering this memset.
7074   AAMDNodes NewAAInfo = AAInfo;
7075   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7076
7077   for (unsigned i = 0; i < NumMemOps; i++) {
7078     EVT VT = MemOps[i];
7079     unsigned VTSize = VT.getSizeInBits() / 8;
7080     if (VTSize > Size) {
7081       // Issuing an unaligned load / store pair  that overlaps with the previous
7082       // pair. Adjust the offset accordingly.
7083       assert(i == NumMemOps-1 && i != 0);
7084       DstOff -= VTSize - Size;
7085     }
7086
7087     // If this store is smaller than the largest store see whether we can get
7088     // the smaller value for free with a truncate.
7089     SDValue Value = MemSetValue;
7090     if (VT.bitsLT(LargestVT)) {
7091       if (!LargestVT.isVector() && !VT.isVector() &&
7092           TLI.isTruncateFree(LargestVT, VT))
7093         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7094       else
7095         Value = getMemsetValue(Src, VT, DAG, dl);
7096     }
7097     assert(Value.getValueType() == VT && "Value with wrong type.");
7098     SDValue Store = DAG.getStore(
7099         Chain, dl, Value,
7100         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7101         DstPtrInfo.getWithOffset(DstOff), Alignment,
7102         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7103         NewAAInfo);
7104     OutChains.push_back(Store);
7105     DstOff += VT.getSizeInBits() / 8;
7106     Size -= VTSize;
7107   }
7108
7109   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7110 }
7111
7112 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7113                                             unsigned AS) {
7114   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7115   // pointer operands can be losslessly bitcasted to pointers of address space 0
7116   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7117     report_fatal_error("cannot lower memory intrinsic in address space " +
7118                        Twine(AS));
7119   }
7120 }
7121
7122 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7123                                 SDValue Src, SDValue Size, Align Alignment,
7124                                 bool isVol, bool AlwaysInline, bool isTailCall,
7125                                 MachinePointerInfo DstPtrInfo,
7126                                 MachinePointerInfo SrcPtrInfo,
7127                                 const AAMDNodes &AAInfo, AAResults *AA) {
7128   // Check to see if we should lower the memcpy to loads and stores first.
7129   // For cases within the target-specified limits, this is the best choice.
7130   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7131   if (ConstantSize) {
7132     // Memcpy with size zero? Just return the original chain.
7133     if (ConstantSize->isZero())
7134       return Chain;
7135
7136     SDValue Result = getMemcpyLoadsAndStores(
7137         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7138         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, AA);
7139     if (Result.getNode())
7140       return Result;
7141   }
7142
7143   // Then check to see if we should lower the memcpy with target-specific
7144   // code. If the target chooses to do this, this is the next best.
7145   if (TSI) {
7146     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7147         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7148         DstPtrInfo, SrcPtrInfo);
7149     if (Result.getNode())
7150       return Result;
7151   }
7152
7153   // If we really need inline code and the target declined to provide it,
7154   // use a (potentially long) sequence of loads and stores.
7155   if (AlwaysInline) {
7156     assert(ConstantSize && "AlwaysInline requires a constant size!");
7157     return getMemcpyLoadsAndStores(
7158         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7159         isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, AA);
7160   }
7161
7162   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7163   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7164
7165   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7166   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7167   // respect volatile, so they may do things like read or write memory
7168   // beyond the given memory regions. But fixing this isn't easy, and most
7169   // people don't care.
7170
7171   // Emit a library call.
7172   TargetLowering::ArgListTy Args;
7173   TargetLowering::ArgListEntry Entry;
7174   Entry.Ty = Type::getInt8PtrTy(*getContext());
7175   Entry.Node = Dst; Args.push_back(Entry);
7176   Entry.Node = Src; Args.push_back(Entry);
7177
7178   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7179   Entry.Node = Size; Args.push_back(Entry);
7180   // FIXME: pass in SDLoc
7181   TargetLowering::CallLoweringInfo CLI(*this);
7182   CLI.setDebugLoc(dl)
7183       .setChain(Chain)
7184       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7185                     Dst.getValueType().getTypeForEVT(*getContext()),
7186                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7187                                       TLI->getPointerTy(getDataLayout())),
7188                     std::move(Args))
7189       .setDiscardResult()
7190       .setTailCall(isTailCall);
7191
7192   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7193   return CallResult.second;
7194 }
7195
7196 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7197                                       SDValue Dst, SDValue Src, SDValue Size,
7198                                       Type *SizeTy, unsigned ElemSz,
7199                                       bool isTailCall,
7200                                       MachinePointerInfo DstPtrInfo,
7201                                       MachinePointerInfo SrcPtrInfo) {
7202   // Emit a library call.
7203   TargetLowering::ArgListTy Args;
7204   TargetLowering::ArgListEntry Entry;
7205   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7206   Entry.Node = Dst;
7207   Args.push_back(Entry);
7208
7209   Entry.Node = Src;
7210   Args.push_back(Entry);
7211
7212   Entry.Ty = SizeTy;
7213   Entry.Node = Size;
7214   Args.push_back(Entry);
7215
7216   RTLIB::Libcall LibraryCall =
7217       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7218   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7219     report_fatal_error("Unsupported element size");
7220
7221   TargetLowering::CallLoweringInfo CLI(*this);
7222   CLI.setDebugLoc(dl)
7223       .setChain(Chain)
7224       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7225                     Type::getVoidTy(*getContext()),
7226                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7227                                       TLI->getPointerTy(getDataLayout())),
7228                     std::move(Args))
7229       .setDiscardResult()
7230       .setTailCall(isTailCall);
7231
7232   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7233   return CallResult.second;
7234 }
7235
7236 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7237                                  SDValue Src, SDValue Size, Align Alignment,
7238                                  bool isVol, bool isTailCall,
7239                                  MachinePointerInfo DstPtrInfo,
7240                                  MachinePointerInfo SrcPtrInfo,
7241                                  const AAMDNodes &AAInfo, AAResults *AA) {
7242   // Check to see if we should lower the memmove to loads and stores first.
7243   // For cases within the target-specified limits, this is the best choice.
7244   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7245   if (ConstantSize) {
7246     // Memmove with size zero? Just return the original chain.
7247     if (ConstantSize->isZero())
7248       return Chain;
7249
7250     SDValue Result = getMemmoveLoadsAndStores(
7251         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7252         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7253     if (Result.getNode())
7254       return Result;
7255   }
7256
7257   // Then check to see if we should lower the memmove with target-specific
7258   // code. If the target chooses to do this, this is the next best.
7259   if (TSI) {
7260     SDValue Result =
7261         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7262                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7263     if (Result.getNode())
7264       return Result;
7265   }
7266
7267   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7268   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7269
7270   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7271   // not be safe.  See memcpy above for more details.
7272
7273   // Emit a library call.
7274   TargetLowering::ArgListTy Args;
7275   TargetLowering::ArgListEntry Entry;
7276   Entry.Ty = Type::getInt8PtrTy(*getContext());
7277   Entry.Node = Dst; Args.push_back(Entry);
7278   Entry.Node = Src; Args.push_back(Entry);
7279
7280   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7281   Entry.Node = Size; Args.push_back(Entry);
7282   // FIXME:  pass in SDLoc
7283   TargetLowering::CallLoweringInfo CLI(*this);
7284   CLI.setDebugLoc(dl)
7285       .setChain(Chain)
7286       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7287                     Dst.getValueType().getTypeForEVT(*getContext()),
7288                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7289                                       TLI->getPointerTy(getDataLayout())),
7290                     std::move(Args))
7291       .setDiscardResult()
7292       .setTailCall(isTailCall);
7293
7294   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7295   return CallResult.second;
7296 }
7297
7298 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7299                                        SDValue Dst, SDValue Src, SDValue Size,
7300                                        Type *SizeTy, unsigned ElemSz,
7301                                        bool isTailCall,
7302                                        MachinePointerInfo DstPtrInfo,
7303                                        MachinePointerInfo SrcPtrInfo) {
7304   // Emit a library call.
7305   TargetLowering::ArgListTy Args;
7306   TargetLowering::ArgListEntry Entry;
7307   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7308   Entry.Node = Dst;
7309   Args.push_back(Entry);
7310
7311   Entry.Node = Src;
7312   Args.push_back(Entry);
7313
7314   Entry.Ty = SizeTy;
7315   Entry.Node = Size;
7316   Args.push_back(Entry);
7317
7318   RTLIB::Libcall LibraryCall =
7319       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7320   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7321     report_fatal_error("Unsupported element size");
7322
7323   TargetLowering::CallLoweringInfo CLI(*this);
7324   CLI.setDebugLoc(dl)
7325       .setChain(Chain)
7326       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7327                     Type::getVoidTy(*getContext()),
7328                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7329                                       TLI->getPointerTy(getDataLayout())),
7330                     std::move(Args))
7331       .setDiscardResult()
7332       .setTailCall(isTailCall);
7333
7334   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7335   return CallResult.second;
7336 }
7337
7338 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7339                                 SDValue Src, SDValue Size, Align Alignment,
7340                                 bool isVol, bool AlwaysInline, bool isTailCall,
7341                                 MachinePointerInfo DstPtrInfo,
7342                                 const AAMDNodes &AAInfo) {
7343   // Check to see if we should lower the memset to stores first.
7344   // For cases within the target-specified limits, this is the best choice.
7345   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7346   if (ConstantSize) {
7347     // Memset with size zero? Just return the original chain.
7348     if (ConstantSize->isZero())
7349       return Chain;
7350
7351     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7352                                      ConstantSize->getZExtValue(), Alignment,
7353                                      isVol, false, DstPtrInfo, AAInfo);
7354
7355     if (Result.getNode())
7356       return Result;
7357   }
7358
7359   // Then check to see if we should lower the memset with target-specific
7360   // code. If the target chooses to do this, this is the next best.
7361   if (TSI) {
7362     SDValue Result = TSI->EmitTargetCodeForMemset(
7363         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
7364     if (Result.getNode())
7365       return Result;
7366   }
7367
7368   // If we really need inline code and the target declined to provide it,
7369   // use a (potentially long) sequence of loads and stores.
7370   if (AlwaysInline) {
7371     assert(ConstantSize && "AlwaysInline requires a constant size!");
7372     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7373                                      ConstantSize->getZExtValue(), Alignment,
7374                                      isVol, true, DstPtrInfo, AAInfo);
7375     assert(Result &&
7376            "getMemsetStores must return a valid sequence when AlwaysInline");
7377     return Result;
7378   }
7379
7380   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7381
7382   // Emit a library call.
7383   auto &Ctx = *getContext();
7384   const auto& DL = getDataLayout();
7385
7386   TargetLowering::CallLoweringInfo CLI(*this);
7387   // FIXME: pass in SDLoc
7388   CLI.setDebugLoc(dl).setChain(Chain);
7389
7390   ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src);
7391   const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero();
7392   const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO);
7393
7394   // Helper function to create an Entry from Node and Type.
7395   const auto CreateEntry = [](SDValue Node, Type *Ty) {
7396     TargetLowering::ArgListEntry Entry;
7397     Entry.Node = Node;
7398     Entry.Ty = Ty;
7399     return Entry;
7400   };
7401
7402   // If zeroing out and bzero is present, use it.
7403   if (SrcIsZero && BzeroName) {
7404     TargetLowering::ArgListTy Args;
7405     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7406     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7407     CLI.setLibCallee(
7408         TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx),
7409         getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args));
7410   } else {
7411     TargetLowering::ArgListTy Args;
7412     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7413     Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx)));
7414     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7415     CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7416                      Dst.getValueType().getTypeForEVT(Ctx),
7417                      getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7418                                        TLI->getPointerTy(DL)),
7419                      std::move(Args));
7420   }
7421
7422   CLI.setDiscardResult().setTailCall(isTailCall);
7423
7424   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7425   return CallResult.second;
7426 }
7427
7428 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7429                                       SDValue Dst, SDValue Value, SDValue Size,
7430                                       Type *SizeTy, unsigned ElemSz,
7431                                       bool isTailCall,
7432                                       MachinePointerInfo DstPtrInfo) {
7433   // Emit a library call.
7434   TargetLowering::ArgListTy Args;
7435   TargetLowering::ArgListEntry Entry;
7436   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7437   Entry.Node = Dst;
7438   Args.push_back(Entry);
7439
7440   Entry.Ty = Type::getInt8Ty(*getContext());
7441   Entry.Node = Value;
7442   Args.push_back(Entry);
7443
7444   Entry.Ty = SizeTy;
7445   Entry.Node = Size;
7446   Args.push_back(Entry);
7447
7448   RTLIB::Libcall LibraryCall =
7449       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7450   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7451     report_fatal_error("Unsupported element size");
7452
7453   TargetLowering::CallLoweringInfo CLI(*this);
7454   CLI.setDebugLoc(dl)
7455       .setChain(Chain)
7456       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7457                     Type::getVoidTy(*getContext()),
7458                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7459                                       TLI->getPointerTy(getDataLayout())),
7460                     std::move(Args))
7461       .setDiscardResult()
7462       .setTailCall(isTailCall);
7463
7464   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7465   return CallResult.second;
7466 }
7467
7468 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7469                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7470                                 MachineMemOperand *MMO) {
7471   FoldingSetNodeID ID;
7472   ID.AddInteger(MemVT.getRawBits());
7473   AddNodeIDNode(ID, Opcode, VTList, Ops);
7474   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7475   ID.AddInteger(MMO->getFlags());
7476   void* IP = nullptr;
7477   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7478     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7479     return SDValue(E, 0);
7480   }
7481
7482   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7483                                     VTList, MemVT, MMO);
7484   createOperands(N, Ops);
7485
7486   CSEMap.InsertNode(N, IP);
7487   InsertNode(N);
7488   return SDValue(N, 0);
7489 }
7490
7491 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7492                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7493                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7494                                        MachineMemOperand *MMO) {
7495   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7496          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7497   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7498
7499   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7500   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7501 }
7502
7503 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7504                                 SDValue Chain, SDValue Ptr, SDValue Val,
7505                                 MachineMemOperand *MMO) {
7506   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7507           Opcode == ISD::ATOMIC_LOAD_SUB ||
7508           Opcode == ISD::ATOMIC_LOAD_AND ||
7509           Opcode == ISD::ATOMIC_LOAD_CLR ||
7510           Opcode == ISD::ATOMIC_LOAD_OR ||
7511           Opcode == ISD::ATOMIC_LOAD_XOR ||
7512           Opcode == ISD::ATOMIC_LOAD_NAND ||
7513           Opcode == ISD::ATOMIC_LOAD_MIN ||
7514           Opcode == ISD::ATOMIC_LOAD_MAX ||
7515           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7516           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7517           Opcode == ISD::ATOMIC_LOAD_FADD ||
7518           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7519           Opcode == ISD::ATOMIC_LOAD_FMAX ||
7520           Opcode == ISD::ATOMIC_LOAD_FMIN ||
7521           Opcode == ISD::ATOMIC_SWAP ||
7522           Opcode == ISD::ATOMIC_STORE) &&
7523          "Invalid Atomic Op");
7524
7525   EVT VT = Val.getValueType();
7526
7527   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7528                                                getVTList(VT, MVT::Other);
7529   SDValue Ops[] = {Chain, Ptr, Val};
7530   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7531 }
7532
7533 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7534                                 EVT VT, SDValue Chain, SDValue Ptr,
7535                                 MachineMemOperand *MMO) {
7536   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7537
7538   SDVTList VTs = getVTList(VT, MVT::Other);
7539   SDValue Ops[] = {Chain, Ptr};
7540   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7541 }
7542
7543 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7544 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7545   if (Ops.size() == 1)
7546     return Ops[0];
7547
7548   SmallVector<EVT, 4> VTs;
7549   VTs.reserve(Ops.size());
7550   for (const SDValue &Op : Ops)
7551     VTs.push_back(Op.getValueType());
7552   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7553 }
7554
7555 SDValue SelectionDAG::getMemIntrinsicNode(
7556     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7557     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7558     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7559   if (!Size && MemVT.isScalableVector())
7560     Size = MemoryLocation::UnknownSize;
7561   else if (!Size)
7562     Size = MemVT.getStoreSize();
7563
7564   MachineFunction &MF = getMachineFunction();
7565   MachineMemOperand *MMO =
7566       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7567
7568   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7569 }
7570
7571 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7572                                           SDVTList VTList,
7573                                           ArrayRef<SDValue> Ops, EVT MemVT,
7574                                           MachineMemOperand *MMO) {
7575   assert((Opcode == ISD::INTRINSIC_VOID ||
7576           Opcode == ISD::INTRINSIC_W_CHAIN ||
7577           Opcode == ISD::PREFETCH ||
7578           ((int)Opcode <= std::numeric_limits<int>::max() &&
7579            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7580          "Opcode is not a memory-accessing opcode!");
7581
7582   // Memoize the node unless it returns a flag.
7583   MemIntrinsicSDNode *N;
7584   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7585     FoldingSetNodeID ID;
7586     AddNodeIDNode(ID, Opcode, VTList, Ops);
7587     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7588         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7589     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7590     ID.AddInteger(MMO->getFlags());
7591     void *IP = nullptr;
7592     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7593       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7594       return SDValue(E, 0);
7595     }
7596
7597     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7598                                       VTList, MemVT, MMO);
7599     createOperands(N, Ops);
7600
7601   CSEMap.InsertNode(N, IP);
7602   } else {
7603     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7604                                       VTList, MemVT, MMO);
7605     createOperands(N, Ops);
7606   }
7607   InsertNode(N);
7608   SDValue V(N, 0);
7609   NewSDValueDbgMsg(V, "Creating new node: ", this);
7610   return V;
7611 }
7612
7613 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7614                                       SDValue Chain, int FrameIndex,
7615                                       int64_t Size, int64_t Offset) {
7616   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7617   const auto VTs = getVTList(MVT::Other);
7618   SDValue Ops[2] = {
7619       Chain,
7620       getFrameIndex(FrameIndex,
7621                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7622                     true)};
7623
7624   FoldingSetNodeID ID;
7625   AddNodeIDNode(ID, Opcode, VTs, Ops);
7626   ID.AddInteger(FrameIndex);
7627   ID.AddInteger(Size);
7628   ID.AddInteger(Offset);
7629   void *IP = nullptr;
7630   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7631     return SDValue(E, 0);
7632
7633   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7634       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7635   createOperands(N, Ops);
7636   CSEMap.InsertNode(N, IP);
7637   InsertNode(N);
7638   SDValue V(N, 0);
7639   NewSDValueDbgMsg(V, "Creating new node: ", this);
7640   return V;
7641 }
7642
7643 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7644                                          uint64_t Guid, uint64_t Index,
7645                                          uint32_t Attr) {
7646   const unsigned Opcode = ISD::PSEUDO_PROBE;
7647   const auto VTs = getVTList(MVT::Other);
7648   SDValue Ops[] = {Chain};
7649   FoldingSetNodeID ID;
7650   AddNodeIDNode(ID, Opcode, VTs, Ops);
7651   ID.AddInteger(Guid);
7652   ID.AddInteger(Index);
7653   void *IP = nullptr;
7654   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7655     return SDValue(E, 0);
7656
7657   auto *N = newSDNode<PseudoProbeSDNode>(
7658       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7659   createOperands(N, Ops);
7660   CSEMap.InsertNode(N, IP);
7661   InsertNode(N);
7662   SDValue V(N, 0);
7663   NewSDValueDbgMsg(V, "Creating new node: ", this);
7664   return V;
7665 }
7666
7667 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7668 /// MachinePointerInfo record from it.  This is particularly useful because the
7669 /// code generator has many cases where it doesn't bother passing in a
7670 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7671 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7672                                            SelectionDAG &DAG, SDValue Ptr,
7673                                            int64_t Offset = 0) {
7674   // If this is FI+Offset, we can model it.
7675   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7676     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7677                                              FI->getIndex(), Offset);
7678
7679   // If this is (FI+Offset1)+Offset2, we can model it.
7680   if (Ptr.getOpcode() != ISD::ADD ||
7681       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7682       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7683     return Info;
7684
7685   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7686   return MachinePointerInfo::getFixedStack(
7687       DAG.getMachineFunction(), FI,
7688       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7689 }
7690
7691 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7692 /// MachinePointerInfo record from it.  This is particularly useful because the
7693 /// code generator has many cases where it doesn't bother passing in a
7694 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7695 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7696                                            SelectionDAG &DAG, SDValue Ptr,
7697                                            SDValue OffsetOp) {
7698   // If the 'Offset' value isn't a constant, we can't handle this.
7699   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7700     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7701   if (OffsetOp.isUndef())
7702     return InferPointerInfo(Info, DAG, Ptr);
7703   return Info;
7704 }
7705
7706 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7707                               EVT VT, const SDLoc &dl, SDValue Chain,
7708                               SDValue Ptr, SDValue Offset,
7709                               MachinePointerInfo PtrInfo, EVT MemVT,
7710                               Align Alignment,
7711                               MachineMemOperand::Flags MMOFlags,
7712                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7713   assert(Chain.getValueType() == MVT::Other &&
7714         "Invalid chain type");
7715
7716   MMOFlags |= MachineMemOperand::MOLoad;
7717   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7718   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7719   // clients.
7720   if (PtrInfo.V.isNull())
7721     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7722
7723   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7724   MachineFunction &MF = getMachineFunction();
7725   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7726                                                    Alignment, AAInfo, Ranges);
7727   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7728 }
7729
7730 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7731                               EVT VT, const SDLoc &dl, SDValue Chain,
7732                               SDValue Ptr, SDValue Offset, EVT MemVT,
7733                               MachineMemOperand *MMO) {
7734   if (VT == MemVT) {
7735     ExtType = ISD::NON_EXTLOAD;
7736   } else if (ExtType == ISD::NON_EXTLOAD) {
7737     assert(VT == MemVT && "Non-extending load from different memory type!");
7738   } else {
7739     // Extending load.
7740     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7741            "Should only be an extending load, not truncating!");
7742     assert(VT.isInteger() == MemVT.isInteger() &&
7743            "Cannot convert from FP to Int or Int -> FP!");
7744     assert(VT.isVector() == MemVT.isVector() &&
7745            "Cannot use an ext load to convert to or from a vector!");
7746     assert((!VT.isVector() ||
7747             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7748            "Cannot use an ext load to change the number of vector elements!");
7749   }
7750
7751   bool Indexed = AM != ISD::UNINDEXED;
7752   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7753
7754   SDVTList VTs = Indexed ?
7755     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7756   SDValue Ops[] = { Chain, Ptr, Offset };
7757   FoldingSetNodeID ID;
7758   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7759   ID.AddInteger(MemVT.getRawBits());
7760   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7761       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7762   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7763   ID.AddInteger(MMO->getFlags());
7764   void *IP = nullptr;
7765   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7766     cast<LoadSDNode>(E)->refineAlignment(MMO);
7767     return SDValue(E, 0);
7768   }
7769   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7770                                   ExtType, MemVT, MMO);
7771   createOperands(N, Ops);
7772
7773   CSEMap.InsertNode(N, IP);
7774   InsertNode(N);
7775   SDValue V(N, 0);
7776   NewSDValueDbgMsg(V, "Creating new node: ", this);
7777   return V;
7778 }
7779
7780 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7781                               SDValue Ptr, MachinePointerInfo PtrInfo,
7782                               MaybeAlign Alignment,
7783                               MachineMemOperand::Flags MMOFlags,
7784                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7785   SDValue Undef = getUNDEF(Ptr.getValueType());
7786   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7787                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7788 }
7789
7790 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7791                               SDValue Ptr, MachineMemOperand *MMO) {
7792   SDValue Undef = getUNDEF(Ptr.getValueType());
7793   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7794                  VT, MMO);
7795 }
7796
7797 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7798                                  EVT VT, SDValue Chain, SDValue Ptr,
7799                                  MachinePointerInfo PtrInfo, EVT MemVT,
7800                                  MaybeAlign Alignment,
7801                                  MachineMemOperand::Flags MMOFlags,
7802                                  const AAMDNodes &AAInfo) {
7803   SDValue Undef = getUNDEF(Ptr.getValueType());
7804   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7805                  MemVT, Alignment, MMOFlags, AAInfo);
7806 }
7807
7808 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7809                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7810                                  MachineMemOperand *MMO) {
7811   SDValue Undef = getUNDEF(Ptr.getValueType());
7812   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7813                  MemVT, MMO);
7814 }
7815
7816 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7817                                      SDValue Base, SDValue Offset,
7818                                      ISD::MemIndexedMode AM) {
7819   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7820   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7821   // Don't propagate the invariant or dereferenceable flags.
7822   auto MMOFlags =
7823       LD->getMemOperand()->getFlags() &
7824       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7825   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7826                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7827                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7828 }
7829
7830 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7831                                SDValue Ptr, MachinePointerInfo PtrInfo,
7832                                Align Alignment,
7833                                MachineMemOperand::Flags MMOFlags,
7834                                const AAMDNodes &AAInfo) {
7835   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7836
7837   MMOFlags |= MachineMemOperand::MOStore;
7838   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7839
7840   if (PtrInfo.V.isNull())
7841     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7842
7843   MachineFunction &MF = getMachineFunction();
7844   uint64_t Size =
7845       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7846   MachineMemOperand *MMO =
7847       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7848   return getStore(Chain, dl, Val, Ptr, MMO);
7849 }
7850
7851 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7852                                SDValue Ptr, MachineMemOperand *MMO) {
7853   assert(Chain.getValueType() == MVT::Other &&
7854         "Invalid chain type");
7855   EVT VT = Val.getValueType();
7856   SDVTList VTs = getVTList(MVT::Other);
7857   SDValue Undef = getUNDEF(Ptr.getValueType());
7858   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7859   FoldingSetNodeID ID;
7860   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7861   ID.AddInteger(VT.getRawBits());
7862   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7863       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7864   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7865   ID.AddInteger(MMO->getFlags());
7866   void *IP = nullptr;
7867   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7868     cast<StoreSDNode>(E)->refineAlignment(MMO);
7869     return SDValue(E, 0);
7870   }
7871   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7872                                    ISD::UNINDEXED, false, VT, MMO);
7873   createOperands(N, Ops);
7874
7875   CSEMap.InsertNode(N, IP);
7876   InsertNode(N);
7877   SDValue V(N, 0);
7878   NewSDValueDbgMsg(V, "Creating new node: ", this);
7879   return V;
7880 }
7881
7882 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7883                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7884                                     EVT SVT, Align Alignment,
7885                                     MachineMemOperand::Flags MMOFlags,
7886                                     const AAMDNodes &AAInfo) {
7887   assert(Chain.getValueType() == MVT::Other &&
7888         "Invalid chain type");
7889
7890   MMOFlags |= MachineMemOperand::MOStore;
7891   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7892
7893   if (PtrInfo.V.isNull())
7894     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7895
7896   MachineFunction &MF = getMachineFunction();
7897   MachineMemOperand *MMO = MF.getMachineMemOperand(
7898       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7899       Alignment, AAInfo);
7900   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7901 }
7902
7903 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7904                                     SDValue Ptr, EVT SVT,
7905                                     MachineMemOperand *MMO) {
7906   EVT VT = Val.getValueType();
7907
7908   assert(Chain.getValueType() == MVT::Other &&
7909         "Invalid chain type");
7910   if (VT == SVT)
7911     return getStore(Chain, dl, Val, Ptr, MMO);
7912
7913   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7914          "Should only be a truncating store, not extending!");
7915   assert(VT.isInteger() == SVT.isInteger() &&
7916          "Can't do FP-INT conversion!");
7917   assert(VT.isVector() == SVT.isVector() &&
7918          "Cannot use trunc store to convert to or from a vector!");
7919   assert((!VT.isVector() ||
7920           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7921          "Cannot use trunc store to change the number of vector elements!");
7922
7923   SDVTList VTs = getVTList(MVT::Other);
7924   SDValue Undef = getUNDEF(Ptr.getValueType());
7925   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7926   FoldingSetNodeID ID;
7927   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7928   ID.AddInteger(SVT.getRawBits());
7929   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7930       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7931   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7932   ID.AddInteger(MMO->getFlags());
7933   void *IP = nullptr;
7934   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7935     cast<StoreSDNode>(E)->refineAlignment(MMO);
7936     return SDValue(E, 0);
7937   }
7938   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7939                                    ISD::UNINDEXED, true, SVT, MMO);
7940   createOperands(N, Ops);
7941
7942   CSEMap.InsertNode(N, IP);
7943   InsertNode(N);
7944   SDValue V(N, 0);
7945   NewSDValueDbgMsg(V, "Creating new node: ", this);
7946   return V;
7947 }
7948
7949 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7950                                       SDValue Base, SDValue Offset,
7951                                       ISD::MemIndexedMode AM) {
7952   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7953   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7954   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7955   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7956   FoldingSetNodeID ID;
7957   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7958   ID.AddInteger(ST->getMemoryVT().getRawBits());
7959   ID.AddInteger(ST->getRawSubclassData());
7960   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7961   ID.AddInteger(ST->getMemOperand()->getFlags());
7962   void *IP = nullptr;
7963   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7964     return SDValue(E, 0);
7965
7966   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7967                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7968                                    ST->getMemOperand());
7969   createOperands(N, Ops);
7970
7971   CSEMap.InsertNode(N, IP);
7972   InsertNode(N);
7973   SDValue V(N, 0);
7974   NewSDValueDbgMsg(V, "Creating new node: ", this);
7975   return V;
7976 }
7977
7978 SDValue SelectionDAG::getLoadVP(
7979     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7980     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7981     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7982     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7983     const MDNode *Ranges, bool IsExpanding) {
7984   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7985
7986   MMOFlags |= MachineMemOperand::MOLoad;
7987   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7988   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7989   // clients.
7990   if (PtrInfo.V.isNull())
7991     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7992
7993   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7994   MachineFunction &MF = getMachineFunction();
7995   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7996                                                    Alignment, AAInfo, Ranges);
7997   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7998                    MMO, IsExpanding);
7999 }
8000
8001 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
8002                                 ISD::LoadExtType ExtType, EVT VT,
8003                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
8004                                 SDValue Offset, SDValue Mask, SDValue EVL,
8005                                 EVT MemVT, MachineMemOperand *MMO,
8006                                 bool IsExpanding) {
8007   bool Indexed = AM != ISD::UNINDEXED;
8008   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8009
8010   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8011                          : getVTList(VT, MVT::Other);
8012   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
8013   FoldingSetNodeID ID;
8014   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
8015   ID.AddInteger(VT.getRawBits());
8016   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
8017       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8018   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8019   ID.AddInteger(MMO->getFlags());
8020   void *IP = nullptr;
8021   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8022     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
8023     return SDValue(E, 0);
8024   }
8025   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8026                                     ExtType, IsExpanding, MemVT, MMO);
8027   createOperands(N, Ops);
8028
8029   CSEMap.InsertNode(N, IP);
8030   InsertNode(N);
8031   SDValue V(N, 0);
8032   NewSDValueDbgMsg(V, "Creating new node: ", this);
8033   return V;
8034 }
8035
8036 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8037                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8038                                 MachinePointerInfo PtrInfo,
8039                                 MaybeAlign Alignment,
8040                                 MachineMemOperand::Flags MMOFlags,
8041                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
8042                                 bool IsExpanding) {
8043   SDValue Undef = getUNDEF(Ptr.getValueType());
8044   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8045                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
8046                    IsExpanding);
8047 }
8048
8049 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8050                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8051                                 MachineMemOperand *MMO, bool IsExpanding) {
8052   SDValue Undef = getUNDEF(Ptr.getValueType());
8053   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8054                    Mask, EVL, VT, MMO, IsExpanding);
8055 }
8056
8057 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8058                                    EVT VT, SDValue Chain, SDValue Ptr,
8059                                    SDValue Mask, SDValue EVL,
8060                                    MachinePointerInfo PtrInfo, EVT MemVT,
8061                                    MaybeAlign Alignment,
8062                                    MachineMemOperand::Flags MMOFlags,
8063                                    const AAMDNodes &AAInfo, bool IsExpanding) {
8064   SDValue Undef = getUNDEF(Ptr.getValueType());
8065   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8066                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8067                    IsExpanding);
8068 }
8069
8070 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8071                                    EVT VT, SDValue Chain, SDValue Ptr,
8072                                    SDValue Mask, SDValue EVL, EVT MemVT,
8073                                    MachineMemOperand *MMO, bool IsExpanding) {
8074   SDValue Undef = getUNDEF(Ptr.getValueType());
8075   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8076                    EVL, MemVT, MMO, IsExpanding);
8077 }
8078
8079 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8080                                        SDValue Base, SDValue Offset,
8081                                        ISD::MemIndexedMode AM) {
8082   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8083   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8084   // Don't propagate the invariant or dereferenceable flags.
8085   auto MMOFlags =
8086       LD->getMemOperand()->getFlags() &
8087       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8088   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8089                    LD->getChain(), Base, Offset, LD->getMask(),
8090                    LD->getVectorLength(), LD->getPointerInfo(),
8091                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8092                    nullptr, LD->isExpandingLoad());
8093 }
8094
8095 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8096                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8097                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8098                                  ISD::MemIndexedMode AM, bool IsTruncating,
8099                                  bool IsCompressing) {
8100   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8101   bool Indexed = AM != ISD::UNINDEXED;
8102   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8103   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8104                          : getVTList(MVT::Other);
8105   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8106   FoldingSetNodeID ID;
8107   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8108   ID.AddInteger(MemVT.getRawBits());
8109   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8110       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8111   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8112   ID.AddInteger(MMO->getFlags());
8113   void *IP = nullptr;
8114   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8115     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8116     return SDValue(E, 0);
8117   }
8118   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8119                                      IsTruncating, IsCompressing, MemVT, MMO);
8120   createOperands(N, Ops);
8121
8122   CSEMap.InsertNode(N, IP);
8123   InsertNode(N);
8124   SDValue V(N, 0);
8125   NewSDValueDbgMsg(V, "Creating new node: ", this);
8126   return V;
8127 }
8128
8129 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8130                                       SDValue Val, SDValue Ptr, SDValue Mask,
8131                                       SDValue EVL, MachinePointerInfo PtrInfo,
8132                                       EVT SVT, Align Alignment,
8133                                       MachineMemOperand::Flags MMOFlags,
8134                                       const AAMDNodes &AAInfo,
8135                                       bool IsCompressing) {
8136   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8137
8138   MMOFlags |= MachineMemOperand::MOStore;
8139   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8140
8141   if (PtrInfo.V.isNull())
8142     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8143
8144   MachineFunction &MF = getMachineFunction();
8145   MachineMemOperand *MMO = MF.getMachineMemOperand(
8146       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8147       Alignment, AAInfo);
8148   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8149                          IsCompressing);
8150 }
8151
8152 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8153                                       SDValue Val, SDValue Ptr, SDValue Mask,
8154                                       SDValue EVL, EVT SVT,
8155                                       MachineMemOperand *MMO,
8156                                       bool IsCompressing) {
8157   EVT VT = Val.getValueType();
8158
8159   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8160   if (VT == SVT)
8161     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8162                       EVL, VT, MMO, ISD::UNINDEXED,
8163                       /*IsTruncating*/ false, IsCompressing);
8164
8165   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8166          "Should only be a truncating store, not extending!");
8167   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8168   assert(VT.isVector() == SVT.isVector() &&
8169          "Cannot use trunc store to convert to or from a vector!");
8170   assert((!VT.isVector() ||
8171           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8172          "Cannot use trunc store to change the number of vector elements!");
8173
8174   SDVTList VTs = getVTList(MVT::Other);
8175   SDValue Undef = getUNDEF(Ptr.getValueType());
8176   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8177   FoldingSetNodeID ID;
8178   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8179   ID.AddInteger(SVT.getRawBits());
8180   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8181       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8182   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8183   ID.AddInteger(MMO->getFlags());
8184   void *IP = nullptr;
8185   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8186     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8187     return SDValue(E, 0);
8188   }
8189   auto *N =
8190       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8191                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8192   createOperands(N, Ops);
8193
8194   CSEMap.InsertNode(N, IP);
8195   InsertNode(N);
8196   SDValue V(N, 0);
8197   NewSDValueDbgMsg(V, "Creating new node: ", this);
8198   return V;
8199 }
8200
8201 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8202                                         SDValue Base, SDValue Offset,
8203                                         ISD::MemIndexedMode AM) {
8204   auto *ST = cast<VPStoreSDNode>(OrigStore);
8205   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8206   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8207   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8208                    Offset,         ST->getMask(),  ST->getVectorLength()};
8209   FoldingSetNodeID ID;
8210   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8211   ID.AddInteger(ST->getMemoryVT().getRawBits());
8212   ID.AddInteger(ST->getRawSubclassData());
8213   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8214   ID.AddInteger(ST->getMemOperand()->getFlags());
8215   void *IP = nullptr;
8216   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8217     return SDValue(E, 0);
8218
8219   auto *N = newSDNode<VPStoreSDNode>(
8220       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8221       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8222   createOperands(N, Ops);
8223
8224   CSEMap.InsertNode(N, IP);
8225   InsertNode(N);
8226   SDValue V(N, 0);
8227   NewSDValueDbgMsg(V, "Creating new node: ", this);
8228   return V;
8229 }
8230
8231 SDValue SelectionDAG::getStridedLoadVP(
8232     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8233     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8234     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8235     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8236     const MDNode *Ranges, bool IsExpanding) {
8237   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8238
8239   MMOFlags |= MachineMemOperand::MOLoad;
8240   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8241   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8242   // clients.
8243   if (PtrInfo.V.isNull())
8244     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8245
8246   uint64_t Size = MemoryLocation::UnknownSize;
8247   MachineFunction &MF = getMachineFunction();
8248   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8249                                                    Alignment, AAInfo, Ranges);
8250   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8251                           EVL, MemVT, MMO, IsExpanding);
8252 }
8253
8254 SDValue SelectionDAG::getStridedLoadVP(
8255     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8256     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8257     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8258   bool Indexed = AM != ISD::UNINDEXED;
8259   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8260
8261   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8262   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8263                          : getVTList(VT, MVT::Other);
8264   FoldingSetNodeID ID;
8265   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8266   ID.AddInteger(VT.getRawBits());
8267   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8268       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8269   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8270
8271   void *IP = nullptr;
8272   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8273     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8274     return SDValue(E, 0);
8275   }
8276
8277   auto *N =
8278       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8279                                      ExtType, IsExpanding, MemVT, MMO);
8280   createOperands(N, Ops);
8281   CSEMap.InsertNode(N, IP);
8282   InsertNode(N);
8283   SDValue V(N, 0);
8284   NewSDValueDbgMsg(V, "Creating new node: ", this);
8285   return V;
8286 }
8287
8288 SDValue SelectionDAG::getStridedLoadVP(
8289     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8290     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8291     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8292     const MDNode *Ranges, bool IsExpanding) {
8293   SDValue Undef = getUNDEF(Ptr.getValueType());
8294   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8295                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8296                           MMOFlags, AAInfo, Ranges, IsExpanding);
8297 }
8298
8299 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8300                                        SDValue Ptr, SDValue Stride,
8301                                        SDValue Mask, SDValue EVL,
8302                                        MachineMemOperand *MMO,
8303                                        bool IsExpanding) {
8304   SDValue Undef = getUNDEF(Ptr.getValueType());
8305   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8306                           Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8307 }
8308
8309 SDValue SelectionDAG::getExtStridedLoadVP(
8310     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8311     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8312     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8313     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8314     bool IsExpanding) {
8315   SDValue Undef = getUNDEF(Ptr.getValueType());
8316   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8317                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8318                           MMOFlags, AAInfo, nullptr, IsExpanding);
8319 }
8320
8321 SDValue SelectionDAG::getExtStridedLoadVP(
8322     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8323     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8324     MachineMemOperand *MMO, bool IsExpanding) {
8325   SDValue Undef = getUNDEF(Ptr.getValueType());
8326   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8327                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8328 }
8329
8330 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8331                                               SDValue Base, SDValue Offset,
8332                                               ISD::MemIndexedMode AM) {
8333   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8334   assert(SLD->getOffset().isUndef() &&
8335          "Strided load is already a indexed load!");
8336   // Don't propagate the invariant or dereferenceable flags.
8337   auto MMOFlags =
8338       SLD->getMemOperand()->getFlags() &
8339       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8340   return getStridedLoadVP(
8341       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8342       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8343       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8344       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8345 }
8346
8347 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8348                                         SDValue Val, SDValue Ptr,
8349                                         SDValue Offset, SDValue Stride,
8350                                         SDValue Mask, SDValue EVL, EVT MemVT,
8351                                         MachineMemOperand *MMO,
8352                                         ISD::MemIndexedMode AM,
8353                                         bool IsTruncating, bool IsCompressing) {
8354   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8355   bool Indexed = AM != ISD::UNINDEXED;
8356   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8357   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8358                          : getVTList(MVT::Other);
8359   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8360   FoldingSetNodeID ID;
8361   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8362   ID.AddInteger(MemVT.getRawBits());
8363   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8364       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8365   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8366   void *IP = nullptr;
8367   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8368     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8369     return SDValue(E, 0);
8370   }
8371   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8372                                             VTs, AM, IsTruncating,
8373                                             IsCompressing, MemVT, MMO);
8374   createOperands(N, Ops);
8375
8376   CSEMap.InsertNode(N, IP);
8377   InsertNode(N);
8378   SDValue V(N, 0);
8379   NewSDValueDbgMsg(V, "Creating new node: ", this);
8380   return V;
8381 }
8382
8383 SDValue SelectionDAG::getTruncStridedStoreVP(
8384     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8385     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8386     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8387     bool IsCompressing) {
8388   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8389
8390   MMOFlags |= MachineMemOperand::MOStore;
8391   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8392
8393   if (PtrInfo.V.isNull())
8394     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8395
8396   MachineFunction &MF = getMachineFunction();
8397   MachineMemOperand *MMO = MF.getMachineMemOperand(
8398       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8399   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8400                                 MMO, IsCompressing);
8401 }
8402
8403 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8404                                              SDValue Val, SDValue Ptr,
8405                                              SDValue Stride, SDValue Mask,
8406                                              SDValue EVL, EVT SVT,
8407                                              MachineMemOperand *MMO,
8408                                              bool IsCompressing) {
8409   EVT VT = Val.getValueType();
8410
8411   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8412   if (VT == SVT)
8413     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8414                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8415                              /*IsTruncating*/ false, IsCompressing);
8416
8417   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8418          "Should only be a truncating store, not extending!");
8419   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8420   assert(VT.isVector() == SVT.isVector() &&
8421          "Cannot use trunc store to convert to or from a vector!");
8422   assert((!VT.isVector() ||
8423           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8424          "Cannot use trunc store to change the number of vector elements!");
8425
8426   SDVTList VTs = getVTList(MVT::Other);
8427   SDValue Undef = getUNDEF(Ptr.getValueType());
8428   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8429   FoldingSetNodeID ID;
8430   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8431   ID.AddInteger(SVT.getRawBits());
8432   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8433       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8434   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8435   void *IP = nullptr;
8436   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8437     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8438     return SDValue(E, 0);
8439   }
8440   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8441                                             VTs, ISD::UNINDEXED, true,
8442                                             IsCompressing, SVT, MMO);
8443   createOperands(N, Ops);
8444
8445   CSEMap.InsertNode(N, IP);
8446   InsertNode(N);
8447   SDValue V(N, 0);
8448   NewSDValueDbgMsg(V, "Creating new node: ", this);
8449   return V;
8450 }
8451
8452 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8453                                                const SDLoc &DL, SDValue Base,
8454                                                SDValue Offset,
8455                                                ISD::MemIndexedMode AM) {
8456   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8457   assert(SST->getOffset().isUndef() &&
8458          "Strided store is already an indexed store!");
8459   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8460   SDValue Ops[] = {
8461       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8462       SST->getMask(),  SST->getVectorLength()};
8463   FoldingSetNodeID ID;
8464   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8465   ID.AddInteger(SST->getMemoryVT().getRawBits());
8466   ID.AddInteger(SST->getRawSubclassData());
8467   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8468   void *IP = nullptr;
8469   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8470     return SDValue(E, 0);
8471
8472   auto *N = newSDNode<VPStridedStoreSDNode>(
8473       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8474       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8475   createOperands(N, Ops);
8476
8477   CSEMap.InsertNode(N, IP);
8478   InsertNode(N);
8479   SDValue V(N, 0);
8480   NewSDValueDbgMsg(V, "Creating new node: ", this);
8481   return V;
8482 }
8483
8484 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8485                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8486                                   ISD::MemIndexType IndexType) {
8487   assert(Ops.size() == 6 && "Incompatible number of operands");
8488
8489   FoldingSetNodeID ID;
8490   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8491   ID.AddInteger(VT.getRawBits());
8492   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8493       dl.getIROrder(), VTs, VT, MMO, IndexType));
8494   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8495   ID.AddInteger(MMO->getFlags());
8496   void *IP = nullptr;
8497   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8498     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8499     return SDValue(E, 0);
8500   }
8501
8502   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8503                                       VT, MMO, IndexType);
8504   createOperands(N, Ops);
8505
8506   assert(N->getMask().getValueType().getVectorElementCount() ==
8507              N->getValueType(0).getVectorElementCount() &&
8508          "Vector width mismatch between mask and data");
8509   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8510              N->getValueType(0).getVectorElementCount().isScalable() &&
8511          "Scalable flags of index and data do not match");
8512   assert(ElementCount::isKnownGE(
8513              N->getIndex().getValueType().getVectorElementCount(),
8514              N->getValueType(0).getVectorElementCount()) &&
8515          "Vector width mismatch between index and data");
8516   assert(isa<ConstantSDNode>(N->getScale()) &&
8517          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8518          "Scale should be a constant power of 2");
8519
8520   CSEMap.InsertNode(N, IP);
8521   InsertNode(N);
8522   SDValue V(N, 0);
8523   NewSDValueDbgMsg(V, "Creating new node: ", this);
8524   return V;
8525 }
8526
8527 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8528                                    ArrayRef<SDValue> Ops,
8529                                    MachineMemOperand *MMO,
8530                                    ISD::MemIndexType IndexType) {
8531   assert(Ops.size() == 7 && "Incompatible number of operands");
8532
8533   FoldingSetNodeID ID;
8534   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8535   ID.AddInteger(VT.getRawBits());
8536   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8537       dl.getIROrder(), VTs, VT, MMO, IndexType));
8538   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8539   ID.AddInteger(MMO->getFlags());
8540   void *IP = nullptr;
8541   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8542     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8543     return SDValue(E, 0);
8544   }
8545   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8546                                        VT, MMO, IndexType);
8547   createOperands(N, Ops);
8548
8549   assert(N->getMask().getValueType().getVectorElementCount() ==
8550              N->getValue().getValueType().getVectorElementCount() &&
8551          "Vector width mismatch between mask and data");
8552   assert(
8553       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8554           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8555       "Scalable flags of index and data do not match");
8556   assert(ElementCount::isKnownGE(
8557              N->getIndex().getValueType().getVectorElementCount(),
8558              N->getValue().getValueType().getVectorElementCount()) &&
8559          "Vector width mismatch between index and data");
8560   assert(isa<ConstantSDNode>(N->getScale()) &&
8561          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8562          "Scale should be a constant power of 2");
8563
8564   CSEMap.InsertNode(N, IP);
8565   InsertNode(N);
8566   SDValue V(N, 0);
8567   NewSDValueDbgMsg(V, "Creating new node: ", this);
8568   return V;
8569 }
8570
8571 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8572                                     SDValue Base, SDValue Offset, SDValue Mask,
8573                                     SDValue PassThru, EVT MemVT,
8574                                     MachineMemOperand *MMO,
8575                                     ISD::MemIndexedMode AM,
8576                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8577   bool Indexed = AM != ISD::UNINDEXED;
8578   assert((Indexed || Offset.isUndef()) &&
8579          "Unindexed masked load with an offset!");
8580   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8581                          : getVTList(VT, MVT::Other);
8582   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8583   FoldingSetNodeID ID;
8584   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8585   ID.AddInteger(MemVT.getRawBits());
8586   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8587       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8588   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8589   ID.AddInteger(MMO->getFlags());
8590   void *IP = nullptr;
8591   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8592     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8593     return SDValue(E, 0);
8594   }
8595   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8596                                         AM, ExtTy, isExpanding, MemVT, MMO);
8597   createOperands(N, Ops);
8598
8599   CSEMap.InsertNode(N, IP);
8600   InsertNode(N);
8601   SDValue V(N, 0);
8602   NewSDValueDbgMsg(V, "Creating new node: ", this);
8603   return V;
8604 }
8605
8606 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8607                                            SDValue Base, SDValue Offset,
8608                                            ISD::MemIndexedMode AM) {
8609   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8610   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8611   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8612                        Offset, LD->getMask(), LD->getPassThru(),
8613                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8614                        LD->getExtensionType(), LD->isExpandingLoad());
8615 }
8616
8617 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8618                                      SDValue Val, SDValue Base, SDValue Offset,
8619                                      SDValue Mask, EVT MemVT,
8620                                      MachineMemOperand *MMO,
8621                                      ISD::MemIndexedMode AM, bool IsTruncating,
8622                                      bool IsCompressing) {
8623   assert(Chain.getValueType() == MVT::Other &&
8624         "Invalid chain type");
8625   bool Indexed = AM != ISD::UNINDEXED;
8626   assert((Indexed || Offset.isUndef()) &&
8627          "Unindexed masked store with an offset!");
8628   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8629                          : getVTList(MVT::Other);
8630   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8631   FoldingSetNodeID ID;
8632   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8633   ID.AddInteger(MemVT.getRawBits());
8634   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8635       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8636   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8637   ID.AddInteger(MMO->getFlags());
8638   void *IP = nullptr;
8639   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8640     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8641     return SDValue(E, 0);
8642   }
8643   auto *N =
8644       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8645                                    IsTruncating, IsCompressing, MemVT, MMO);
8646   createOperands(N, Ops);
8647
8648   CSEMap.InsertNode(N, IP);
8649   InsertNode(N);
8650   SDValue V(N, 0);
8651   NewSDValueDbgMsg(V, "Creating new node: ", this);
8652   return V;
8653 }
8654
8655 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8656                                             SDValue Base, SDValue Offset,
8657                                             ISD::MemIndexedMode AM) {
8658   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8659   assert(ST->getOffset().isUndef() &&
8660          "Masked store is already a indexed store!");
8661   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8662                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8663                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8664 }
8665
8666 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8667                                       ArrayRef<SDValue> Ops,
8668                                       MachineMemOperand *MMO,
8669                                       ISD::MemIndexType IndexType,
8670                                       ISD::LoadExtType ExtTy) {
8671   assert(Ops.size() == 6 && "Incompatible number of operands");
8672
8673   FoldingSetNodeID ID;
8674   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8675   ID.AddInteger(MemVT.getRawBits());
8676   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8677       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8678   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8679   ID.AddInteger(MMO->getFlags());
8680   void *IP = nullptr;
8681   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8682     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8683     return SDValue(E, 0);
8684   }
8685
8686   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8687                                           VTs, MemVT, MMO, IndexType, ExtTy);
8688   createOperands(N, Ops);
8689
8690   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8691          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8692   assert(N->getMask().getValueType().getVectorElementCount() ==
8693              N->getValueType(0).getVectorElementCount() &&
8694          "Vector width mismatch between mask and data");
8695   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8696              N->getValueType(0).getVectorElementCount().isScalable() &&
8697          "Scalable flags of index and data do not match");
8698   assert(ElementCount::isKnownGE(
8699              N->getIndex().getValueType().getVectorElementCount(),
8700              N->getValueType(0).getVectorElementCount()) &&
8701          "Vector width mismatch between index and data");
8702   assert(isa<ConstantSDNode>(N->getScale()) &&
8703          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8704          "Scale should be a constant power of 2");
8705
8706   CSEMap.InsertNode(N, IP);
8707   InsertNode(N);
8708   SDValue V(N, 0);
8709   NewSDValueDbgMsg(V, "Creating new node: ", this);
8710   return V;
8711 }
8712
8713 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8714                                        ArrayRef<SDValue> Ops,
8715                                        MachineMemOperand *MMO,
8716                                        ISD::MemIndexType IndexType,
8717                                        bool IsTrunc) {
8718   assert(Ops.size() == 6 && "Incompatible number of operands");
8719
8720   FoldingSetNodeID ID;
8721   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8722   ID.AddInteger(MemVT.getRawBits());
8723   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8724       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8725   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8726   ID.AddInteger(MMO->getFlags());
8727   void *IP = nullptr;
8728   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8729     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8730     return SDValue(E, 0);
8731   }
8732
8733   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8734                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8735   createOperands(N, Ops);
8736
8737   assert(N->getMask().getValueType().getVectorElementCount() ==
8738              N->getValue().getValueType().getVectorElementCount() &&
8739          "Vector width mismatch between mask and data");
8740   assert(
8741       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8742           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8743       "Scalable flags of index and data do not match");
8744   assert(ElementCount::isKnownGE(
8745              N->getIndex().getValueType().getVectorElementCount(),
8746              N->getValue().getValueType().getVectorElementCount()) &&
8747          "Vector width mismatch between index and data");
8748   assert(isa<ConstantSDNode>(N->getScale()) &&
8749          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8750          "Scale should be a constant power of 2");
8751
8752   CSEMap.InsertNode(N, IP);
8753   InsertNode(N);
8754   SDValue V(N, 0);
8755   NewSDValueDbgMsg(V, "Creating new node: ", this);
8756   return V;
8757 }
8758
8759 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8760   // select undef, T, F --> T (if T is a constant), otherwise F
8761   // select, ?, undef, F --> F
8762   // select, ?, T, undef --> T
8763   if (Cond.isUndef())
8764     return isConstantValueOfAnyType(T) ? T : F;
8765   if (T.isUndef())
8766     return F;
8767   if (F.isUndef())
8768     return T;
8769
8770   // select true, T, F --> T
8771   // select false, T, F --> F
8772   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8773     return CondC->isZero() ? F : T;
8774
8775   // TODO: This should simplify VSELECT with constant condition using something
8776   // like this (but check boolean contents to be complete?):
8777   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8778   //    return T;
8779   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8780   //    return F;
8781
8782   // select ?, T, T --> T
8783   if (T == F)
8784     return T;
8785
8786   return SDValue();
8787 }
8788
8789 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8790   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8791   if (X.isUndef())
8792     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8793   // shift X, undef --> undef (because it may shift by the bitwidth)
8794   if (Y.isUndef())
8795     return getUNDEF(X.getValueType());
8796
8797   // shift 0, Y --> 0
8798   // shift X, 0 --> X
8799   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8800     return X;
8801
8802   // shift X, C >= bitwidth(X) --> undef
8803   // All vector elements must be too big (or undef) to avoid partial undefs.
8804   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8805     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8806   };
8807   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8808     return getUNDEF(X.getValueType());
8809
8810   return SDValue();
8811 }
8812
8813 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8814                                       SDNodeFlags Flags) {
8815   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8816   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8817   // operation is poison. That result can be relaxed to undef.
8818   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8819   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8820   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8821                 (YC && YC->getValueAPF().isNaN());
8822   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8823                 (YC && YC->getValueAPF().isInfinity());
8824
8825   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8826     return getUNDEF(X.getValueType());
8827
8828   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8829     return getUNDEF(X.getValueType());
8830
8831   if (!YC)
8832     return SDValue();
8833
8834   // X + -0.0 --> X
8835   if (Opcode == ISD::FADD)
8836     if (YC->getValueAPF().isNegZero())
8837       return X;
8838
8839   // X - +0.0 --> X
8840   if (Opcode == ISD::FSUB)
8841     if (YC->getValueAPF().isPosZero())
8842       return X;
8843
8844   // X * 1.0 --> X
8845   // X / 1.0 --> X
8846   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8847     if (YC->getValueAPF().isExactlyValue(1.0))
8848       return X;
8849
8850   // X * 0.0 --> 0.0
8851   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8852     if (YC->getValueAPF().isZero())
8853       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8854
8855   return SDValue();
8856 }
8857
8858 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8859                                SDValue Ptr, SDValue SV, unsigned Align) {
8860   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8861   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8862 }
8863
8864 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8865                               ArrayRef<SDUse> Ops) {
8866   switch (Ops.size()) {
8867   case 0: return getNode(Opcode, DL, VT);
8868   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8869   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8870   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8871   default: break;
8872   }
8873
8874   // Copy from an SDUse array into an SDValue array for use with
8875   // the regular getNode logic.
8876   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8877   return getNode(Opcode, DL, VT, NewOps);
8878 }
8879
8880 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8881                               ArrayRef<SDValue> Ops) {
8882   SDNodeFlags Flags;
8883   if (Inserter)
8884     Flags = Inserter->getFlags();
8885   return getNode(Opcode, DL, VT, Ops, Flags);
8886 }
8887
8888 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8889                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8890   unsigned NumOps = Ops.size();
8891   switch (NumOps) {
8892   case 0: return getNode(Opcode, DL, VT);
8893   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8894   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8895   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8896   default: break;
8897   }
8898
8899 #ifndef NDEBUG
8900   for (const auto &Op : Ops)
8901     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8902            "Operand is DELETED_NODE!");
8903 #endif
8904
8905   switch (Opcode) {
8906   default: break;
8907   case ISD::BUILD_VECTOR:
8908     // Attempt to simplify BUILD_VECTOR.
8909     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8910       return V;
8911     break;
8912   case ISD::CONCAT_VECTORS:
8913     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8914       return V;
8915     break;
8916   case ISD::SELECT_CC:
8917     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8918     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8919            "LHS and RHS of condition must have same type!");
8920     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8921            "True and False arms of SelectCC must have same type!");
8922     assert(Ops[2].getValueType() == VT &&
8923            "select_cc node must be of same type as true and false value!");
8924     assert((!Ops[0].getValueType().isVector() ||
8925             Ops[0].getValueType().getVectorElementCount() ==
8926                 VT.getVectorElementCount()) &&
8927            "Expected select_cc with vector result to have the same sized "
8928            "comparison type!");
8929     break;
8930   case ISD::BR_CC:
8931     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8932     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8933            "LHS/RHS of comparison should match types!");
8934     break;
8935   case ISD::VP_ADD:
8936   case ISD::VP_SUB:
8937     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8938     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8939       Opcode = ISD::VP_XOR;
8940     break;
8941   case ISD::VP_MUL:
8942     // If it is VP_MUL mask operation then turn it to VP_AND
8943     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8944       Opcode = ISD::VP_AND;
8945     break;
8946   case ISD::VP_REDUCE_MUL:
8947     // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
8948     if (VT == MVT::i1)
8949       Opcode = ISD::VP_REDUCE_AND;
8950     break;
8951   case ISD::VP_REDUCE_ADD:
8952     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8953     if (VT == MVT::i1)
8954       Opcode = ISD::VP_REDUCE_XOR;
8955     break;
8956   case ISD::VP_REDUCE_SMAX:
8957   case ISD::VP_REDUCE_UMIN:
8958     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
8959     // VP_REDUCE_AND.
8960     if (VT == MVT::i1)
8961       Opcode = ISD::VP_REDUCE_AND;
8962     break;
8963   case ISD::VP_REDUCE_SMIN:
8964   case ISD::VP_REDUCE_UMAX:
8965     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
8966     // VP_REDUCE_OR.
8967     if (VT == MVT::i1)
8968       Opcode = ISD::VP_REDUCE_OR;
8969     break;
8970   }
8971
8972   // Memoize nodes.
8973   SDNode *N;
8974   SDVTList VTs = getVTList(VT);
8975
8976   if (VT != MVT::Glue) {
8977     FoldingSetNodeID ID;
8978     AddNodeIDNode(ID, Opcode, VTs, Ops);
8979     void *IP = nullptr;
8980
8981     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8982       return SDValue(E, 0);
8983
8984     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8985     createOperands(N, Ops);
8986
8987     CSEMap.InsertNode(N, IP);
8988   } else {
8989     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8990     createOperands(N, Ops);
8991   }
8992
8993   N->setFlags(Flags);
8994   InsertNode(N);
8995   SDValue V(N, 0);
8996   NewSDValueDbgMsg(V, "Creating new node: ", this);
8997   return V;
8998 }
8999
9000 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9001                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
9002   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
9003 }
9004
9005 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9006                               ArrayRef<SDValue> Ops) {
9007   SDNodeFlags Flags;
9008   if (Inserter)
9009     Flags = Inserter->getFlags();
9010   return getNode(Opcode, DL, VTList, Ops, Flags);
9011 }
9012
9013 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9014                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
9015   if (VTList.NumVTs == 1)
9016     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
9017
9018 #ifndef NDEBUG
9019   for (const auto &Op : Ops)
9020     assert(Op.getOpcode() != ISD::DELETED_NODE &&
9021            "Operand is DELETED_NODE!");
9022 #endif
9023
9024   switch (Opcode) {
9025   case ISD::SADDO:
9026   case ISD::UADDO:
9027   case ISD::SSUBO:
9028   case ISD::USUBO: {
9029     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9030            "Invalid add/sub overflow op!");
9031     assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
9032            Ops[0].getValueType() == Ops[1].getValueType() &&
9033            Ops[0].getValueType() == VTList.VTs[0] &&
9034            "Binary operator types must match!");
9035     SDValue N1 = Ops[0], N2 = Ops[1];
9036     canonicalizeCommutativeBinop(Opcode, N1, N2);
9037
9038     // (X +- 0) -> X with zero-overflow.
9039     ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
9040                                                /*AllowTruncation*/ true);
9041     if (N2CV && N2CV->isZero()) {
9042       SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
9043       return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
9044     }
9045     break;
9046   }
9047   case ISD::SMUL_LOHI:
9048   case ISD::UMUL_LOHI: {
9049     assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
9050     assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
9051            VTList.VTs[0] == Ops[0].getValueType() &&
9052            VTList.VTs[0] == Ops[1].getValueType() &&
9053            "Binary operator types must match!");
9054     break;
9055   }
9056   case ISD::STRICT_FP_EXTEND:
9057     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9058            "Invalid STRICT_FP_EXTEND!");
9059     assert(VTList.VTs[0].isFloatingPoint() &&
9060            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
9061     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9062            "STRICT_FP_EXTEND result type should be vector iff the operand "
9063            "type is vector!");
9064     assert((!VTList.VTs[0].isVector() ||
9065             VTList.VTs[0].getVectorNumElements() ==
9066             Ops[1].getValueType().getVectorNumElements()) &&
9067            "Vector element count mismatch!");
9068     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
9069            "Invalid fpext node, dst <= src!");
9070     break;
9071   case ISD::STRICT_FP_ROUND:
9072     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
9073     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9074            "STRICT_FP_ROUND result type should be vector iff the operand "
9075            "type is vector!");
9076     assert((!VTList.VTs[0].isVector() ||
9077             VTList.VTs[0].getVectorNumElements() ==
9078             Ops[1].getValueType().getVectorNumElements()) &&
9079            "Vector element count mismatch!");
9080     assert(VTList.VTs[0].isFloatingPoint() &&
9081            Ops[1].getValueType().isFloatingPoint() &&
9082            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
9083            isa<ConstantSDNode>(Ops[2]) &&
9084            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
9085             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
9086            "Invalid STRICT_FP_ROUND!");
9087     break;
9088 #if 0
9089   // FIXME: figure out how to safely handle things like
9090   // int foo(int x) { return 1 << (x & 255); }
9091   // int bar() { return foo(256); }
9092   case ISD::SRA_PARTS:
9093   case ISD::SRL_PARTS:
9094   case ISD::SHL_PARTS:
9095     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
9096         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
9097       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9098     else if (N3.getOpcode() == ISD::AND)
9099       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9100         // If the and is only masking out bits that cannot effect the shift,
9101         // eliminate the and.
9102         unsigned NumBits = VT.getScalarSizeInBits()*2;
9103         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9104           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9105       }
9106     break;
9107 #endif
9108   }
9109
9110   // Memoize the node unless it returns a flag.
9111   SDNode *N;
9112   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9113     FoldingSetNodeID ID;
9114     AddNodeIDNode(ID, Opcode, VTList, Ops);
9115     void *IP = nullptr;
9116     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9117       return SDValue(E, 0);
9118
9119     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9120     createOperands(N, Ops);
9121     CSEMap.InsertNode(N, IP);
9122   } else {
9123     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9124     createOperands(N, Ops);
9125   }
9126
9127   N->setFlags(Flags);
9128   InsertNode(N);
9129   SDValue V(N, 0);
9130   NewSDValueDbgMsg(V, "Creating new node: ", this);
9131   return V;
9132 }
9133
9134 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9135                               SDVTList VTList) {
9136   return getNode(Opcode, DL, VTList, None);
9137 }
9138
9139 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9140                               SDValue N1) {
9141   SDValue Ops[] = { N1 };
9142   return getNode(Opcode, DL, VTList, Ops);
9143 }
9144
9145 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9146                               SDValue N1, SDValue N2) {
9147   SDValue Ops[] = { N1, N2 };
9148   return getNode(Opcode, DL, VTList, Ops);
9149 }
9150
9151 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9152                               SDValue N1, SDValue N2, SDValue N3) {
9153   SDValue Ops[] = { N1, N2, N3 };
9154   return getNode(Opcode, DL, VTList, Ops);
9155 }
9156
9157 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9158                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9159   SDValue Ops[] = { N1, N2, N3, N4 };
9160   return getNode(Opcode, DL, VTList, Ops);
9161 }
9162
9163 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9164                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9165                               SDValue N5) {
9166   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9167   return getNode(Opcode, DL, VTList, Ops);
9168 }
9169
9170 SDVTList SelectionDAG::getVTList(EVT VT) {
9171   return makeVTList(SDNode::getValueTypeList(VT), 1);
9172 }
9173
9174 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9175   FoldingSetNodeID ID;
9176   ID.AddInteger(2U);
9177   ID.AddInteger(VT1.getRawBits());
9178   ID.AddInteger(VT2.getRawBits());
9179
9180   void *IP = nullptr;
9181   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9182   if (!Result) {
9183     EVT *Array = Allocator.Allocate<EVT>(2);
9184     Array[0] = VT1;
9185     Array[1] = VT2;
9186     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9187     VTListMap.InsertNode(Result, IP);
9188   }
9189   return Result->getSDVTList();
9190 }
9191
9192 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9193   FoldingSetNodeID ID;
9194   ID.AddInteger(3U);
9195   ID.AddInteger(VT1.getRawBits());
9196   ID.AddInteger(VT2.getRawBits());
9197   ID.AddInteger(VT3.getRawBits());
9198
9199   void *IP = nullptr;
9200   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9201   if (!Result) {
9202     EVT *Array = Allocator.Allocate<EVT>(3);
9203     Array[0] = VT1;
9204     Array[1] = VT2;
9205     Array[2] = VT3;
9206     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9207     VTListMap.InsertNode(Result, IP);
9208   }
9209   return Result->getSDVTList();
9210 }
9211
9212 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9213   FoldingSetNodeID ID;
9214   ID.AddInteger(4U);
9215   ID.AddInteger(VT1.getRawBits());
9216   ID.AddInteger(VT2.getRawBits());
9217   ID.AddInteger(VT3.getRawBits());
9218   ID.AddInteger(VT4.getRawBits());
9219
9220   void *IP = nullptr;
9221   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9222   if (!Result) {
9223     EVT *Array = Allocator.Allocate<EVT>(4);
9224     Array[0] = VT1;
9225     Array[1] = VT2;
9226     Array[2] = VT3;
9227     Array[3] = VT4;
9228     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9229     VTListMap.InsertNode(Result, IP);
9230   }
9231   return Result->getSDVTList();
9232 }
9233
9234 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9235   unsigned NumVTs = VTs.size();
9236   FoldingSetNodeID ID;
9237   ID.AddInteger(NumVTs);
9238   for (unsigned index = 0; index < NumVTs; index++) {
9239     ID.AddInteger(VTs[index].getRawBits());
9240   }
9241
9242   void *IP = nullptr;
9243   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9244   if (!Result) {
9245     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9246     llvm::copy(VTs, Array);
9247     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9248     VTListMap.InsertNode(Result, IP);
9249   }
9250   return Result->getSDVTList();
9251 }
9252
9253
9254 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9255 /// specified operands.  If the resultant node already exists in the DAG,
9256 /// this does not modify the specified node, instead it returns the node that
9257 /// already exists.  If the resultant node does not exist in the DAG, the
9258 /// input node is returned.  As a degenerate case, if you specify the same
9259 /// input operands as the node already has, the input node is returned.
9260 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9261   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9262
9263   // Check to see if there is no change.
9264   if (Op == N->getOperand(0)) return N;
9265
9266   // See if the modified node already exists.
9267   void *InsertPos = nullptr;
9268   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9269     return Existing;
9270
9271   // Nope it doesn't.  Remove the node from its current place in the maps.
9272   if (InsertPos)
9273     if (!RemoveNodeFromCSEMaps(N))
9274       InsertPos = nullptr;
9275
9276   // Now we update the operands.
9277   N->OperandList[0].set(Op);
9278
9279   updateDivergence(N);
9280   // If this gets put into a CSE map, add it.
9281   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9282   return N;
9283 }
9284
9285 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9286   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9287
9288   // Check to see if there is no change.
9289   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9290     return N;   // No operands changed, just return the input node.
9291
9292   // See if the modified node already exists.
9293   void *InsertPos = nullptr;
9294   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9295     return Existing;
9296
9297   // Nope it doesn't.  Remove the node from its current place in the maps.
9298   if (InsertPos)
9299     if (!RemoveNodeFromCSEMaps(N))
9300       InsertPos = nullptr;
9301
9302   // Now we update the operands.
9303   if (N->OperandList[0] != Op1)
9304     N->OperandList[0].set(Op1);
9305   if (N->OperandList[1] != Op2)
9306     N->OperandList[1].set(Op2);
9307
9308   updateDivergence(N);
9309   // If this gets put into a CSE map, add it.
9310   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9311   return N;
9312 }
9313
9314 SDNode *SelectionDAG::
9315 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9316   SDValue Ops[] = { Op1, Op2, Op3 };
9317   return UpdateNodeOperands(N, Ops);
9318 }
9319
9320 SDNode *SelectionDAG::
9321 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9322                    SDValue Op3, SDValue Op4) {
9323   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9324   return UpdateNodeOperands(N, Ops);
9325 }
9326
9327 SDNode *SelectionDAG::
9328 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9329                    SDValue Op3, SDValue Op4, SDValue Op5) {
9330   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9331   return UpdateNodeOperands(N, Ops);
9332 }
9333
9334 SDNode *SelectionDAG::
9335 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9336   unsigned NumOps = Ops.size();
9337   assert(N->getNumOperands() == NumOps &&
9338          "Update with wrong number of operands");
9339
9340   // If no operands changed just return the input node.
9341   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9342     return N;
9343
9344   // See if the modified node already exists.
9345   void *InsertPos = nullptr;
9346   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9347     return Existing;
9348
9349   // Nope it doesn't.  Remove the node from its current place in the maps.
9350   if (InsertPos)
9351     if (!RemoveNodeFromCSEMaps(N))
9352       InsertPos = nullptr;
9353
9354   // Now we update the operands.
9355   for (unsigned i = 0; i != NumOps; ++i)
9356     if (N->OperandList[i] != Ops[i])
9357       N->OperandList[i].set(Ops[i]);
9358
9359   updateDivergence(N);
9360   // If this gets put into a CSE map, add it.
9361   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9362   return N;
9363 }
9364
9365 /// DropOperands - Release the operands and set this node to have
9366 /// zero operands.
9367 void SDNode::DropOperands() {
9368   // Unlike the code in MorphNodeTo that does this, we don't need to
9369   // watch for dead nodes here.
9370   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9371     SDUse &Use = *I++;
9372     Use.set(SDValue());
9373   }
9374 }
9375
9376 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9377                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9378   if (NewMemRefs.empty()) {
9379     N->clearMemRefs();
9380     return;
9381   }
9382
9383   // Check if we can avoid allocating by storing a single reference directly.
9384   if (NewMemRefs.size() == 1) {
9385     N->MemRefs = NewMemRefs[0];
9386     N->NumMemRefs = 1;
9387     return;
9388   }
9389
9390   MachineMemOperand **MemRefsBuffer =
9391       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9392   llvm::copy(NewMemRefs, MemRefsBuffer);
9393   N->MemRefs = MemRefsBuffer;
9394   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9395 }
9396
9397 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9398 /// machine opcode.
9399 ///
9400 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9401                                    EVT VT) {
9402   SDVTList VTs = getVTList(VT);
9403   return SelectNodeTo(N, MachineOpc, VTs, None);
9404 }
9405
9406 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9407                                    EVT VT, SDValue Op1) {
9408   SDVTList VTs = getVTList(VT);
9409   SDValue Ops[] = { Op1 };
9410   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9411 }
9412
9413 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9414                                    EVT VT, SDValue Op1,
9415                                    SDValue Op2) {
9416   SDVTList VTs = getVTList(VT);
9417   SDValue Ops[] = { Op1, Op2 };
9418   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9419 }
9420
9421 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9422                                    EVT VT, SDValue Op1,
9423                                    SDValue Op2, SDValue Op3) {
9424   SDVTList VTs = getVTList(VT);
9425   SDValue Ops[] = { Op1, Op2, Op3 };
9426   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9427 }
9428
9429 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9430                                    EVT VT, ArrayRef<SDValue> Ops) {
9431   SDVTList VTs = getVTList(VT);
9432   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9433 }
9434
9435 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9436                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9437   SDVTList VTs = getVTList(VT1, VT2);
9438   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9439 }
9440
9441 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9442                                    EVT VT1, EVT VT2) {
9443   SDVTList VTs = getVTList(VT1, VT2);
9444   return SelectNodeTo(N, MachineOpc, VTs, None);
9445 }
9446
9447 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9448                                    EVT VT1, EVT VT2, EVT VT3,
9449                                    ArrayRef<SDValue> Ops) {
9450   SDVTList VTs = getVTList(VT1, VT2, VT3);
9451   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9452 }
9453
9454 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9455                                    EVT VT1, EVT VT2,
9456                                    SDValue Op1, SDValue Op2) {
9457   SDVTList VTs = getVTList(VT1, VT2);
9458   SDValue Ops[] = { Op1, Op2 };
9459   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9460 }
9461
9462 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9463                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9464   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9465   // Reset the NodeID to -1.
9466   New->setNodeId(-1);
9467   if (New != N) {
9468     ReplaceAllUsesWith(N, New);
9469     RemoveDeadNode(N);
9470   }
9471   return New;
9472 }
9473
9474 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9475 /// the line number information on the merged node since it is not possible to
9476 /// preserve the information that operation is associated with multiple lines.
9477 /// This will make the debugger working better at -O0, were there is a higher
9478 /// probability having other instructions associated with that line.
9479 ///
9480 /// For IROrder, we keep the smaller of the two
9481 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9482   DebugLoc NLoc = N->getDebugLoc();
9483   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9484     N->setDebugLoc(DebugLoc());
9485   }
9486   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9487   N->setIROrder(Order);
9488   return N;
9489 }
9490
9491 /// MorphNodeTo - This *mutates* the specified node to have the specified
9492 /// return type, opcode, and operands.
9493 ///
9494 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9495 /// node of the specified opcode and operands, it returns that node instead of
9496 /// the current one.  Note that the SDLoc need not be the same.
9497 ///
9498 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9499 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9500 /// node, and because it doesn't require CSE recalculation for any of
9501 /// the node's users.
9502 ///
9503 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9504 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9505 /// the legalizer which maintain worklists that would need to be updated when
9506 /// deleting things.
9507 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9508                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9509   // If an identical node already exists, use it.
9510   void *IP = nullptr;
9511   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9512     FoldingSetNodeID ID;
9513     AddNodeIDNode(ID, Opc, VTs, Ops);
9514     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9515       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9516   }
9517
9518   if (!RemoveNodeFromCSEMaps(N))
9519     IP = nullptr;
9520
9521   // Start the morphing.
9522   N->NodeType = Opc;
9523   N->ValueList = VTs.VTs;
9524   N->NumValues = VTs.NumVTs;
9525
9526   // Clear the operands list, updating used nodes to remove this from their
9527   // use list.  Keep track of any operands that become dead as a result.
9528   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9529   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9530     SDUse &Use = *I++;
9531     SDNode *Used = Use.getNode();
9532     Use.set(SDValue());
9533     if (Used->use_empty())
9534       DeadNodeSet.insert(Used);
9535   }
9536
9537   // For MachineNode, initialize the memory references information.
9538   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9539     MN->clearMemRefs();
9540
9541   // Swap for an appropriately sized array from the recycler.
9542   removeOperands(N);
9543   createOperands(N, Ops);
9544
9545   // Delete any nodes that are still dead after adding the uses for the
9546   // new operands.
9547   if (!DeadNodeSet.empty()) {
9548     SmallVector<SDNode *, 16> DeadNodes;
9549     for (SDNode *N : DeadNodeSet)
9550       if (N->use_empty())
9551         DeadNodes.push_back(N);
9552     RemoveDeadNodes(DeadNodes);
9553   }
9554
9555   if (IP)
9556     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9557   return N;
9558 }
9559
9560 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9561   unsigned OrigOpc = Node->getOpcode();
9562   unsigned NewOpc;
9563   switch (OrigOpc) {
9564   default:
9565     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9566 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9567   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9568 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9569   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9570 #include "llvm/IR/ConstrainedOps.def"
9571   }
9572
9573   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9574
9575   // We're taking this node out of the chain, so we need to re-link things.
9576   SDValue InputChain = Node->getOperand(0);
9577   SDValue OutputChain = SDValue(Node, 1);
9578   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9579
9580   SmallVector<SDValue, 3> Ops;
9581   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9582     Ops.push_back(Node->getOperand(i));
9583
9584   SDVTList VTs = getVTList(Node->getValueType(0));
9585   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9586
9587   // MorphNodeTo can operate in two ways: if an existing node with the
9588   // specified operands exists, it can just return it.  Otherwise, it
9589   // updates the node in place to have the requested operands.
9590   if (Res == Node) {
9591     // If we updated the node in place, reset the node ID.  To the isel,
9592     // this should be just like a newly allocated machine node.
9593     Res->setNodeId(-1);
9594   } else {
9595     ReplaceAllUsesWith(Node, Res);
9596     RemoveDeadNode(Node);
9597   }
9598
9599   return Res;
9600 }
9601
9602 /// getMachineNode - These are used for target selectors to create a new node
9603 /// with specified return type(s), MachineInstr opcode, and operands.
9604 ///
9605 /// Note that getMachineNode returns the resultant node.  If there is already a
9606 /// node of the specified opcode and operands, it returns that node instead of
9607 /// the current one.
9608 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9609                                             EVT VT) {
9610   SDVTList VTs = getVTList(VT);
9611   return getMachineNode(Opcode, dl, VTs, None);
9612 }
9613
9614 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9615                                             EVT VT, SDValue Op1) {
9616   SDVTList VTs = getVTList(VT);
9617   SDValue Ops[] = { Op1 };
9618   return getMachineNode(Opcode, dl, VTs, Ops);
9619 }
9620
9621 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9622                                             EVT VT, SDValue Op1, SDValue Op2) {
9623   SDVTList VTs = getVTList(VT);
9624   SDValue Ops[] = { Op1, Op2 };
9625   return getMachineNode(Opcode, dl, VTs, Ops);
9626 }
9627
9628 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9629                                             EVT VT, SDValue Op1, SDValue Op2,
9630                                             SDValue Op3) {
9631   SDVTList VTs = getVTList(VT);
9632   SDValue Ops[] = { Op1, Op2, Op3 };
9633   return getMachineNode(Opcode, dl, VTs, Ops);
9634 }
9635
9636 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9637                                             EVT VT, ArrayRef<SDValue> Ops) {
9638   SDVTList VTs = getVTList(VT);
9639   return getMachineNode(Opcode, dl, VTs, Ops);
9640 }
9641
9642 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9643                                             EVT VT1, EVT VT2, SDValue Op1,
9644                                             SDValue Op2) {
9645   SDVTList VTs = getVTList(VT1, VT2);
9646   SDValue Ops[] = { Op1, Op2 };
9647   return getMachineNode(Opcode, dl, VTs, Ops);
9648 }
9649
9650 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9651                                             EVT VT1, EVT VT2, SDValue Op1,
9652                                             SDValue Op2, SDValue Op3) {
9653   SDVTList VTs = getVTList(VT1, VT2);
9654   SDValue Ops[] = { Op1, Op2, Op3 };
9655   return getMachineNode(Opcode, dl, VTs, Ops);
9656 }
9657
9658 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9659                                             EVT VT1, EVT VT2,
9660                                             ArrayRef<SDValue> Ops) {
9661   SDVTList VTs = getVTList(VT1, VT2);
9662   return getMachineNode(Opcode, dl, VTs, Ops);
9663 }
9664
9665 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9666                                             EVT VT1, EVT VT2, EVT VT3,
9667                                             SDValue Op1, SDValue Op2) {
9668   SDVTList VTs = getVTList(VT1, VT2, VT3);
9669   SDValue Ops[] = { Op1, Op2 };
9670   return getMachineNode(Opcode, dl, VTs, Ops);
9671 }
9672
9673 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9674                                             EVT VT1, EVT VT2, EVT VT3,
9675                                             SDValue Op1, SDValue Op2,
9676                                             SDValue Op3) {
9677   SDVTList VTs = getVTList(VT1, VT2, VT3);
9678   SDValue Ops[] = { Op1, Op2, Op3 };
9679   return getMachineNode(Opcode, dl, VTs, Ops);
9680 }
9681
9682 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9683                                             EVT VT1, EVT VT2, EVT VT3,
9684                                             ArrayRef<SDValue> Ops) {
9685   SDVTList VTs = getVTList(VT1, VT2, VT3);
9686   return getMachineNode(Opcode, dl, VTs, Ops);
9687 }
9688
9689 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9690                                             ArrayRef<EVT> ResultTys,
9691                                             ArrayRef<SDValue> Ops) {
9692   SDVTList VTs = getVTList(ResultTys);
9693   return getMachineNode(Opcode, dl, VTs, Ops);
9694 }
9695
9696 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9697                                             SDVTList VTs,
9698                                             ArrayRef<SDValue> Ops) {
9699   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9700   MachineSDNode *N;
9701   void *IP = nullptr;
9702
9703   if (DoCSE) {
9704     FoldingSetNodeID ID;
9705     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9706     IP = nullptr;
9707     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9708       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9709     }
9710   }
9711
9712   // Allocate a new MachineSDNode.
9713   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9714   createOperands(N, Ops);
9715
9716   if (DoCSE)
9717     CSEMap.InsertNode(N, IP);
9718
9719   InsertNode(N);
9720   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9721   return N;
9722 }
9723
9724 /// getTargetExtractSubreg - A convenience function for creating
9725 /// TargetOpcode::EXTRACT_SUBREG nodes.
9726 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9727                                              SDValue Operand) {
9728   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9729   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9730                                   VT, Operand, SRIdxVal);
9731   return SDValue(Subreg, 0);
9732 }
9733
9734 /// getTargetInsertSubreg - A convenience function for creating
9735 /// TargetOpcode::INSERT_SUBREG nodes.
9736 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9737                                             SDValue Operand, SDValue Subreg) {
9738   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9739   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9740                                   VT, Operand, Subreg, SRIdxVal);
9741   return SDValue(Result, 0);
9742 }
9743
9744 /// getNodeIfExists - Get the specified node if it's already available, or
9745 /// else return NULL.
9746 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9747                                       ArrayRef<SDValue> Ops) {
9748   SDNodeFlags Flags;
9749   if (Inserter)
9750     Flags = Inserter->getFlags();
9751   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9752 }
9753
9754 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9755                                       ArrayRef<SDValue> Ops,
9756                                       const SDNodeFlags Flags) {
9757   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9758     FoldingSetNodeID ID;
9759     AddNodeIDNode(ID, Opcode, VTList, Ops);
9760     void *IP = nullptr;
9761     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9762       E->intersectFlagsWith(Flags);
9763       return E;
9764     }
9765   }
9766   return nullptr;
9767 }
9768
9769 /// doesNodeExist - Check if a node exists without modifying its flags.
9770 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9771                                  ArrayRef<SDValue> Ops) {
9772   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9773     FoldingSetNodeID ID;
9774     AddNodeIDNode(ID, Opcode, VTList, Ops);
9775     void *IP = nullptr;
9776     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9777       return true;
9778   }
9779   return false;
9780 }
9781
9782 /// getDbgValue - Creates a SDDbgValue node.
9783 ///
9784 /// SDNode
9785 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9786                                       SDNode *N, unsigned R, bool IsIndirect,
9787                                       const DebugLoc &DL, unsigned O) {
9788   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9789          "Expected inlined-at fields to agree");
9790   return new (DbgInfo->getAlloc())
9791       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9792                  {}, IsIndirect, DL, O,
9793                  /*IsVariadic=*/false);
9794 }
9795
9796 /// Constant
9797 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9798                                               DIExpression *Expr,
9799                                               const Value *C,
9800                                               const DebugLoc &DL, unsigned O) {
9801   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9802          "Expected inlined-at fields to agree");
9803   return new (DbgInfo->getAlloc())
9804       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9805                  /*IsIndirect=*/false, DL, O,
9806                  /*IsVariadic=*/false);
9807 }
9808
9809 /// FrameIndex
9810 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9811                                                 DIExpression *Expr, unsigned FI,
9812                                                 bool IsIndirect,
9813                                                 const DebugLoc &DL,
9814                                                 unsigned O) {
9815   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9816          "Expected inlined-at fields to agree");
9817   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9818 }
9819
9820 /// FrameIndex with dependencies
9821 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9822                                                 DIExpression *Expr, unsigned FI,
9823                                                 ArrayRef<SDNode *> Dependencies,
9824                                                 bool IsIndirect,
9825                                                 const DebugLoc &DL,
9826                                                 unsigned O) {
9827   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9828          "Expected inlined-at fields to agree");
9829   return new (DbgInfo->getAlloc())
9830       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9831                  Dependencies, IsIndirect, DL, O,
9832                  /*IsVariadic=*/false);
9833 }
9834
9835 /// VReg
9836 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9837                                           unsigned VReg, bool IsIndirect,
9838                                           const DebugLoc &DL, unsigned O) {
9839   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9840          "Expected inlined-at fields to agree");
9841   return new (DbgInfo->getAlloc())
9842       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9843                  {}, IsIndirect, DL, O,
9844                  /*IsVariadic=*/false);
9845 }
9846
9847 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9848                                           ArrayRef<SDDbgOperand> Locs,
9849                                           ArrayRef<SDNode *> Dependencies,
9850                                           bool IsIndirect, const DebugLoc &DL,
9851                                           unsigned O, bool IsVariadic) {
9852   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9853          "Expected inlined-at fields to agree");
9854   return new (DbgInfo->getAlloc())
9855       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9856                  DL, O, IsVariadic);
9857 }
9858
9859 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9860                                      unsigned OffsetInBits, unsigned SizeInBits,
9861                                      bool InvalidateDbg) {
9862   SDNode *FromNode = From.getNode();
9863   SDNode *ToNode = To.getNode();
9864   assert(FromNode && ToNode && "Can't modify dbg values");
9865
9866   // PR35338
9867   // TODO: assert(From != To && "Redundant dbg value transfer");
9868   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9869   if (From == To || FromNode == ToNode)
9870     return;
9871
9872   if (!FromNode->getHasDebugValue())
9873     return;
9874
9875   SDDbgOperand FromLocOp =
9876       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9877   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9878
9879   SmallVector<SDDbgValue *, 2> ClonedDVs;
9880   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9881     if (Dbg->isInvalidated())
9882       continue;
9883
9884     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9885
9886     // Create a new location ops vector that is equal to the old vector, but
9887     // with each instance of FromLocOp replaced with ToLocOp.
9888     bool Changed = false;
9889     auto NewLocOps = Dbg->copyLocationOps();
9890     std::replace_if(
9891         NewLocOps.begin(), NewLocOps.end(),
9892         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9893           bool Match = Op == FromLocOp;
9894           Changed |= Match;
9895           return Match;
9896         },
9897         ToLocOp);
9898     // Ignore this SDDbgValue if we didn't find a matching location.
9899     if (!Changed)
9900       continue;
9901
9902     DIVariable *Var = Dbg->getVariable();
9903     auto *Expr = Dbg->getExpression();
9904     // If a fragment is requested, update the expression.
9905     if (SizeInBits) {
9906       // When splitting a larger (e.g., sign-extended) value whose
9907       // lower bits are described with an SDDbgValue, do not attempt
9908       // to transfer the SDDbgValue to the upper bits.
9909       if (auto FI = Expr->getFragmentInfo())
9910         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9911           continue;
9912       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9913                                                              SizeInBits);
9914       if (!Fragment)
9915         continue;
9916       Expr = *Fragment;
9917     }
9918
9919     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9920     // Clone the SDDbgValue and move it to To.
9921     SDDbgValue *Clone = getDbgValueList(
9922         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9923         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9924         Dbg->isVariadic());
9925     ClonedDVs.push_back(Clone);
9926
9927     if (InvalidateDbg) {
9928       // Invalidate value and indicate the SDDbgValue should not be emitted.
9929       Dbg->setIsInvalidated();
9930       Dbg->setIsEmitted();
9931     }
9932   }
9933
9934   for (SDDbgValue *Dbg : ClonedDVs) {
9935     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9936            "Transferred DbgValues should depend on the new SDNode");
9937     AddDbgValue(Dbg, false);
9938   }
9939 }
9940
9941 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9942   if (!N.getHasDebugValue())
9943     return;
9944
9945   SmallVector<SDDbgValue *, 2> ClonedDVs;
9946   for (auto *DV : GetDbgValues(&N)) {
9947     if (DV->isInvalidated())
9948       continue;
9949     switch (N.getOpcode()) {
9950     default:
9951       break;
9952     case ISD::ADD:
9953       SDValue N0 = N.getOperand(0);
9954       SDValue N1 = N.getOperand(1);
9955       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9956           isConstantIntBuildVectorOrConstantInt(N1)) {
9957         uint64_t Offset = N.getConstantOperandVal(1);
9958
9959         // Rewrite an ADD constant node into a DIExpression. Since we are
9960         // performing arithmetic to compute the variable's *value* in the
9961         // DIExpression, we need to mark the expression with a
9962         // DW_OP_stack_value.
9963         auto *DIExpr = DV->getExpression();
9964         auto NewLocOps = DV->copyLocationOps();
9965         bool Changed = false;
9966         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9967           // We're not given a ResNo to compare against because the whole
9968           // node is going away. We know that any ISD::ADD only has one
9969           // result, so we can assume any node match is using the result.
9970           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9971               NewLocOps[i].getSDNode() != &N)
9972             continue;
9973           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9974           SmallVector<uint64_t, 3> ExprOps;
9975           DIExpression::appendOffset(ExprOps, Offset);
9976           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9977           Changed = true;
9978         }
9979         (void)Changed;
9980         assert(Changed && "Salvage target doesn't use N");
9981
9982         auto AdditionalDependencies = DV->getAdditionalDependencies();
9983         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9984                                             NewLocOps, AdditionalDependencies,
9985                                             DV->isIndirect(), DV->getDebugLoc(),
9986                                             DV->getOrder(), DV->isVariadic());
9987         ClonedDVs.push_back(Clone);
9988         DV->setIsInvalidated();
9989         DV->setIsEmitted();
9990         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9991                    N0.getNode()->dumprFull(this);
9992                    dbgs() << " into " << *DIExpr << '\n');
9993       }
9994     }
9995   }
9996
9997   for (SDDbgValue *Dbg : ClonedDVs) {
9998     assert(!Dbg->getSDNodes().empty() &&
9999            "Salvaged DbgValue should depend on a new SDNode");
10000     AddDbgValue(Dbg, false);
10001   }
10002 }
10003
10004 /// Creates a SDDbgLabel node.
10005 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
10006                                       const DebugLoc &DL, unsigned O) {
10007   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
10008          "Expected inlined-at fields to agree");
10009   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
10010 }
10011
10012 namespace {
10013
10014 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
10015 /// pointed to by a use iterator is deleted, increment the use iterator
10016 /// so that it doesn't dangle.
10017 ///
10018 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
10019   SDNode::use_iterator &UI;
10020   SDNode::use_iterator &UE;
10021
10022   void NodeDeleted(SDNode *N, SDNode *E) override {
10023     // Increment the iterator as needed.
10024     while (UI != UE && N == *UI)
10025       ++UI;
10026   }
10027
10028 public:
10029   RAUWUpdateListener(SelectionDAG &d,
10030                      SDNode::use_iterator &ui,
10031                      SDNode::use_iterator &ue)
10032     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
10033 };
10034
10035 } // end anonymous namespace
10036
10037 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10038 /// This can cause recursive merging of nodes in the DAG.
10039 ///
10040 /// This version assumes From has a single result value.
10041 ///
10042 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
10043   SDNode *From = FromN.getNode();
10044   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
10045          "Cannot replace with this method!");
10046   assert(From != To.getNode() && "Cannot replace uses of with self");
10047
10048   // Preserve Debug Values
10049   transferDbgValues(FromN, To);
10050
10051   // Iterate over all the existing uses of From. New uses will be added
10052   // to the beginning of the use list, which we avoid visiting.
10053   // This specifically avoids visiting uses of From that arise while the
10054   // replacement is happening, because any such uses would be the result
10055   // of CSE: If an existing node looks like From after one of its operands
10056   // is replaced by To, we don't want to replace of all its users with To
10057   // too. See PR3018 for more info.
10058   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10059   RAUWUpdateListener Listener(*this, UI, UE);
10060   while (UI != UE) {
10061     SDNode *User = *UI;
10062
10063     // This node is about to morph, remove its old self from the CSE maps.
10064     RemoveNodeFromCSEMaps(User);
10065
10066     // A user can appear in a use list multiple times, and when this
10067     // happens the uses are usually next to each other in the list.
10068     // To help reduce the number of CSE recomputations, process all
10069     // the uses of this user that we can find this way.
10070     do {
10071       SDUse &Use = UI.getUse();
10072       ++UI;
10073       Use.set(To);
10074       if (To->isDivergent() != From->isDivergent())
10075         updateDivergence(User);
10076     } while (UI != UE && *UI == User);
10077     // Now that we have modified User, add it back to the CSE maps.  If it
10078     // already exists there, recursively merge the results together.
10079     AddModifiedNodeToCSEMaps(User);
10080   }
10081
10082   // If we just RAUW'd the root, take note.
10083   if (FromN == getRoot())
10084     setRoot(To);
10085 }
10086
10087 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10088 /// This can cause recursive merging of nodes in the DAG.
10089 ///
10090 /// This version assumes that for each value of From, there is a
10091 /// corresponding value in To in the same position with the same type.
10092 ///
10093 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
10094 #ifndef NDEBUG
10095   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10096     assert((!From->hasAnyUseOfValue(i) ||
10097             From->getValueType(i) == To->getValueType(i)) &&
10098            "Cannot use this version of ReplaceAllUsesWith!");
10099 #endif
10100
10101   // Handle the trivial case.
10102   if (From == To)
10103     return;
10104
10105   // Preserve Debug Info. Only do this if there's a use.
10106   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10107     if (From->hasAnyUseOfValue(i)) {
10108       assert((i < To->getNumValues()) && "Invalid To location");
10109       transferDbgValues(SDValue(From, i), SDValue(To, i));
10110     }
10111
10112   // Iterate over just the existing users of From. See the comments in
10113   // the ReplaceAllUsesWith above.
10114   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10115   RAUWUpdateListener Listener(*this, UI, UE);
10116   while (UI != UE) {
10117     SDNode *User = *UI;
10118
10119     // This node is about to morph, remove its old self from the CSE maps.
10120     RemoveNodeFromCSEMaps(User);
10121
10122     // A user can appear in a use list multiple times, and when this
10123     // happens the uses are usually next to each other in the list.
10124     // To help reduce the number of CSE recomputations, process all
10125     // the uses of this user that we can find this way.
10126     do {
10127       SDUse &Use = UI.getUse();
10128       ++UI;
10129       Use.setNode(To);
10130       if (To->isDivergent() != From->isDivergent())
10131         updateDivergence(User);
10132     } while (UI != UE && *UI == User);
10133
10134     // Now that we have modified User, add it back to the CSE maps.  If it
10135     // already exists there, recursively merge the results together.
10136     AddModifiedNodeToCSEMaps(User);
10137   }
10138
10139   // If we just RAUW'd the root, take note.
10140   if (From == getRoot().getNode())
10141     setRoot(SDValue(To, getRoot().getResNo()));
10142 }
10143
10144 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10145 /// This can cause recursive merging of nodes in the DAG.
10146 ///
10147 /// This version can replace From with any result values.  To must match the
10148 /// number and types of values returned by From.
10149 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10150   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10151     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10152
10153   // Preserve Debug Info.
10154   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10155     transferDbgValues(SDValue(From, i), To[i]);
10156
10157   // Iterate over just the existing users of From. See the comments in
10158   // the ReplaceAllUsesWith above.
10159   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10160   RAUWUpdateListener Listener(*this, UI, UE);
10161   while (UI != UE) {
10162     SDNode *User = *UI;
10163
10164     // This node is about to morph, remove its old self from the CSE maps.
10165     RemoveNodeFromCSEMaps(User);
10166
10167     // A user can appear in a use list multiple times, and when this happens the
10168     // uses are usually next to each other in the list.  To help reduce the
10169     // number of CSE and divergence recomputations, process all the uses of this
10170     // user that we can find this way.
10171     bool To_IsDivergent = false;
10172     do {
10173       SDUse &Use = UI.getUse();
10174       const SDValue &ToOp = To[Use.getResNo()];
10175       ++UI;
10176       Use.set(ToOp);
10177       To_IsDivergent |= ToOp->isDivergent();
10178     } while (UI != UE && *UI == User);
10179
10180     if (To_IsDivergent != From->isDivergent())
10181       updateDivergence(User);
10182
10183     // Now that we have modified User, add it back to the CSE maps.  If it
10184     // already exists there, recursively merge the results together.
10185     AddModifiedNodeToCSEMaps(User);
10186   }
10187
10188   // If we just RAUW'd the root, take note.
10189   if (From == getRoot().getNode())
10190     setRoot(SDValue(To[getRoot().getResNo()]));
10191 }
10192
10193 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10194 /// uses of other values produced by From.getNode() alone.  The Deleted
10195 /// vector is handled the same way as for ReplaceAllUsesWith.
10196 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10197   // Handle the really simple, really trivial case efficiently.
10198   if (From == To) return;
10199
10200   // Handle the simple, trivial, case efficiently.
10201   if (From.getNode()->getNumValues() == 1) {
10202     ReplaceAllUsesWith(From, To);
10203     return;
10204   }
10205
10206   // Preserve Debug Info.
10207   transferDbgValues(From, To);
10208
10209   // Iterate over just the existing users of From. See the comments in
10210   // the ReplaceAllUsesWith above.
10211   SDNode::use_iterator UI = From.getNode()->use_begin(),
10212                        UE = From.getNode()->use_end();
10213   RAUWUpdateListener Listener(*this, UI, UE);
10214   while (UI != UE) {
10215     SDNode *User = *UI;
10216     bool UserRemovedFromCSEMaps = false;
10217
10218     // A user can appear in a use list multiple times, and when this
10219     // happens the uses are usually next to each other in the list.
10220     // To help reduce the number of CSE recomputations, process all
10221     // the uses of this user that we can find this way.
10222     do {
10223       SDUse &Use = UI.getUse();
10224
10225       // Skip uses of different values from the same node.
10226       if (Use.getResNo() != From.getResNo()) {
10227         ++UI;
10228         continue;
10229       }
10230
10231       // If this node hasn't been modified yet, it's still in the CSE maps,
10232       // so remove its old self from the CSE maps.
10233       if (!UserRemovedFromCSEMaps) {
10234         RemoveNodeFromCSEMaps(User);
10235         UserRemovedFromCSEMaps = true;
10236       }
10237
10238       ++UI;
10239       Use.set(To);
10240       if (To->isDivergent() != From->isDivergent())
10241         updateDivergence(User);
10242     } while (UI != UE && *UI == User);
10243     // We are iterating over all uses of the From node, so if a use
10244     // doesn't use the specific value, no changes are made.
10245     if (!UserRemovedFromCSEMaps)
10246       continue;
10247
10248     // Now that we have modified User, add it back to the CSE maps.  If it
10249     // already exists there, recursively merge the results together.
10250     AddModifiedNodeToCSEMaps(User);
10251   }
10252
10253   // If we just RAUW'd the root, take note.
10254   if (From == getRoot())
10255     setRoot(To);
10256 }
10257
10258 namespace {
10259
10260 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10261 /// to record information about a use.
10262 struct UseMemo {
10263   SDNode *User;
10264   unsigned Index;
10265   SDUse *Use;
10266 };
10267
10268 /// operator< - Sort Memos by User.
10269 bool operator<(const UseMemo &L, const UseMemo &R) {
10270   return (intptr_t)L.User < (intptr_t)R.User;
10271 }
10272
10273 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10274 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10275 /// the node already has been taken care of recursively.
10276 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10277   SmallVector<UseMemo, 4> &Uses;
10278
10279   void NodeDeleted(SDNode *N, SDNode *E) override {
10280     for (UseMemo &Memo : Uses)
10281       if (Memo.User == N)
10282         Memo.User = nullptr;
10283   }
10284
10285 public:
10286   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10287       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10288 };
10289
10290 } // end anonymous namespace
10291
10292 bool SelectionDAG::calculateDivergence(SDNode *N) {
10293   if (TLI->isSDNodeAlwaysUniform(N)) {
10294     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10295            "Conflicting divergence information!");
10296     return false;
10297   }
10298   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10299     return true;
10300   for (const auto &Op : N->ops()) {
10301     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10302       return true;
10303   }
10304   return false;
10305 }
10306
10307 void SelectionDAG::updateDivergence(SDNode *N) {
10308   SmallVector<SDNode *, 16> Worklist(1, N);
10309   do {
10310     N = Worklist.pop_back_val();
10311     bool IsDivergent = calculateDivergence(N);
10312     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10313       N->SDNodeBits.IsDivergent = IsDivergent;
10314       llvm::append_range(Worklist, N->uses());
10315     }
10316   } while (!Worklist.empty());
10317 }
10318
10319 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10320   DenseMap<SDNode *, unsigned> Degree;
10321   Order.reserve(AllNodes.size());
10322   for (auto &N : allnodes()) {
10323     unsigned NOps = N.getNumOperands();
10324     Degree[&N] = NOps;
10325     if (0 == NOps)
10326       Order.push_back(&N);
10327   }
10328   for (size_t I = 0; I != Order.size(); ++I) {
10329     SDNode *N = Order[I];
10330     for (auto *U : N->uses()) {
10331       unsigned &UnsortedOps = Degree[U];
10332       if (0 == --UnsortedOps)
10333         Order.push_back(U);
10334     }
10335   }
10336 }
10337
10338 #ifndef NDEBUG
10339 void SelectionDAG::VerifyDAGDivergence() {
10340   std::vector<SDNode *> TopoOrder;
10341   CreateTopologicalOrder(TopoOrder);
10342   for (auto *N : TopoOrder) {
10343     assert(calculateDivergence(N) == N->isDivergent() &&
10344            "Divergence bit inconsistency detected");
10345   }
10346 }
10347 #endif
10348
10349 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10350 /// uses of other values produced by From.getNode() alone.  The same value
10351 /// may appear in both the From and To list.  The Deleted vector is
10352 /// handled the same way as for ReplaceAllUsesWith.
10353 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10354                                               const SDValue *To,
10355                                               unsigned Num){
10356   // Handle the simple, trivial case efficiently.
10357   if (Num == 1)
10358     return ReplaceAllUsesOfValueWith(*From, *To);
10359
10360   transferDbgValues(*From, *To);
10361
10362   // Read up all the uses and make records of them. This helps
10363   // processing new uses that are introduced during the
10364   // replacement process.
10365   SmallVector<UseMemo, 4> Uses;
10366   for (unsigned i = 0; i != Num; ++i) {
10367     unsigned FromResNo = From[i].getResNo();
10368     SDNode *FromNode = From[i].getNode();
10369     for (SDNode::use_iterator UI = FromNode->use_begin(),
10370          E = FromNode->use_end(); UI != E; ++UI) {
10371       SDUse &Use = UI.getUse();
10372       if (Use.getResNo() == FromResNo) {
10373         UseMemo Memo = { *UI, i, &Use };
10374         Uses.push_back(Memo);
10375       }
10376     }
10377   }
10378
10379   // Sort the uses, so that all the uses from a given User are together.
10380   llvm::sort(Uses);
10381   RAUOVWUpdateListener Listener(*this, Uses);
10382
10383   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10384        UseIndex != UseIndexEnd; ) {
10385     // We know that this user uses some value of From.  If it is the right
10386     // value, update it.
10387     SDNode *User = Uses[UseIndex].User;
10388     // If the node has been deleted by recursive CSE updates when updating
10389     // another node, then just skip this entry.
10390     if (User == nullptr) {
10391       ++UseIndex;
10392       continue;
10393     }
10394
10395     // This node is about to morph, remove its old self from the CSE maps.
10396     RemoveNodeFromCSEMaps(User);
10397
10398     // The Uses array is sorted, so all the uses for a given User
10399     // are next to each other in the list.
10400     // To help reduce the number of CSE recomputations, process all
10401     // the uses of this user that we can find this way.
10402     do {
10403       unsigned i = Uses[UseIndex].Index;
10404       SDUse &Use = *Uses[UseIndex].Use;
10405       ++UseIndex;
10406
10407       Use.set(To[i]);
10408     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10409
10410     // Now that we have modified User, add it back to the CSE maps.  If it
10411     // already exists there, recursively merge the results together.
10412     AddModifiedNodeToCSEMaps(User);
10413   }
10414 }
10415
10416 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10417 /// based on their topological order. It returns the maximum id and a vector
10418 /// of the SDNodes* in assigned order by reference.
10419 unsigned SelectionDAG::AssignTopologicalOrder() {
10420   unsigned DAGSize = 0;
10421
10422   // SortedPos tracks the progress of the algorithm. Nodes before it are
10423   // sorted, nodes after it are unsorted. When the algorithm completes
10424   // it is at the end of the list.
10425   allnodes_iterator SortedPos = allnodes_begin();
10426
10427   // Visit all the nodes. Move nodes with no operands to the front of
10428   // the list immediately. Annotate nodes that do have operands with their
10429   // operand count. Before we do this, the Node Id fields of the nodes
10430   // may contain arbitrary values. After, the Node Id fields for nodes
10431   // before SortedPos will contain the topological sort index, and the
10432   // Node Id fields for nodes At SortedPos and after will contain the
10433   // count of outstanding operands.
10434   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10435     checkForCycles(&N, this);
10436     unsigned Degree = N.getNumOperands();
10437     if (Degree == 0) {
10438       // A node with no uses, add it to the result array immediately.
10439       N.setNodeId(DAGSize++);
10440       allnodes_iterator Q(&N);
10441       if (Q != SortedPos)
10442         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10443       assert(SortedPos != AllNodes.end() && "Overran node list");
10444       ++SortedPos;
10445     } else {
10446       // Temporarily use the Node Id as scratch space for the degree count.
10447       N.setNodeId(Degree);
10448     }
10449   }
10450
10451   // Visit all the nodes. As we iterate, move nodes into sorted order,
10452   // such that by the time the end is reached all nodes will be sorted.
10453   for (SDNode &Node : allnodes()) {
10454     SDNode *N = &Node;
10455     checkForCycles(N, this);
10456     // N is in sorted position, so all its uses have one less operand
10457     // that needs to be sorted.
10458     for (SDNode *P : N->uses()) {
10459       unsigned Degree = P->getNodeId();
10460       assert(Degree != 0 && "Invalid node degree");
10461       --Degree;
10462       if (Degree == 0) {
10463         // All of P's operands are sorted, so P may sorted now.
10464         P->setNodeId(DAGSize++);
10465         if (P->getIterator() != SortedPos)
10466           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10467         assert(SortedPos != AllNodes.end() && "Overran node list");
10468         ++SortedPos;
10469       } else {
10470         // Update P's outstanding operand count.
10471         P->setNodeId(Degree);
10472       }
10473     }
10474     if (Node.getIterator() == SortedPos) {
10475 #ifndef NDEBUG
10476       allnodes_iterator I(N);
10477       SDNode *S = &*++I;
10478       dbgs() << "Overran sorted position:\n";
10479       S->dumprFull(this); dbgs() << "\n";
10480       dbgs() << "Checking if this is due to cycles\n";
10481       checkForCycles(this, true);
10482 #endif
10483       llvm_unreachable(nullptr);
10484     }
10485   }
10486
10487   assert(SortedPos == AllNodes.end() &&
10488          "Topological sort incomplete!");
10489   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10490          "First node in topological sort is not the entry token!");
10491   assert(AllNodes.front().getNodeId() == 0 &&
10492          "First node in topological sort has non-zero id!");
10493   assert(AllNodes.front().getNumOperands() == 0 &&
10494          "First node in topological sort has operands!");
10495   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10496          "Last node in topologic sort has unexpected id!");
10497   assert(AllNodes.back().use_empty() &&
10498          "Last node in topologic sort has users!");
10499   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10500   return DAGSize;
10501 }
10502
10503 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10504 /// value is produced by SD.
10505 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10506   for (SDNode *SD : DB->getSDNodes()) {
10507     if (!SD)
10508       continue;
10509     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10510     SD->setHasDebugValue(true);
10511   }
10512   DbgInfo->add(DB, isParameter);
10513 }
10514
10515 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10516
10517 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10518                                                    SDValue NewMemOpChain) {
10519   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10520   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10521   // The new memory operation must have the same position as the old load in
10522   // terms of memory dependency. Create a TokenFactor for the old load and new
10523   // memory operation and update uses of the old load's output chain to use that
10524   // TokenFactor.
10525   if (OldChain == NewMemOpChain || OldChain.use_empty())
10526     return NewMemOpChain;
10527
10528   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10529                                 OldChain, NewMemOpChain);
10530   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10531   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10532   return TokenFactor;
10533 }
10534
10535 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10536                                                    SDValue NewMemOp) {
10537   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10538   SDValue OldChain = SDValue(OldLoad, 1);
10539   SDValue NewMemOpChain = NewMemOp.getValue(1);
10540   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10541 }
10542
10543 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10544                                                      Function **OutFunction) {
10545   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10546
10547   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10548   auto *Module = MF->getFunction().getParent();
10549   auto *Function = Module->getFunction(Symbol);
10550
10551   if (OutFunction != nullptr)
10552       *OutFunction = Function;
10553
10554   if (Function != nullptr) {
10555     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10556     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10557   }
10558
10559   std::string ErrorStr;
10560   raw_string_ostream ErrorFormatter(ErrorStr);
10561   ErrorFormatter << "Undefined external symbol ";
10562   ErrorFormatter << '"' << Symbol << '"';
10563   report_fatal_error(Twine(ErrorFormatter.str()));
10564 }
10565
10566 //===----------------------------------------------------------------------===//
10567 //                              SDNode Class
10568 //===----------------------------------------------------------------------===//
10569
10570 bool llvm::isNullConstant(SDValue V) {
10571   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10572   return Const != nullptr && Const->isZero();
10573 }
10574
10575 bool llvm::isNullFPConstant(SDValue V) {
10576   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10577   return Const != nullptr && Const->isZero() && !Const->isNegative();
10578 }
10579
10580 bool llvm::isAllOnesConstant(SDValue V) {
10581   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10582   return Const != nullptr && Const->isAllOnes();
10583 }
10584
10585 bool llvm::isOneConstant(SDValue V) {
10586   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10587   return Const != nullptr && Const->isOne();
10588 }
10589
10590 bool llvm::isMinSignedConstant(SDValue V) {
10591   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10592   return Const != nullptr && Const->isMinSignedValue();
10593 }
10594
10595 SDValue llvm::peekThroughBitcasts(SDValue V) {
10596   while (V.getOpcode() == ISD::BITCAST)
10597     V = V.getOperand(0);
10598   return V;
10599 }
10600
10601 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10602   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10603     V = V.getOperand(0);
10604   return V;
10605 }
10606
10607 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10608   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10609     V = V.getOperand(0);
10610   return V;
10611 }
10612
10613 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10614   if (V.getOpcode() != ISD::XOR)
10615     return false;
10616   V = peekThroughBitcasts(V.getOperand(1));
10617   unsigned NumBits = V.getScalarValueSizeInBits();
10618   ConstantSDNode *C =
10619       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10620   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10621 }
10622
10623 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10624                                           bool AllowTruncation) {
10625   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10626     return CN;
10627
10628   // SplatVectors can truncate their operands. Ignore that case here unless
10629   // AllowTruncation is set.
10630   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10631     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10632     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10633       EVT CVT = CN->getValueType(0);
10634       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10635       if (AllowTruncation || CVT == VecEltVT)
10636         return CN;
10637     }
10638   }
10639
10640   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10641     BitVector UndefElements;
10642     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10643
10644     // BuildVectors can truncate their operands. Ignore that case here unless
10645     // AllowTruncation is set.
10646     if (CN && (UndefElements.none() || AllowUndefs)) {
10647       EVT CVT = CN->getValueType(0);
10648       EVT NSVT = N.getValueType().getScalarType();
10649       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10650       if (AllowTruncation || (CVT == NSVT))
10651         return CN;
10652     }
10653   }
10654
10655   return nullptr;
10656 }
10657
10658 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10659                                           bool AllowUndefs,
10660                                           bool AllowTruncation) {
10661   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10662     return CN;
10663
10664   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10665     BitVector UndefElements;
10666     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10667
10668     // BuildVectors can truncate their operands. Ignore that case here unless
10669     // AllowTruncation is set.
10670     if (CN && (UndefElements.none() || AllowUndefs)) {
10671       EVT CVT = CN->getValueType(0);
10672       EVT NSVT = N.getValueType().getScalarType();
10673       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10674       if (AllowTruncation || (CVT == NSVT))
10675         return CN;
10676     }
10677   }
10678
10679   return nullptr;
10680 }
10681
10682 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10683   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10684     return CN;
10685
10686   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10687     BitVector UndefElements;
10688     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10689     if (CN && (UndefElements.none() || AllowUndefs))
10690       return CN;
10691   }
10692
10693   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10694     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10695       return CN;
10696
10697   return nullptr;
10698 }
10699
10700 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10701                                               const APInt &DemandedElts,
10702                                               bool AllowUndefs) {
10703   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10704     return CN;
10705
10706   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10707     BitVector UndefElements;
10708     ConstantFPSDNode *CN =
10709         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10710     if (CN && (UndefElements.none() || AllowUndefs))
10711       return CN;
10712   }
10713
10714   return nullptr;
10715 }
10716
10717 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10718   // TODO: may want to use peekThroughBitcast() here.
10719   ConstantSDNode *C =
10720       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10721   return C && C->isZero();
10722 }
10723
10724 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10725   ConstantSDNode *C =
10726       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
10727   return C && C->isOne();
10728 }
10729
10730 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10731   N = peekThroughBitcasts(N);
10732   unsigned BitWidth = N.getScalarValueSizeInBits();
10733   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10734   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10735 }
10736
10737 HandleSDNode::~HandleSDNode() {
10738   DropOperands();
10739 }
10740
10741 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10742                                          const DebugLoc &DL,
10743                                          const GlobalValue *GA, EVT VT,
10744                                          int64_t o, unsigned TF)
10745     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10746   TheGlobal = GA;
10747 }
10748
10749 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10750                                          EVT VT, unsigned SrcAS,
10751                                          unsigned DestAS)
10752     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10753       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10754
10755 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10756                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10757     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10758   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10759   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10760   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10761   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10762
10763   // We check here that the size of the memory operand fits within the size of
10764   // the MMO. This is because the MMO might indicate only a possible address
10765   // range instead of specifying the affected memory addresses precisely.
10766   // TODO: Make MachineMemOperands aware of scalable vectors.
10767   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10768          "Size mismatch!");
10769 }
10770
10771 /// Profile - Gather unique data for the node.
10772 ///
10773 void SDNode::Profile(FoldingSetNodeID &ID) const {
10774   AddNodeIDNode(ID, this);
10775 }
10776
10777 namespace {
10778
10779   struct EVTArray {
10780     std::vector<EVT> VTs;
10781
10782     EVTArray() {
10783       VTs.reserve(MVT::VALUETYPE_SIZE);
10784       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10785         VTs.push_back(MVT((MVT::SimpleValueType)i));
10786     }
10787   };
10788
10789 } // end anonymous namespace
10790
10791 /// getValueTypeList - Return a pointer to the specified value type.
10792 ///
10793 const EVT *SDNode::getValueTypeList(EVT VT) {
10794   static std::set<EVT, EVT::compareRawBits> EVTs;
10795   static EVTArray SimpleVTArray;
10796   static sys::SmartMutex<true> VTMutex;
10797
10798   if (VT.isExtended()) {
10799     sys::SmartScopedLock<true> Lock(VTMutex);
10800     return &(*EVTs.insert(VT).first);
10801   }
10802   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10803   return &SimpleVTArray.VTs[VT.getSimpleVT().SimpleTy];
10804 }
10805
10806 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10807 /// indicated value.  This method ignores uses of other values defined by this
10808 /// operation.
10809 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10810   assert(Value < getNumValues() && "Bad value!");
10811
10812   // TODO: Only iterate over uses of a given value of the node
10813   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10814     if (UI.getUse().getResNo() == Value) {
10815       if (NUses == 0)
10816         return false;
10817       --NUses;
10818     }
10819   }
10820
10821   // Found exactly the right number of uses?
10822   return NUses == 0;
10823 }
10824
10825 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10826 /// value. This method ignores uses of other values defined by this operation.
10827 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10828   assert(Value < getNumValues() && "Bad value!");
10829
10830   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10831     if (UI.getUse().getResNo() == Value)
10832       return true;
10833
10834   return false;
10835 }
10836
10837 /// isOnlyUserOf - Return true if this node is the only use of N.
10838 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10839   bool Seen = false;
10840   for (const SDNode *User : N->uses()) {
10841     if (User == this)
10842       Seen = true;
10843     else
10844       return false;
10845   }
10846
10847   return Seen;
10848 }
10849
10850 /// Return true if the only users of N are contained in Nodes.
10851 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10852   bool Seen = false;
10853   for (const SDNode *User : N->uses()) {
10854     if (llvm::is_contained(Nodes, User))
10855       Seen = true;
10856     else
10857       return false;
10858   }
10859
10860   return Seen;
10861 }
10862
10863 /// isOperand - Return true if this node is an operand of N.
10864 bool SDValue::isOperandOf(const SDNode *N) const {
10865   return is_contained(N->op_values(), *this);
10866 }
10867
10868 bool SDNode::isOperandOf(const SDNode *N) const {
10869   return any_of(N->op_values(),
10870                 [this](SDValue Op) { return this == Op.getNode(); });
10871 }
10872
10873 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10874 /// be a chain) reaches the specified operand without crossing any
10875 /// side-effecting instructions on any chain path.  In practice, this looks
10876 /// through token factors and non-volatile loads.  In order to remain efficient,
10877 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10878 ///
10879 /// Note that we only need to examine chains when we're searching for
10880 /// side-effects; SelectionDAG requires that all side-effects are represented
10881 /// by chains, even if another operand would force a specific ordering. This
10882 /// constraint is necessary to allow transformations like splitting loads.
10883 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10884                                              unsigned Depth) const {
10885   if (*this == Dest) return true;
10886
10887   // Don't search too deeply, we just want to be able to see through
10888   // TokenFactor's etc.
10889   if (Depth == 0) return false;
10890
10891   // If this is a token factor, all inputs to the TF happen in parallel.
10892   if (getOpcode() == ISD::TokenFactor) {
10893     // First, try a shallow search.
10894     if (is_contained((*this)->ops(), Dest)) {
10895       // We found the chain we want as an operand of this TokenFactor.
10896       // Essentially, we reach the chain without side-effects if we could
10897       // serialize the TokenFactor into a simple chain of operations with
10898       // Dest as the last operation. This is automatically true if the
10899       // chain has one use: there are no other ordering constraints.
10900       // If the chain has more than one use, we give up: some other
10901       // use of Dest might force a side-effect between Dest and the current
10902       // node.
10903       if (Dest.hasOneUse())
10904         return true;
10905     }
10906     // Next, try a deep search: check whether every operand of the TokenFactor
10907     // reaches Dest.
10908     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10909       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10910     });
10911   }
10912
10913   // Loads don't have side effects, look through them.
10914   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10915     if (Ld->isUnordered())
10916       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10917   }
10918   return false;
10919 }
10920
10921 bool SDNode::hasPredecessor(const SDNode *N) const {
10922   SmallPtrSet<const SDNode *, 32> Visited;
10923   SmallVector<const SDNode *, 16> Worklist;
10924   Worklist.push_back(this);
10925   return hasPredecessorHelper(N, Visited, Worklist);
10926 }
10927
10928 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10929   this->Flags.intersectWith(Flags);
10930 }
10931
10932 SDValue
10933 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10934                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10935                                   bool AllowPartials) {
10936   // The pattern must end in an extract from index 0.
10937   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10938       !isNullConstant(Extract->getOperand(1)))
10939     return SDValue();
10940
10941   // Match against one of the candidate binary ops.
10942   SDValue Op = Extract->getOperand(0);
10943   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10944         return Op.getOpcode() == unsigned(BinOp);
10945       }))
10946     return SDValue();
10947
10948   // Floating-point reductions may require relaxed constraints on the final step
10949   // of the reduction because they may reorder intermediate operations.
10950   unsigned CandidateBinOp = Op.getOpcode();
10951   if (Op.getValueType().isFloatingPoint()) {
10952     SDNodeFlags Flags = Op->getFlags();
10953     switch (CandidateBinOp) {
10954     case ISD::FADD:
10955       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10956         return SDValue();
10957       break;
10958     default:
10959       llvm_unreachable("Unhandled FP opcode for binop reduction");
10960     }
10961   }
10962
10963   // Matching failed - attempt to see if we did enough stages that a partial
10964   // reduction from a subvector is possible.
10965   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10966     if (!AllowPartials || !Op)
10967       return SDValue();
10968     EVT OpVT = Op.getValueType();
10969     EVT OpSVT = OpVT.getScalarType();
10970     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10971     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10972       return SDValue();
10973     BinOp = (ISD::NodeType)CandidateBinOp;
10974     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10975                    getVectorIdxConstant(0, SDLoc(Op)));
10976   };
10977
10978   // At each stage, we're looking for something that looks like:
10979   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10980   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10981   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10982   // %a = binop <8 x i32> %op, %s
10983   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10984   // we expect something like:
10985   // <4,5,6,7,u,u,u,u>
10986   // <2,3,u,u,u,u,u,u>
10987   // <1,u,u,u,u,u,u,u>
10988   // While a partial reduction match would be:
10989   // <2,3,u,u,u,u,u,u>
10990   // <1,u,u,u,u,u,u,u>
10991   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10992   SDValue PrevOp;
10993   for (unsigned i = 0; i < Stages; ++i) {
10994     unsigned MaskEnd = (1 << i);
10995
10996     if (Op.getOpcode() != CandidateBinOp)
10997       return PartialReduction(PrevOp, MaskEnd);
10998
10999     SDValue Op0 = Op.getOperand(0);
11000     SDValue Op1 = Op.getOperand(1);
11001
11002     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
11003     if (Shuffle) {
11004       Op = Op1;
11005     } else {
11006       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
11007       Op = Op0;
11008     }
11009
11010     // The first operand of the shuffle should be the same as the other operand
11011     // of the binop.
11012     if (!Shuffle || Shuffle->getOperand(0) != Op)
11013       return PartialReduction(PrevOp, MaskEnd);
11014
11015     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
11016     for (int Index = 0; Index < (int)MaskEnd; ++Index)
11017       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
11018         return PartialReduction(PrevOp, MaskEnd);
11019
11020     PrevOp = Op;
11021   }
11022
11023   // Handle subvector reductions, which tend to appear after the shuffle
11024   // reduction stages.
11025   while (Op.getOpcode() == CandidateBinOp) {
11026     unsigned NumElts = Op.getValueType().getVectorNumElements();
11027     SDValue Op0 = Op.getOperand(0);
11028     SDValue Op1 = Op.getOperand(1);
11029     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
11030         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
11031         Op0.getOperand(0) != Op1.getOperand(0))
11032       break;
11033     SDValue Src = Op0.getOperand(0);
11034     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
11035     if (NumSrcElts != (2 * NumElts))
11036       break;
11037     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
11038           Op1.getConstantOperandAPInt(1) == NumElts) &&
11039         !(Op1.getConstantOperandAPInt(1) == 0 &&
11040           Op0.getConstantOperandAPInt(1) == NumElts))
11041       break;
11042     Op = Src;
11043   }
11044
11045   BinOp = (ISD::NodeType)CandidateBinOp;
11046   return Op;
11047 }
11048
11049 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
11050   assert(N->getNumValues() == 1 &&
11051          "Can't unroll a vector with multiple results!");
11052
11053   EVT VT = N->getValueType(0);
11054   unsigned NE = VT.getVectorNumElements();
11055   EVT EltVT = VT.getVectorElementType();
11056   SDLoc dl(N);
11057
11058   SmallVector<SDValue, 8> Scalars;
11059   SmallVector<SDValue, 4> Operands(N->getNumOperands());
11060
11061   // If ResNE is 0, fully unroll the vector op.
11062   if (ResNE == 0)
11063     ResNE = NE;
11064   else if (NE > ResNE)
11065     NE = ResNE;
11066
11067   unsigned i;
11068   for (i= 0; i != NE; ++i) {
11069     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
11070       SDValue Operand = N->getOperand(j);
11071       EVT OperandVT = Operand.getValueType();
11072       if (OperandVT.isVector()) {
11073         // A vector operand; extract a single element.
11074         EVT OperandEltVT = OperandVT.getVectorElementType();
11075         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
11076                               Operand, getVectorIdxConstant(i, dl));
11077       } else {
11078         // A scalar operand; just use it as is.
11079         Operands[j] = Operand;
11080       }
11081     }
11082
11083     switch (N->getOpcode()) {
11084     default: {
11085       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
11086                                 N->getFlags()));
11087       break;
11088     }
11089     case ISD::VSELECT:
11090       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
11091       break;
11092     case ISD::SHL:
11093     case ISD::SRA:
11094     case ISD::SRL:
11095     case ISD::ROTL:
11096     case ISD::ROTR:
11097       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11098                                getShiftAmountOperand(Operands[0].getValueType(),
11099                                                      Operands[1])));
11100       break;
11101     case ISD::SIGN_EXTEND_INREG: {
11102       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11103       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11104                                 Operands[0],
11105                                 getValueType(ExtVT)));
11106     }
11107     }
11108   }
11109
11110   for (; i < ResNE; ++i)
11111     Scalars.push_back(getUNDEF(EltVT));
11112
11113   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11114   return getBuildVector(VecVT, dl, Scalars);
11115 }
11116
11117 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11118     SDNode *N, unsigned ResNE) {
11119   unsigned Opcode = N->getOpcode();
11120   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11121           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11122           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11123          "Expected an overflow opcode");
11124
11125   EVT ResVT = N->getValueType(0);
11126   EVT OvVT = N->getValueType(1);
11127   EVT ResEltVT = ResVT.getVectorElementType();
11128   EVT OvEltVT = OvVT.getVectorElementType();
11129   SDLoc dl(N);
11130
11131   // If ResNE is 0, fully unroll the vector op.
11132   unsigned NE = ResVT.getVectorNumElements();
11133   if (ResNE == 0)
11134     ResNE = NE;
11135   else if (NE > ResNE)
11136     NE = ResNE;
11137
11138   SmallVector<SDValue, 8> LHSScalars;
11139   SmallVector<SDValue, 8> RHSScalars;
11140   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11141   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11142
11143   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11144   SDVTList VTs = getVTList(ResEltVT, SVT);
11145   SmallVector<SDValue, 8> ResScalars;
11146   SmallVector<SDValue, 8> OvScalars;
11147   for (unsigned i = 0; i < NE; ++i) {
11148     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11149     SDValue Ov =
11150         getSelect(dl, OvEltVT, Res.getValue(1),
11151                   getBoolConstant(true, dl, OvEltVT, ResVT),
11152                   getConstant(0, dl, OvEltVT));
11153
11154     ResScalars.push_back(Res);
11155     OvScalars.push_back(Ov);
11156   }
11157
11158   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11159   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11160
11161   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11162   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11163   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11164                         getBuildVector(NewOvVT, dl, OvScalars));
11165 }
11166
11167 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11168                                                   LoadSDNode *Base,
11169                                                   unsigned Bytes,
11170                                                   int Dist) const {
11171   if (LD->isVolatile() || Base->isVolatile())
11172     return false;
11173   // TODO: probably too restrictive for atomics, revisit
11174   if (!LD->isSimple())
11175     return false;
11176   if (LD->isIndexed() || Base->isIndexed())
11177     return false;
11178   if (LD->getChain() != Base->getChain())
11179     return false;
11180   EVT VT = LD->getValueType(0);
11181   if (VT.getSizeInBits() / 8 != Bytes)
11182     return false;
11183
11184   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11185   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11186
11187   int64_t Offset = 0;
11188   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11189     return (Dist * Bytes == Offset);
11190   return false;
11191 }
11192
11193 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11194 /// if it cannot be inferred.
11195 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11196   // If this is a GlobalAddress + cst, return the alignment.
11197   const GlobalValue *GV = nullptr;
11198   int64_t GVOffset = 0;
11199   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11200     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11201     KnownBits Known(PtrWidth);
11202     llvm::computeKnownBits(GV, Known, getDataLayout());
11203     unsigned AlignBits = Known.countMinTrailingZeros();
11204     if (AlignBits)
11205       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11206   }
11207
11208   // If this is a direct reference to a stack slot, use information about the
11209   // stack slot's alignment.
11210   int FrameIdx = INT_MIN;
11211   int64_t FrameOffset = 0;
11212   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11213     FrameIdx = FI->getIndex();
11214   } else if (isBaseWithConstantOffset(Ptr) &&
11215              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11216     // Handle FI+Cst
11217     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11218     FrameOffset = Ptr.getConstantOperandVal(1);
11219   }
11220
11221   if (FrameIdx != INT_MIN) {
11222     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11223     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11224   }
11225
11226   return None;
11227 }
11228
11229 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11230 /// which is split (or expanded) into two not necessarily identical pieces.
11231 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11232   // Currently all types are split in half.
11233   EVT LoVT, HiVT;
11234   if (!VT.isVector())
11235     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11236   else
11237     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11238
11239   return std::make_pair(LoVT, HiVT);
11240 }
11241
11242 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11243 /// type, dependent on an enveloping VT that has been split into two identical
11244 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11245 std::pair<EVT, EVT>
11246 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11247                                        bool *HiIsEmpty) const {
11248   EVT EltTp = VT.getVectorElementType();
11249   // Examples:
11250   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11251   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11252   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11253   //   etc.
11254   ElementCount VTNumElts = VT.getVectorElementCount();
11255   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11256   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11257          "Mixing fixed width and scalable vectors when enveloping a type");
11258   EVT LoVT, HiVT;
11259   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11260     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11261     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11262     *HiIsEmpty = false;
11263   } else {
11264     // Flag that hi type has zero storage size, but return split envelop type
11265     // (this would be easier if vector types with zero elements were allowed).
11266     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11267     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11268     *HiIsEmpty = true;
11269   }
11270   return std::make_pair(LoVT, HiVT);
11271 }
11272
11273 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11274 /// low/high part.
11275 std::pair<SDValue, SDValue>
11276 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11277                           const EVT &HiVT) {
11278   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11279          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11280          "Splitting vector with an invalid mixture of fixed and scalable "
11281          "vector types");
11282   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11283              N.getValueType().getVectorMinNumElements() &&
11284          "More vector elements requested than available!");
11285   SDValue Lo, Hi;
11286   Lo =
11287       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11288   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11289   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11290   // IDX with the runtime scaling factor of the result vector type. For
11291   // fixed-width result vectors, that runtime scaling factor is 1.
11292   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11293                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11294   return std::make_pair(Lo, Hi);
11295 }
11296
11297 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11298                                                    const SDLoc &DL) {
11299   // Split the vector length parameter.
11300   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11301   EVT VT = N.getValueType();
11302   assert(VecVT.getVectorElementCount().isKnownEven() &&
11303          "Expecting the mask to be an evenly-sized vector");
11304   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11305   SDValue HalfNumElts =
11306       VecVT.isFixedLengthVector()
11307           ? getConstant(HalfMinNumElts, DL, VT)
11308           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11309   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11310   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11311   return std::make_pair(Lo, Hi);
11312 }
11313
11314 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11315 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11316   EVT VT = N.getValueType();
11317   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11318                                 NextPowerOf2(VT.getVectorNumElements()));
11319   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11320                  getVectorIdxConstant(0, DL));
11321 }
11322
11323 void SelectionDAG::ExtractVectorElements(SDValue Op,
11324                                          SmallVectorImpl<SDValue> &Args,
11325                                          unsigned Start, unsigned Count,
11326                                          EVT EltVT) {
11327   EVT VT = Op.getValueType();
11328   if (Count == 0)
11329     Count = VT.getVectorNumElements();
11330   if (EltVT == EVT())
11331     EltVT = VT.getVectorElementType();
11332   SDLoc SL(Op);
11333   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11334     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11335                            getVectorIdxConstant(i, SL)));
11336   }
11337 }
11338
11339 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11340 unsigned GlobalAddressSDNode::getAddressSpace() const {
11341   return getGlobal()->getType()->getAddressSpace();
11342 }
11343
11344 Type *ConstantPoolSDNode::getType() const {
11345   if (isMachineConstantPoolEntry())
11346     return Val.MachineCPVal->getType();
11347   return Val.ConstVal->getType();
11348 }
11349
11350 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11351                                         unsigned &SplatBitSize,
11352                                         bool &HasAnyUndefs,
11353                                         unsigned MinSplatBits,
11354                                         bool IsBigEndian) const {
11355   EVT VT = getValueType(0);
11356   assert(VT.isVector() && "Expected a vector type");
11357   unsigned VecWidth = VT.getSizeInBits();
11358   if (MinSplatBits > VecWidth)
11359     return false;
11360
11361   // FIXME: The widths are based on this node's type, but build vectors can
11362   // truncate their operands.
11363   SplatValue = APInt(VecWidth, 0);
11364   SplatUndef = APInt(VecWidth, 0);
11365
11366   // Get the bits. Bits with undefined values (when the corresponding element
11367   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11368   // in SplatValue. If any of the values are not constant, give up and return
11369   // false.
11370   unsigned int NumOps = getNumOperands();
11371   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11372   unsigned EltWidth = VT.getScalarSizeInBits();
11373
11374   for (unsigned j = 0; j < NumOps; ++j) {
11375     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11376     SDValue OpVal = getOperand(i);
11377     unsigned BitPos = j * EltWidth;
11378
11379     if (OpVal.isUndef())
11380       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11381     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11382       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11383     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11384       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11385     else
11386       return false;
11387   }
11388
11389   // The build_vector is all constants or undefs. Find the smallest element
11390   // size that splats the vector.
11391   HasAnyUndefs = (SplatUndef != 0);
11392
11393   // FIXME: This does not work for vectors with elements less than 8 bits.
11394   while (VecWidth > 8) {
11395     unsigned HalfSize = VecWidth / 2;
11396     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11397     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11398     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11399     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11400
11401     // If the two halves do not match (ignoring undef bits), stop here.
11402     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11403         MinSplatBits > HalfSize)
11404       break;
11405
11406     SplatValue = HighValue | LowValue;
11407     SplatUndef = HighUndef & LowUndef;
11408
11409     VecWidth = HalfSize;
11410   }
11411
11412   SplatBitSize = VecWidth;
11413   return true;
11414 }
11415
11416 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11417                                          BitVector *UndefElements) const {
11418   unsigned NumOps = getNumOperands();
11419   if (UndefElements) {
11420     UndefElements->clear();
11421     UndefElements->resize(NumOps);
11422   }
11423   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11424   if (!DemandedElts)
11425     return SDValue();
11426   SDValue Splatted;
11427   for (unsigned i = 0; i != NumOps; ++i) {
11428     if (!DemandedElts[i])
11429       continue;
11430     SDValue Op = getOperand(i);
11431     if (Op.isUndef()) {
11432       if (UndefElements)
11433         (*UndefElements)[i] = true;
11434     } else if (!Splatted) {
11435       Splatted = Op;
11436     } else if (Splatted != Op) {
11437       return SDValue();
11438     }
11439   }
11440
11441   if (!Splatted) {
11442     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11443     assert(getOperand(FirstDemandedIdx).isUndef() &&
11444            "Can only have a splat without a constant for all undefs.");
11445     return getOperand(FirstDemandedIdx);
11446   }
11447
11448   return Splatted;
11449 }
11450
11451 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11452   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11453   return getSplatValue(DemandedElts, UndefElements);
11454 }
11455
11456 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11457                                             SmallVectorImpl<SDValue> &Sequence,
11458                                             BitVector *UndefElements) const {
11459   unsigned NumOps = getNumOperands();
11460   Sequence.clear();
11461   if (UndefElements) {
11462     UndefElements->clear();
11463     UndefElements->resize(NumOps);
11464   }
11465   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11466   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11467     return false;
11468
11469   // Set the undefs even if we don't find a sequence (like getSplatValue).
11470   if (UndefElements)
11471     for (unsigned I = 0; I != NumOps; ++I)
11472       if (DemandedElts[I] && getOperand(I).isUndef())
11473         (*UndefElements)[I] = true;
11474
11475   // Iteratively widen the sequence length looking for repetitions.
11476   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11477     Sequence.append(SeqLen, SDValue());
11478     for (unsigned I = 0; I != NumOps; ++I) {
11479       if (!DemandedElts[I])
11480         continue;
11481       SDValue &SeqOp = Sequence[I % SeqLen];
11482       SDValue Op = getOperand(I);
11483       if (Op.isUndef()) {
11484         if (!SeqOp)
11485           SeqOp = Op;
11486         continue;
11487       }
11488       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11489         Sequence.clear();
11490         break;
11491       }
11492       SeqOp = Op;
11493     }
11494     if (!Sequence.empty())
11495       return true;
11496   }
11497
11498   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11499   return false;
11500 }
11501
11502 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11503                                             BitVector *UndefElements) const {
11504   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11505   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11506 }
11507
11508 ConstantSDNode *
11509 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11510                                         BitVector *UndefElements) const {
11511   return dyn_cast_or_null<ConstantSDNode>(
11512       getSplatValue(DemandedElts, UndefElements));
11513 }
11514
11515 ConstantSDNode *
11516 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11517   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11518 }
11519
11520 ConstantFPSDNode *
11521 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11522                                           BitVector *UndefElements) const {
11523   return dyn_cast_or_null<ConstantFPSDNode>(
11524       getSplatValue(DemandedElts, UndefElements));
11525 }
11526
11527 ConstantFPSDNode *
11528 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11529   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11530 }
11531
11532 int32_t
11533 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11534                                                    uint32_t BitWidth) const {
11535   if (ConstantFPSDNode *CN =
11536           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11537     bool IsExact;
11538     APSInt IntVal(BitWidth);
11539     const APFloat &APF = CN->getValueAPF();
11540     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11541             APFloat::opOK ||
11542         !IsExact)
11543       return -1;
11544
11545     return IntVal.exactLogBase2();
11546   }
11547   return -1;
11548 }
11549
11550 bool BuildVectorSDNode::getConstantRawBits(
11551     bool IsLittleEndian, unsigned DstEltSizeInBits,
11552     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11553   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11554   if (!isConstant())
11555     return false;
11556
11557   unsigned NumSrcOps = getNumOperands();
11558   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11559   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11560          "Invalid bitcast scale");
11561
11562   // Extract raw src bits.
11563   SmallVector<APInt> SrcBitElements(NumSrcOps,
11564                                     APInt::getNullValue(SrcEltSizeInBits));
11565   BitVector SrcUndeElements(NumSrcOps, false);
11566
11567   for (unsigned I = 0; I != NumSrcOps; ++I) {
11568     SDValue Op = getOperand(I);
11569     if (Op.isUndef()) {
11570       SrcUndeElements.set(I);
11571       continue;
11572     }
11573     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11574     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11575     assert((CInt || CFP) && "Unknown constant");
11576     SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
11577                              : CFP->getValueAPF().bitcastToAPInt();
11578   }
11579
11580   // Recast to dst width.
11581   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11582                 SrcBitElements, UndefElements, SrcUndeElements);
11583   return true;
11584 }
11585
11586 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11587                                       unsigned DstEltSizeInBits,
11588                                       SmallVectorImpl<APInt> &DstBitElements,
11589                                       ArrayRef<APInt> SrcBitElements,
11590                                       BitVector &DstUndefElements,
11591                                       const BitVector &SrcUndefElements) {
11592   unsigned NumSrcOps = SrcBitElements.size();
11593   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11594   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11595          "Invalid bitcast scale");
11596   assert(NumSrcOps == SrcUndefElements.size() &&
11597          "Vector size mismatch");
11598
11599   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11600   DstUndefElements.clear();
11601   DstUndefElements.resize(NumDstOps, false);
11602   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11603
11604   // Concatenate src elements constant bits together into dst element.
11605   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11606     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11607     for (unsigned I = 0; I != NumDstOps; ++I) {
11608       DstUndefElements.set(I);
11609       APInt &DstBits = DstBitElements[I];
11610       for (unsigned J = 0; J != Scale; ++J) {
11611         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11612         if (SrcUndefElements[Idx])
11613           continue;
11614         DstUndefElements.reset(I);
11615         const APInt &SrcBits = SrcBitElements[Idx];
11616         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11617                "Illegal constant bitwidths");
11618         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11619       }
11620     }
11621     return;
11622   }
11623
11624   // Split src element constant bits into dst elements.
11625   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11626   for (unsigned I = 0; I != NumSrcOps; ++I) {
11627     if (SrcUndefElements[I]) {
11628       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11629       continue;
11630     }
11631     const APInt &SrcBits = SrcBitElements[I];
11632     for (unsigned J = 0; J != Scale; ++J) {
11633       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11634       APInt &DstBits = DstBitElements[Idx];
11635       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11636     }
11637   }
11638 }
11639
11640 bool BuildVectorSDNode::isConstant() const {
11641   for (const SDValue &Op : op_values()) {
11642     unsigned Opc = Op.getOpcode();
11643     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11644       return false;
11645   }
11646   return true;
11647 }
11648
11649 Optional<std::pair<APInt, APInt>>
11650 BuildVectorSDNode::isConstantSequence() const {
11651   unsigned NumOps = getNumOperands();
11652   if (NumOps < 2)
11653     return None;
11654
11655   if (!isa<ConstantSDNode>(getOperand(0)) ||
11656       !isa<ConstantSDNode>(getOperand(1)))
11657     return None;
11658
11659   unsigned EltSize = getValueType(0).getScalarSizeInBits();
11660   APInt Start = getConstantOperandAPInt(0).trunc(EltSize);
11661   APInt Stride = getConstantOperandAPInt(1).trunc(EltSize) - Start;
11662
11663   if (Stride.isZero())
11664     return None;
11665
11666   for (unsigned i = 2; i < NumOps; ++i) {
11667     if (!isa<ConstantSDNode>(getOperand(i)))
11668       return None;
11669
11670     APInt Val = getConstantOperandAPInt(i).trunc(EltSize);
11671     if (Val != (Start + (Stride * i)))
11672       return None;
11673   }
11674
11675   return std::make_pair(Start, Stride);
11676 }
11677
11678 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11679   // Find the first non-undef value in the shuffle mask.
11680   unsigned i, e;
11681   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11682     /* search */;
11683
11684   // If all elements are undefined, this shuffle can be considered a splat
11685   // (although it should eventually get simplified away completely).
11686   if (i == e)
11687     return true;
11688
11689   // Make sure all remaining elements are either undef or the same as the first
11690   // non-undef value.
11691   for (int Idx = Mask[i]; i != e; ++i)
11692     if (Mask[i] >= 0 && Mask[i] != Idx)
11693       return false;
11694   return true;
11695 }
11696
11697 // Returns the SDNode if it is a constant integer BuildVector
11698 // or constant integer.
11699 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11700   if (isa<ConstantSDNode>(N))
11701     return N.getNode();
11702   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11703     return N.getNode();
11704   // Treat a GlobalAddress supporting constant offset folding as a
11705   // constant integer.
11706   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11707     if (GA->getOpcode() == ISD::GlobalAddress &&
11708         TLI->isOffsetFoldingLegal(GA))
11709       return GA;
11710   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11711       isa<ConstantSDNode>(N.getOperand(0)))
11712     return N.getNode();
11713   return nullptr;
11714 }
11715
11716 // Returns the SDNode if it is a constant float BuildVector
11717 // or constant float.
11718 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11719   if (isa<ConstantFPSDNode>(N))
11720     return N.getNode();
11721
11722   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11723     return N.getNode();
11724
11725   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11726       isa<ConstantFPSDNode>(N.getOperand(0)))
11727     return N.getNode();
11728
11729   return nullptr;
11730 }
11731
11732 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11733   assert(!Node->OperandList && "Node already has operands");
11734   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11735          "too many operands to fit into SDNode");
11736   SDUse *Ops = OperandRecycler.allocate(
11737       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11738
11739   bool IsDivergent = false;
11740   for (unsigned I = 0; I != Vals.size(); ++I) {
11741     Ops[I].setUser(Node);
11742     Ops[I].setInitial(Vals[I]);
11743     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11744       IsDivergent |= Ops[I].getNode()->isDivergent();
11745   }
11746   Node->NumOperands = Vals.size();
11747   Node->OperandList = Ops;
11748   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11749     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11750     Node->SDNodeBits.IsDivergent = IsDivergent;
11751   }
11752   checkForCycles(Node);
11753 }
11754
11755 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11756                                      SmallVectorImpl<SDValue> &Vals) {
11757   size_t Limit = SDNode::getMaxNumOperands();
11758   while (Vals.size() > Limit) {
11759     unsigned SliceIdx = Vals.size() - Limit;
11760     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11761     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11762     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11763     Vals.emplace_back(NewTF);
11764   }
11765   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11766 }
11767
11768 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11769                                         EVT VT, SDNodeFlags Flags) {
11770   switch (Opcode) {
11771   default:
11772     return SDValue();
11773   case ISD::ADD:
11774   case ISD::OR:
11775   case ISD::XOR:
11776   case ISD::UMAX:
11777     return getConstant(0, DL, VT);
11778   case ISD::MUL:
11779     return getConstant(1, DL, VT);
11780   case ISD::AND:
11781   case ISD::UMIN:
11782     return getAllOnesConstant(DL, VT);
11783   case ISD::SMAX:
11784     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11785   case ISD::SMIN:
11786     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11787   case ISD::FADD:
11788     return getConstantFP(-0.0, DL, VT);
11789   case ISD::FMUL:
11790     return getConstantFP(1.0, DL, VT);
11791   case ISD::FMINNUM:
11792   case ISD::FMAXNUM: {
11793     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11794     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11795     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11796                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11797                         APFloat::getLargest(Semantics);
11798     if (Opcode == ISD::FMAXNUM)
11799       NeutralAF.changeSign();
11800
11801     return getConstantFP(NeutralAF, DL, VT);
11802   }
11803   }
11804 }
11805
11806 #ifndef NDEBUG
11807 static void checkForCyclesHelper(const SDNode *N,
11808                                  SmallPtrSetImpl<const SDNode*> &Visited,
11809                                  SmallPtrSetImpl<const SDNode*> &Checked,
11810                                  const llvm::SelectionDAG *DAG) {
11811   // If this node has already been checked, don't check it again.
11812   if (Checked.count(N))
11813     return;
11814
11815   // If a node has already been visited on this depth-first walk, reject it as
11816   // a cycle.
11817   if (!Visited.insert(N).second) {
11818     errs() << "Detected cycle in SelectionDAG\n";
11819     dbgs() << "Offending node:\n";
11820     N->dumprFull(DAG); dbgs() << "\n";
11821     abort();
11822   }
11823
11824   for (const SDValue &Op : N->op_values())
11825     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11826
11827   Checked.insert(N);
11828   Visited.erase(N);
11829 }
11830 #endif
11831
11832 void llvm::checkForCycles(const llvm::SDNode *N,
11833                           const llvm::SelectionDAG *DAG,
11834                           bool force) {
11835 #ifndef NDEBUG
11836   bool check = force;
11837 #ifdef EXPENSIVE_CHECKS
11838   check = true;
11839 #endif  // EXPENSIVE_CHECKS
11840   if (check) {
11841     assert(N && "Checking nonexistent SDNode");
11842     SmallPtrSet<const SDNode*, 32> visited;
11843     SmallPtrSet<const SDNode*, 32> checked;
11844     checkForCyclesHelper(N, visited, checked, DAG);
11845   }
11846 #endif  // !NDEBUG
11847 }
11848
11849 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11850   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11851 }