1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/FunctionLoweringInfo.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineBasicBlock.h"
34 #include "llvm/CodeGen/MachineConstantPool.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineMemOperand.h"
38 #include "llvm/CodeGen/RuntimeLibcalls.h"
39 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
40 #include "llvm/CodeGen/SelectionDAGNodes.h"
41 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
42 #include "llvm/CodeGen/TargetFrameLowering.h"
43 #include "llvm/CodeGen/TargetLowering.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Constant.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugInfoMetadata.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CodeGen.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/KnownBits.h"
64 #include "llvm/Support/MachineValueType.h"
65 #include "llvm/Support/ManagedStatic.h"
66 #include "llvm/Support/MathExtras.h"
67 #include "llvm/Support/Mutex.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include "llvm/Target/TargetOptions.h"
71 #include "llvm/Transforms/Utils/SizeOpts.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstdint>
75 #include <cstdlib>
76 #include <limits>
77 #include <set>
78 #include <string>
79 #include <utility>
80 #include <vector>
81 
82 using namespace llvm;
83 
84 /// makeVTList - Return an instance of the SDVTList struct initialized with the
85 /// specified members.
86 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
87   SDVTList Res = {VTs, NumVTs};
88   return Res;
89 }
90 
91 // Default null implementations of the callbacks.
92 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
93 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
94 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
95 
96 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
97 
98 #define DEBUG_TYPE "selectiondag"
99 
100 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
101        cl::Hidden, cl::init(true),
102        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
103 
104 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
105        cl::desc("Number limit for gluing ld/st of memcpy."),
106        cl::Hidden, cl::init(0));
107 
108 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
109   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
110 }
111 
112 //===----------------------------------------------------------------------===//
113 //                              ConstantFPSDNode Class
114 //===----------------------------------------------------------------------===//
115 
116 /// isExactlyValue - We don't rely on operator== working on double values, as
117 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
118 /// As such, this method can be used to do an exact bit-for-bit comparison of
119 /// two floating point values.
120 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
121   return getValueAPF().bitwiseIsEqual(V);
122 }
123 
124 bool ConstantFPSDNode::isValueValidForType(EVT VT,
125                                            const APFloat& Val) {
126   assert(VT.isFloatingPoint() && "Can only convert between FP types");
127 
128   // convert modifies in place, so make a copy.
129   APFloat Val2 = APFloat(Val);
130   bool losesInfo;
131   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
132                       APFloat::rmNearestTiesToEven,
133                       &losesInfo);
134   return !losesInfo;
135 }
136 
137 //===----------------------------------------------------------------------===//
138 //                              ISD Namespace
139 //===----------------------------------------------------------------------===//
140 
141 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
142   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
143     unsigned EltSize =
144         N->getValueType(0).getVectorElementType().getSizeInBits();
145     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
146       SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
147       return true;
148     }
149   }
150 
151   auto *BV = dyn_cast<BuildVectorSDNode>(N);
152   if (!BV)
153     return false;
154 
155   APInt SplatUndef;
156   unsigned SplatBitSize;
157   bool HasUndefs;
158   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
159   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
160                              EltSize) &&
161          EltSize == SplatBitSize;
162 }
163 
164 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
165 // specializations of the more general isConstantSplatVector()?
166 
167 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
168   // Look through a bit convert.
169   while (N->getOpcode() == ISD::BITCAST)
170     N = N->getOperand(0).getNode();
171 
172   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
173 
174   unsigned i = 0, e = N->getNumOperands();
175 
176   // Skip over all of the undef values.
177   while (i != e && N->getOperand(i).isUndef())
178     ++i;
179 
180   // Do not accept an all-undef vector.
181   if (i == e) return false;
182 
183   // Do not accept build_vectors that aren't all constants or which have non-~0
184   // elements. We have to be a bit careful here, as the type of the constant
185   // may not be the same as the type of the vector elements due to type
186   // legalization (the elements are promoted to a legal type for the target and
187   // a vector of a type may be legal when the base element type is not).
188   // We only want to check enough bits to cover the vector elements, because
189   // we care if the resultant vector is all ones, not whether the individual
190   // constants are.
191   SDValue NotZero = N->getOperand(i);
192   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
193   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
194     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
195       return false;
196   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
197     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
198       return false;
199   } else
200     return false;
201 
202   // Okay, we have at least one ~0 value, check to see if the rest match or are
203   // undefs. Even with the above element type twiddling, this should be OK, as
204   // the same type legalization should have applied to all the elements.
205   for (++i; i != e; ++i)
206     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
207       return false;
208   return true;
209 }
210 
211 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
212   // Look through a bit convert.
213   while (N->getOpcode() == ISD::BITCAST)
214     N = N->getOperand(0).getNode();
215 
216   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
217 
218   bool IsAllUndef = true;
219   for (const SDValue &Op : N->op_values()) {
220     if (Op.isUndef())
221       continue;
222     IsAllUndef = false;
223     // Do not accept build_vectors that aren't all constants or which have non-0
224     // elements. We have to be a bit careful here, as the type of the constant
225     // may not be the same as the type of the vector elements due to type
226     // legalization (the elements are promoted to a legal type for the target
227     // and a vector of a type may be legal when the base element type is not).
228     // We only want to check enough bits to cover the vector elements, because
229     // we care if the resultant vector is all zeros, not whether the individual
230     // constants are.
231     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
232     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
233       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
234         return false;
235     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
236       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
237         return false;
238     } else
239       return false;
240   }
241 
242   // Do not accept an all-undef vector.
243   if (IsAllUndef)
244     return false;
245   return true;
246 }
247 
248 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
249   if (N->getOpcode() != ISD::BUILD_VECTOR)
250     return false;
251 
252   for (const SDValue &Op : N->op_values()) {
253     if (Op.isUndef())
254       continue;
255     if (!isa<ConstantSDNode>(Op))
256       return false;
257   }
258   return true;
259 }
260 
261 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
262   if (N->getOpcode() != ISD::BUILD_VECTOR)
263     return false;
264 
265   for (const SDValue &Op : N->op_values()) {
266     if (Op.isUndef())
267       continue;
268     if (!isa<ConstantFPSDNode>(Op))
269       return false;
270   }
271   return true;
272 }
273 
274 bool ISD::allOperandsUndef(const SDNode *N) {
275   // Return false if the node has no operands.
276   // This is "logically inconsistent" with the definition of "all" but
277   // is probably the desired behavior.
278   if (N->getNumOperands() == 0)
279     return false;
280   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
281 }
282 
283 bool ISD::matchUnaryPredicate(SDValue Op,
284                               std::function<bool(ConstantSDNode *)> Match,
285                               bool AllowUndefs) {
286   // FIXME: Add support for scalar UNDEF cases?
287   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
288     return Match(Cst);
289 
290   // FIXME: Add support for vector UNDEF cases?
291   if (ISD::BUILD_VECTOR != Op.getOpcode())
292     return false;
293 
294   EVT SVT = Op.getValueType().getScalarType();
295   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
296     if (AllowUndefs && Op.getOperand(i).isUndef()) {
297       if (!Match(nullptr))
298         return false;
299       continue;
300     }
301 
302     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
303     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
304       return false;
305   }
306   return true;
307 }
308 
309 bool ISD::matchBinaryPredicate(
310     SDValue LHS, SDValue RHS,
311     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
312     bool AllowUndefs, bool AllowTypeMismatch) {
313   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
314     return false;
315 
316   // TODO: Add support for scalar UNDEF cases?
317   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
318     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
319       return Match(LHSCst, RHSCst);
320 
321   // TODO: Add support for vector UNDEF cases?
322   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
323       ISD::BUILD_VECTOR != RHS.getOpcode())
324     return false;
325 
326   EVT SVT = LHS.getValueType().getScalarType();
327   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
328     SDValue LHSOp = LHS.getOperand(i);
329     SDValue RHSOp = RHS.getOperand(i);
330     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
331     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
332     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
333     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
334     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
335       return false;
336     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
337                                LHSOp.getValueType() != RHSOp.getValueType()))
338       return false;
339     if (!Match(LHSCst, RHSCst))
340       return false;
341   }
342   return true;
343 }
344 
345 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
346   switch (VecReduceOpcode) {
347   default:
348     llvm_unreachable("Expected VECREDUCE opcode");
349   case ISD::VECREDUCE_FADD:
350   case ISD::VECREDUCE_SEQ_FADD:
351     return ISD::FADD;
352   case ISD::VECREDUCE_FMUL:
353   case ISD::VECREDUCE_SEQ_FMUL:
354     return ISD::FMUL;
355   case ISD::VECREDUCE_ADD:
356     return ISD::ADD;
357   case ISD::VECREDUCE_MUL:
358     return ISD::MUL;
359   case ISD::VECREDUCE_AND:
360     return ISD::AND;
361   case ISD::VECREDUCE_OR:
362     return ISD::OR;
363   case ISD::VECREDUCE_XOR:
364     return ISD::XOR;
365   case ISD::VECREDUCE_SMAX:
366     return ISD::SMAX;
367   case ISD::VECREDUCE_SMIN:
368     return ISD::SMIN;
369   case ISD::VECREDUCE_UMAX:
370     return ISD::UMAX;
371   case ISD::VECREDUCE_UMIN:
372     return ISD::UMIN;
373   case ISD::VECREDUCE_FMAX:
374     return ISD::FMAXNUM;
375   case ISD::VECREDUCE_FMIN:
376     return ISD::FMINNUM;
377   }
378 }
379 
380 bool ISD::isVPOpcode(unsigned Opcode) {
381   switch (Opcode) {
382   default:
383     return false;
384 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
385   case ISD::SDOPC:                                                             \
386     return true;
387 #include "llvm/IR/VPIntrinsics.def"
388   }
389 }
390 
391 /// The operand position of the vector mask.
392 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
393   switch (Opcode) {
394   default:
395     return None;
396 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...)        \
397   case ISD::SDOPC:                                                             \
398     return MASKPOS;
399 #include "llvm/IR/VPIntrinsics.def"
400   }
401 }
402 
403 /// The operand position of the explicit vector length parameter.
404 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
405   switch (Opcode) {
406   default:
407     return None;
408 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS)     \
409   case ISD::SDOPC:                                                             \
410     return EVLPOS;
411 #include "llvm/IR/VPIntrinsics.def"
412   }
413 }
414 
415 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
416   switch (ExtType) {
417   case ISD::EXTLOAD:
418     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
419   case ISD::SEXTLOAD:
420     return ISD::SIGN_EXTEND;
421   case ISD::ZEXTLOAD:
422     return ISD::ZERO_EXTEND;
423   default:
424     break;
425   }
426 
427   llvm_unreachable("Invalid LoadExtType");
428 }
429 
430 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
431   // To perform this operation, we just need to swap the L and G bits of the
432   // operation.
433   unsigned OldL = (Operation >> 2) & 1;
434   unsigned OldG = (Operation >> 1) & 1;
435   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
436                        (OldL << 1) |       // New G bit
437                        (OldG << 2));       // New L bit.
438 }
439 
440 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
441   unsigned Operation = Op;
442   if (isIntegerLike)
443     Operation ^= 7;   // Flip L, G, E bits, but not U.
444   else
445     Operation ^= 15;  // Flip all of the condition bits.
446 
447   if (Operation > ISD::SETTRUE2)
448     Operation &= ~8;  // Don't let N and U bits get set.
449 
450   return ISD::CondCode(Operation);
451 }
452 
453 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
454   return getSetCCInverseImpl(Op, Type.isInteger());
455 }
456 
457 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
458                                                bool isIntegerLike) {
459   return getSetCCInverseImpl(Op, isIntegerLike);
460 }
461 
462 /// For an integer comparison, return 1 if the comparison is a signed operation
463 /// and 2 if the result is an unsigned comparison. Return zero if the operation
464 /// does not depend on the sign of the input (setne and seteq).
465 static int isSignedOp(ISD::CondCode Opcode) {
466   switch (Opcode) {
467   default: llvm_unreachable("Illegal integer setcc operation!");
468   case ISD::SETEQ:
469   case ISD::SETNE: return 0;
470   case ISD::SETLT:
471   case ISD::SETLE:
472   case ISD::SETGT:
473   case ISD::SETGE: return 1;
474   case ISD::SETULT:
475   case ISD::SETULE:
476   case ISD::SETUGT:
477   case ISD::SETUGE: return 2;
478   }
479 }
480 
481 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
482                                        EVT Type) {
483   bool IsInteger = Type.isInteger();
484   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
485     // Cannot fold a signed integer setcc with an unsigned integer setcc.
486     return ISD::SETCC_INVALID;
487 
488   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
489 
490   // If the N and U bits get set, then the resultant comparison DOES suddenly
491   // care about orderedness, and it is true when ordered.
492   if (Op > ISD::SETTRUE2)
493     Op &= ~16;     // Clear the U bit if the N bit is set.
494 
495   // Canonicalize illegal integer setcc's.
496   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
497     Op = ISD::SETNE;
498 
499   return ISD::CondCode(Op);
500 }
501 
502 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
503                                         EVT Type) {
504   bool IsInteger = Type.isInteger();
505   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
506     // Cannot fold a signed setcc with an unsigned setcc.
507     return ISD::SETCC_INVALID;
508 
509   // Combine all of the condition bits.
510   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
511 
512   // Canonicalize illegal integer setcc's.
513   if (IsInteger) {
514     switch (Result) {
515     default: break;
516     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
517     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
518     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
519     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
520     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
521     }
522   }
523 
524   return Result;
525 }
526 
527 //===----------------------------------------------------------------------===//
528 //                           SDNode Profile Support
529 //===----------------------------------------------------------------------===//
530 
531 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
532 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
533   ID.AddInteger(OpC);
534 }
535 
536 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
537 /// solely with their pointer.
538 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
539   ID.AddPointer(VTList.VTs);
540 }
541 
542 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
543 static void AddNodeIDOperands(FoldingSetNodeID &ID,
544                               ArrayRef<SDValue> Ops) {
545   for (auto& Op : Ops) {
546     ID.AddPointer(Op.getNode());
547     ID.AddInteger(Op.getResNo());
548   }
549 }
550 
551 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
552 static void AddNodeIDOperands(FoldingSetNodeID &ID,
553                               ArrayRef<SDUse> Ops) {
554   for (auto& Op : Ops) {
555     ID.AddPointer(Op.getNode());
556     ID.AddInteger(Op.getResNo());
557   }
558 }
559 
560 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
561                           SDVTList VTList, ArrayRef<SDValue> OpList) {
562   AddNodeIDOpcode(ID, OpC);
563   AddNodeIDValueTypes(ID, VTList);
564   AddNodeIDOperands(ID, OpList);
565 }
566 
567 /// If this is an SDNode with special info, add this info to the NodeID data.
568 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
569   switch (N->getOpcode()) {
570   case ISD::TargetExternalSymbol:
571   case ISD::ExternalSymbol:
572   case ISD::MCSymbol:
573     llvm_unreachable("Should only be used on nodes with operands");
574   default: break;  // Normal nodes don't need extra info.
575   case ISD::TargetConstant:
576   case ISD::Constant: {
577     const ConstantSDNode *C = cast<ConstantSDNode>(N);
578     ID.AddPointer(C->getConstantIntValue());
579     ID.AddBoolean(C->isOpaque());
580     break;
581   }
582   case ISD::TargetConstantFP:
583   case ISD::ConstantFP:
584     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
585     break;
586   case ISD::TargetGlobalAddress:
587   case ISD::GlobalAddress:
588   case ISD::TargetGlobalTLSAddress:
589   case ISD::GlobalTLSAddress: {
590     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
591     ID.AddPointer(GA->getGlobal());
592     ID.AddInteger(GA->getOffset());
593     ID.AddInteger(GA->getTargetFlags());
594     break;
595   }
596   case ISD::BasicBlock:
597     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
598     break;
599   case ISD::Register:
600     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
601     break;
602   case ISD::RegisterMask:
603     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
604     break;
605   case ISD::SRCVALUE:
606     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
607     break;
608   case ISD::FrameIndex:
609   case ISD::TargetFrameIndex:
610     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
611     break;
612   case ISD::LIFETIME_START:
613   case ISD::LIFETIME_END:
614     if (cast<LifetimeSDNode>(N)->hasOffset()) {
615       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
616       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
617     }
618     break;
619   case ISD::PSEUDO_PROBE:
620     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
621     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
622     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
623     break;
624   case ISD::JumpTable:
625   case ISD::TargetJumpTable:
626     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
627     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
628     break;
629   case ISD::ConstantPool:
630   case ISD::TargetConstantPool: {
631     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
632     ID.AddInteger(CP->getAlign().value());
633     ID.AddInteger(CP->getOffset());
634     if (CP->isMachineConstantPoolEntry())
635       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
636     else
637       ID.AddPointer(CP->getConstVal());
638     ID.AddInteger(CP->getTargetFlags());
639     break;
640   }
641   case ISD::TargetIndex: {
642     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
643     ID.AddInteger(TI->getIndex());
644     ID.AddInteger(TI->getOffset());
645     ID.AddInteger(TI->getTargetFlags());
646     break;
647   }
648   case ISD::LOAD: {
649     const LoadSDNode *LD = cast<LoadSDNode>(N);
650     ID.AddInteger(LD->getMemoryVT().getRawBits());
651     ID.AddInteger(LD->getRawSubclassData());
652     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
653     break;
654   }
655   case ISD::STORE: {
656     const StoreSDNode *ST = cast<StoreSDNode>(N);
657     ID.AddInteger(ST->getMemoryVT().getRawBits());
658     ID.AddInteger(ST->getRawSubclassData());
659     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
660     break;
661   }
662   case ISD::MLOAD: {
663     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
664     ID.AddInteger(MLD->getMemoryVT().getRawBits());
665     ID.AddInteger(MLD->getRawSubclassData());
666     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
667     break;
668   }
669   case ISD::MSTORE: {
670     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
671     ID.AddInteger(MST->getMemoryVT().getRawBits());
672     ID.AddInteger(MST->getRawSubclassData());
673     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
674     break;
675   }
676   case ISD::MGATHER: {
677     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
678     ID.AddInteger(MG->getMemoryVT().getRawBits());
679     ID.AddInteger(MG->getRawSubclassData());
680     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
681     break;
682   }
683   case ISD::MSCATTER: {
684     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
685     ID.AddInteger(MS->getMemoryVT().getRawBits());
686     ID.AddInteger(MS->getRawSubclassData());
687     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
688     break;
689   }
690   case ISD::ATOMIC_CMP_SWAP:
691   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
692   case ISD::ATOMIC_SWAP:
693   case ISD::ATOMIC_LOAD_ADD:
694   case ISD::ATOMIC_LOAD_SUB:
695   case ISD::ATOMIC_LOAD_AND:
696   case ISD::ATOMIC_LOAD_CLR:
697   case ISD::ATOMIC_LOAD_OR:
698   case ISD::ATOMIC_LOAD_XOR:
699   case ISD::ATOMIC_LOAD_NAND:
700   case ISD::ATOMIC_LOAD_MIN:
701   case ISD::ATOMIC_LOAD_MAX:
702   case ISD::ATOMIC_LOAD_UMIN:
703   case ISD::ATOMIC_LOAD_UMAX:
704   case ISD::ATOMIC_LOAD:
705   case ISD::ATOMIC_STORE: {
706     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
707     ID.AddInteger(AT->getMemoryVT().getRawBits());
708     ID.AddInteger(AT->getRawSubclassData());
709     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
710     break;
711   }
712   case ISD::PREFETCH: {
713     const MemSDNode *PF = cast<MemSDNode>(N);
714     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
715     break;
716   }
717   case ISD::VECTOR_SHUFFLE: {
718     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
719     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
720          i != e; ++i)
721       ID.AddInteger(SVN->getMaskElt(i));
722     break;
723   }
724   case ISD::TargetBlockAddress:
725   case ISD::BlockAddress: {
726     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
727     ID.AddPointer(BA->getBlockAddress());
728     ID.AddInteger(BA->getOffset());
729     ID.AddInteger(BA->getTargetFlags());
730     break;
731   }
732   } // end switch (N->getOpcode())
733 
734   // Target specific memory nodes could also have address spaces to check.
735   if (N->isTargetMemoryOpcode())
736     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
737 }
738 
739 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
740 /// data.
741 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
742   AddNodeIDOpcode(ID, N->getOpcode());
743   // Add the return value info.
744   AddNodeIDValueTypes(ID, N->getVTList());
745   // Add the operand info.
746   AddNodeIDOperands(ID, N->ops());
747 
748   // Handle SDNode leafs with special info.
749   AddNodeIDCustom(ID, N);
750 }
751 
752 //===----------------------------------------------------------------------===//
753 //                              SelectionDAG Class
754 //===----------------------------------------------------------------------===//
755 
756 /// doNotCSE - Return true if CSE should not be performed for this node.
757 static bool doNotCSE(SDNode *N) {
758   if (N->getValueType(0) == MVT::Glue)
759     return true; // Never CSE anything that produces a flag.
760 
761   switch (N->getOpcode()) {
762   default: break;
763   case ISD::HANDLENODE:
764   case ISD::EH_LABEL:
765     return true;   // Never CSE these nodes.
766   }
767 
768   // Check that remaining values produced are not flags.
769   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
770     if (N->getValueType(i) == MVT::Glue)
771       return true; // Never CSE anything that produces a flag.
772 
773   return false;
774 }
775 
776 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
777 /// SelectionDAG.
778 void SelectionDAG::RemoveDeadNodes() {
779   // Create a dummy node (which is not added to allnodes), that adds a reference
780   // to the root node, preventing it from being deleted.
781   HandleSDNode Dummy(getRoot());
782 
783   SmallVector<SDNode*, 128> DeadNodes;
784 
785   // Add all obviously-dead nodes to the DeadNodes worklist.
786   for (SDNode &Node : allnodes())
787     if (Node.use_empty())
788       DeadNodes.push_back(&Node);
789 
790   RemoveDeadNodes(DeadNodes);
791 
792   // If the root changed (e.g. it was a dead load, update the root).
793   setRoot(Dummy.getValue());
794 }
795 
796 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
797 /// given list, and any nodes that become unreachable as a result.
798 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
799 
800   // Process the worklist, deleting the nodes and adding their uses to the
801   // worklist.
802   while (!DeadNodes.empty()) {
803     SDNode *N = DeadNodes.pop_back_val();
804     // Skip to next node if we've already managed to delete the node. This could
805     // happen if replacing a node causes a node previously added to the node to
806     // be deleted.
807     if (N->getOpcode() == ISD::DELETED_NODE)
808       continue;
809 
810     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
811       DUL->NodeDeleted(N, nullptr);
812 
813     // Take the node out of the appropriate CSE map.
814     RemoveNodeFromCSEMaps(N);
815 
816     // Next, brutally remove the operand list.  This is safe to do, as there are
817     // no cycles in the graph.
818     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
819       SDUse &Use = *I++;
820       SDNode *Operand = Use.getNode();
821       Use.set(SDValue());
822 
823       // Now that we removed this operand, see if there are no uses of it left.
824       if (Operand->use_empty())
825         DeadNodes.push_back(Operand);
826     }
827 
828     DeallocateNode(N);
829   }
830 }
831 
832 void SelectionDAG::RemoveDeadNode(SDNode *N){
833   SmallVector<SDNode*, 16> DeadNodes(1, N);
834 
835   // Create a dummy node that adds a reference to the root node, preventing
836   // it from being deleted.  (This matters if the root is an operand of the
837   // dead node.)
838   HandleSDNode Dummy(getRoot());
839 
840   RemoveDeadNodes(DeadNodes);
841 }
842 
843 void SelectionDAG::DeleteNode(SDNode *N) {
844   // First take this out of the appropriate CSE map.
845   RemoveNodeFromCSEMaps(N);
846 
847   // Finally, remove uses due to operands of this node, remove from the
848   // AllNodes list, and delete the node.
849   DeleteNodeNotInCSEMaps(N);
850 }
851 
852 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
853   assert(N->getIterator() != AllNodes.begin() &&
854          "Cannot delete the entry node!");
855   assert(N->use_empty() && "Cannot delete a node that is not dead!");
856 
857   // Drop all of the operands and decrement used node's use counts.
858   N->DropOperands();
859 
860   DeallocateNode(N);
861 }
862 
863 void SDDbgInfo::erase(const SDNode *Node) {
864   DbgValMapType::iterator I = DbgValMap.find(Node);
865   if (I == DbgValMap.end())
866     return;
867   for (auto &Val: I->second)
868     Val->setIsInvalidated();
869   DbgValMap.erase(I);
870 }
871 
872 void SelectionDAG::DeallocateNode(SDNode *N) {
873   // If we have operands, deallocate them.
874   removeOperands(N);
875 
876   NodeAllocator.Deallocate(AllNodes.remove(N));
877 
878   // Set the opcode to DELETED_NODE to help catch bugs when node
879   // memory is reallocated.
880   // FIXME: There are places in SDag that have grown a dependency on the opcode
881   // value in the released node.
882   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
883   N->NodeType = ISD::DELETED_NODE;
884 
885   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
886   // them and forget about that node.
887   DbgInfo->erase(N);
888 }
889 
890 #ifndef NDEBUG
891 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
892 static void VerifySDNode(SDNode *N) {
893   switch (N->getOpcode()) {
894   default:
895     break;
896   case ISD::BUILD_PAIR: {
897     EVT VT = N->getValueType(0);
898     assert(N->getNumValues() == 1 && "Too many results!");
899     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
900            "Wrong return type!");
901     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
902     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
903            "Mismatched operand types!");
904     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
905            "Wrong operand type!");
906     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
907            "Wrong return type size");
908     break;
909   }
910   case ISD::BUILD_VECTOR: {
911     assert(N->getNumValues() == 1 && "Too many results!");
912     assert(N->getValueType(0).isVector() && "Wrong return type!");
913     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
914            "Wrong number of operands!");
915     EVT EltVT = N->getValueType(0).getVectorElementType();
916     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
917       assert((I->getValueType() == EltVT ||
918              (EltVT.isInteger() && I->getValueType().isInteger() &&
919               EltVT.bitsLE(I->getValueType()))) &&
920             "Wrong operand type!");
921       assert(I->getValueType() == N->getOperand(0).getValueType() &&
922              "Operands must all have the same type");
923     }
924     break;
925   }
926   }
927 }
928 #endif // NDEBUG
929 
930 /// Insert a newly allocated node into the DAG.
931 ///
932 /// Handles insertion into the all nodes list and CSE map, as well as
933 /// verification and other common operations when a new node is allocated.
934 void SelectionDAG::InsertNode(SDNode *N) {
935   AllNodes.push_back(N);
936 #ifndef NDEBUG
937   N->PersistentId = NextPersistentId++;
938   VerifySDNode(N);
939 #endif
940   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
941     DUL->NodeInserted(N);
942 }
943 
944 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
945 /// correspond to it.  This is useful when we're about to delete or repurpose
946 /// the node.  We don't want future request for structurally identical nodes
947 /// to return N anymore.
948 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
949   bool Erased = false;
950   switch (N->getOpcode()) {
951   case ISD::HANDLENODE: return false;  // noop.
952   case ISD::CONDCODE:
953     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
954            "Cond code doesn't exist!");
955     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
956     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
957     break;
958   case ISD::ExternalSymbol:
959     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
960     break;
961   case ISD::TargetExternalSymbol: {
962     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
963     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
964         ESN->getSymbol(), ESN->getTargetFlags()));
965     break;
966   }
967   case ISD::MCSymbol: {
968     auto *MCSN = cast<MCSymbolSDNode>(N);
969     Erased = MCSymbols.erase(MCSN->getMCSymbol());
970     break;
971   }
972   case ISD::VALUETYPE: {
973     EVT VT = cast<VTSDNode>(N)->getVT();
974     if (VT.isExtended()) {
975       Erased = ExtendedValueTypeNodes.erase(VT);
976     } else {
977       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
978       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
979     }
980     break;
981   }
982   default:
983     // Remove it from the CSE Map.
984     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
985     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
986     Erased = CSEMap.RemoveNode(N);
987     break;
988   }
989 #ifndef NDEBUG
990   // Verify that the node was actually in one of the CSE maps, unless it has a
991   // flag result (which cannot be CSE'd) or is one of the special cases that are
992   // not subject to CSE.
993   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
994       !N->isMachineOpcode() && !doNotCSE(N)) {
995     N->dump(this);
996     dbgs() << "\n";
997     llvm_unreachable("Node is not in map!");
998   }
999 #endif
1000   return Erased;
1001 }
1002 
1003 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1004 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1005 /// node already exists, in which case transfer all its users to the existing
1006 /// node. This transfer can potentially trigger recursive merging.
1007 void
1008 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1009   // For node types that aren't CSE'd, just act as if no identical node
1010   // already exists.
1011   if (!doNotCSE(N)) {
1012     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1013     if (Existing != N) {
1014       // If there was already an existing matching node, use ReplaceAllUsesWith
1015       // to replace the dead one with the existing one.  This can cause
1016       // recursive merging of other unrelated nodes down the line.
1017       ReplaceAllUsesWith(N, Existing);
1018 
1019       // N is now dead. Inform the listeners and delete it.
1020       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1021         DUL->NodeDeleted(N, Existing);
1022       DeleteNodeNotInCSEMaps(N);
1023       return;
1024     }
1025   }
1026 
1027   // If the node doesn't already exist, we updated it.  Inform listeners.
1028   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1029     DUL->NodeUpdated(N);
1030 }
1031 
1032 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1033 /// were replaced with those specified.  If this node is never memoized,
1034 /// return null, otherwise return a pointer to the slot it would take.  If a
1035 /// node already exists with these operands, the slot will be non-null.
1036 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1037                                            void *&InsertPos) {
1038   if (doNotCSE(N))
1039     return nullptr;
1040 
1041   SDValue Ops[] = { Op };
1042   FoldingSetNodeID ID;
1043   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1044   AddNodeIDCustom(ID, N);
1045   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1046   if (Node)
1047     Node->intersectFlagsWith(N->getFlags());
1048   return Node;
1049 }
1050 
1051 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1052 /// were replaced with those specified.  If this node is never memoized,
1053 /// return null, otherwise return a pointer to the slot it would take.  If a
1054 /// node already exists with these operands, the slot will be non-null.
1055 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1056                                            SDValue Op1, SDValue Op2,
1057                                            void *&InsertPos) {
1058   if (doNotCSE(N))
1059     return nullptr;
1060 
1061   SDValue Ops[] = { Op1, Op2 };
1062   FoldingSetNodeID ID;
1063   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1064   AddNodeIDCustom(ID, N);
1065   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1066   if (Node)
1067     Node->intersectFlagsWith(N->getFlags());
1068   return Node;
1069 }
1070 
1071 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1072 /// were replaced with those specified.  If this node is never memoized,
1073 /// return null, otherwise return a pointer to the slot it would take.  If a
1074 /// node already exists with these operands, the slot will be non-null.
1075 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1076                                            void *&InsertPos) {
1077   if (doNotCSE(N))
1078     return nullptr;
1079 
1080   FoldingSetNodeID ID;
1081   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1082   AddNodeIDCustom(ID, N);
1083   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1084   if (Node)
1085     Node->intersectFlagsWith(N->getFlags());
1086   return Node;
1087 }
1088 
1089 Align SelectionDAG::getEVTAlign(EVT VT) const {
1090   Type *Ty = VT == MVT::iPTR ?
1091                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1092                    VT.getTypeForEVT(*getContext());
1093 
1094   return getDataLayout().getABITypeAlign(Ty);
1095 }
1096 
1097 // EntryNode could meaningfully have debug info if we can find it...
1098 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1099     : TM(tm), OptLevel(OL),
1100       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1101       Root(getEntryNode()) {
1102   InsertNode(&EntryNode);
1103   DbgInfo = new SDDbgInfo();
1104 }
1105 
1106 void SelectionDAG::init(MachineFunction &NewMF,
1107                         OptimizationRemarkEmitter &NewORE,
1108                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1109                         LegacyDivergenceAnalysis * Divergence,
1110                         ProfileSummaryInfo *PSIin,
1111                         BlockFrequencyInfo *BFIin) {
1112   MF = &NewMF;
1113   SDAGISelPass = PassPtr;
1114   ORE = &NewORE;
1115   TLI = getSubtarget().getTargetLowering();
1116   TSI = getSubtarget().getSelectionDAGInfo();
1117   LibInfo = LibraryInfo;
1118   Context = &MF->getFunction().getContext();
1119   DA = Divergence;
1120   PSI = PSIin;
1121   BFI = BFIin;
1122 }
1123 
1124 SelectionDAG::~SelectionDAG() {
1125   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1126   allnodes_clear();
1127   OperandRecycler.clear(OperandAllocator);
1128   delete DbgInfo;
1129 }
1130 
1131 bool SelectionDAG::shouldOptForSize() const {
1132   return MF->getFunction().hasOptSize() ||
1133       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1134 }
1135 
1136 void SelectionDAG::allnodes_clear() {
1137   assert(&*AllNodes.begin() == &EntryNode);
1138   AllNodes.remove(AllNodes.begin());
1139   while (!AllNodes.empty())
1140     DeallocateNode(&AllNodes.front());
1141 #ifndef NDEBUG
1142   NextPersistentId = 0;
1143 #endif
1144 }
1145 
1146 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1147                                           void *&InsertPos) {
1148   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1149   if (N) {
1150     switch (N->getOpcode()) {
1151     default: break;
1152     case ISD::Constant:
1153     case ISD::ConstantFP:
1154       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1155                        "debug location.  Use another overload.");
1156     }
1157   }
1158   return N;
1159 }
1160 
1161 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1162                                           const SDLoc &DL, void *&InsertPos) {
1163   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1164   if (N) {
1165     switch (N->getOpcode()) {
1166     case ISD::Constant:
1167     case ISD::ConstantFP:
1168       // Erase debug location from the node if the node is used at several
1169       // different places. Do not propagate one location to all uses as it
1170       // will cause a worse single stepping debugging experience.
1171       if (N->getDebugLoc() != DL.getDebugLoc())
1172         N->setDebugLoc(DebugLoc());
1173       break;
1174     default:
1175       // When the node's point of use is located earlier in the instruction
1176       // sequence than its prior point of use, update its debug info to the
1177       // earlier location.
1178       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1179         N->setDebugLoc(DL.getDebugLoc());
1180       break;
1181     }
1182   }
1183   return N;
1184 }
1185 
1186 void SelectionDAG::clear() {
1187   allnodes_clear();
1188   OperandRecycler.clear(OperandAllocator);
1189   OperandAllocator.Reset();
1190   CSEMap.clear();
1191 
1192   ExtendedValueTypeNodes.clear();
1193   ExternalSymbols.clear();
1194   TargetExternalSymbols.clear();
1195   MCSymbols.clear();
1196   SDCallSiteDbgInfo.clear();
1197   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1198             static_cast<CondCodeSDNode*>(nullptr));
1199   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1200             static_cast<SDNode*>(nullptr));
1201 
1202   EntryNode.UseList = nullptr;
1203   InsertNode(&EntryNode);
1204   Root = getEntryNode();
1205   DbgInfo->clear();
1206 }
1207 
1208 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1209   return VT.bitsGT(Op.getValueType())
1210              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1211              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1212 }
1213 
1214 std::pair<SDValue, SDValue>
1215 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1216                                        const SDLoc &DL, EVT VT) {
1217   assert(!VT.bitsEq(Op.getValueType()) &&
1218          "Strict no-op FP extend/round not allowed.");
1219   SDValue Res =
1220       VT.bitsGT(Op.getValueType())
1221           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1222           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1223                     {Chain, Op, getIntPtrConstant(0, DL)});
1224 
1225   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1226 }
1227 
1228 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1229   return VT.bitsGT(Op.getValueType()) ?
1230     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1231     getNode(ISD::TRUNCATE, DL, VT, Op);
1232 }
1233 
1234 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1235   return VT.bitsGT(Op.getValueType()) ?
1236     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1237     getNode(ISD::TRUNCATE, DL, VT, Op);
1238 }
1239 
1240 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1241   return VT.bitsGT(Op.getValueType()) ?
1242     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1243     getNode(ISD::TRUNCATE, DL, VT, Op);
1244 }
1245 
1246 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1247                                         EVT OpVT) {
1248   if (VT.bitsLE(Op.getValueType()))
1249     return getNode(ISD::TRUNCATE, SL, VT, Op);
1250 
1251   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1252   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1253 }
1254 
1255 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1256   EVT OpVT = Op.getValueType();
1257   assert(VT.isInteger() && OpVT.isInteger() &&
1258          "Cannot getZeroExtendInReg FP types");
1259   assert(VT.isVector() == OpVT.isVector() &&
1260          "getZeroExtendInReg type should be vector iff the operand "
1261          "type is vector!");
1262   assert((!VT.isVector() ||
1263           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1264          "Vector element counts must match in getZeroExtendInReg");
1265   assert(VT.bitsLE(OpVT) && "Not extending!");
1266   if (OpVT == VT)
1267     return Op;
1268   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1269                                    VT.getScalarSizeInBits());
1270   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1271 }
1272 
1273 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1274   // Only unsigned pointer semantics are supported right now. In the future this
1275   // might delegate to TLI to check pointer signedness.
1276   return getZExtOrTrunc(Op, DL, VT);
1277 }
1278 
1279 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1280   // Only unsigned pointer semantics are supported right now. In the future this
1281   // might delegate to TLI to check pointer signedness.
1282   return getZeroExtendInReg(Op, DL, VT);
1283 }
1284 
1285 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1286 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1287   EVT EltVT = VT.getScalarType();
1288   SDValue NegOne =
1289     getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1290   return getNode(ISD::XOR, DL, VT, Val, NegOne);
1291 }
1292 
1293 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1294   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1295   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1296 }
1297 
1298 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1299                                       EVT OpVT) {
1300   if (!V)
1301     return getConstant(0, DL, VT);
1302 
1303   switch (TLI->getBooleanContents(OpVT)) {
1304   case TargetLowering::ZeroOrOneBooleanContent:
1305   case TargetLowering::UndefinedBooleanContent:
1306     return getConstant(1, DL, VT);
1307   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1308     return getAllOnesConstant(DL, VT);
1309   }
1310   llvm_unreachable("Unexpected boolean content enum!");
1311 }
1312 
1313 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1314                                   bool isT, bool isO) {
1315   EVT EltVT = VT.getScalarType();
1316   assert((EltVT.getSizeInBits() >= 64 ||
1317           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1318          "getConstant with a uint64_t value that doesn't fit in the type!");
1319   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1320 }
1321 
1322 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1323                                   bool isT, bool isO) {
1324   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1325 }
1326 
1327 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1328                                   EVT VT, bool isT, bool isO) {
1329   assert(VT.isInteger() && "Cannot create FP integer constant!");
1330 
1331   EVT EltVT = VT.getScalarType();
1332   const ConstantInt *Elt = &Val;
1333 
1334   // In some cases the vector type is legal but the element type is illegal and
1335   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1336   // inserted value (the type does not need to match the vector element type).
1337   // Any extra bits introduced will be truncated away.
1338   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1339                            TargetLowering::TypePromoteInteger) {
1340     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1341     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1342     Elt = ConstantInt::get(*getContext(), NewVal);
1343   }
1344   // In other cases the element type is illegal and needs to be expanded, for
1345   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1346   // the value into n parts and use a vector type with n-times the elements.
1347   // Then bitcast to the type requested.
1348   // Legalizing constants too early makes the DAGCombiner's job harder so we
1349   // only legalize if the DAG tells us we must produce legal types.
1350   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1351            TLI->getTypeAction(*getContext(), EltVT) ==
1352                TargetLowering::TypeExpandInteger) {
1353     const APInt &NewVal = Elt->getValue();
1354     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1355     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1356     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1357     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1358 
1359     // Check the temporary vector is the correct size. If this fails then
1360     // getTypeToTransformTo() probably returned a type whose size (in bits)
1361     // isn't a power-of-2 factor of the requested type size.
1362     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1363 
1364     SmallVector<SDValue, 2> EltParts;
1365     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1366       EltParts.push_back(getConstant(
1367           NewVal.lshr(i * ViaEltSizeInBits).zextOrTrunc(ViaEltSizeInBits), DL,
1368           ViaEltVT, isT, isO));
1369     }
1370 
1371     // EltParts is currently in little endian order. If we actually want
1372     // big-endian order then reverse it now.
1373     if (getDataLayout().isBigEndian())
1374       std::reverse(EltParts.begin(), EltParts.end());
1375 
1376     // The elements must be reversed when the element order is different
1377     // to the endianness of the elements (because the BITCAST is itself a
1378     // vector shuffle in this situation). However, we do not need any code to
1379     // perform this reversal because getConstant() is producing a vector
1380     // splat.
1381     // This situation occurs in MIPS MSA.
1382 
1383     SmallVector<SDValue, 8> Ops;
1384     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1385       llvm::append_range(Ops, EltParts);
1386 
1387     SDValue V =
1388         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1389     return V;
1390   }
1391 
1392   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1393          "APInt size does not match type size!");
1394   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1395   FoldingSetNodeID ID;
1396   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1397   ID.AddPointer(Elt);
1398   ID.AddBoolean(isO);
1399   void *IP = nullptr;
1400   SDNode *N = nullptr;
1401   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1402     if (!VT.isVector())
1403       return SDValue(N, 0);
1404 
1405   if (!N) {
1406     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1407     CSEMap.InsertNode(N, IP);
1408     InsertNode(N);
1409     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1410   }
1411 
1412   SDValue Result(N, 0);
1413   if (VT.isScalableVector())
1414     Result = getSplatVector(VT, DL, Result);
1415   else if (VT.isVector())
1416     Result = getSplatBuildVector(VT, DL, Result);
1417 
1418   return Result;
1419 }
1420 
1421 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1422                                         bool isTarget) {
1423   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1424 }
1425 
1426 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1427                                              const SDLoc &DL, bool LegalTypes) {
1428   assert(VT.isInteger() && "Shift amount is not an integer type!");
1429   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1430   return getConstant(Val, DL, ShiftVT);
1431 }
1432 
1433 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1434                                            bool isTarget) {
1435   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1436 }
1437 
1438 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1439                                     bool isTarget) {
1440   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1441 }
1442 
1443 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1444                                     EVT VT, bool isTarget) {
1445   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1446 
1447   EVT EltVT = VT.getScalarType();
1448 
1449   // Do the map lookup using the actual bit pattern for the floating point
1450   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1451   // we don't have issues with SNANs.
1452   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1453   FoldingSetNodeID ID;
1454   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1455   ID.AddPointer(&V);
1456   void *IP = nullptr;
1457   SDNode *N = nullptr;
1458   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1459     if (!VT.isVector())
1460       return SDValue(N, 0);
1461 
1462   if (!N) {
1463     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1464     CSEMap.InsertNode(N, IP);
1465     InsertNode(N);
1466   }
1467 
1468   SDValue Result(N, 0);
1469   if (VT.isScalableVector())
1470     Result = getSplatVector(VT, DL, Result);
1471   else if (VT.isVector())
1472     Result = getSplatBuildVector(VT, DL, Result);
1473   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1474   return Result;
1475 }
1476 
1477 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1478                                     bool isTarget) {
1479   EVT EltVT = VT.getScalarType();
1480   if (EltVT == MVT::f32)
1481     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1482   else if (EltVT == MVT::f64)
1483     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1484   else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1485            EltVT == MVT::f16 || EltVT == MVT::bf16) {
1486     bool Ignored;
1487     APFloat APF = APFloat(Val);
1488     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1489                 &Ignored);
1490     return getConstantFP(APF, DL, VT, isTarget);
1491   } else
1492     llvm_unreachable("Unsupported type in getConstantFP");
1493 }
1494 
1495 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1496                                        EVT VT, int64_t Offset, bool isTargetGA,
1497                                        unsigned TargetFlags) {
1498   assert((TargetFlags == 0 || isTargetGA) &&
1499          "Cannot set target flags on target-independent globals");
1500 
1501   // Truncate (with sign-extension) the offset value to the pointer size.
1502   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1503   if (BitWidth < 64)
1504     Offset = SignExtend64(Offset, BitWidth);
1505 
1506   unsigned Opc;
1507   if (GV->isThreadLocal())
1508     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1509   else
1510     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1511 
1512   FoldingSetNodeID ID;
1513   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1514   ID.AddPointer(GV);
1515   ID.AddInteger(Offset);
1516   ID.AddInteger(TargetFlags);
1517   void *IP = nullptr;
1518   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1519     return SDValue(E, 0);
1520 
1521   auto *N = newSDNode<GlobalAddressSDNode>(
1522       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1523   CSEMap.InsertNode(N, IP);
1524     InsertNode(N);
1525   return SDValue(N, 0);
1526 }
1527 
1528 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1529   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1530   FoldingSetNodeID ID;
1531   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1532   ID.AddInteger(FI);
1533   void *IP = nullptr;
1534   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1535     return SDValue(E, 0);
1536 
1537   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1538   CSEMap.InsertNode(N, IP);
1539   InsertNode(N);
1540   return SDValue(N, 0);
1541 }
1542 
1543 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1544                                    unsigned TargetFlags) {
1545   assert((TargetFlags == 0 || isTarget) &&
1546          "Cannot set target flags on target-independent jump tables");
1547   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1548   FoldingSetNodeID ID;
1549   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1550   ID.AddInteger(JTI);
1551   ID.AddInteger(TargetFlags);
1552   void *IP = nullptr;
1553   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1554     return SDValue(E, 0);
1555 
1556   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1557   CSEMap.InsertNode(N, IP);
1558   InsertNode(N);
1559   return SDValue(N, 0);
1560 }
1561 
1562 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1563                                       MaybeAlign Alignment, int Offset,
1564                                       bool isTarget, unsigned TargetFlags) {
1565   assert((TargetFlags == 0 || isTarget) &&
1566          "Cannot set target flags on target-independent globals");
1567   if (!Alignment)
1568     Alignment = shouldOptForSize()
1569                     ? getDataLayout().getABITypeAlign(C->getType())
1570                     : getDataLayout().getPrefTypeAlign(C->getType());
1571   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1572   FoldingSetNodeID ID;
1573   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1574   ID.AddInteger(Alignment->value());
1575   ID.AddInteger(Offset);
1576   ID.AddPointer(C);
1577   ID.AddInteger(TargetFlags);
1578   void *IP = nullptr;
1579   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1580     return SDValue(E, 0);
1581 
1582   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1583                                           TargetFlags);
1584   CSEMap.InsertNode(N, IP);
1585   InsertNode(N);
1586   SDValue V = SDValue(N, 0);
1587   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1588   return V;
1589 }
1590 
1591 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1592                                       MaybeAlign Alignment, int Offset,
1593                                       bool isTarget, unsigned TargetFlags) {
1594   assert((TargetFlags == 0 || isTarget) &&
1595          "Cannot set target flags on target-independent globals");
1596   if (!Alignment)
1597     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1598   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1599   FoldingSetNodeID ID;
1600   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1601   ID.AddInteger(Alignment->value());
1602   ID.AddInteger(Offset);
1603   C->addSelectionDAGCSEId(ID);
1604   ID.AddInteger(TargetFlags);
1605   void *IP = nullptr;
1606   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1607     return SDValue(E, 0);
1608 
1609   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1610                                           TargetFlags);
1611   CSEMap.InsertNode(N, IP);
1612   InsertNode(N);
1613   return SDValue(N, 0);
1614 }
1615 
1616 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1617                                      unsigned TargetFlags) {
1618   FoldingSetNodeID ID;
1619   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1620   ID.AddInteger(Index);
1621   ID.AddInteger(Offset);
1622   ID.AddInteger(TargetFlags);
1623   void *IP = nullptr;
1624   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1625     return SDValue(E, 0);
1626 
1627   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1628   CSEMap.InsertNode(N, IP);
1629   InsertNode(N);
1630   return SDValue(N, 0);
1631 }
1632 
1633 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1634   FoldingSetNodeID ID;
1635   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1636   ID.AddPointer(MBB);
1637   void *IP = nullptr;
1638   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1639     return SDValue(E, 0);
1640 
1641   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1642   CSEMap.InsertNode(N, IP);
1643   InsertNode(N);
1644   return SDValue(N, 0);
1645 }
1646 
1647 SDValue SelectionDAG::getValueType(EVT VT) {
1648   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1649       ValueTypeNodes.size())
1650     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1651 
1652   SDNode *&N = VT.isExtended() ?
1653     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1654 
1655   if (N) return SDValue(N, 0);
1656   N = newSDNode<VTSDNode>(VT);
1657   InsertNode(N);
1658   return SDValue(N, 0);
1659 }
1660 
1661 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1662   SDNode *&N = ExternalSymbols[Sym];
1663   if (N) return SDValue(N, 0);
1664   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1665   InsertNode(N);
1666   return SDValue(N, 0);
1667 }
1668 
1669 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1670   SDNode *&N = MCSymbols[Sym];
1671   if (N)
1672     return SDValue(N, 0);
1673   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1674   InsertNode(N);
1675   return SDValue(N, 0);
1676 }
1677 
1678 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1679                                               unsigned TargetFlags) {
1680   SDNode *&N =
1681       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1682   if (N) return SDValue(N, 0);
1683   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1684   InsertNode(N);
1685   return SDValue(N, 0);
1686 }
1687 
1688 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1689   if ((unsigned)Cond >= CondCodeNodes.size())
1690     CondCodeNodes.resize(Cond+1);
1691 
1692   if (!CondCodeNodes[Cond]) {
1693     auto *N = newSDNode<CondCodeSDNode>(Cond);
1694     CondCodeNodes[Cond] = N;
1695     InsertNode(N);
1696   }
1697 
1698   return SDValue(CondCodeNodes[Cond], 0);
1699 }
1700 
1701 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1702 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1703 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1704   std::swap(N1, N2);
1705   ShuffleVectorSDNode::commuteMask(M);
1706 }
1707 
1708 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1709                                        SDValue N2, ArrayRef<int> Mask) {
1710   assert(VT.getVectorNumElements() == Mask.size() &&
1711            "Must have the same number of vector elements as mask elements!");
1712   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1713          "Invalid VECTOR_SHUFFLE");
1714 
1715   // Canonicalize shuffle undef, undef -> undef
1716   if (N1.isUndef() && N2.isUndef())
1717     return getUNDEF(VT);
1718 
1719   // Validate that all indices in Mask are within the range of the elements
1720   // input to the shuffle.
1721   int NElts = Mask.size();
1722   assert(llvm::all_of(Mask,
1723                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1724          "Index out of range");
1725 
1726   // Copy the mask so we can do any needed cleanup.
1727   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1728 
1729   // Canonicalize shuffle v, v -> v, undef
1730   if (N1 == N2) {
1731     N2 = getUNDEF(VT);
1732     for (int i = 0; i != NElts; ++i)
1733       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1734   }
1735 
1736   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1737   if (N1.isUndef())
1738     commuteShuffle(N1, N2, MaskVec);
1739 
1740   if (TLI->hasVectorBlend()) {
1741     // If shuffling a splat, try to blend the splat instead. We do this here so
1742     // that even when this arises during lowering we don't have to re-handle it.
1743     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1744       BitVector UndefElements;
1745       SDValue Splat = BV->getSplatValue(&UndefElements);
1746       if (!Splat)
1747         return;
1748 
1749       for (int i = 0; i < NElts; ++i) {
1750         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1751           continue;
1752 
1753         // If this input comes from undef, mark it as such.
1754         if (UndefElements[MaskVec[i] - Offset]) {
1755           MaskVec[i] = -1;
1756           continue;
1757         }
1758 
1759         // If we can blend a non-undef lane, use that instead.
1760         if (!UndefElements[i])
1761           MaskVec[i] = i + Offset;
1762       }
1763     };
1764     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1765       BlendSplat(N1BV, 0);
1766     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1767       BlendSplat(N2BV, NElts);
1768   }
1769 
1770   // Canonicalize all index into lhs, -> shuffle lhs, undef
1771   // Canonicalize all index into rhs, -> shuffle rhs, undef
1772   bool AllLHS = true, AllRHS = true;
1773   bool N2Undef = N2.isUndef();
1774   for (int i = 0; i != NElts; ++i) {
1775     if (MaskVec[i] >= NElts) {
1776       if (N2Undef)
1777         MaskVec[i] = -1;
1778       else
1779         AllLHS = false;
1780     } else if (MaskVec[i] >= 0) {
1781       AllRHS = false;
1782     }
1783   }
1784   if (AllLHS && AllRHS)
1785     return getUNDEF(VT);
1786   if (AllLHS && !N2Undef)
1787     N2 = getUNDEF(VT);
1788   if (AllRHS) {
1789     N1 = getUNDEF(VT);
1790     commuteShuffle(N1, N2, MaskVec);
1791   }
1792   // Reset our undef status after accounting for the mask.
1793   N2Undef = N2.isUndef();
1794   // Re-check whether both sides ended up undef.
1795   if (N1.isUndef() && N2Undef)
1796     return getUNDEF(VT);
1797 
1798   // If Identity shuffle return that node.
1799   bool Identity = true, AllSame = true;
1800   for (int i = 0; i != NElts; ++i) {
1801     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1802     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1803   }
1804   if (Identity && NElts)
1805     return N1;
1806 
1807   // Shuffling a constant splat doesn't change the result.
1808   if (N2Undef) {
1809     SDValue V = N1;
1810 
1811     // Look through any bitcasts. We check that these don't change the number
1812     // (and size) of elements and just changes their types.
1813     while (V.getOpcode() == ISD::BITCAST)
1814       V = V->getOperand(0);
1815 
1816     // A splat should always show up as a build vector node.
1817     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1818       BitVector UndefElements;
1819       SDValue Splat = BV->getSplatValue(&UndefElements);
1820       // If this is a splat of an undef, shuffling it is also undef.
1821       if (Splat && Splat.isUndef())
1822         return getUNDEF(VT);
1823 
1824       bool SameNumElts =
1825           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1826 
1827       // We only have a splat which can skip shuffles if there is a splatted
1828       // value and no undef lanes rearranged by the shuffle.
1829       if (Splat && UndefElements.none()) {
1830         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1831         // number of elements match or the value splatted is a zero constant.
1832         if (SameNumElts)
1833           return N1;
1834         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1835           if (C->isNullValue())
1836             return N1;
1837       }
1838 
1839       // If the shuffle itself creates a splat, build the vector directly.
1840       if (AllSame && SameNumElts) {
1841         EVT BuildVT = BV->getValueType(0);
1842         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1843         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1844 
1845         // We may have jumped through bitcasts, so the type of the
1846         // BUILD_VECTOR may not match the type of the shuffle.
1847         if (BuildVT != VT)
1848           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1849         return NewBV;
1850       }
1851     }
1852   }
1853 
1854   FoldingSetNodeID ID;
1855   SDValue Ops[2] = { N1, N2 };
1856   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1857   for (int i = 0; i != NElts; ++i)
1858     ID.AddInteger(MaskVec[i]);
1859 
1860   void* IP = nullptr;
1861   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1862     return SDValue(E, 0);
1863 
1864   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1865   // SDNode doesn't have access to it.  This memory will be "leaked" when
1866   // the node is deallocated, but recovered when the NodeAllocator is released.
1867   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1868   llvm::copy(MaskVec, MaskAlloc);
1869 
1870   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1871                                            dl.getDebugLoc(), MaskAlloc);
1872   createOperands(N, Ops);
1873 
1874   CSEMap.InsertNode(N, IP);
1875   InsertNode(N);
1876   SDValue V = SDValue(N, 0);
1877   NewSDValueDbgMsg(V, "Creating new node: ", this);
1878   return V;
1879 }
1880 
1881 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1882   EVT VT = SV.getValueType(0);
1883   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1884   ShuffleVectorSDNode::commuteMask(MaskVec);
1885 
1886   SDValue Op0 = SV.getOperand(0);
1887   SDValue Op1 = SV.getOperand(1);
1888   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1889 }
1890 
1891 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1892   FoldingSetNodeID ID;
1893   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1894   ID.AddInteger(RegNo);
1895   void *IP = nullptr;
1896   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1897     return SDValue(E, 0);
1898 
1899   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1900   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1901   CSEMap.InsertNode(N, IP);
1902   InsertNode(N);
1903   return SDValue(N, 0);
1904 }
1905 
1906 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1907   FoldingSetNodeID ID;
1908   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1909   ID.AddPointer(RegMask);
1910   void *IP = nullptr;
1911   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1912     return SDValue(E, 0);
1913 
1914   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1915   CSEMap.InsertNode(N, IP);
1916   InsertNode(N);
1917   return SDValue(N, 0);
1918 }
1919 
1920 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1921                                  MCSymbol *Label) {
1922   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1923 }
1924 
1925 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1926                                    SDValue Root, MCSymbol *Label) {
1927   FoldingSetNodeID ID;
1928   SDValue Ops[] = { Root };
1929   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1930   ID.AddPointer(Label);
1931   void *IP = nullptr;
1932   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1933     return SDValue(E, 0);
1934 
1935   auto *N =
1936       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
1937   createOperands(N, Ops);
1938 
1939   CSEMap.InsertNode(N, IP);
1940   InsertNode(N);
1941   return SDValue(N, 0);
1942 }
1943 
1944 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1945                                       int64_t Offset, bool isTarget,
1946                                       unsigned TargetFlags) {
1947   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1948 
1949   FoldingSetNodeID ID;
1950   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1951   ID.AddPointer(BA);
1952   ID.AddInteger(Offset);
1953   ID.AddInteger(TargetFlags);
1954   void *IP = nullptr;
1955   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1956     return SDValue(E, 0);
1957 
1958   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1959   CSEMap.InsertNode(N, IP);
1960   InsertNode(N);
1961   return SDValue(N, 0);
1962 }
1963 
1964 SDValue SelectionDAG::getSrcValue(const Value *V) {
1965   FoldingSetNodeID ID;
1966   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1967   ID.AddPointer(V);
1968 
1969   void *IP = nullptr;
1970   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1971     return SDValue(E, 0);
1972 
1973   auto *N = newSDNode<SrcValueSDNode>(V);
1974   CSEMap.InsertNode(N, IP);
1975   InsertNode(N);
1976   return SDValue(N, 0);
1977 }
1978 
1979 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1980   FoldingSetNodeID ID;
1981   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1982   ID.AddPointer(MD);
1983 
1984   void *IP = nullptr;
1985   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1986     return SDValue(E, 0);
1987 
1988   auto *N = newSDNode<MDNodeSDNode>(MD);
1989   CSEMap.InsertNode(N, IP);
1990   InsertNode(N);
1991   return SDValue(N, 0);
1992 }
1993 
1994 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1995   if (VT == V.getValueType())
1996     return V;
1997 
1998   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1999 }
2000 
2001 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2002                                        unsigned SrcAS, unsigned DestAS) {
2003   SDValue Ops[] = {Ptr};
2004   FoldingSetNodeID ID;
2005   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2006   ID.AddInteger(SrcAS);
2007   ID.AddInteger(DestAS);
2008 
2009   void *IP = nullptr;
2010   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2011     return SDValue(E, 0);
2012 
2013   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2014                                            VT, SrcAS, DestAS);
2015   createOperands(N, Ops);
2016 
2017   CSEMap.InsertNode(N, IP);
2018   InsertNode(N);
2019   return SDValue(N, 0);
2020 }
2021 
2022 SDValue SelectionDAG::getFreeze(SDValue V) {
2023   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2024 }
2025 
2026 /// getShiftAmountOperand - Return the specified value casted to
2027 /// the target's desired shift amount type.
2028 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2029   EVT OpTy = Op.getValueType();
2030   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2031   if (OpTy == ShTy || OpTy.isVector()) return Op;
2032 
2033   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2034 }
2035 
2036 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2037   SDLoc dl(Node);
2038   const TargetLowering &TLI = getTargetLoweringInfo();
2039   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2040   EVT VT = Node->getValueType(0);
2041   SDValue Tmp1 = Node->getOperand(0);
2042   SDValue Tmp2 = Node->getOperand(1);
2043   const MaybeAlign MA(Node->getConstantOperandVal(3));
2044 
2045   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2046                                Tmp2, MachinePointerInfo(V));
2047   SDValue VAList = VAListLoad;
2048 
2049   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2050     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2051                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2052 
2053     VAList =
2054         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2055                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2056   }
2057 
2058   // Increment the pointer, VAList, to the next vaarg
2059   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2060                  getConstant(getDataLayout().getTypeAllocSize(
2061                                                VT.getTypeForEVT(*getContext())),
2062                              dl, VAList.getValueType()));
2063   // Store the incremented VAList to the legalized pointer
2064   Tmp1 =
2065       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2066   // Load the actual argument out of the pointer VAList
2067   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2068 }
2069 
2070 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2071   SDLoc dl(Node);
2072   const TargetLowering &TLI = getTargetLoweringInfo();
2073   // This defaults to loading a pointer from the input and storing it to the
2074   // output, returning the chain.
2075   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2076   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2077   SDValue Tmp1 =
2078       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2079               Node->getOperand(2), MachinePointerInfo(VS));
2080   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2081                   MachinePointerInfo(VD));
2082 }
2083 
2084 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2085   const DataLayout &DL = getDataLayout();
2086   Type *Ty = VT.getTypeForEVT(*getContext());
2087   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2088 
2089   if (TLI->isTypeLegal(VT) || !VT.isVector())
2090     return RedAlign;
2091 
2092   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2093   const Align StackAlign = TFI->getStackAlign();
2094 
2095   // See if we can choose a smaller ABI alignment in cases where it's an
2096   // illegal vector type that will get broken down.
2097   if (RedAlign > StackAlign) {
2098     EVT IntermediateVT;
2099     MVT RegisterVT;
2100     unsigned NumIntermediates;
2101     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2102                                 NumIntermediates, RegisterVT);
2103     Ty = IntermediateVT.getTypeForEVT(*getContext());
2104     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2105     if (RedAlign2 < RedAlign)
2106       RedAlign = RedAlign2;
2107   }
2108 
2109   return RedAlign;
2110 }
2111 
2112 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2113   MachineFrameInfo &MFI = MF->getFrameInfo();
2114   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2115   int StackID = 0;
2116   if (Bytes.isScalable())
2117     StackID = TFI->getStackIDForScalableVectors();
2118   // The stack id gives an indication of whether the object is scalable or
2119   // not, so it's safe to pass in the minimum size here.
2120   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2121                                        false, nullptr, StackID);
2122   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2123 }
2124 
2125 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2126   Type *Ty = VT.getTypeForEVT(*getContext());
2127   Align StackAlign =
2128       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2129   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2130 }
2131 
2132 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2133   TypeSize VT1Size = VT1.getStoreSize();
2134   TypeSize VT2Size = VT2.getStoreSize();
2135   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2136          "Don't know how to choose the maximum size when creating a stack "
2137          "temporary");
2138   TypeSize Bytes =
2139       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2140 
2141   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2142   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2143   const DataLayout &DL = getDataLayout();
2144   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2145   return CreateStackTemporary(Bytes, Align);
2146 }
2147 
2148 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2149                                 ISD::CondCode Cond, const SDLoc &dl) {
2150   EVT OpVT = N1.getValueType();
2151 
2152   // These setcc operations always fold.
2153   switch (Cond) {
2154   default: break;
2155   case ISD::SETFALSE:
2156   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2157   case ISD::SETTRUE:
2158   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2159 
2160   case ISD::SETOEQ:
2161   case ISD::SETOGT:
2162   case ISD::SETOGE:
2163   case ISD::SETOLT:
2164   case ISD::SETOLE:
2165   case ISD::SETONE:
2166   case ISD::SETO:
2167   case ISD::SETUO:
2168   case ISD::SETUEQ:
2169   case ISD::SETUNE:
2170     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2171     break;
2172   }
2173 
2174   if (OpVT.isInteger()) {
2175     // For EQ and NE, we can always pick a value for the undef to make the
2176     // predicate pass or fail, so we can return undef.
2177     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2178     // icmp eq/ne X, undef -> undef.
2179     if ((N1.isUndef() || N2.isUndef()) &&
2180         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2181       return getUNDEF(VT);
2182 
2183     // If both operands are undef, we can return undef for int comparison.
2184     // icmp undef, undef -> undef.
2185     if (N1.isUndef() && N2.isUndef())
2186       return getUNDEF(VT);
2187 
2188     // icmp X, X -> true/false
2189     // icmp X, undef -> true/false because undef could be X.
2190     if (N1 == N2)
2191       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2192   }
2193 
2194   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2195     const APInt &C2 = N2C->getAPIntValue();
2196     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2197       const APInt &C1 = N1C->getAPIntValue();
2198 
2199       switch (Cond) {
2200       default: llvm_unreachable("Unknown integer setcc!");
2201       case ISD::SETEQ:  return getBoolConstant(C1 == C2, dl, VT, OpVT);
2202       case ISD::SETNE:  return getBoolConstant(C1 != C2, dl, VT, OpVT);
2203       case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2204       case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2205       case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2206       case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2207       case ISD::SETLT:  return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2208       case ISD::SETGT:  return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2209       case ISD::SETLE:  return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2210       case ISD::SETGE:  return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2211       }
2212     }
2213   }
2214 
2215   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2216   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2217 
2218   if (N1CFP && N2CFP) {
2219     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2220     switch (Cond) {
2221     default: break;
2222     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2223                         return getUNDEF(VT);
2224                       LLVM_FALLTHROUGH;
2225     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2226                                              OpVT);
2227     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2228                         return getUNDEF(VT);
2229                       LLVM_FALLTHROUGH;
2230     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2231                                              R==APFloat::cmpLessThan, dl, VT,
2232                                              OpVT);
2233     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2234                         return getUNDEF(VT);
2235                       LLVM_FALLTHROUGH;
2236     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2237                                              OpVT);
2238     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2239                         return getUNDEF(VT);
2240                       LLVM_FALLTHROUGH;
2241     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2242                                              VT, OpVT);
2243     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2244                         return getUNDEF(VT);
2245                       LLVM_FALLTHROUGH;
2246     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2247                                              R==APFloat::cmpEqual, dl, VT,
2248                                              OpVT);
2249     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2250                         return getUNDEF(VT);
2251                       LLVM_FALLTHROUGH;
2252     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2253                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2254     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2255                                              OpVT);
2256     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2257                                              OpVT);
2258     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2259                                              R==APFloat::cmpEqual, dl, VT,
2260                                              OpVT);
2261     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2262                                              OpVT);
2263     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2264                                              R==APFloat::cmpLessThan, dl, VT,
2265                                              OpVT);
2266     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2267                                              R==APFloat::cmpUnordered, dl, VT,
2268                                              OpVT);
2269     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2270                                              VT, OpVT);
2271     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2272                                              OpVT);
2273     }
2274   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2275     // Ensure that the constant occurs on the RHS.
2276     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2277     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2278       return SDValue();
2279     return getSetCC(dl, VT, N2, N1, SwappedCond);
2280   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2281              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2282     // If an operand is known to be a nan (or undef that could be a nan), we can
2283     // fold it.
2284     // Choosing NaN for the undef will always make unordered comparison succeed
2285     // and ordered comparison fails.
2286     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2287     switch (ISD::getUnorderedFlavor(Cond)) {
2288     default:
2289       llvm_unreachable("Unknown flavor!");
2290     case 0: // Known false.
2291       return getBoolConstant(false, dl, VT, OpVT);
2292     case 1: // Known true.
2293       return getBoolConstant(true, dl, VT, OpVT);
2294     case 2: // Undefined.
2295       return getUNDEF(VT);
2296     }
2297   }
2298 
2299   // Could not fold it.
2300   return SDValue();
2301 }
2302 
2303 /// See if the specified operand can be simplified with the knowledge that only
2304 /// the bits specified by DemandedBits are used.
2305 /// TODO: really we should be making this into the DAG equivalent of
2306 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2307 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2308   EVT VT = V.getValueType();
2309 
2310   if (VT.isScalableVector())
2311     return SDValue();
2312 
2313   APInt DemandedElts = VT.isVector()
2314                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2315                            : APInt(1, 1);
2316   return GetDemandedBits(V, DemandedBits, DemandedElts);
2317 }
2318 
2319 /// See if the specified operand can be simplified with the knowledge that only
2320 /// the bits specified by DemandedBits are used in the elements specified by
2321 /// DemandedElts.
2322 /// TODO: really we should be making this into the DAG equivalent of
2323 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2324 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2325                                       const APInt &DemandedElts) {
2326   switch (V.getOpcode()) {
2327   default:
2328     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2329                                                 *this, 0);
2330   case ISD::Constant: {
2331     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2332     APInt NewVal = CVal & DemandedBits;
2333     if (NewVal != CVal)
2334       return getConstant(NewVal, SDLoc(V), V.getValueType());
2335     break;
2336   }
2337   case ISD::SRL:
2338     // Only look at single-use SRLs.
2339     if (!V.getNode()->hasOneUse())
2340       break;
2341     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2342       // See if we can recursively simplify the LHS.
2343       unsigned Amt = RHSC->getZExtValue();
2344 
2345       // Watch out for shift count overflow though.
2346       if (Amt >= DemandedBits.getBitWidth())
2347         break;
2348       APInt SrcDemandedBits = DemandedBits << Amt;
2349       if (SDValue SimplifyLHS =
2350               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2351         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2352                        V.getOperand(1));
2353     }
2354     break;
2355   }
2356   return SDValue();
2357 }
2358 
2359 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2360 /// use this predicate to simplify operations downstream.
2361 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2362   unsigned BitWidth = Op.getScalarValueSizeInBits();
2363   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2364 }
2365 
2366 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2367 /// this predicate to simplify operations downstream.  Mask is known to be zero
2368 /// for bits that V cannot have.
2369 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2370                                      unsigned Depth) const {
2371   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2372 }
2373 
2374 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2375 /// DemandedElts.  We use this predicate to simplify operations downstream.
2376 /// Mask is known to be zero for bits that V cannot have.
2377 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2378                                      const APInt &DemandedElts,
2379                                      unsigned Depth) const {
2380   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2381 }
2382 
2383 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2384 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2385                                         unsigned Depth) const {
2386   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2387 }
2388 
2389 /// isSplatValue - Return true if the vector V has the same value
2390 /// across all DemandedElts. For scalable vectors it does not make
2391 /// sense to specify which elements are demanded or undefined, therefore
2392 /// they are simply ignored.
2393 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2394                                 APInt &UndefElts, unsigned Depth) {
2395   EVT VT = V.getValueType();
2396   assert(VT.isVector() && "Vector type expected");
2397 
2398   if (!VT.isScalableVector() && !DemandedElts)
2399     return false; // No demanded elts, better to assume we don't know anything.
2400 
2401   if (Depth >= MaxRecursionDepth)
2402     return false; // Limit search depth.
2403 
2404   // Deal with some common cases here that work for both fixed and scalable
2405   // vector types.
2406   switch (V.getOpcode()) {
2407   case ISD::SPLAT_VECTOR:
2408     UndefElts = V.getOperand(0).isUndef()
2409                     ? APInt::getAllOnesValue(DemandedElts.getBitWidth())
2410                     : APInt(DemandedElts.getBitWidth(), 0);
2411     return true;
2412   case ISD::ADD:
2413   case ISD::SUB:
2414   case ISD::AND: {
2415     APInt UndefLHS, UndefRHS;
2416     SDValue LHS = V.getOperand(0);
2417     SDValue RHS = V.getOperand(1);
2418     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2419         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2420       UndefElts = UndefLHS | UndefRHS;
2421       return true;
2422     }
2423     break;
2424   }
2425   case ISD::TRUNCATE:
2426   case ISD::SIGN_EXTEND:
2427   case ISD::ZERO_EXTEND:
2428     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2429   }
2430 
2431   // We don't support other cases than those above for scalable vectors at
2432   // the moment.
2433   if (VT.isScalableVector())
2434     return false;
2435 
2436   unsigned NumElts = VT.getVectorNumElements();
2437   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2438   UndefElts = APInt::getNullValue(NumElts);
2439 
2440   switch (V.getOpcode()) {
2441   case ISD::BUILD_VECTOR: {
2442     SDValue Scl;
2443     for (unsigned i = 0; i != NumElts; ++i) {
2444       SDValue Op = V.getOperand(i);
2445       if (Op.isUndef()) {
2446         UndefElts.setBit(i);
2447         continue;
2448       }
2449       if (!DemandedElts[i])
2450         continue;
2451       if (Scl && Scl != Op)
2452         return false;
2453       Scl = Op;
2454     }
2455     return true;
2456   }
2457   case ISD::VECTOR_SHUFFLE: {
2458     // Check if this is a shuffle node doing a splat.
2459     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2460     int SplatIndex = -1;
2461     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2462     for (int i = 0; i != (int)NumElts; ++i) {
2463       int M = Mask[i];
2464       if (M < 0) {
2465         UndefElts.setBit(i);
2466         continue;
2467       }
2468       if (!DemandedElts[i])
2469         continue;
2470       if (0 <= SplatIndex && SplatIndex != M)
2471         return false;
2472       SplatIndex = M;
2473     }
2474     return true;
2475   }
2476   case ISD::EXTRACT_SUBVECTOR: {
2477     // Offset the demanded elts by the subvector index.
2478     SDValue Src = V.getOperand(0);
2479     uint64_t Idx = V.getConstantOperandVal(1);
2480     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2481     APInt UndefSrcElts;
2482     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2483     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2484       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2485       return true;
2486     }
2487     break;
2488   }
2489   }
2490 
2491   return false;
2492 }
2493 
2494 /// Helper wrapper to main isSplatValue function.
2495 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2496   EVT VT = V.getValueType();
2497   assert(VT.isVector() && "Vector type expected");
2498 
2499   APInt UndefElts;
2500   APInt DemandedElts;
2501 
2502   // For now we don't support this with scalable vectors.
2503   if (!VT.isScalableVector())
2504     DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2505   return isSplatValue(V, DemandedElts, UndefElts) &&
2506          (AllowUndefs || !UndefElts);
2507 }
2508 
2509 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2510   V = peekThroughExtractSubvectors(V);
2511 
2512   EVT VT = V.getValueType();
2513   unsigned Opcode = V.getOpcode();
2514   switch (Opcode) {
2515   default: {
2516     APInt UndefElts;
2517     APInt DemandedElts;
2518 
2519     if (!VT.isScalableVector())
2520       DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2521 
2522     if (isSplatValue(V, DemandedElts, UndefElts)) {
2523       if (VT.isScalableVector()) {
2524         // DemandedElts and UndefElts are ignored for scalable vectors, since
2525         // the only supported cases are SPLAT_VECTOR nodes.
2526         SplatIdx = 0;
2527       } else {
2528         // Handle case where all demanded elements are UNDEF.
2529         if (DemandedElts.isSubsetOf(UndefElts)) {
2530           SplatIdx = 0;
2531           return getUNDEF(VT);
2532         }
2533         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2534       }
2535       return V;
2536     }
2537     break;
2538   }
2539   case ISD::SPLAT_VECTOR:
2540     SplatIdx = 0;
2541     return V;
2542   case ISD::VECTOR_SHUFFLE: {
2543     if (VT.isScalableVector())
2544       return SDValue();
2545 
2546     // Check if this is a shuffle node doing a splat.
2547     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2548     // getTargetVShiftNode currently struggles without the splat source.
2549     auto *SVN = cast<ShuffleVectorSDNode>(V);
2550     if (!SVN->isSplat())
2551       break;
2552     int Idx = SVN->getSplatIndex();
2553     int NumElts = V.getValueType().getVectorNumElements();
2554     SplatIdx = Idx % NumElts;
2555     return V.getOperand(Idx / NumElts);
2556   }
2557   }
2558 
2559   return SDValue();
2560 }
2561 
2562 SDValue SelectionDAG::getSplatValue(SDValue V) {
2563   int SplatIdx;
2564   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
2565     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V),
2566                    SrcVector.getValueType().getScalarType(), SrcVector,
2567                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2568   return SDValue();
2569 }
2570 
2571 const APInt *
2572 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2573                                           const APInt &DemandedElts) const {
2574   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2575           V.getOpcode() == ISD::SRA) &&
2576          "Unknown shift node");
2577   unsigned BitWidth = V.getScalarValueSizeInBits();
2578   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2579     // Shifting more than the bitwidth is not valid.
2580     const APInt &ShAmt = SA->getAPIntValue();
2581     if (ShAmt.ult(BitWidth))
2582       return &ShAmt;
2583   }
2584   return nullptr;
2585 }
2586 
2587 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2588     SDValue V, const APInt &DemandedElts) const {
2589   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2590           V.getOpcode() == ISD::SRA) &&
2591          "Unknown shift node");
2592   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2593     return ValidAmt;
2594   unsigned BitWidth = V.getScalarValueSizeInBits();
2595   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2596   if (!BV)
2597     return nullptr;
2598   const APInt *MinShAmt = nullptr;
2599   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2600     if (!DemandedElts[i])
2601       continue;
2602     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2603     if (!SA)
2604       return nullptr;
2605     // Shifting more than the bitwidth is not valid.
2606     const APInt &ShAmt = SA->getAPIntValue();
2607     if (ShAmt.uge(BitWidth))
2608       return nullptr;
2609     if (MinShAmt && MinShAmt->ule(ShAmt))
2610       continue;
2611     MinShAmt = &ShAmt;
2612   }
2613   return MinShAmt;
2614 }
2615 
2616 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2617     SDValue V, const APInt &DemandedElts) const {
2618   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2619           V.getOpcode() == ISD::SRA) &&
2620          "Unknown shift node");
2621   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2622     return ValidAmt;
2623   unsigned BitWidth = V.getScalarValueSizeInBits();
2624   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2625   if (!BV)
2626     return nullptr;
2627   const APInt *MaxShAmt = nullptr;
2628   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2629     if (!DemandedElts[i])
2630       continue;
2631     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2632     if (!SA)
2633       return nullptr;
2634     // Shifting more than the bitwidth is not valid.
2635     const APInt &ShAmt = SA->getAPIntValue();
2636     if (ShAmt.uge(BitWidth))
2637       return nullptr;
2638     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2639       continue;
2640     MaxShAmt = &ShAmt;
2641   }
2642   return MaxShAmt;
2643 }
2644 
2645 /// Determine which bits of Op are known to be either zero or one and return
2646 /// them in Known. For vectors, the known bits are those that are shared by
2647 /// every vector element.
2648 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2649   EVT VT = Op.getValueType();
2650 
2651   // TOOD: Until we have a plan for how to represent demanded elements for
2652   // scalable vectors, we can just bail out for now.
2653   if (Op.getValueType().isScalableVector()) {
2654     unsigned BitWidth = Op.getScalarValueSizeInBits();
2655     return KnownBits(BitWidth);
2656   }
2657 
2658   APInt DemandedElts = VT.isVector()
2659                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2660                            : APInt(1, 1);
2661   return computeKnownBits(Op, DemandedElts, Depth);
2662 }
2663 
2664 /// Determine which bits of Op are known to be either zero or one and return
2665 /// them in Known. The DemandedElts argument allows us to only collect the known
2666 /// bits that are shared by the requested vector elements.
2667 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2668                                          unsigned Depth) const {
2669   unsigned BitWidth = Op.getScalarValueSizeInBits();
2670 
2671   KnownBits Known(BitWidth);   // Don't know anything.
2672 
2673   // TOOD: Until we have a plan for how to represent demanded elements for
2674   // scalable vectors, we can just bail out for now.
2675   if (Op.getValueType().isScalableVector())
2676     return Known;
2677 
2678   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2679     // We know all of the bits for a constant!
2680     return KnownBits::makeConstant(C->getAPIntValue());
2681   }
2682   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2683     // We know all of the bits for a constant fp!
2684     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2685   }
2686 
2687   if (Depth >= MaxRecursionDepth)
2688     return Known;  // Limit search depth.
2689 
2690   KnownBits Known2;
2691   unsigned NumElts = DemandedElts.getBitWidth();
2692   assert((!Op.getValueType().isVector() ||
2693           NumElts == Op.getValueType().getVectorNumElements()) &&
2694          "Unexpected vector size");
2695 
2696   if (!DemandedElts)
2697     return Known;  // No demanded elts, better to assume we don't know anything.
2698 
2699   unsigned Opcode = Op.getOpcode();
2700   switch (Opcode) {
2701   case ISD::BUILD_VECTOR:
2702     // Collect the known bits that are shared by every demanded vector element.
2703     Known.Zero.setAllBits(); Known.One.setAllBits();
2704     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2705       if (!DemandedElts[i])
2706         continue;
2707 
2708       SDValue SrcOp = Op.getOperand(i);
2709       Known2 = computeKnownBits(SrcOp, Depth + 1);
2710 
2711       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2712       if (SrcOp.getValueSizeInBits() != BitWidth) {
2713         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2714                "Expected BUILD_VECTOR implicit truncation");
2715         Known2 = Known2.trunc(BitWidth);
2716       }
2717 
2718       // Known bits are the values that are shared by every demanded element.
2719       Known = KnownBits::commonBits(Known, Known2);
2720 
2721       // If we don't know any bits, early out.
2722       if (Known.isUnknown())
2723         break;
2724     }
2725     break;
2726   case ISD::VECTOR_SHUFFLE: {
2727     // Collect the known bits that are shared by every vector element referenced
2728     // by the shuffle.
2729     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2730     Known.Zero.setAllBits(); Known.One.setAllBits();
2731     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2732     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2733     for (unsigned i = 0; i != NumElts; ++i) {
2734       if (!DemandedElts[i])
2735         continue;
2736 
2737       int M = SVN->getMaskElt(i);
2738       if (M < 0) {
2739         // For UNDEF elements, we don't know anything about the common state of
2740         // the shuffle result.
2741         Known.resetAll();
2742         DemandedLHS.clearAllBits();
2743         DemandedRHS.clearAllBits();
2744         break;
2745       }
2746 
2747       if ((unsigned)M < NumElts)
2748         DemandedLHS.setBit((unsigned)M % NumElts);
2749       else
2750         DemandedRHS.setBit((unsigned)M % NumElts);
2751     }
2752     // Known bits are the values that are shared by every demanded element.
2753     if (!!DemandedLHS) {
2754       SDValue LHS = Op.getOperand(0);
2755       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2756       Known = KnownBits::commonBits(Known, Known2);
2757     }
2758     // If we don't know any bits, early out.
2759     if (Known.isUnknown())
2760       break;
2761     if (!!DemandedRHS) {
2762       SDValue RHS = Op.getOperand(1);
2763       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2764       Known = KnownBits::commonBits(Known, Known2);
2765     }
2766     break;
2767   }
2768   case ISD::CONCAT_VECTORS: {
2769     // Split DemandedElts and test each of the demanded subvectors.
2770     Known.Zero.setAllBits(); Known.One.setAllBits();
2771     EVT SubVectorVT = Op.getOperand(0).getValueType();
2772     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2773     unsigned NumSubVectors = Op.getNumOperands();
2774     for (unsigned i = 0; i != NumSubVectors; ++i) {
2775       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2776       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2777       if (!!DemandedSub) {
2778         SDValue Sub = Op.getOperand(i);
2779         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2780         Known = KnownBits::commonBits(Known, Known2);
2781       }
2782       // If we don't know any bits, early out.
2783       if (Known.isUnknown())
2784         break;
2785     }
2786     break;
2787   }
2788   case ISD::INSERT_SUBVECTOR: {
2789     // Demand any elements from the subvector and the remainder from the src its
2790     // inserted into.
2791     SDValue Src = Op.getOperand(0);
2792     SDValue Sub = Op.getOperand(1);
2793     uint64_t Idx = Op.getConstantOperandVal(2);
2794     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2795     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2796     APInt DemandedSrcElts = DemandedElts;
2797     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2798 
2799     Known.One.setAllBits();
2800     Known.Zero.setAllBits();
2801     if (!!DemandedSubElts) {
2802       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2803       if (Known.isUnknown())
2804         break; // early-out.
2805     }
2806     if (!!DemandedSrcElts) {
2807       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2808       Known = KnownBits::commonBits(Known, Known2);
2809     }
2810     break;
2811   }
2812   case ISD::EXTRACT_SUBVECTOR: {
2813     // Offset the demanded elts by the subvector index.
2814     SDValue Src = Op.getOperand(0);
2815     // Bail until we can represent demanded elements for scalable vectors.
2816     if (Src.getValueType().isScalableVector())
2817       break;
2818     uint64_t Idx = Op.getConstantOperandVal(1);
2819     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2820     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2821     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2822     break;
2823   }
2824   case ISD::SCALAR_TO_VECTOR: {
2825     // We know about scalar_to_vector as much as we know about it source,
2826     // which becomes the first element of otherwise unknown vector.
2827     if (DemandedElts != 1)
2828       break;
2829 
2830     SDValue N0 = Op.getOperand(0);
2831     Known = computeKnownBits(N0, Depth + 1);
2832     if (N0.getValueSizeInBits() != BitWidth)
2833       Known = Known.trunc(BitWidth);
2834 
2835     break;
2836   }
2837   case ISD::BITCAST: {
2838     SDValue N0 = Op.getOperand(0);
2839     EVT SubVT = N0.getValueType();
2840     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2841 
2842     // Ignore bitcasts from unsupported types.
2843     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2844       break;
2845 
2846     // Fast handling of 'identity' bitcasts.
2847     if (BitWidth == SubBitWidth) {
2848       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2849       break;
2850     }
2851 
2852     bool IsLE = getDataLayout().isLittleEndian();
2853 
2854     // Bitcast 'small element' vector to 'large element' scalar/vector.
2855     if ((BitWidth % SubBitWidth) == 0) {
2856       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2857 
2858       // Collect known bits for the (larger) output by collecting the known
2859       // bits from each set of sub elements and shift these into place.
2860       // We need to separately call computeKnownBits for each set of
2861       // sub elements as the knownbits for each is likely to be different.
2862       unsigned SubScale = BitWidth / SubBitWidth;
2863       APInt SubDemandedElts(NumElts * SubScale, 0);
2864       for (unsigned i = 0; i != NumElts; ++i)
2865         if (DemandedElts[i])
2866           SubDemandedElts.setBit(i * SubScale);
2867 
2868       for (unsigned i = 0; i != SubScale; ++i) {
2869         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2870                          Depth + 1);
2871         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2872         Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2873         Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2874       }
2875     }
2876 
2877     // Bitcast 'large element' scalar/vector to 'small element' vector.
2878     if ((SubBitWidth % BitWidth) == 0) {
2879       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2880 
2881       // Collect known bits for the (smaller) output by collecting the known
2882       // bits from the overlapping larger input elements and extracting the
2883       // sub sections we actually care about.
2884       unsigned SubScale = SubBitWidth / BitWidth;
2885       APInt SubDemandedElts(NumElts / SubScale, 0);
2886       for (unsigned i = 0; i != NumElts; ++i)
2887         if (DemandedElts[i])
2888           SubDemandedElts.setBit(i / SubScale);
2889 
2890       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2891 
2892       Known.Zero.setAllBits(); Known.One.setAllBits();
2893       for (unsigned i = 0; i != NumElts; ++i)
2894         if (DemandedElts[i]) {
2895           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2896           unsigned Offset = (Shifts % SubScale) * BitWidth;
2897           Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2898           Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2899           // If we don't know any bits, early out.
2900           if (Known.isUnknown())
2901             break;
2902         }
2903     }
2904     break;
2905   }
2906   case ISD::AND:
2907     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2908     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2909 
2910     Known &= Known2;
2911     break;
2912   case ISD::OR:
2913     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2914     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2915 
2916     Known |= Known2;
2917     break;
2918   case ISD::XOR:
2919     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2920     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2921 
2922     Known ^= Known2;
2923     break;
2924   case ISD::MUL: {
2925     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2926     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2927     Known = KnownBits::computeForMul(Known, Known2);
2928     break;
2929   }
2930   case ISD::UDIV: {
2931     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2932     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2933     Known = KnownBits::udiv(Known, Known2);
2934     break;
2935   }
2936   case ISD::SELECT:
2937   case ISD::VSELECT:
2938     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2939     // If we don't know any bits, early out.
2940     if (Known.isUnknown())
2941       break;
2942     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
2943 
2944     // Only known if known in both the LHS and RHS.
2945     Known = KnownBits::commonBits(Known, Known2);
2946     break;
2947   case ISD::SELECT_CC:
2948     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
2949     // If we don't know any bits, early out.
2950     if (Known.isUnknown())
2951       break;
2952     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2953 
2954     // Only known if known in both the LHS and RHS.
2955     Known = KnownBits::commonBits(Known, Known2);
2956     break;
2957   case ISD::SMULO:
2958   case ISD::UMULO:
2959   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2960     if (Op.getResNo() != 1)
2961       break;
2962     // The boolean result conforms to getBooleanContents.
2963     // If we know the result of a setcc has the top bits zero, use this info.
2964     // We know that we have an integer-based boolean since these operations
2965     // are only available for integer.
2966     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2967             TargetLowering::ZeroOrOneBooleanContent &&
2968         BitWidth > 1)
2969       Known.Zero.setBitsFrom(1);
2970     break;
2971   case ISD::SETCC:
2972   case ISD::STRICT_FSETCC:
2973   case ISD::STRICT_FSETCCS: {
2974     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
2975     // If we know the result of a setcc has the top bits zero, use this info.
2976     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
2977             TargetLowering::ZeroOrOneBooleanContent &&
2978         BitWidth > 1)
2979       Known.Zero.setBitsFrom(1);
2980     break;
2981   }
2982   case ISD::SHL:
2983     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2984     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2985     Known = KnownBits::shl(Known, Known2);
2986 
2987     // Minimum shift low bits are known zero.
2988     if (const APInt *ShMinAmt =
2989             getValidMinimumShiftAmountConstant(Op, DemandedElts))
2990       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
2991     break;
2992   case ISD::SRL:
2993     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2994     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2995     Known = KnownBits::lshr(Known, Known2);
2996 
2997     // Minimum shift high bits are known zero.
2998     if (const APInt *ShMinAmt =
2999             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3000       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3001     break;
3002   case ISD::SRA:
3003     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3004     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3005     Known = KnownBits::ashr(Known, Known2);
3006     // TODO: Add minimum shift high known sign bits.
3007     break;
3008   case ISD::FSHL:
3009   case ISD::FSHR:
3010     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3011       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3012 
3013       // For fshl, 0-shift returns the 1st arg.
3014       // For fshr, 0-shift returns the 2nd arg.
3015       if (Amt == 0) {
3016         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3017                                  DemandedElts, Depth + 1);
3018         break;
3019       }
3020 
3021       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3022       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3023       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3024       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3025       if (Opcode == ISD::FSHL) {
3026         Known.One <<= Amt;
3027         Known.Zero <<= Amt;
3028         Known2.One.lshrInPlace(BitWidth - Amt);
3029         Known2.Zero.lshrInPlace(BitWidth - Amt);
3030       } else {
3031         Known.One <<= BitWidth - Amt;
3032         Known.Zero <<= BitWidth - Amt;
3033         Known2.One.lshrInPlace(Amt);
3034         Known2.Zero.lshrInPlace(Amt);
3035       }
3036       Known.One |= Known2.One;
3037       Known.Zero |= Known2.Zero;
3038     }
3039     break;
3040   case ISD::SIGN_EXTEND_INREG: {
3041     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3042     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3043     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3044     break;
3045   }
3046   case ISD::CTTZ:
3047   case ISD::CTTZ_ZERO_UNDEF: {
3048     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3049     // If we have a known 1, its position is our upper bound.
3050     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3051     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3052     Known.Zero.setBitsFrom(LowBits);
3053     break;
3054   }
3055   case ISD::CTLZ:
3056   case ISD::CTLZ_ZERO_UNDEF: {
3057     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3058     // If we have a known 1, its position is our upper bound.
3059     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3060     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3061     Known.Zero.setBitsFrom(LowBits);
3062     break;
3063   }
3064   case ISD::CTPOP: {
3065     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3066     // If we know some of the bits are zero, they can't be one.
3067     unsigned PossibleOnes = Known2.countMaxPopulation();
3068     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3069     break;
3070   }
3071   case ISD::PARITY: {
3072     // Parity returns 0 everywhere but the LSB.
3073     Known.Zero.setBitsFrom(1);
3074     break;
3075   }
3076   case ISD::LOAD: {
3077     LoadSDNode *LD = cast<LoadSDNode>(Op);
3078     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3079     if (ISD::isNON_EXTLoad(LD) && Cst) {
3080       // Determine any common known bits from the loaded constant pool value.
3081       Type *CstTy = Cst->getType();
3082       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3083         // If its a vector splat, then we can (quickly) reuse the scalar path.
3084         // NOTE: We assume all elements match and none are UNDEF.
3085         if (CstTy->isVectorTy()) {
3086           if (const Constant *Splat = Cst->getSplatValue()) {
3087             Cst = Splat;
3088             CstTy = Cst->getType();
3089           }
3090         }
3091         // TODO - do we need to handle different bitwidths?
3092         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3093           // Iterate across all vector elements finding common known bits.
3094           Known.One.setAllBits();
3095           Known.Zero.setAllBits();
3096           for (unsigned i = 0; i != NumElts; ++i) {
3097             if (!DemandedElts[i])
3098               continue;
3099             if (Constant *Elt = Cst->getAggregateElement(i)) {
3100               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3101                 const APInt &Value = CInt->getValue();
3102                 Known.One &= Value;
3103                 Known.Zero &= ~Value;
3104                 continue;
3105               }
3106               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3107                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3108                 Known.One &= Value;
3109                 Known.Zero &= ~Value;
3110                 continue;
3111               }
3112             }
3113             Known.One.clearAllBits();
3114             Known.Zero.clearAllBits();
3115             break;
3116           }
3117         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3118           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3119             const APInt &Value = CInt->getValue();
3120             Known.One = Value;
3121             Known.Zero = ~Value;
3122           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3123             APInt Value = CFP->getValueAPF().bitcastToAPInt();
3124             Known.One = Value;
3125             Known.Zero = ~Value;
3126           }
3127         }
3128       }
3129     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3130       // If this is a ZEXTLoad and we are looking at the loaded value.
3131       EVT VT = LD->getMemoryVT();
3132       unsigned MemBits = VT.getScalarSizeInBits();
3133       Known.Zero.setBitsFrom(MemBits);
3134     } else if (const MDNode *Ranges = LD->getRanges()) {
3135       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3136         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3137     }
3138     break;
3139   }
3140   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3141     EVT InVT = Op.getOperand(0).getValueType();
3142     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3143     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3144     Known = Known.zext(BitWidth);
3145     break;
3146   }
3147   case ISD::ZERO_EXTEND: {
3148     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3149     Known = Known.zext(BitWidth);
3150     break;
3151   }
3152   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3153     EVT InVT = Op.getOperand(0).getValueType();
3154     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3155     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3156     // If the sign bit is known to be zero or one, then sext will extend
3157     // it to the top bits, else it will just zext.
3158     Known = Known.sext(BitWidth);
3159     break;
3160   }
3161   case ISD::SIGN_EXTEND: {
3162     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3163     // If the sign bit is known to be zero or one, then sext will extend
3164     // it to the top bits, else it will just zext.
3165     Known = Known.sext(BitWidth);
3166     break;
3167   }
3168   case ISD::ANY_EXTEND_VECTOR_INREG: {
3169     EVT InVT = Op.getOperand(0).getValueType();
3170     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3171     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3172     Known = Known.anyext(BitWidth);
3173     break;
3174   }
3175   case ISD::ANY_EXTEND: {
3176     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3177     Known = Known.anyext(BitWidth);
3178     break;
3179   }
3180   case ISD::TRUNCATE: {
3181     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3182     Known = Known.trunc(BitWidth);
3183     break;
3184   }
3185   case ISD::AssertZext: {
3186     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3187     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3188     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3189     Known.Zero |= (~InMask);
3190     Known.One  &= (~Known.Zero);
3191     break;
3192   }
3193   case ISD::AssertAlign: {
3194     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3195     assert(LogOfAlign != 0);
3196     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3197     // well as clearing one bits.
3198     Known.Zero.setLowBits(LogOfAlign);
3199     Known.One.clearLowBits(LogOfAlign);
3200     break;
3201   }
3202   case ISD::FGETSIGN:
3203     // All bits are zero except the low bit.
3204     Known.Zero.setBitsFrom(1);
3205     break;
3206   case ISD::USUBO:
3207   case ISD::SSUBO:
3208     if (Op.getResNo() == 1) {
3209       // If we know the result of a setcc has the top bits zero, use this info.
3210       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3211               TargetLowering::ZeroOrOneBooleanContent &&
3212           BitWidth > 1)
3213         Known.Zero.setBitsFrom(1);
3214       break;
3215     }
3216     LLVM_FALLTHROUGH;
3217   case ISD::SUB:
3218   case ISD::SUBC: {
3219     assert(Op.getResNo() == 0 &&
3220            "We only compute knownbits for the difference here.");
3221 
3222     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3223     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3224     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3225                                         Known, Known2);
3226     break;
3227   }
3228   case ISD::UADDO:
3229   case ISD::SADDO:
3230   case ISD::ADDCARRY:
3231     if (Op.getResNo() == 1) {
3232       // If we know the result of a setcc has the top bits zero, use this info.
3233       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3234               TargetLowering::ZeroOrOneBooleanContent &&
3235           BitWidth > 1)
3236         Known.Zero.setBitsFrom(1);
3237       break;
3238     }
3239     LLVM_FALLTHROUGH;
3240   case ISD::ADD:
3241   case ISD::ADDC:
3242   case ISD::ADDE: {
3243     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3244 
3245     // With ADDE and ADDCARRY, a carry bit may be added in.
3246     KnownBits Carry(1);
3247     if (Opcode == ISD::ADDE)
3248       // Can't track carry from glue, set carry to unknown.
3249       Carry.resetAll();
3250     else if (Opcode == ISD::ADDCARRY)
3251       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3252       // the trouble (how often will we find a known carry bit). And I haven't
3253       // tested this very much yet, but something like this might work:
3254       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3255       //   Carry = Carry.zextOrTrunc(1, false);
3256       Carry.resetAll();
3257     else
3258       Carry.setAllZero();
3259 
3260     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3261     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3262     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3263     break;
3264   }
3265   case ISD::SREM: {
3266     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3267     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3268     Known = KnownBits::srem(Known, Known2);
3269     break;
3270   }
3271   case ISD::UREM: {
3272     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3273     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3274     Known = KnownBits::urem(Known, Known2);
3275     break;
3276   }
3277   case ISD::EXTRACT_ELEMENT: {
3278     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3279     const unsigned Index = Op.getConstantOperandVal(1);
3280     const unsigned EltBitWidth = Op.getValueSizeInBits();
3281 
3282     // Remove low part of known bits mask
3283     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3284     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3285 
3286     // Remove high part of known bit mask
3287     Known = Known.trunc(EltBitWidth);
3288     break;
3289   }
3290   case ISD::EXTRACT_VECTOR_ELT: {
3291     SDValue InVec = Op.getOperand(0);
3292     SDValue EltNo = Op.getOperand(1);
3293     EVT VecVT = InVec.getValueType();
3294     // computeKnownBits not yet implemented for scalable vectors.
3295     if (VecVT.isScalableVector())
3296       break;
3297     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3298     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3299 
3300     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3301     // anything about the extended bits.
3302     if (BitWidth > EltBitWidth)
3303       Known = Known.trunc(EltBitWidth);
3304 
3305     // If we know the element index, just demand that vector element, else for
3306     // an unknown element index, ignore DemandedElts and demand them all.
3307     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3308     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3309     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3310       DemandedSrcElts =
3311           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3312 
3313     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3314     if (BitWidth > EltBitWidth)
3315       Known = Known.anyext(BitWidth);
3316     break;
3317   }
3318   case ISD::INSERT_VECTOR_ELT: {
3319     // If we know the element index, split the demand between the
3320     // source vector and the inserted element, otherwise assume we need
3321     // the original demanded vector elements and the value.
3322     SDValue InVec = Op.getOperand(0);
3323     SDValue InVal = Op.getOperand(1);
3324     SDValue EltNo = Op.getOperand(2);
3325     bool DemandedVal = true;
3326     APInt DemandedVecElts = DemandedElts;
3327     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3328     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3329       unsigned EltIdx = CEltNo->getZExtValue();
3330       DemandedVal = !!DemandedElts[EltIdx];
3331       DemandedVecElts.clearBit(EltIdx);
3332     }
3333     Known.One.setAllBits();
3334     Known.Zero.setAllBits();
3335     if (DemandedVal) {
3336       Known2 = computeKnownBits(InVal, Depth + 1);
3337       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3338     }
3339     if (!!DemandedVecElts) {
3340       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3341       Known = KnownBits::commonBits(Known, Known2);
3342     }
3343     break;
3344   }
3345   case ISD::BITREVERSE: {
3346     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3347     Known = Known2.reverseBits();
3348     break;
3349   }
3350   case ISD::BSWAP: {
3351     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3352     Known = Known2.byteSwap();
3353     break;
3354   }
3355   case ISD::ABS: {
3356     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3357     Known = Known2.abs();
3358     break;
3359   }
3360   case ISD::UMIN: {
3361     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3362     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3363     Known = KnownBits::umin(Known, Known2);
3364     break;
3365   }
3366   case ISD::UMAX: {
3367     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3368     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3369     Known = KnownBits::umax(Known, Known2);
3370     break;
3371   }
3372   case ISD::SMIN:
3373   case ISD::SMAX: {
3374     // If we have a clamp pattern, we know that the number of sign bits will be
3375     // the minimum of the clamp min/max range.
3376     bool IsMax = (Opcode == ISD::SMAX);
3377     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3378     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3379       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3380         CstHigh =
3381             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3382     if (CstLow && CstHigh) {
3383       if (!IsMax)
3384         std::swap(CstLow, CstHigh);
3385 
3386       const APInt &ValueLow = CstLow->getAPIntValue();
3387       const APInt &ValueHigh = CstHigh->getAPIntValue();
3388       if (ValueLow.sle(ValueHigh)) {
3389         unsigned LowSignBits = ValueLow.getNumSignBits();
3390         unsigned HighSignBits = ValueHigh.getNumSignBits();
3391         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3392         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3393           Known.One.setHighBits(MinSignBits);
3394           break;
3395         }
3396         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3397           Known.Zero.setHighBits(MinSignBits);
3398           break;
3399         }
3400       }
3401     }
3402 
3403     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3404     if (Known.isUnknown()) break; // Early-out
3405     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3406     if (IsMax)
3407       Known = KnownBits::smax(Known, Known2);
3408     else
3409       Known = KnownBits::smin(Known, Known2);
3410     break;
3411   }
3412   case ISD::FrameIndex:
3413   case ISD::TargetFrameIndex:
3414     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3415                                        Known, getMachineFunction());
3416     break;
3417 
3418   default:
3419     if (Opcode < ISD::BUILTIN_OP_END)
3420       break;
3421     LLVM_FALLTHROUGH;
3422   case ISD::INTRINSIC_WO_CHAIN:
3423   case ISD::INTRINSIC_W_CHAIN:
3424   case ISD::INTRINSIC_VOID:
3425     // Allow the target to implement this method for its nodes.
3426     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3427     break;
3428   }
3429 
3430   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3431   return Known;
3432 }
3433 
3434 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3435                                                              SDValue N1) const {
3436   // X + 0 never overflow
3437   if (isNullConstant(N1))
3438     return OFK_Never;
3439 
3440   KnownBits N1Known = computeKnownBits(N1);
3441   if (N1Known.Zero.getBoolValue()) {
3442     KnownBits N0Known = computeKnownBits(N0);
3443 
3444     bool overflow;
3445     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3446     if (!overflow)
3447       return OFK_Never;
3448   }
3449 
3450   // mulhi + 1 never overflow
3451   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3452       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3453     return OFK_Never;
3454 
3455   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3456     KnownBits N0Known = computeKnownBits(N0);
3457 
3458     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3459       return OFK_Never;
3460   }
3461 
3462   return OFK_Sometime;
3463 }
3464 
3465 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3466   EVT OpVT = Val.getValueType();
3467   unsigned BitWidth = OpVT.getScalarSizeInBits();
3468 
3469   // Is the constant a known power of 2?
3470   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3471     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3472 
3473   // A left-shift of a constant one will have exactly one bit set because
3474   // shifting the bit off the end is undefined.
3475   if (Val.getOpcode() == ISD::SHL) {
3476     auto *C = isConstOrConstSplat(Val.getOperand(0));
3477     if (C && C->getAPIntValue() == 1)
3478       return true;
3479   }
3480 
3481   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3482   // one bit set.
3483   if (Val.getOpcode() == ISD::SRL) {
3484     auto *C = isConstOrConstSplat(Val.getOperand(0));
3485     if (C && C->getAPIntValue().isSignMask())
3486       return true;
3487   }
3488 
3489   // Are all operands of a build vector constant powers of two?
3490   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3491     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3492           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3493             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3494           return false;
3495         }))
3496       return true;
3497 
3498   // More could be done here, though the above checks are enough
3499   // to handle some common cases.
3500 
3501   // Fall back to computeKnownBits to catch other known cases.
3502   KnownBits Known = computeKnownBits(Val);
3503   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3504 }
3505 
3506 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3507   EVT VT = Op.getValueType();
3508 
3509   // TODO: Assume we don't know anything for now.
3510   if (VT.isScalableVector())
3511     return 1;
3512 
3513   APInt DemandedElts = VT.isVector()
3514                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
3515                            : APInt(1, 1);
3516   return ComputeNumSignBits(Op, DemandedElts, Depth);
3517 }
3518 
3519 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3520                                           unsigned Depth) const {
3521   EVT VT = Op.getValueType();
3522   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3523   unsigned VTBits = VT.getScalarSizeInBits();
3524   unsigned NumElts = DemandedElts.getBitWidth();
3525   unsigned Tmp, Tmp2;
3526   unsigned FirstAnswer = 1;
3527 
3528   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3529     const APInt &Val = C->getAPIntValue();
3530     return Val.getNumSignBits();
3531   }
3532 
3533   if (Depth >= MaxRecursionDepth)
3534     return 1;  // Limit search depth.
3535 
3536   if (!DemandedElts || VT.isScalableVector())
3537     return 1;  // No demanded elts, better to assume we don't know anything.
3538 
3539   unsigned Opcode = Op.getOpcode();
3540   switch (Opcode) {
3541   default: break;
3542   case ISD::AssertSext:
3543     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3544     return VTBits-Tmp+1;
3545   case ISD::AssertZext:
3546     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3547     return VTBits-Tmp;
3548 
3549   case ISD::BUILD_VECTOR:
3550     Tmp = VTBits;
3551     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3552       if (!DemandedElts[i])
3553         continue;
3554 
3555       SDValue SrcOp = Op.getOperand(i);
3556       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3557 
3558       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3559       if (SrcOp.getValueSizeInBits() != VTBits) {
3560         assert(SrcOp.getValueSizeInBits() > VTBits &&
3561                "Expected BUILD_VECTOR implicit truncation");
3562         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3563         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3564       }
3565       Tmp = std::min(Tmp, Tmp2);
3566     }
3567     return Tmp;
3568 
3569   case ISD::VECTOR_SHUFFLE: {
3570     // Collect the minimum number of sign bits that are shared by every vector
3571     // element referenced by the shuffle.
3572     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3573     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3574     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3575     for (unsigned i = 0; i != NumElts; ++i) {
3576       int M = SVN->getMaskElt(i);
3577       if (!DemandedElts[i])
3578         continue;
3579       // For UNDEF elements, we don't know anything about the common state of
3580       // the shuffle result.
3581       if (M < 0)
3582         return 1;
3583       if ((unsigned)M < NumElts)
3584         DemandedLHS.setBit((unsigned)M % NumElts);
3585       else
3586         DemandedRHS.setBit((unsigned)M % NumElts);
3587     }
3588     Tmp = std::numeric_limits<unsigned>::max();
3589     if (!!DemandedLHS)
3590       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3591     if (!!DemandedRHS) {
3592       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3593       Tmp = std::min(Tmp, Tmp2);
3594     }
3595     // If we don't know anything, early out and try computeKnownBits fall-back.
3596     if (Tmp == 1)
3597       break;
3598     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3599     return Tmp;
3600   }
3601 
3602   case ISD::BITCAST: {
3603     SDValue N0 = Op.getOperand(0);
3604     EVT SrcVT = N0.getValueType();
3605     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3606 
3607     // Ignore bitcasts from unsupported types..
3608     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3609       break;
3610 
3611     // Fast handling of 'identity' bitcasts.
3612     if (VTBits == SrcBits)
3613       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3614 
3615     bool IsLE = getDataLayout().isLittleEndian();
3616 
3617     // Bitcast 'large element' scalar/vector to 'small element' vector.
3618     if ((SrcBits % VTBits) == 0) {
3619       assert(VT.isVector() && "Expected bitcast to vector");
3620 
3621       unsigned Scale = SrcBits / VTBits;
3622       APInt SrcDemandedElts(NumElts / Scale, 0);
3623       for (unsigned i = 0; i != NumElts; ++i)
3624         if (DemandedElts[i])
3625           SrcDemandedElts.setBit(i / Scale);
3626 
3627       // Fast case - sign splat can be simply split across the small elements.
3628       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3629       if (Tmp == SrcBits)
3630         return VTBits;
3631 
3632       // Slow case - determine how far the sign extends into each sub-element.
3633       Tmp2 = VTBits;
3634       for (unsigned i = 0; i != NumElts; ++i)
3635         if (DemandedElts[i]) {
3636           unsigned SubOffset = i % Scale;
3637           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3638           SubOffset = SubOffset * VTBits;
3639           if (Tmp <= SubOffset)
3640             return 1;
3641           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3642         }
3643       return Tmp2;
3644     }
3645     break;
3646   }
3647 
3648   case ISD::SIGN_EXTEND:
3649     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3650     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3651   case ISD::SIGN_EXTEND_INREG:
3652     // Max of the input and what this extends.
3653     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3654     Tmp = VTBits-Tmp+1;
3655     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3656     return std::max(Tmp, Tmp2);
3657   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3658     SDValue Src = Op.getOperand(0);
3659     EVT SrcVT = Src.getValueType();
3660     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3661     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3662     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3663   }
3664   case ISD::SRA:
3665     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3666     // SRA X, C -> adds C sign bits.
3667     if (const APInt *ShAmt =
3668             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3669       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3670     return Tmp;
3671   case ISD::SHL:
3672     if (const APInt *ShAmt =
3673             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3674       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3675       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3676       if (ShAmt->ult(Tmp))
3677         return Tmp - ShAmt->getZExtValue();
3678     }
3679     break;
3680   case ISD::AND:
3681   case ISD::OR:
3682   case ISD::XOR:    // NOT is handled here.
3683     // Logical binary ops preserve the number of sign bits at the worst.
3684     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3685     if (Tmp != 1) {
3686       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3687       FirstAnswer = std::min(Tmp, Tmp2);
3688       // We computed what we know about the sign bits as our first
3689       // answer. Now proceed to the generic code that uses
3690       // computeKnownBits, and pick whichever answer is better.
3691     }
3692     break;
3693 
3694   case ISD::SELECT:
3695   case ISD::VSELECT:
3696     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3697     if (Tmp == 1) return 1;  // Early out.
3698     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3699     return std::min(Tmp, Tmp2);
3700   case ISD::SELECT_CC:
3701     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3702     if (Tmp == 1) return 1;  // Early out.
3703     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3704     return std::min(Tmp, Tmp2);
3705 
3706   case ISD::SMIN:
3707   case ISD::SMAX: {
3708     // If we have a clamp pattern, we know that the number of sign bits will be
3709     // the minimum of the clamp min/max range.
3710     bool IsMax = (Opcode == ISD::SMAX);
3711     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3712     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3713       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3714         CstHigh =
3715             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3716     if (CstLow && CstHigh) {
3717       if (!IsMax)
3718         std::swap(CstLow, CstHigh);
3719       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3720         Tmp = CstLow->getAPIntValue().getNumSignBits();
3721         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3722         return std::min(Tmp, Tmp2);
3723       }
3724     }
3725 
3726     // Fallback - just get the minimum number of sign bits of the operands.
3727     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3728     if (Tmp == 1)
3729       return 1;  // Early out.
3730     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3731     return std::min(Tmp, Tmp2);
3732   }
3733   case ISD::UMIN:
3734   case ISD::UMAX:
3735     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3736     if (Tmp == 1)
3737       return 1;  // Early out.
3738     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3739     return std::min(Tmp, Tmp2);
3740   case ISD::SADDO:
3741   case ISD::UADDO:
3742   case ISD::SSUBO:
3743   case ISD::USUBO:
3744   case ISD::SMULO:
3745   case ISD::UMULO:
3746     if (Op.getResNo() != 1)
3747       break;
3748     // The boolean result conforms to getBooleanContents.  Fall through.
3749     // If setcc returns 0/-1, all bits are sign bits.
3750     // We know that we have an integer-based boolean since these operations
3751     // are only available for integer.
3752     if (TLI->getBooleanContents(VT.isVector(), false) ==
3753         TargetLowering::ZeroOrNegativeOneBooleanContent)
3754       return VTBits;
3755     break;
3756   case ISD::SETCC:
3757   case ISD::STRICT_FSETCC:
3758   case ISD::STRICT_FSETCCS: {
3759     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3760     // If setcc returns 0/-1, all bits are sign bits.
3761     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3762         TargetLowering::ZeroOrNegativeOneBooleanContent)
3763       return VTBits;
3764     break;
3765   }
3766   case ISD::ROTL:
3767   case ISD::ROTR:
3768     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3769 
3770     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3771     if (Tmp == VTBits)
3772       return VTBits;
3773 
3774     if (ConstantSDNode *C =
3775             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3776       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3777 
3778       // Handle rotate right by N like a rotate left by 32-N.
3779       if (Opcode == ISD::ROTR)
3780         RotAmt = (VTBits - RotAmt) % VTBits;
3781 
3782       // If we aren't rotating out all of the known-in sign bits, return the
3783       // number that are left.  This handles rotl(sext(x), 1) for example.
3784       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3785     }
3786     break;
3787   case ISD::ADD:
3788   case ISD::ADDC:
3789     // Add can have at most one carry bit.  Thus we know that the output
3790     // is, at worst, one more bit than the inputs.
3791     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3792     if (Tmp == 1) return 1; // Early out.
3793 
3794     // Special case decrementing a value (ADD X, -1):
3795     if (ConstantSDNode *CRHS =
3796             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3797       if (CRHS->isAllOnesValue()) {
3798         KnownBits Known =
3799             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3800 
3801         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3802         // sign bits set.
3803         if ((Known.Zero | 1).isAllOnesValue())
3804           return VTBits;
3805 
3806         // If we are subtracting one from a positive number, there is no carry
3807         // out of the result.
3808         if (Known.isNonNegative())
3809           return Tmp;
3810       }
3811 
3812     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3813     if (Tmp2 == 1) return 1; // Early out.
3814     return std::min(Tmp, Tmp2) - 1;
3815   case ISD::SUB:
3816     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3817     if (Tmp2 == 1) return 1; // Early out.
3818 
3819     // Handle NEG.
3820     if (ConstantSDNode *CLHS =
3821             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
3822       if (CLHS->isNullValue()) {
3823         KnownBits Known =
3824             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3825         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3826         // sign bits set.
3827         if ((Known.Zero | 1).isAllOnesValue())
3828           return VTBits;
3829 
3830         // If the input is known to be positive (the sign bit is known clear),
3831         // the output of the NEG has the same number of sign bits as the input.
3832         if (Known.isNonNegative())
3833           return Tmp2;
3834 
3835         // Otherwise, we treat this like a SUB.
3836       }
3837 
3838     // Sub can have at most one carry bit.  Thus we know that the output
3839     // is, at worst, one more bit than the inputs.
3840     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3841     if (Tmp == 1) return 1; // Early out.
3842     return std::min(Tmp, Tmp2) - 1;
3843   case ISD::MUL: {
3844     // The output of the Mul can be at most twice the valid bits in the inputs.
3845     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3846     if (SignBitsOp0 == 1)
3847       break;
3848     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3849     if (SignBitsOp1 == 1)
3850       break;
3851     unsigned OutValidBits =
3852         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
3853     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
3854   }
3855   case ISD::TRUNCATE: {
3856     // Check if the sign bits of source go down as far as the truncated value.
3857     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3858     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3859     if (NumSrcSignBits > (NumSrcBits - VTBits))
3860       return NumSrcSignBits - (NumSrcBits - VTBits);
3861     break;
3862   }
3863   case ISD::EXTRACT_ELEMENT: {
3864     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3865     const int BitWidth = Op.getValueSizeInBits();
3866     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3867 
3868     // Get reverse index (starting from 1), Op1 value indexes elements from
3869     // little end. Sign starts at big end.
3870     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3871 
3872     // If the sign portion ends in our element the subtraction gives correct
3873     // result. Otherwise it gives either negative or > bitwidth result
3874     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3875   }
3876   case ISD::INSERT_VECTOR_ELT: {
3877     // If we know the element index, split the demand between the
3878     // source vector and the inserted element, otherwise assume we need
3879     // the original demanded vector elements and the value.
3880     SDValue InVec = Op.getOperand(0);
3881     SDValue InVal = Op.getOperand(1);
3882     SDValue EltNo = Op.getOperand(2);
3883     bool DemandedVal = true;
3884     APInt DemandedVecElts = DemandedElts;
3885     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3886     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3887       unsigned EltIdx = CEltNo->getZExtValue();
3888       DemandedVal = !!DemandedElts[EltIdx];
3889       DemandedVecElts.clearBit(EltIdx);
3890     }
3891     Tmp = std::numeric_limits<unsigned>::max();
3892     if (DemandedVal) {
3893       // TODO - handle implicit truncation of inserted elements.
3894       if (InVal.getScalarValueSizeInBits() != VTBits)
3895         break;
3896       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3897       Tmp = std::min(Tmp, Tmp2);
3898     }
3899     if (!!DemandedVecElts) {
3900       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
3901       Tmp = std::min(Tmp, Tmp2);
3902     }
3903     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3904     return Tmp;
3905   }
3906   case ISD::EXTRACT_VECTOR_ELT: {
3907     SDValue InVec = Op.getOperand(0);
3908     SDValue EltNo = Op.getOperand(1);
3909     EVT VecVT = InVec.getValueType();
3910     const unsigned BitWidth = Op.getValueSizeInBits();
3911     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3912     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3913 
3914     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3915     // anything about sign bits. But if the sizes match we can derive knowledge
3916     // about sign bits from the vector operand.
3917     if (BitWidth != EltBitWidth)
3918       break;
3919 
3920     // If we know the element index, just demand that vector element, else for
3921     // an unknown element index, ignore DemandedElts and demand them all.
3922     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3923     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3924     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3925       DemandedSrcElts =
3926           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3927 
3928     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3929   }
3930   case ISD::EXTRACT_SUBVECTOR: {
3931     // Offset the demanded elts by the subvector index.
3932     SDValue Src = Op.getOperand(0);
3933     // Bail until we can represent demanded elements for scalable vectors.
3934     if (Src.getValueType().isScalableVector())
3935       break;
3936     uint64_t Idx = Op.getConstantOperandVal(1);
3937     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3938     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
3939     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
3940   }
3941   case ISD::CONCAT_VECTORS: {
3942     // Determine the minimum number of sign bits across all demanded
3943     // elts of the input vectors. Early out if the result is already 1.
3944     Tmp = std::numeric_limits<unsigned>::max();
3945     EVT SubVectorVT = Op.getOperand(0).getValueType();
3946     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3947     unsigned NumSubVectors = Op.getNumOperands();
3948     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3949       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3950       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3951       if (!DemandedSub)
3952         continue;
3953       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3954       Tmp = std::min(Tmp, Tmp2);
3955     }
3956     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3957     return Tmp;
3958   }
3959   case ISD::INSERT_SUBVECTOR: {
3960     // Demand any elements from the subvector and the remainder from the src its
3961     // inserted into.
3962     SDValue Src = Op.getOperand(0);
3963     SDValue Sub = Op.getOperand(1);
3964     uint64_t Idx = Op.getConstantOperandVal(2);
3965     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3966     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3967     APInt DemandedSrcElts = DemandedElts;
3968     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
3969 
3970     Tmp = std::numeric_limits<unsigned>::max();
3971     if (!!DemandedSubElts) {
3972       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
3973       if (Tmp == 1)
3974         return 1; // early-out
3975     }
3976     if (!!DemandedSrcElts) {
3977       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
3978       Tmp = std::min(Tmp, Tmp2);
3979     }
3980     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3981     return Tmp;
3982   }
3983   }
3984 
3985   // If we are looking at the loaded value of the SDNode.
3986   if (Op.getResNo() == 0) {
3987     // Handle LOADX separately here. EXTLOAD case will fallthrough.
3988     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3989       unsigned ExtType = LD->getExtensionType();
3990       switch (ExtType) {
3991       default: break;
3992       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
3993         Tmp = LD->getMemoryVT().getScalarSizeInBits();
3994         return VTBits - Tmp + 1;
3995       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
3996         Tmp = LD->getMemoryVT().getScalarSizeInBits();
3997         return VTBits - Tmp;
3998       case ISD::NON_EXTLOAD:
3999         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4000           // We only need to handle vectors - computeKnownBits should handle
4001           // scalar cases.
4002           Type *CstTy = Cst->getType();
4003           if (CstTy->isVectorTy() &&
4004               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4005             Tmp = VTBits;
4006             for (unsigned i = 0; i != NumElts; ++i) {
4007               if (!DemandedElts[i])
4008                 continue;
4009               if (Constant *Elt = Cst->getAggregateElement(i)) {
4010                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4011                   const APInt &Value = CInt->getValue();
4012                   Tmp = std::min(Tmp, Value.getNumSignBits());
4013                   continue;
4014                 }
4015                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4016                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4017                   Tmp = std::min(Tmp, Value.getNumSignBits());
4018                   continue;
4019                 }
4020               }
4021               // Unknown type. Conservatively assume no bits match sign bit.
4022               return 1;
4023             }
4024             return Tmp;
4025           }
4026         }
4027         break;
4028       }
4029     }
4030   }
4031 
4032   // Allow the target to implement this method for its nodes.
4033   if (Opcode >= ISD::BUILTIN_OP_END ||
4034       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4035       Opcode == ISD::INTRINSIC_W_CHAIN ||
4036       Opcode == ISD::INTRINSIC_VOID) {
4037     unsigned NumBits =
4038         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4039     if (NumBits > 1)
4040       FirstAnswer = std::max(FirstAnswer, NumBits);
4041   }
4042 
4043   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4044   // use this information.
4045   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4046 
4047   APInt Mask;
4048   if (Known.isNonNegative()) {        // sign bit is 0
4049     Mask = Known.Zero;
4050   } else if (Known.isNegative()) {  // sign bit is 1;
4051     Mask = Known.One;
4052   } else {
4053     // Nothing known.
4054     return FirstAnswer;
4055   }
4056 
4057   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4058   // the number of identical bits in the top of the input value.
4059   Mask <<= Mask.getBitWidth()-VTBits;
4060   return std::max(FirstAnswer, Mask.countLeadingOnes());
4061 }
4062 
4063 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4064   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4065       !isa<ConstantSDNode>(Op.getOperand(1)))
4066     return false;
4067 
4068   if (Op.getOpcode() == ISD::OR &&
4069       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4070     return false;
4071 
4072   return true;
4073 }
4074 
4075 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4076   // If we're told that NaNs won't happen, assume they won't.
4077   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4078     return true;
4079 
4080   if (Depth >= MaxRecursionDepth)
4081     return false; // Limit search depth.
4082 
4083   // TODO: Handle vectors.
4084   // If the value is a constant, we can obviously see if it is a NaN or not.
4085   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4086     return !C->getValueAPF().isNaN() ||
4087            (SNaN && !C->getValueAPF().isSignaling());
4088   }
4089 
4090   unsigned Opcode = Op.getOpcode();
4091   switch (Opcode) {
4092   case ISD::FADD:
4093   case ISD::FSUB:
4094   case ISD::FMUL:
4095   case ISD::FDIV:
4096   case ISD::FREM:
4097   case ISD::FSIN:
4098   case ISD::FCOS: {
4099     if (SNaN)
4100       return true;
4101     // TODO: Need isKnownNeverInfinity
4102     return false;
4103   }
4104   case ISD::FCANONICALIZE:
4105   case ISD::FEXP:
4106   case ISD::FEXP2:
4107   case ISD::FTRUNC:
4108   case ISD::FFLOOR:
4109   case ISD::FCEIL:
4110   case ISD::FROUND:
4111   case ISD::FROUNDEVEN:
4112   case ISD::FRINT:
4113   case ISD::FNEARBYINT: {
4114     if (SNaN)
4115       return true;
4116     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4117   }
4118   case ISD::FABS:
4119   case ISD::FNEG:
4120   case ISD::FCOPYSIGN: {
4121     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4122   }
4123   case ISD::SELECT:
4124     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4125            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4126   case ISD::FP_EXTEND:
4127   case ISD::FP_ROUND: {
4128     if (SNaN)
4129       return true;
4130     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4131   }
4132   case ISD::SINT_TO_FP:
4133   case ISD::UINT_TO_FP:
4134     return true;
4135   case ISD::FMA:
4136   case ISD::FMAD: {
4137     if (SNaN)
4138       return true;
4139     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4140            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4141            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4142   }
4143   case ISD::FSQRT: // Need is known positive
4144   case ISD::FLOG:
4145   case ISD::FLOG2:
4146   case ISD::FLOG10:
4147   case ISD::FPOWI:
4148   case ISD::FPOW: {
4149     if (SNaN)
4150       return true;
4151     // TODO: Refine on operand
4152     return false;
4153   }
4154   case ISD::FMINNUM:
4155   case ISD::FMAXNUM: {
4156     // Only one needs to be known not-nan, since it will be returned if the
4157     // other ends up being one.
4158     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4159            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4160   }
4161   case ISD::FMINNUM_IEEE:
4162   case ISD::FMAXNUM_IEEE: {
4163     if (SNaN)
4164       return true;
4165     // This can return a NaN if either operand is an sNaN, or if both operands
4166     // are NaN.
4167     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4168             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4169            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4170             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4171   }
4172   case ISD::FMINIMUM:
4173   case ISD::FMAXIMUM: {
4174     // TODO: Does this quiet or return the origina NaN as-is?
4175     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4176            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4177   }
4178   case ISD::EXTRACT_VECTOR_ELT: {
4179     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4180   }
4181   default:
4182     if (Opcode >= ISD::BUILTIN_OP_END ||
4183         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4184         Opcode == ISD::INTRINSIC_W_CHAIN ||
4185         Opcode == ISD::INTRINSIC_VOID) {
4186       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4187     }
4188 
4189     return false;
4190   }
4191 }
4192 
4193 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4194   assert(Op.getValueType().isFloatingPoint() &&
4195          "Floating point type expected");
4196 
4197   // If the value is a constant, we can obviously see if it is a zero or not.
4198   // TODO: Add BuildVector support.
4199   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4200     return !C->isZero();
4201   return false;
4202 }
4203 
4204 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4205   assert(!Op.getValueType().isFloatingPoint() &&
4206          "Floating point types unsupported - use isKnownNeverZeroFloat");
4207 
4208   // If the value is a constant, we can obviously see if it is a zero or not.
4209   if (ISD::matchUnaryPredicate(
4210           Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4211     return true;
4212 
4213   // TODO: Recognize more cases here.
4214   switch (Op.getOpcode()) {
4215   default: break;
4216   case ISD::OR:
4217     if (isKnownNeverZero(Op.getOperand(1)) ||
4218         isKnownNeverZero(Op.getOperand(0)))
4219       return true;
4220     break;
4221   }
4222 
4223   return false;
4224 }
4225 
4226 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4227   // Check the obvious case.
4228   if (A == B) return true;
4229 
4230   // For for negative and positive zero.
4231   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4232     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4233       if (CA->isZero() && CB->isZero()) return true;
4234 
4235   // Otherwise they may not be equal.
4236   return false;
4237 }
4238 
4239 // FIXME: unify with llvm::haveNoCommonBitsSet.
4240 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4241 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4242   assert(A.getValueType() == B.getValueType() &&
4243          "Values must have the same type");
4244   return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
4245 }
4246 
4247 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4248                                 ArrayRef<SDValue> Ops,
4249                                 SelectionDAG &DAG) {
4250   int NumOps = Ops.size();
4251   assert(NumOps != 0 && "Can't build an empty vector!");
4252   assert(!VT.isScalableVector() &&
4253          "BUILD_VECTOR cannot be used with scalable types");
4254   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4255          "Incorrect element count in BUILD_VECTOR!");
4256 
4257   // BUILD_VECTOR of UNDEFs is UNDEF.
4258   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4259     return DAG.getUNDEF(VT);
4260 
4261   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4262   SDValue IdentitySrc;
4263   bool IsIdentity = true;
4264   for (int i = 0; i != NumOps; ++i) {
4265     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4266         Ops[i].getOperand(0).getValueType() != VT ||
4267         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4268         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4269         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4270       IsIdentity = false;
4271       break;
4272     }
4273     IdentitySrc = Ops[i].getOperand(0);
4274   }
4275   if (IsIdentity)
4276     return IdentitySrc;
4277 
4278   return SDValue();
4279 }
4280 
4281 /// Try to simplify vector concatenation to an input value, undef, or build
4282 /// vector.
4283 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4284                                   ArrayRef<SDValue> Ops,
4285                                   SelectionDAG &DAG) {
4286   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4287   assert(llvm::all_of(Ops,
4288                       [Ops](SDValue Op) {
4289                         return Ops[0].getValueType() == Op.getValueType();
4290                       }) &&
4291          "Concatenation of vectors with inconsistent value types!");
4292   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4293              VT.getVectorElementCount() &&
4294          "Incorrect element count in vector concatenation!");
4295 
4296   if (Ops.size() == 1)
4297     return Ops[0];
4298 
4299   // Concat of UNDEFs is UNDEF.
4300   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4301     return DAG.getUNDEF(VT);
4302 
4303   // Scan the operands and look for extract operations from a single source
4304   // that correspond to insertion at the same location via this concatenation:
4305   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4306   SDValue IdentitySrc;
4307   bool IsIdentity = true;
4308   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4309     SDValue Op = Ops[i];
4310     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4311     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4312         Op.getOperand(0).getValueType() != VT ||
4313         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4314         Op.getConstantOperandVal(1) != IdentityIndex) {
4315       IsIdentity = false;
4316       break;
4317     }
4318     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4319            "Unexpected identity source vector for concat of extracts");
4320     IdentitySrc = Op.getOperand(0);
4321   }
4322   if (IsIdentity) {
4323     assert(IdentitySrc && "Failed to set source vector of extracts");
4324     return IdentitySrc;
4325   }
4326 
4327   // The code below this point is only designed to work for fixed width
4328   // vectors, so we bail out for now.
4329   if (VT.isScalableVector())
4330     return SDValue();
4331 
4332   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4333   // simplified to one big BUILD_VECTOR.
4334   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4335   EVT SVT = VT.getScalarType();
4336   SmallVector<SDValue, 16> Elts;
4337   for (SDValue Op : Ops) {
4338     EVT OpVT = Op.getValueType();
4339     if (Op.isUndef())
4340       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4341     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4342       Elts.append(Op->op_begin(), Op->op_end());
4343     else
4344       return SDValue();
4345   }
4346 
4347   // BUILD_VECTOR requires all inputs to be of the same type, find the
4348   // maximum type and extend them all.
4349   for (SDValue Op : Elts)
4350     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4351 
4352   if (SVT.bitsGT(VT.getScalarType())) {
4353     for (SDValue &Op : Elts) {
4354       if (Op.isUndef())
4355         Op = DAG.getUNDEF(SVT);
4356       else
4357         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4358                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4359                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4360     }
4361   }
4362 
4363   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4364   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4365   return V;
4366 }
4367 
4368 /// Gets or creates the specified node.
4369 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4370   FoldingSetNodeID ID;
4371   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4372   void *IP = nullptr;
4373   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4374     return SDValue(E, 0);
4375 
4376   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4377                               getVTList(VT));
4378   CSEMap.InsertNode(N, IP);
4379 
4380   InsertNode(N);
4381   SDValue V = SDValue(N, 0);
4382   NewSDValueDbgMsg(V, "Creating new node: ", this);
4383   return V;
4384 }
4385 
4386 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4387                               SDValue Operand) {
4388   SDNodeFlags Flags;
4389   if (Inserter)
4390     Flags = Inserter->getFlags();
4391   return getNode(Opcode, DL, VT, Operand, Flags);
4392 }
4393 
4394 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4395                               SDValue Operand, const SDNodeFlags Flags) {
4396   // Constant fold unary operations with an integer constant operand. Even
4397   // opaque constant will be folded, because the folding of unary operations
4398   // doesn't create new constants with different values. Nevertheless, the
4399   // opaque flag is preserved during folding to prevent future folding with
4400   // other constants.
4401   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4402     const APInt &Val = C->getAPIntValue();
4403     switch (Opcode) {
4404     default: break;
4405     case ISD::SIGN_EXTEND:
4406       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4407                          C->isTargetOpcode(), C->isOpaque());
4408     case ISD::TRUNCATE:
4409       if (C->isOpaque())
4410         break;
4411       LLVM_FALLTHROUGH;
4412     case ISD::ANY_EXTEND:
4413     case ISD::ZERO_EXTEND:
4414       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4415                          C->isTargetOpcode(), C->isOpaque());
4416     case ISD::UINT_TO_FP:
4417     case ISD::SINT_TO_FP: {
4418       APFloat apf(EVTToAPFloatSemantics(VT),
4419                   APInt::getNullValue(VT.getSizeInBits()));
4420       (void)apf.convertFromAPInt(Val,
4421                                  Opcode==ISD::SINT_TO_FP,
4422                                  APFloat::rmNearestTiesToEven);
4423       return getConstantFP(apf, DL, VT);
4424     }
4425     case ISD::BITCAST:
4426       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4427         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4428       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4429         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4430       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4431         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4432       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4433         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4434       break;
4435     case ISD::ABS:
4436       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4437                          C->isOpaque());
4438     case ISD::BITREVERSE:
4439       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4440                          C->isOpaque());
4441     case ISD::BSWAP:
4442       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4443                          C->isOpaque());
4444     case ISD::CTPOP:
4445       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4446                          C->isOpaque());
4447     case ISD::CTLZ:
4448     case ISD::CTLZ_ZERO_UNDEF:
4449       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4450                          C->isOpaque());
4451     case ISD::CTTZ:
4452     case ISD::CTTZ_ZERO_UNDEF:
4453       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4454                          C->isOpaque());
4455     case ISD::FP16_TO_FP: {
4456       bool Ignored;
4457       APFloat FPV(APFloat::IEEEhalf(),
4458                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4459 
4460       // This can return overflow, underflow, or inexact; we don't care.
4461       // FIXME need to be more flexible about rounding mode.
4462       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4463                         APFloat::rmNearestTiesToEven, &Ignored);
4464       return getConstantFP(FPV, DL, VT);
4465     }
4466     }
4467   }
4468 
4469   // Constant fold unary operations with a floating point constant operand.
4470   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4471     APFloat V = C->getValueAPF();    // make copy
4472     switch (Opcode) {
4473     case ISD::FNEG:
4474       V.changeSign();
4475       return getConstantFP(V, DL, VT);
4476     case ISD::FABS:
4477       V.clearSign();
4478       return getConstantFP(V, DL, VT);
4479     case ISD::FCEIL: {
4480       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4481       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4482         return getConstantFP(V, DL, VT);
4483       break;
4484     }
4485     case ISD::FTRUNC: {
4486       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4487       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4488         return getConstantFP(V, DL, VT);
4489       break;
4490     }
4491     case ISD::FFLOOR: {
4492       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4493       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4494         return getConstantFP(V, DL, VT);
4495       break;
4496     }
4497     case ISD::FP_EXTEND: {
4498       bool ignored;
4499       // This can return overflow, underflow, or inexact; we don't care.
4500       // FIXME need to be more flexible about rounding mode.
4501       (void)V.convert(EVTToAPFloatSemantics(VT),
4502                       APFloat::rmNearestTiesToEven, &ignored);
4503       return getConstantFP(V, DL, VT);
4504     }
4505     case ISD::FP_TO_SINT:
4506     case ISD::FP_TO_UINT: {
4507       bool ignored;
4508       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4509       // FIXME need to be more flexible about rounding mode.
4510       APFloat::opStatus s =
4511           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4512       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4513         break;
4514       return getConstant(IntVal, DL, VT);
4515     }
4516     case ISD::BITCAST:
4517       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4518         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4519       else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4520         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4521       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4522         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4523       break;
4524     case ISD::FP_TO_FP16: {
4525       bool Ignored;
4526       // This can return overflow, underflow, or inexact; we don't care.
4527       // FIXME need to be more flexible about rounding mode.
4528       (void)V.convert(APFloat::IEEEhalf(),
4529                       APFloat::rmNearestTiesToEven, &Ignored);
4530       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4531     }
4532     }
4533   }
4534 
4535   // Constant fold unary operations with a vector integer or float operand.
4536   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4537     if (BV->isConstant()) {
4538       switch (Opcode) {
4539       default:
4540         // FIXME: Entirely reasonable to perform folding of other unary
4541         // operations here as the need arises.
4542         break;
4543       case ISD::FNEG:
4544       case ISD::FABS:
4545       case ISD::FCEIL:
4546       case ISD::FTRUNC:
4547       case ISD::FFLOOR:
4548       case ISD::FP_EXTEND:
4549       case ISD::FP_TO_SINT:
4550       case ISD::FP_TO_UINT:
4551       case ISD::TRUNCATE:
4552       case ISD::ANY_EXTEND:
4553       case ISD::ZERO_EXTEND:
4554       case ISD::SIGN_EXTEND:
4555       case ISD::UINT_TO_FP:
4556       case ISD::SINT_TO_FP:
4557       case ISD::ABS:
4558       case ISD::BITREVERSE:
4559       case ISD::BSWAP:
4560       case ISD::CTLZ:
4561       case ISD::CTLZ_ZERO_UNDEF:
4562       case ISD::CTTZ:
4563       case ISD::CTTZ_ZERO_UNDEF:
4564       case ISD::CTPOP: {
4565         SDValue Ops = { Operand };
4566         if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4567           return Fold;
4568       }
4569       }
4570     }
4571   }
4572 
4573   unsigned OpOpcode = Operand.getNode()->getOpcode();
4574   switch (Opcode) {
4575   case ISD::FREEZE:
4576     assert(VT == Operand.getValueType() && "Unexpected VT!");
4577     break;
4578   case ISD::TokenFactor:
4579   case ISD::MERGE_VALUES:
4580   case ISD::CONCAT_VECTORS:
4581     return Operand;         // Factor, merge or concat of one node?  No need.
4582   case ISD::BUILD_VECTOR: {
4583     // Attempt to simplify BUILD_VECTOR.
4584     SDValue Ops[] = {Operand};
4585     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4586       return V;
4587     break;
4588   }
4589   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4590   case ISD::FP_EXTEND:
4591     assert(VT.isFloatingPoint() &&
4592            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4593     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4594     assert((!VT.isVector() ||
4595             VT.getVectorElementCount() ==
4596             Operand.getValueType().getVectorElementCount()) &&
4597            "Vector element count mismatch!");
4598     assert(Operand.getValueType().bitsLT(VT) &&
4599            "Invalid fpext node, dst < src!");
4600     if (Operand.isUndef())
4601       return getUNDEF(VT);
4602     break;
4603   case ISD::FP_TO_SINT:
4604   case ISD::FP_TO_UINT:
4605     if (Operand.isUndef())
4606       return getUNDEF(VT);
4607     break;
4608   case ISD::SINT_TO_FP:
4609   case ISD::UINT_TO_FP:
4610     // [us]itofp(undef) = 0, because the result value is bounded.
4611     if (Operand.isUndef())
4612       return getConstantFP(0.0, DL, VT);
4613     break;
4614   case ISD::SIGN_EXTEND:
4615     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4616            "Invalid SIGN_EXTEND!");
4617     assert(VT.isVector() == Operand.getValueType().isVector() &&
4618            "SIGN_EXTEND result type type should be vector iff the operand "
4619            "type is vector!");
4620     if (Operand.getValueType() == VT) return Operand;   // noop extension
4621     assert((!VT.isVector() ||
4622             VT.getVectorElementCount() ==
4623                 Operand.getValueType().getVectorElementCount()) &&
4624            "Vector element count mismatch!");
4625     assert(Operand.getValueType().bitsLT(VT) &&
4626            "Invalid sext node, dst < src!");
4627     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4628       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4629     else if (OpOpcode == ISD::UNDEF)
4630       // sext(undef) = 0, because the top bits will all be the same.
4631       return getConstant(0, DL, VT);
4632     break;
4633   case ISD::ZERO_EXTEND:
4634     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4635            "Invalid ZERO_EXTEND!");
4636     assert(VT.isVector() == Operand.getValueType().isVector() &&
4637            "ZERO_EXTEND result type type should be vector iff the operand "
4638            "type is vector!");
4639     if (Operand.getValueType() == VT) return Operand;   // noop extension
4640     assert((!VT.isVector() ||
4641             VT.getVectorElementCount() ==
4642                 Operand.getValueType().getVectorElementCount()) &&
4643            "Vector element count mismatch!");
4644     assert(Operand.getValueType().bitsLT(VT) &&
4645            "Invalid zext node, dst < src!");
4646     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4647       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4648     else if (OpOpcode == ISD::UNDEF)
4649       // zext(undef) = 0, because the top bits will be zero.
4650       return getConstant(0, DL, VT);
4651     break;
4652   case ISD::ANY_EXTEND:
4653     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4654            "Invalid ANY_EXTEND!");
4655     assert(VT.isVector() == Operand.getValueType().isVector() &&
4656            "ANY_EXTEND result type type should be vector iff the operand "
4657            "type is vector!");
4658     if (Operand.getValueType() == VT) return Operand;   // noop extension
4659     assert((!VT.isVector() ||
4660             VT.getVectorElementCount() ==
4661                 Operand.getValueType().getVectorElementCount()) &&
4662            "Vector element count mismatch!");
4663     assert(Operand.getValueType().bitsLT(VT) &&
4664            "Invalid anyext node, dst < src!");
4665 
4666     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4667         OpOpcode == ISD::ANY_EXTEND)
4668       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4669       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4670     else if (OpOpcode == ISD::UNDEF)
4671       return getUNDEF(VT);
4672 
4673     // (ext (trunc x)) -> x
4674     if (OpOpcode == ISD::TRUNCATE) {
4675       SDValue OpOp = Operand.getOperand(0);
4676       if (OpOp.getValueType() == VT) {
4677         transferDbgValues(Operand, OpOp);
4678         return OpOp;
4679       }
4680     }
4681     break;
4682   case ISD::TRUNCATE:
4683     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4684            "Invalid TRUNCATE!");
4685     assert(VT.isVector() == Operand.getValueType().isVector() &&
4686            "TRUNCATE result type type should be vector iff the operand "
4687            "type is vector!");
4688     if (Operand.getValueType() == VT) return Operand;   // noop truncate
4689     assert((!VT.isVector() ||
4690             VT.getVectorElementCount() ==
4691                 Operand.getValueType().getVectorElementCount()) &&
4692            "Vector element count mismatch!");
4693     assert(Operand.getValueType().bitsGT(VT) &&
4694            "Invalid truncate node, src < dst!");
4695     if (OpOpcode == ISD::TRUNCATE)
4696       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4697     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4698         OpOpcode == ISD::ANY_EXTEND) {
4699       // If the source is smaller than the dest, we still need an extend.
4700       if (Operand.getOperand(0).getValueType().getScalarType()
4701             .bitsLT(VT.getScalarType()))
4702         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4703       if (Operand.getOperand(0).getValueType().bitsGT(VT))
4704         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4705       return Operand.getOperand(0);
4706     }
4707     if (OpOpcode == ISD::UNDEF)
4708       return getUNDEF(VT);
4709     break;
4710   case ISD::ANY_EXTEND_VECTOR_INREG:
4711   case ISD::ZERO_EXTEND_VECTOR_INREG:
4712   case ISD::SIGN_EXTEND_VECTOR_INREG:
4713     assert(VT.isVector() && "This DAG node is restricted to vector types.");
4714     assert(Operand.getValueType().bitsLE(VT) &&
4715            "The input must be the same size or smaller than the result.");
4716     assert(VT.getVectorNumElements() <
4717              Operand.getValueType().getVectorNumElements() &&
4718            "The destination vector type must have fewer lanes than the input.");
4719     break;
4720   case ISD::ABS:
4721     assert(VT.isInteger() && VT == Operand.getValueType() &&
4722            "Invalid ABS!");
4723     if (OpOpcode == ISD::UNDEF)
4724       return getUNDEF(VT);
4725     break;
4726   case ISD::BSWAP:
4727     assert(VT.isInteger() && VT == Operand.getValueType() &&
4728            "Invalid BSWAP!");
4729     assert((VT.getScalarSizeInBits() % 16 == 0) &&
4730            "BSWAP types must be a multiple of 16 bits!");
4731     if (OpOpcode == ISD::UNDEF)
4732       return getUNDEF(VT);
4733     break;
4734   case ISD::BITREVERSE:
4735     assert(VT.isInteger() && VT == Operand.getValueType() &&
4736            "Invalid BITREVERSE!");
4737     if (OpOpcode == ISD::UNDEF)
4738       return getUNDEF(VT);
4739     break;
4740   case ISD::BITCAST:
4741     // Basic sanity checking.
4742     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4743            "Cannot BITCAST between types of different sizes!");
4744     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
4745     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
4746       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4747     if (OpOpcode == ISD::UNDEF)
4748       return getUNDEF(VT);
4749     break;
4750   case ISD::SCALAR_TO_VECTOR:
4751     assert(VT.isVector() && !Operand.getValueType().isVector() &&
4752            (VT.getVectorElementType() == Operand.getValueType() ||
4753             (VT.getVectorElementType().isInteger() &&
4754              Operand.getValueType().isInteger() &&
4755              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4756            "Illegal SCALAR_TO_VECTOR node!");
4757     if (OpOpcode == ISD::UNDEF)
4758       return getUNDEF(VT);
4759     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4760     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4761         isa<ConstantSDNode>(Operand.getOperand(1)) &&
4762         Operand.getConstantOperandVal(1) == 0 &&
4763         Operand.getOperand(0).getValueType() == VT)
4764       return Operand.getOperand(0);
4765     break;
4766   case ISD::FNEG:
4767     // Negation of an unknown bag of bits is still completely undefined.
4768     if (OpOpcode == ISD::UNDEF)
4769       return getUNDEF(VT);
4770 
4771     if (OpOpcode == ISD::FNEG)  // --X -> X
4772       return Operand.getOperand(0);
4773     break;
4774   case ISD::FABS:
4775     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
4776       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4777     break;
4778   case ISD::VSCALE:
4779     assert(VT == Operand.getValueType() && "Unexpected VT!");
4780     break;
4781   case ISD::VECREDUCE_SMIN:
4782   case ISD::VECREDUCE_UMAX:
4783     if (Operand.getValueType().getScalarType() == MVT::i1)
4784       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
4785     break;
4786   case ISD::VECREDUCE_SMAX:
4787   case ISD::VECREDUCE_UMIN:
4788     if (Operand.getValueType().getScalarType() == MVT::i1)
4789       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
4790     break;
4791   }
4792 
4793   SDNode *N;
4794   SDVTList VTs = getVTList(VT);
4795   SDValue Ops[] = {Operand};
4796   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4797     FoldingSetNodeID ID;
4798     AddNodeIDNode(ID, Opcode, VTs, Ops);
4799     void *IP = nullptr;
4800     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4801       E->intersectFlagsWith(Flags);
4802       return SDValue(E, 0);
4803     }
4804 
4805     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4806     N->setFlags(Flags);
4807     createOperands(N, Ops);
4808     CSEMap.InsertNode(N, IP);
4809   } else {
4810     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4811     createOperands(N, Ops);
4812   }
4813 
4814   InsertNode(N);
4815   SDValue V = SDValue(N, 0);
4816   NewSDValueDbgMsg(V, "Creating new node: ", this);
4817   return V;
4818 }
4819 
4820 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
4821                                        const APInt &C2) {
4822   switch (Opcode) {
4823   case ISD::ADD:  return C1 + C2;
4824   case ISD::SUB:  return C1 - C2;
4825   case ISD::MUL:  return C1 * C2;
4826   case ISD::AND:  return C1 & C2;
4827   case ISD::OR:   return C1 | C2;
4828   case ISD::XOR:  return C1 ^ C2;
4829   case ISD::SHL:  return C1 << C2;
4830   case ISD::SRL:  return C1.lshr(C2);
4831   case ISD::SRA:  return C1.ashr(C2);
4832   case ISD::ROTL: return C1.rotl(C2);
4833   case ISD::ROTR: return C1.rotr(C2);
4834   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
4835   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
4836   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
4837   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
4838   case ISD::SADDSAT: return C1.sadd_sat(C2);
4839   case ISD::UADDSAT: return C1.uadd_sat(C2);
4840   case ISD::SSUBSAT: return C1.ssub_sat(C2);
4841   case ISD::USUBSAT: return C1.usub_sat(C2);
4842   case ISD::UDIV:
4843     if (!C2.getBoolValue())
4844       break;
4845     return C1.udiv(C2);
4846   case ISD::UREM:
4847     if (!C2.getBoolValue())
4848       break;
4849     return C1.urem(C2);
4850   case ISD::SDIV:
4851     if (!C2.getBoolValue())
4852       break;
4853     return C1.sdiv(C2);
4854   case ISD::SREM:
4855     if (!C2.getBoolValue())
4856       break;
4857     return C1.srem(C2);
4858   }
4859   return llvm::None;
4860 }
4861 
4862 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
4863                                        const GlobalAddressSDNode *GA,
4864                                        const SDNode *N2) {
4865   if (GA->getOpcode() != ISD::GlobalAddress)
4866     return SDValue();
4867   if (!TLI->isOffsetFoldingLegal(GA))
4868     return SDValue();
4869   auto *C2 = dyn_cast<ConstantSDNode>(N2);
4870   if (!C2)
4871     return SDValue();
4872   int64_t Offset = C2->getSExtValue();
4873   switch (Opcode) {
4874   case ISD::ADD: break;
4875   case ISD::SUB: Offset = -uint64_t(Offset); break;
4876   default: return SDValue();
4877   }
4878   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
4879                           GA->getOffset() + uint64_t(Offset));
4880 }
4881 
4882 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4883   switch (Opcode) {
4884   case ISD::SDIV:
4885   case ISD::UDIV:
4886   case ISD::SREM:
4887   case ISD::UREM: {
4888     // If a divisor is zero/undef or any element of a divisor vector is
4889     // zero/undef, the whole op is undef.
4890     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4891     SDValue Divisor = Ops[1];
4892     if (Divisor.isUndef() || isNullConstant(Divisor))
4893       return true;
4894 
4895     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
4896            llvm::any_of(Divisor->op_values(),
4897                         [](SDValue V) { return V.isUndef() ||
4898                                         isNullConstant(V); });
4899     // TODO: Handle signed overflow.
4900   }
4901   // TODO: Handle oversized shifts.
4902   default:
4903     return false;
4904   }
4905 }
4906 
4907 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4908                                              EVT VT, ArrayRef<SDValue> Ops) {
4909   // If the opcode is a target-specific ISD node, there's nothing we can
4910   // do here and the operand rules may not line up with the below, so
4911   // bail early.
4912   if (Opcode >= ISD::BUILTIN_OP_END)
4913     return SDValue();
4914 
4915   // For now, the array Ops should only contain two values.
4916   // This enforcement will be removed once this function is merged with
4917   // FoldConstantVectorArithmetic
4918   if (Ops.size() != 2)
4919     return SDValue();
4920 
4921   if (isUndef(Opcode, Ops))
4922     return getUNDEF(VT);
4923 
4924   SDNode *N1 = Ops[0].getNode();
4925   SDNode *N2 = Ops[1].getNode();
4926 
4927   // Handle the case of two scalars.
4928   if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
4929     if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
4930       if (C1->isOpaque() || C2->isOpaque())
4931         return SDValue();
4932 
4933       Optional<APInt> FoldAttempt =
4934           FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
4935       if (!FoldAttempt)
4936         return SDValue();
4937 
4938       SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
4939       assert((!Folded || !VT.isVector()) &&
4940              "Can't fold vectors ops with scalar operands");
4941       return Folded;
4942     }
4943   }
4944 
4945   // fold (add Sym, c) -> Sym+c
4946   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
4947     return FoldSymbolOffset(Opcode, VT, GA, N2);
4948   if (TLI->isCommutativeBinOp(Opcode))
4949     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
4950       return FoldSymbolOffset(Opcode, VT, GA, N1);
4951 
4952   // TODO: All the folds below are performed lane-by-lane and assume a fixed
4953   // vector width, however we should be able to do constant folds involving
4954   // splat vector nodes too.
4955   if (VT.isScalableVector())
4956     return SDValue();
4957 
4958   // For fixed width vectors, extract each constant element and fold them
4959   // individually. Either input may be an undef value.
4960   auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
4961   if (!BV1 && !N1->isUndef())
4962     return SDValue();
4963   auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
4964   if (!BV2 && !N2->isUndef())
4965     return SDValue();
4966   // If both operands are undef, that's handled the same way as scalars.
4967   if (!BV1 && !BV2)
4968     return SDValue();
4969 
4970   assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
4971          "Vector binop with different number of elements in operands?");
4972 
4973   EVT SVT = VT.getScalarType();
4974   EVT LegalSVT = SVT;
4975   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4976     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4977     if (LegalSVT.bitsLT(SVT))
4978       return SDValue();
4979   }
4980   SmallVector<SDValue, 4> Outputs;
4981   unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
4982   for (unsigned I = 0; I != NumOps; ++I) {
4983     SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
4984     SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
4985     if (SVT.isInteger()) {
4986       if (V1->getValueType(0).bitsGT(SVT))
4987         V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
4988       if (V2->getValueType(0).bitsGT(SVT))
4989         V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
4990     }
4991 
4992     if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
4993       return SDValue();
4994 
4995     // Fold one vector element.
4996     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
4997     if (LegalSVT != SVT)
4998       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4999 
5000     // Scalar folding only succeeded if the result is a constant or UNDEF.
5001     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5002         ScalarResult.getOpcode() != ISD::ConstantFP)
5003       return SDValue();
5004     Outputs.push_back(ScalarResult);
5005   }
5006 
5007   assert(VT.getVectorNumElements() == Outputs.size() &&
5008          "Vector size mismatch!");
5009 
5010   // We may have a vector type but a scalar result. Create a splat.
5011   Outputs.resize(VT.getVectorNumElements(), Outputs.back());
5012 
5013   // Build a big vector out of the scalar elements we generated.
5014   return getBuildVector(VT, SDLoc(), Outputs);
5015 }
5016 
5017 // TODO: Merge with FoldConstantArithmetic
5018 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
5019                                                    const SDLoc &DL, EVT VT,
5020                                                    ArrayRef<SDValue> Ops,
5021                                                    const SDNodeFlags Flags) {
5022   // If the opcode is a target-specific ISD node, there's nothing we can
5023   // do here and the operand rules may not line up with the below, so
5024   // bail early.
5025   if (Opcode >= ISD::BUILTIN_OP_END)
5026     return SDValue();
5027 
5028   if (isUndef(Opcode, Ops))
5029     return getUNDEF(VT);
5030 
5031   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
5032   if (!VT.isVector())
5033     return SDValue();
5034 
5035   // TODO: All the folds below are performed lane-by-lane and assume a fixed
5036   // vector width, however we should be able to do constant folds involving
5037   // splat vector nodes too.
5038   if (VT.isScalableVector())
5039     return SDValue();
5040 
5041   // From this point onwards all vectors are assumed to be fixed width.
5042   unsigned NumElts = VT.getVectorNumElements();
5043 
5044   auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
5045     return !Op.getValueType().isVector() ||
5046            Op.getValueType().getVectorNumElements() == NumElts;
5047   };
5048 
5049   auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
5050     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
5051     return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
5052            (BV && BV->isConstant());
5053   };
5054 
5055   // All operands must be vector types with the same number of elements as
5056   // the result type and must be either UNDEF or a build vector of constant
5057   // or UNDEF scalars.
5058   if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
5059       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5060     return SDValue();
5061 
5062   // If we are comparing vectors, then the result needs to be a i1 boolean
5063   // that is then sign-extended back to the legal result type.
5064   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5065 
5066   // Find legal integer scalar type for constant promotion and
5067   // ensure that its scalar size is at least as large as source.
5068   EVT LegalSVT = VT.getScalarType();
5069   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5070     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5071     if (LegalSVT.bitsLT(VT.getScalarType()))
5072       return SDValue();
5073   }
5074 
5075   // Constant fold each scalar lane separately.
5076   SmallVector<SDValue, 4> ScalarResults;
5077   for (unsigned i = 0; i != NumElts; i++) {
5078     SmallVector<SDValue, 4> ScalarOps;
5079     for (SDValue Op : Ops) {
5080       EVT InSVT = Op.getValueType().getScalarType();
5081       BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
5082       if (!InBV) {
5083         // We've checked that this is UNDEF or a constant of some kind.
5084         if (Op.isUndef())
5085           ScalarOps.push_back(getUNDEF(InSVT));
5086         else
5087           ScalarOps.push_back(Op);
5088         continue;
5089       }
5090 
5091       SDValue ScalarOp = InBV->getOperand(i);
5092       EVT ScalarVT = ScalarOp.getValueType();
5093 
5094       // Build vector (integer) scalar operands may need implicit
5095       // truncation - do this before constant folding.
5096       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5097         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5098 
5099       ScalarOps.push_back(ScalarOp);
5100     }
5101 
5102     // Constant fold the scalar operands.
5103     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
5104 
5105     // Legalize the (integer) scalar constant if necessary.
5106     if (LegalSVT != SVT)
5107       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5108 
5109     // Scalar folding only succeeded if the result is a constant or UNDEF.
5110     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5111         ScalarResult.getOpcode() != ISD::ConstantFP)
5112       return SDValue();
5113     ScalarResults.push_back(ScalarResult);
5114   }
5115 
5116   SDValue V = getBuildVector(VT, DL, ScalarResults);
5117   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5118   return V;
5119 }
5120 
5121 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5122                                          EVT VT, SDValue N1, SDValue N2) {
5123   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5124   //       should. That will require dealing with a potentially non-default
5125   //       rounding mode, checking the "opStatus" return value from the APFloat
5126   //       math calculations, and possibly other variations.
5127   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5128   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5129   if (N1CFP && N2CFP) {
5130     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5131     switch (Opcode) {
5132     case ISD::FADD:
5133       C1.add(C2, APFloat::rmNearestTiesToEven);
5134       return getConstantFP(C1, DL, VT);
5135     case ISD::FSUB:
5136       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5137       return getConstantFP(C1, DL, VT);
5138     case ISD::FMUL:
5139       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5140       return getConstantFP(C1, DL, VT);
5141     case ISD::FDIV:
5142       C1.divide(C2, APFloat::rmNearestTiesToEven);
5143       return getConstantFP(C1, DL, VT);
5144     case ISD::FREM:
5145       C1.mod(C2);
5146       return getConstantFP(C1, DL, VT);
5147     case ISD::FCOPYSIGN:
5148       C1.copySign(C2);
5149       return getConstantFP(C1, DL, VT);
5150     default: break;
5151     }
5152   }
5153   if (N1CFP && Opcode == ISD::FP_ROUND) {
5154     APFloat C1 = N1CFP->getValueAPF();    // make copy
5155     bool Unused;
5156     // This can return overflow, underflow, or inexact; we don't care.
5157     // FIXME need to be more flexible about rounding mode.
5158     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5159                       &Unused);
5160     return getConstantFP(C1, DL, VT);
5161   }
5162 
5163   switch (Opcode) {
5164   case ISD::FSUB:
5165     // -0.0 - undef --> undef (consistent with "fneg undef")
5166     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5167       return getUNDEF(VT);
5168     LLVM_FALLTHROUGH;
5169 
5170   case ISD::FADD:
5171   case ISD::FMUL:
5172   case ISD::FDIV:
5173   case ISD::FREM:
5174     // If both operands are undef, the result is undef. If 1 operand is undef,
5175     // the result is NaN. This should match the behavior of the IR optimizer.
5176     if (N1.isUndef() && N2.isUndef())
5177       return getUNDEF(VT);
5178     if (N1.isUndef() || N2.isUndef())
5179       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5180   }
5181   return SDValue();
5182 }
5183 
5184 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5185   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5186 
5187   // There's no need to assert on a byte-aligned pointer. All pointers are at
5188   // least byte aligned.
5189   if (A == Align(1))
5190     return Val;
5191 
5192   FoldingSetNodeID ID;
5193   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5194   ID.AddInteger(A.value());
5195 
5196   void *IP = nullptr;
5197   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5198     return SDValue(E, 0);
5199 
5200   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5201                                          Val.getValueType(), A);
5202   createOperands(N, {Val});
5203 
5204   CSEMap.InsertNode(N, IP);
5205   InsertNode(N);
5206 
5207   SDValue V(N, 0);
5208   NewSDValueDbgMsg(V, "Creating new node: ", this);
5209   return V;
5210 }
5211 
5212 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5213                               SDValue N1, SDValue N2) {
5214   SDNodeFlags Flags;
5215   if (Inserter)
5216     Flags = Inserter->getFlags();
5217   return getNode(Opcode, DL, VT, N1, N2, Flags);
5218 }
5219 
5220 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5221                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5222   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5223   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5224   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5225   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5226 
5227   // Canonicalize constant to RHS if commutative.
5228   if (TLI->isCommutativeBinOp(Opcode)) {
5229     if (N1C && !N2C) {
5230       std::swap(N1C, N2C);
5231       std::swap(N1, N2);
5232     } else if (N1CFP && !N2CFP) {
5233       std::swap(N1CFP, N2CFP);
5234       std::swap(N1, N2);
5235     }
5236   }
5237 
5238   switch (Opcode) {
5239   default: break;
5240   case ISD::TokenFactor:
5241     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5242            N2.getValueType() == MVT::Other && "Invalid token factor!");
5243     // Fold trivial token factors.
5244     if (N1.getOpcode() == ISD::EntryToken) return N2;
5245     if (N2.getOpcode() == ISD::EntryToken) return N1;
5246     if (N1 == N2) return N1;
5247     break;
5248   case ISD::BUILD_VECTOR: {
5249     // Attempt to simplify BUILD_VECTOR.
5250     SDValue Ops[] = {N1, N2};
5251     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5252       return V;
5253     break;
5254   }
5255   case ISD::CONCAT_VECTORS: {
5256     SDValue Ops[] = {N1, N2};
5257     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5258       return V;
5259     break;
5260   }
5261   case ISD::AND:
5262     assert(VT.isInteger() && "This operator does not apply to FP types!");
5263     assert(N1.getValueType() == N2.getValueType() &&
5264            N1.getValueType() == VT && "Binary operator types must match!");
5265     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5266     // worth handling here.
5267     if (N2C && N2C->isNullValue())
5268       return N2;
5269     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
5270       return N1;
5271     break;
5272   case ISD::OR:
5273   case ISD::XOR:
5274   case ISD::ADD:
5275   case ISD::SUB:
5276     assert(VT.isInteger() && "This operator does not apply to FP types!");
5277     assert(N1.getValueType() == N2.getValueType() &&
5278            N1.getValueType() == VT && "Binary operator types must match!");
5279     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5280     // it's worth handling here.
5281     if (N2C && N2C->isNullValue())
5282       return N1;
5283     break;
5284   case ISD::MUL:
5285     assert(VT.isInteger() && "This operator does not apply to FP types!");
5286     assert(N1.getValueType() == N2.getValueType() &&
5287            N1.getValueType() == VT && "Binary operator types must match!");
5288     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5289       APInt MulImm = cast<ConstantSDNode>(N1->getOperand(0))->getAPIntValue();
5290       APInt N2CImm = N2C->getAPIntValue();
5291       return getVScale(DL, VT, MulImm * N2CImm);
5292     }
5293     break;
5294   case ISD::UDIV:
5295   case ISD::UREM:
5296   case ISD::MULHU:
5297   case ISD::MULHS:
5298   case ISD::SDIV:
5299   case ISD::SREM:
5300   case ISD::SADDSAT:
5301   case ISD::SSUBSAT:
5302   case ISD::UADDSAT:
5303   case ISD::USUBSAT:
5304     assert(VT.isInteger() && "This operator does not apply to FP types!");
5305     assert(N1.getValueType() == N2.getValueType() &&
5306            N1.getValueType() == VT && "Binary operator types must match!");
5307     break;
5308   case ISD::SMIN:
5309   case ISD::UMAX:
5310     assert(VT.isInteger() && "This operator does not apply to FP types!");
5311     assert(N1.getValueType() == N2.getValueType() &&
5312            N1.getValueType() == VT && "Binary operator types must match!");
5313     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5314       return getNode(ISD::OR, DL, VT, N1, N2);
5315     break;
5316   case ISD::SMAX:
5317   case ISD::UMIN:
5318     assert(VT.isInteger() && "This operator does not apply to FP types!");
5319     assert(N1.getValueType() == N2.getValueType() &&
5320            N1.getValueType() == VT && "Binary operator types must match!");
5321     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5322       return getNode(ISD::AND, DL, VT, N1, N2);
5323     break;
5324   case ISD::FADD:
5325   case ISD::FSUB:
5326   case ISD::FMUL:
5327   case ISD::FDIV:
5328   case ISD::FREM:
5329     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5330     assert(N1.getValueType() == N2.getValueType() &&
5331            N1.getValueType() == VT && "Binary operator types must match!");
5332     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5333       return V;
5334     break;
5335   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5336     assert(N1.getValueType() == VT &&
5337            N1.getValueType().isFloatingPoint() &&
5338            N2.getValueType().isFloatingPoint() &&
5339            "Invalid FCOPYSIGN!");
5340     break;
5341   case ISD::SHL:
5342     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5343       APInt MulImm = cast<ConstantSDNode>(N1->getOperand(0))->getAPIntValue();
5344       APInt ShiftImm = N2C->getAPIntValue();
5345       return getVScale(DL, VT, MulImm << ShiftImm);
5346     }
5347     LLVM_FALLTHROUGH;
5348   case ISD::SRA:
5349   case ISD::SRL:
5350     if (SDValue V = simplifyShift(N1, N2))
5351       return V;
5352     LLVM_FALLTHROUGH;
5353   case ISD::ROTL:
5354   case ISD::ROTR:
5355     assert(VT == N1.getValueType() &&
5356            "Shift operators return type must be the same as their first arg");
5357     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5358            "Shifts only work on integers");
5359     assert((!VT.isVector() || VT == N2.getValueType()) &&
5360            "Vector shift amounts must be in the same as their first arg");
5361     // Verify that the shift amount VT is big enough to hold valid shift
5362     // amounts.  This catches things like trying to shift an i1024 value by an
5363     // i8, which is easy to fall into in generic code that uses
5364     // TLI.getShiftAmount().
5365     assert(N2.getValueType().getScalarSizeInBits() >=
5366                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5367            "Invalid use of small shift amount with oversized value!");
5368 
5369     // Always fold shifts of i1 values so the code generator doesn't need to
5370     // handle them.  Since we know the size of the shift has to be less than the
5371     // size of the value, the shift/rotate count is guaranteed to be zero.
5372     if (VT == MVT::i1)
5373       return N1;
5374     if (N2C && N2C->isNullValue())
5375       return N1;
5376     break;
5377   case ISD::FP_ROUND:
5378     assert(VT.isFloatingPoint() &&
5379            N1.getValueType().isFloatingPoint() &&
5380            VT.bitsLE(N1.getValueType()) &&
5381            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5382            "Invalid FP_ROUND!");
5383     if (N1.getValueType() == VT) return N1;  // noop conversion.
5384     break;
5385   case ISD::AssertSext:
5386   case ISD::AssertZext: {
5387     EVT EVT = cast<VTSDNode>(N2)->getVT();
5388     assert(VT == N1.getValueType() && "Not an inreg extend!");
5389     assert(VT.isInteger() && EVT.isInteger() &&
5390            "Cannot *_EXTEND_INREG FP types");
5391     assert(!EVT.isVector() &&
5392            "AssertSExt/AssertZExt type should be the vector element type "
5393            "rather than the vector type!");
5394     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5395     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5396     break;
5397   }
5398   case ISD::SIGN_EXTEND_INREG: {
5399     EVT EVT = cast<VTSDNode>(N2)->getVT();
5400     assert(VT == N1.getValueType() && "Not an inreg extend!");
5401     assert(VT.isInteger() && EVT.isInteger() &&
5402            "Cannot *_EXTEND_INREG FP types");
5403     assert(EVT.isVector() == VT.isVector() &&
5404            "SIGN_EXTEND_INREG type should be vector iff the operand "
5405            "type is vector!");
5406     assert((!EVT.isVector() ||
5407             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5408            "Vector element counts must match in SIGN_EXTEND_INREG");
5409     assert(EVT.bitsLE(VT) && "Not extending!");
5410     if (EVT == VT) return N1;  // Not actually extending
5411 
5412     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5413       unsigned FromBits = EVT.getScalarSizeInBits();
5414       Val <<= Val.getBitWidth() - FromBits;
5415       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5416       return getConstant(Val, DL, ConstantVT);
5417     };
5418 
5419     if (N1C) {
5420       const APInt &Val = N1C->getAPIntValue();
5421       return SignExtendInReg(Val, VT);
5422     }
5423     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5424       SmallVector<SDValue, 8> Ops;
5425       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5426       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5427         SDValue Op = N1.getOperand(i);
5428         if (Op.isUndef()) {
5429           Ops.push_back(getUNDEF(OpVT));
5430           continue;
5431         }
5432         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5433         APInt Val = C->getAPIntValue();
5434         Ops.push_back(SignExtendInReg(Val, OpVT));
5435       }
5436       return getBuildVector(VT, DL, Ops);
5437     }
5438     break;
5439   }
5440   case ISD::EXTRACT_VECTOR_ELT:
5441     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5442            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5443              element type of the vector.");
5444 
5445     // Extract from an undefined value or using an undefined index is undefined.
5446     if (N1.isUndef() || N2.isUndef())
5447       return getUNDEF(VT);
5448 
5449     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5450     // vectors. For scalable vectors we will provide appropriate support for
5451     // dealing with arbitrary indices.
5452     if (N2C && N1.getValueType().isFixedLengthVector() &&
5453         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5454       return getUNDEF(VT);
5455 
5456     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5457     // expanding copies of large vectors from registers. This only works for
5458     // fixed length vectors, since we need to know the exact number of
5459     // elements.
5460     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5461         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5462       unsigned Factor =
5463         N1.getOperand(0).getValueType().getVectorNumElements();
5464       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5465                      N1.getOperand(N2C->getZExtValue() / Factor),
5466                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5467     }
5468 
5469     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5470     // lowering is expanding large vector constants.
5471     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5472                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5473       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5474               N1.getValueType().isFixedLengthVector()) &&
5475              "BUILD_VECTOR used for scalable vectors");
5476       unsigned Index =
5477           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5478       SDValue Elt = N1.getOperand(Index);
5479 
5480       if (VT != Elt.getValueType())
5481         // If the vector element type is not legal, the BUILD_VECTOR operands
5482         // are promoted and implicitly truncated, and the result implicitly
5483         // extended. Make that explicit here.
5484         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5485 
5486       return Elt;
5487     }
5488 
5489     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5490     // operations are lowered to scalars.
5491     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5492       // If the indices are the same, return the inserted element else
5493       // if the indices are known different, extract the element from
5494       // the original vector.
5495       SDValue N1Op2 = N1.getOperand(2);
5496       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5497 
5498       if (N1Op2C && N2C) {
5499         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5500           if (VT == N1.getOperand(1).getValueType())
5501             return N1.getOperand(1);
5502           else
5503             return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5504         }
5505 
5506         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5507       }
5508     }
5509 
5510     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5511     // when vector types are scalarized and v1iX is legal.
5512     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5513     // Here we are completely ignoring the extract element index (N2),
5514     // which is fine for fixed width vectors, since any index other than 0
5515     // is undefined anyway. However, this cannot be ignored for scalable
5516     // vectors - in theory we could support this, but we don't want to do this
5517     // without a profitability check.
5518     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5519         N1.getValueType().isFixedLengthVector() &&
5520         N1.getValueType().getVectorNumElements() == 1) {
5521       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5522                      N1.getOperand(1));
5523     }
5524     break;
5525   case ISD::EXTRACT_ELEMENT:
5526     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5527     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5528            (N1.getValueType().isInteger() == VT.isInteger()) &&
5529            N1.getValueType() != VT &&
5530            "Wrong types for EXTRACT_ELEMENT!");
5531 
5532     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5533     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5534     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5535     if (N1.getOpcode() == ISD::BUILD_PAIR)
5536       return N1.getOperand(N2C->getZExtValue());
5537 
5538     // EXTRACT_ELEMENT of a constant int is also very common.
5539     if (N1C) {
5540       unsigned ElementSize = VT.getSizeInBits();
5541       unsigned Shift = ElementSize * N2C->getZExtValue();
5542       APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
5543       return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
5544     }
5545     break;
5546   case ISD::EXTRACT_SUBVECTOR:
5547     EVT N1VT = N1.getValueType();
5548     assert(VT.isVector() && N1VT.isVector() &&
5549            "Extract subvector VTs must be vectors!");
5550     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5551            "Extract subvector VTs must have the same element type!");
5552     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5553            "Cannot extract a scalable vector from a fixed length vector!");
5554     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5555             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5556            "Extract subvector must be from larger vector to smaller vector!");
5557     assert(N2C && "Extract subvector index must be a constant");
5558     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5559             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5560                 N1VT.getVectorMinNumElements()) &&
5561            "Extract subvector overflow!");
5562     assert(N2C->getAPIntValue().getBitWidth() ==
5563                TLI->getVectorIdxTy(getDataLayout())
5564                    .getSizeInBits()
5565                    .getFixedSize() &&
5566            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5567 
5568     // Trivial extraction.
5569     if (VT == N1VT)
5570       return N1;
5571 
5572     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5573     if (N1.isUndef())
5574       return getUNDEF(VT);
5575 
5576     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5577     // the concat have the same type as the extract.
5578     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5579         VT == N1.getOperand(0).getValueType()) {
5580       unsigned Factor = VT.getVectorMinNumElements();
5581       return N1.getOperand(N2C->getZExtValue() / Factor);
5582     }
5583 
5584     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5585     // during shuffle legalization.
5586     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5587         VT == N1.getOperand(1).getValueType())
5588       return N1.getOperand(1);
5589     break;
5590   }
5591 
5592   // Perform trivial constant folding.
5593   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5594     return SV;
5595 
5596   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5597     return V;
5598 
5599   // Canonicalize an UNDEF to the RHS, even over a constant.
5600   if (N1.isUndef()) {
5601     if (TLI->isCommutativeBinOp(Opcode)) {
5602       std::swap(N1, N2);
5603     } else {
5604       switch (Opcode) {
5605       case ISD::SIGN_EXTEND_INREG:
5606       case ISD::SUB:
5607         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5608       case ISD::UDIV:
5609       case ISD::SDIV:
5610       case ISD::UREM:
5611       case ISD::SREM:
5612       case ISD::SSUBSAT:
5613       case ISD::USUBSAT:
5614         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5615       }
5616     }
5617   }
5618 
5619   // Fold a bunch of operators when the RHS is undef.
5620   if (N2.isUndef()) {
5621     switch (Opcode) {
5622     case ISD::XOR:
5623       if (N1.isUndef())
5624         // Handle undef ^ undef -> 0 special case. This is a common
5625         // idiom (misuse).
5626         return getConstant(0, DL, VT);
5627       LLVM_FALLTHROUGH;
5628     case ISD::ADD:
5629     case ISD::SUB:
5630     case ISD::UDIV:
5631     case ISD::SDIV:
5632     case ISD::UREM:
5633     case ISD::SREM:
5634       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5635     case ISD::MUL:
5636     case ISD::AND:
5637     case ISD::SSUBSAT:
5638     case ISD::USUBSAT:
5639       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5640     case ISD::OR:
5641     case ISD::SADDSAT:
5642     case ISD::UADDSAT:
5643       return getAllOnesConstant(DL, VT);
5644     }
5645   }
5646 
5647   // Memoize this node if possible.
5648   SDNode *N;
5649   SDVTList VTs = getVTList(VT);
5650   SDValue Ops[] = {N1, N2};
5651   if (VT != MVT::Glue) {
5652     FoldingSetNodeID ID;
5653     AddNodeIDNode(ID, Opcode, VTs, Ops);
5654     void *IP = nullptr;
5655     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5656       E->intersectFlagsWith(Flags);
5657       return SDValue(E, 0);
5658     }
5659 
5660     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5661     N->setFlags(Flags);
5662     createOperands(N, Ops);
5663     CSEMap.InsertNode(N, IP);
5664   } else {
5665     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5666     createOperands(N, Ops);
5667   }
5668 
5669   InsertNode(N);
5670   SDValue V = SDValue(N, 0);
5671   NewSDValueDbgMsg(V, "Creating new node: ", this);
5672   return V;
5673 }
5674 
5675 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5676                               SDValue N1, SDValue N2, SDValue N3) {
5677   SDNodeFlags Flags;
5678   if (Inserter)
5679     Flags = Inserter->getFlags();
5680   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
5681 }
5682 
5683 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5684                               SDValue N1, SDValue N2, SDValue N3,
5685                               const SDNodeFlags Flags) {
5686   // Perform various simplifications.
5687   switch (Opcode) {
5688   case ISD::FMA: {
5689     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5690     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5691            N3.getValueType() == VT && "FMA types must match!");
5692     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5693     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5694     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5695     if (N1CFP && N2CFP && N3CFP) {
5696       APFloat  V1 = N1CFP->getValueAPF();
5697       const APFloat &V2 = N2CFP->getValueAPF();
5698       const APFloat &V3 = N3CFP->getValueAPF();
5699       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
5700       return getConstantFP(V1, DL, VT);
5701     }
5702     break;
5703   }
5704   case ISD::BUILD_VECTOR: {
5705     // Attempt to simplify BUILD_VECTOR.
5706     SDValue Ops[] = {N1, N2, N3};
5707     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5708       return V;
5709     break;
5710   }
5711   case ISD::CONCAT_VECTORS: {
5712     SDValue Ops[] = {N1, N2, N3};
5713     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5714       return V;
5715     break;
5716   }
5717   case ISD::SETCC: {
5718     assert(VT.isInteger() && "SETCC result type must be an integer!");
5719     assert(N1.getValueType() == N2.getValueType() &&
5720            "SETCC operands must have the same type!");
5721     assert(VT.isVector() == N1.getValueType().isVector() &&
5722            "SETCC type should be vector iff the operand type is vector!");
5723     assert((!VT.isVector() || VT.getVectorElementCount() ==
5724                                   N1.getValueType().getVectorElementCount()) &&
5725            "SETCC vector element counts must match!");
5726     // Use FoldSetCC to simplify SETCC's.
5727     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5728       return V;
5729     // Vector constant folding.
5730     SDValue Ops[] = {N1, N2, N3};
5731     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5732       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5733       return V;
5734     }
5735     break;
5736   }
5737   case ISD::SELECT:
5738   case ISD::VSELECT:
5739     if (SDValue V = simplifySelect(N1, N2, N3))
5740       return V;
5741     break;
5742   case ISD::VECTOR_SHUFFLE:
5743     llvm_unreachable("should use getVectorShuffle constructor!");
5744   case ISD::INSERT_VECTOR_ELT: {
5745     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5746     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
5747     // for scalable vectors where we will generate appropriate code to
5748     // deal with out-of-bounds cases correctly.
5749     if (N3C && N1.getValueType().isFixedLengthVector() &&
5750         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5751       return getUNDEF(VT);
5752 
5753     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
5754     if (N3.isUndef())
5755       return getUNDEF(VT);
5756 
5757     // If the inserted element is an UNDEF, just use the input vector.
5758     if (N2.isUndef())
5759       return N1;
5760 
5761     break;
5762   }
5763   case ISD::INSERT_SUBVECTOR: {
5764     // Inserting undef into undef is still undef.
5765     if (N1.isUndef() && N2.isUndef())
5766       return getUNDEF(VT);
5767 
5768     EVT N2VT = N2.getValueType();
5769     assert(VT == N1.getValueType() &&
5770            "Dest and insert subvector source types must match!");
5771     assert(VT.isVector() && N2VT.isVector() &&
5772            "Insert subvector VTs must be vectors!");
5773     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
5774            "Cannot insert a scalable vector into a fixed length vector!");
5775     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5776             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
5777            "Insert subvector must be from smaller vector to larger vector!");
5778     assert(isa<ConstantSDNode>(N3) &&
5779            "Insert subvector index must be constant");
5780     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5781             (N2VT.getVectorMinNumElements() +
5782              cast<ConstantSDNode>(N3)->getZExtValue()) <=
5783                 VT.getVectorMinNumElements()) &&
5784            "Insert subvector overflow!");
5785 
5786     // Trivial insertion.
5787     if (VT == N2VT)
5788       return N2;
5789 
5790     // If this is an insert of an extracted vector into an undef vector, we
5791     // can just use the input to the extract.
5792     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5793         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
5794       return N2.getOperand(0);
5795     break;
5796   }
5797   case ISD::BITCAST:
5798     // Fold bit_convert nodes from a type to themselves.
5799     if (N1.getValueType() == VT)
5800       return N1;
5801     break;
5802   }
5803 
5804   // Memoize node if it doesn't produce a flag.
5805   SDNode *N;
5806   SDVTList VTs = getVTList(VT);
5807   SDValue Ops[] = {N1, N2, N3};
5808   if (VT != MVT::Glue) {
5809     FoldingSetNodeID ID;
5810     AddNodeIDNode(ID, Opcode, VTs, Ops);
5811     void *IP = nullptr;
5812     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5813       E->intersectFlagsWith(Flags);
5814       return SDValue(E, 0);
5815     }
5816 
5817     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5818     N->setFlags(Flags);
5819     createOperands(N, Ops);
5820     CSEMap.InsertNode(N, IP);
5821   } else {
5822     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5823     createOperands(N, Ops);
5824   }
5825 
5826   InsertNode(N);
5827   SDValue V = SDValue(N, 0);
5828   NewSDValueDbgMsg(V, "Creating new node: ", this);
5829   return V;
5830 }
5831 
5832 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5833                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
5834   SDValue Ops[] = { N1, N2, N3, N4 };
5835   return getNode(Opcode, DL, VT, Ops);
5836 }
5837 
5838 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5839                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
5840                               SDValue N5) {
5841   SDValue Ops[] = { N1, N2, N3, N4, N5 };
5842   return getNode(Opcode, DL, VT, Ops);
5843 }
5844 
5845 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
5846 /// the incoming stack arguments to be loaded from the stack.
5847 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
5848   SmallVector<SDValue, 8> ArgChains;
5849 
5850   // Include the original chain at the beginning of the list. When this is
5851   // used by target LowerCall hooks, this helps legalize find the
5852   // CALLSEQ_BEGIN node.
5853   ArgChains.push_back(Chain);
5854 
5855   // Add a chain value for each stack argument.
5856   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
5857        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
5858     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5859       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5860         if (FI->getIndex() < 0)
5861           ArgChains.push_back(SDValue(L, 1));
5862 
5863   // Build a tokenfactor for all the chains.
5864   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5865 }
5866 
5867 /// getMemsetValue - Vectorized representation of the memset value
5868 /// operand.
5869 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
5870                               const SDLoc &dl) {
5871   assert(!Value.isUndef());
5872 
5873   unsigned NumBits = VT.getScalarSizeInBits();
5874   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
5875     assert(C->getAPIntValue().getBitWidth() == 8);
5876     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
5877     if (VT.isInteger()) {
5878       bool IsOpaque = VT.getSizeInBits() > 64 ||
5879           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
5880       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
5881     }
5882     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
5883                              VT);
5884   }
5885 
5886   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
5887   EVT IntVT = VT.getScalarType();
5888   if (!IntVT.isInteger())
5889     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
5890 
5891   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
5892   if (NumBits > 8) {
5893     // Use a multiplication with 0x010101... to extend the input to the
5894     // required length.
5895     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
5896     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
5897                         DAG.getConstant(Magic, dl, IntVT));
5898   }
5899 
5900   if (VT != Value.getValueType() && !VT.isInteger())
5901     Value = DAG.getBitcast(VT.getScalarType(), Value);
5902   if (VT != Value.getValueType())
5903     Value = DAG.getSplatBuildVector(VT, dl, Value);
5904 
5905   return Value;
5906 }
5907 
5908 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
5909 /// used when a memcpy is turned into a memset when the source is a constant
5910 /// string ptr.
5911 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
5912                                   const TargetLowering &TLI,
5913                                   const ConstantDataArraySlice &Slice) {
5914   // Handle vector with all elements zero.
5915   if (Slice.Array == nullptr) {
5916     if (VT.isInteger())
5917       return DAG.getConstant(0, dl, VT);
5918     else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
5919       return DAG.getConstantFP(0.0, dl, VT);
5920     else if (VT.isVector()) {
5921       unsigned NumElts = VT.getVectorNumElements();
5922       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5923       return DAG.getNode(ISD::BITCAST, dl, VT,
5924                          DAG.getConstant(0, dl,
5925                                          EVT::getVectorVT(*DAG.getContext(),
5926                                                           EltVT, NumElts)));
5927     } else
5928       llvm_unreachable("Expected type!");
5929   }
5930 
5931   assert(!VT.isVector() && "Can't handle vector type here!");
5932   unsigned NumVTBits = VT.getSizeInBits();
5933   unsigned NumVTBytes = NumVTBits / 8;
5934   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
5935 
5936   APInt Val(NumVTBits, 0);
5937   if (DAG.getDataLayout().isLittleEndian()) {
5938     for (unsigned i = 0; i != NumBytes; ++i)
5939       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
5940   } else {
5941     for (unsigned i = 0; i != NumBytes; ++i)
5942       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
5943   }
5944 
5945   // If the "cost" of materializing the integer immediate is less than the cost
5946   // of a load, then it is cost effective to turn the load into the immediate.
5947   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
5948   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
5949     return DAG.getConstant(Val, dl, VT);
5950   return SDValue(nullptr, 0);
5951 }
5952 
5953 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
5954                                            const SDLoc &DL,
5955                                            const SDNodeFlags Flags) {
5956   EVT VT = Base.getValueType();
5957   SDValue Index;
5958 
5959   if (Offset.isScalable())
5960     Index = getVScale(DL, Base.getValueType(),
5961                       APInt(Base.getValueSizeInBits().getFixedSize(),
5962                             Offset.getKnownMinSize()));
5963   else
5964     Index = getConstant(Offset.getFixedSize(), DL, VT);
5965 
5966   return getMemBasePlusOffset(Base, Index, DL, Flags);
5967 }
5968 
5969 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
5970                                            const SDLoc &DL,
5971                                            const SDNodeFlags Flags) {
5972   assert(Offset.getValueType().isInteger());
5973   EVT BasePtrVT = Ptr.getValueType();
5974   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
5975 }
5976 
5977 /// Returns true if memcpy source is constant data.
5978 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
5979   uint64_t SrcDelta = 0;
5980   GlobalAddressSDNode *G = nullptr;
5981   if (Src.getOpcode() == ISD::GlobalAddress)
5982     G = cast<GlobalAddressSDNode>(Src);
5983   else if (Src.getOpcode() == ISD::ADD &&
5984            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
5985            Src.getOperand(1).getOpcode() == ISD::Constant) {
5986     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
5987     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
5988   }
5989   if (!G)
5990     return false;
5991 
5992   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
5993                                   SrcDelta + G->getOffset());
5994 }
5995 
5996 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
5997                                       SelectionDAG &DAG) {
5998   // On Darwin, -Os means optimize for size without hurting performance, so
5999   // only really optimize for size when -Oz (MinSize) is used.
6000   if (MF.getTarget().getTargetTriple().isOSDarwin())
6001     return MF.getFunction().hasMinSize();
6002   return DAG.shouldOptForSize();
6003 }
6004 
6005 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6006                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6007                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6008                           SmallVector<SDValue, 16> &OutStoreChains) {
6009   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6010   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6011   SmallVector<SDValue, 16> GluedLoadChains;
6012   for (unsigned i = From; i < To; ++i) {
6013     OutChains.push_back(OutLoadChains[i]);
6014     GluedLoadChains.push_back(OutLoadChains[i]);
6015   }
6016 
6017   // Chain for all loads.
6018   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6019                                   GluedLoadChains);
6020 
6021   for (unsigned i = From; i < To; ++i) {
6022     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6023     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6024                                   ST->getBasePtr(), ST->getMemoryVT(),
6025                                   ST->getMemOperand());
6026     OutChains.push_back(NewStore);
6027   }
6028 }
6029 
6030 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6031                                        SDValue Chain, SDValue Dst, SDValue Src,
6032                                        uint64_t Size, Align Alignment,
6033                                        bool isVol, bool AlwaysInline,
6034                                        MachinePointerInfo DstPtrInfo,
6035                                        MachinePointerInfo SrcPtrInfo) {
6036   // Turn a memcpy of undef to nop.
6037   // FIXME: We need to honor volatile even is Src is undef.
6038   if (Src.isUndef())
6039     return Chain;
6040 
6041   // Expand memcpy to a series of load and store ops if the size operand falls
6042   // below a certain threshold.
6043   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6044   // rather than maybe a humongous number of loads and stores.
6045   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6046   const DataLayout &DL = DAG.getDataLayout();
6047   LLVMContext &C = *DAG.getContext();
6048   std::vector<EVT> MemOps;
6049   bool DstAlignCanChange = false;
6050   MachineFunction &MF = DAG.getMachineFunction();
6051   MachineFrameInfo &MFI = MF.getFrameInfo();
6052   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6053   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6054   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6055     DstAlignCanChange = true;
6056   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6057   if (!SrcAlign || Alignment > *SrcAlign)
6058     SrcAlign = Alignment;
6059   assert(SrcAlign && "SrcAlign must be set");
6060   ConstantDataArraySlice Slice;
6061   // If marked as volatile, perform a copy even when marked as constant.
6062   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6063   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6064   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6065   const MemOp Op = isZeroConstant
6066                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6067                                     /*IsZeroMemset*/ true, isVol)
6068                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6069                                      *SrcAlign, isVol, CopyFromConstant);
6070   if (!TLI.findOptimalMemOpLowering(
6071           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6072           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6073     return SDValue();
6074 
6075   if (DstAlignCanChange) {
6076     Type *Ty = MemOps[0].getTypeForEVT(C);
6077     Align NewAlign = DL.getABITypeAlign(Ty);
6078 
6079     // Don't promote to an alignment that would require dynamic stack
6080     // realignment.
6081     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6082     if (!TRI->needsStackRealignment(MF))
6083       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6084         NewAlign = NewAlign / 2;
6085 
6086     if (NewAlign > Alignment) {
6087       // Give the stack frame object a larger alignment if needed.
6088       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6089         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6090       Alignment = NewAlign;
6091     }
6092   }
6093 
6094   MachineMemOperand::Flags MMOFlags =
6095       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6096   SmallVector<SDValue, 16> OutLoadChains;
6097   SmallVector<SDValue, 16> OutStoreChains;
6098   SmallVector<SDValue, 32> OutChains;
6099   unsigned NumMemOps = MemOps.size();
6100   uint64_t SrcOff = 0, DstOff = 0;
6101   for (unsigned i = 0; i != NumMemOps; ++i) {
6102     EVT VT = MemOps[i];
6103     unsigned VTSize = VT.getSizeInBits() / 8;
6104     SDValue Value, Store;
6105 
6106     if (VTSize > Size) {
6107       // Issuing an unaligned load / store pair  that overlaps with the previous
6108       // pair. Adjust the offset accordingly.
6109       assert(i == NumMemOps-1 && i != 0);
6110       SrcOff -= VTSize - Size;
6111       DstOff -= VTSize - Size;
6112     }
6113 
6114     if (CopyFromConstant &&
6115         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6116       // It's unlikely a store of a vector immediate can be done in a single
6117       // instruction. It would require a load from a constantpool first.
6118       // We only handle zero vectors here.
6119       // FIXME: Handle other cases where store of vector immediate is done in
6120       // a single instruction.
6121       ConstantDataArraySlice SubSlice;
6122       if (SrcOff < Slice.Length) {
6123         SubSlice = Slice;
6124         SubSlice.move(SrcOff);
6125       } else {
6126         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6127         SubSlice.Array = nullptr;
6128         SubSlice.Offset = 0;
6129         SubSlice.Length = VTSize;
6130       }
6131       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6132       if (Value.getNode()) {
6133         Store = DAG.getStore(
6134             Chain, dl, Value,
6135             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6136             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags);
6137         OutChains.push_back(Store);
6138       }
6139     }
6140 
6141     if (!Store.getNode()) {
6142       // The type might not be legal for the target.  This should only happen
6143       // if the type is smaller than a legal type, as on PPC, so the right
6144       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6145       // to Load/Store if NVT==VT.
6146       // FIXME does the case above also need this?
6147       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6148       assert(NVT.bitsGE(VT));
6149 
6150       bool isDereferenceable =
6151         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6152       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6153       if (isDereferenceable)
6154         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6155 
6156       Value = DAG.getExtLoad(
6157           ISD::EXTLOAD, dl, NVT, Chain,
6158           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6159           SrcPtrInfo.getWithOffset(SrcOff), VT,
6160           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags);
6161       OutLoadChains.push_back(Value.getValue(1));
6162 
6163       Store = DAG.getTruncStore(
6164           Chain, dl, Value,
6165           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6166           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags);
6167       OutStoreChains.push_back(Store);
6168     }
6169     SrcOff += VTSize;
6170     DstOff += VTSize;
6171     Size -= VTSize;
6172   }
6173 
6174   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6175                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6176   unsigned NumLdStInMemcpy = OutStoreChains.size();
6177 
6178   if (NumLdStInMemcpy) {
6179     // It may be that memcpy might be converted to memset if it's memcpy
6180     // of constants. In such a case, we won't have loads and stores, but
6181     // just stores. In the absence of loads, there is nothing to gang up.
6182     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6183       // If target does not care, just leave as it.
6184       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6185         OutChains.push_back(OutLoadChains[i]);
6186         OutChains.push_back(OutStoreChains[i]);
6187       }
6188     } else {
6189       // Ld/St less than/equal limit set by target.
6190       if (NumLdStInMemcpy <= GluedLdStLimit) {
6191           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6192                                         NumLdStInMemcpy, OutLoadChains,
6193                                         OutStoreChains);
6194       } else {
6195         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6196         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6197         unsigned GlueIter = 0;
6198 
6199         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6200           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6201           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6202 
6203           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6204                                        OutLoadChains, OutStoreChains);
6205           GlueIter += GluedLdStLimit;
6206         }
6207 
6208         // Residual ld/st.
6209         if (RemainingLdStInMemcpy) {
6210           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6211                                         RemainingLdStInMemcpy, OutLoadChains,
6212                                         OutStoreChains);
6213         }
6214       }
6215     }
6216   }
6217   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6218 }
6219 
6220 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6221                                         SDValue Chain, SDValue Dst, SDValue Src,
6222                                         uint64_t Size, Align Alignment,
6223                                         bool isVol, bool AlwaysInline,
6224                                         MachinePointerInfo DstPtrInfo,
6225                                         MachinePointerInfo SrcPtrInfo) {
6226   // Turn a memmove of undef to nop.
6227   // FIXME: We need to honor volatile even is Src is undef.
6228   if (Src.isUndef())
6229     return Chain;
6230 
6231   // Expand memmove to a series of load and store ops if the size operand falls
6232   // below a certain threshold.
6233   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6234   const DataLayout &DL = DAG.getDataLayout();
6235   LLVMContext &C = *DAG.getContext();
6236   std::vector<EVT> MemOps;
6237   bool DstAlignCanChange = false;
6238   MachineFunction &MF = DAG.getMachineFunction();
6239   MachineFrameInfo &MFI = MF.getFrameInfo();
6240   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6241   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6242   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6243     DstAlignCanChange = true;
6244   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6245   if (!SrcAlign || Alignment > *SrcAlign)
6246     SrcAlign = Alignment;
6247   assert(SrcAlign && "SrcAlign must be set");
6248   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6249   if (!TLI.findOptimalMemOpLowering(
6250           MemOps, Limit,
6251           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6252                       /*IsVolatile*/ true),
6253           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6254           MF.getFunction().getAttributes()))
6255     return SDValue();
6256 
6257   if (DstAlignCanChange) {
6258     Type *Ty = MemOps[0].getTypeForEVT(C);
6259     Align NewAlign = DL.getABITypeAlign(Ty);
6260     if (NewAlign > Alignment) {
6261       // Give the stack frame object a larger alignment if needed.
6262       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6263         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6264       Alignment = NewAlign;
6265     }
6266   }
6267 
6268   MachineMemOperand::Flags MMOFlags =
6269       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6270   uint64_t SrcOff = 0, DstOff = 0;
6271   SmallVector<SDValue, 8> LoadValues;
6272   SmallVector<SDValue, 8> LoadChains;
6273   SmallVector<SDValue, 8> OutChains;
6274   unsigned NumMemOps = MemOps.size();
6275   for (unsigned i = 0; i < NumMemOps; i++) {
6276     EVT VT = MemOps[i];
6277     unsigned VTSize = VT.getSizeInBits() / 8;
6278     SDValue Value;
6279 
6280     bool isDereferenceable =
6281       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6282     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6283     if (isDereferenceable)
6284       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6285 
6286     Value =
6287         DAG.getLoad(VT, dl, Chain,
6288                     DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6289                     SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags);
6290     LoadValues.push_back(Value);
6291     LoadChains.push_back(Value.getValue(1));
6292     SrcOff += VTSize;
6293   }
6294   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6295   OutChains.clear();
6296   for (unsigned i = 0; i < NumMemOps; i++) {
6297     EVT VT = MemOps[i];
6298     unsigned VTSize = VT.getSizeInBits() / 8;
6299     SDValue Store;
6300 
6301     Store =
6302         DAG.getStore(Chain, dl, LoadValues[i],
6303                      DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6304                      DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags);
6305     OutChains.push_back(Store);
6306     DstOff += VTSize;
6307   }
6308 
6309   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6310 }
6311 
6312 /// Lower the call to 'memset' intrinsic function into a series of store
6313 /// operations.
6314 ///
6315 /// \param DAG Selection DAG where lowered code is placed.
6316 /// \param dl Link to corresponding IR location.
6317 /// \param Chain Control flow dependency.
6318 /// \param Dst Pointer to destination memory location.
6319 /// \param Src Value of byte to write into the memory.
6320 /// \param Size Number of bytes to write.
6321 /// \param Alignment Alignment of the destination in bytes.
6322 /// \param isVol True if destination is volatile.
6323 /// \param DstPtrInfo IR information on the memory pointer.
6324 /// \returns New head in the control flow, if lowering was successful, empty
6325 /// SDValue otherwise.
6326 ///
6327 /// The function tries to replace 'llvm.memset' intrinsic with several store
6328 /// operations and value calculation code. This is usually profitable for small
6329 /// memory size.
6330 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6331                                SDValue Chain, SDValue Dst, SDValue Src,
6332                                uint64_t Size, Align Alignment, bool isVol,
6333                                MachinePointerInfo DstPtrInfo) {
6334   // Turn a memset of undef to nop.
6335   // FIXME: We need to honor volatile even is Src is undef.
6336   if (Src.isUndef())
6337     return Chain;
6338 
6339   // Expand memset to a series of load/store ops if the size operand
6340   // falls below a certain threshold.
6341   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6342   std::vector<EVT> MemOps;
6343   bool DstAlignCanChange = false;
6344   MachineFunction &MF = DAG.getMachineFunction();
6345   MachineFrameInfo &MFI = MF.getFrameInfo();
6346   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6347   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6348   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6349     DstAlignCanChange = true;
6350   bool IsZeroVal =
6351     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6352   if (!TLI.findOptimalMemOpLowering(
6353           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6354           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6355           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6356     return SDValue();
6357 
6358   if (DstAlignCanChange) {
6359     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6360     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6361     if (NewAlign > Alignment) {
6362       // Give the stack frame object a larger alignment if needed.
6363       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6364         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6365       Alignment = NewAlign;
6366     }
6367   }
6368 
6369   SmallVector<SDValue, 8> OutChains;
6370   uint64_t DstOff = 0;
6371   unsigned NumMemOps = MemOps.size();
6372 
6373   // Find the largest store and generate the bit pattern for it.
6374   EVT LargestVT = MemOps[0];
6375   for (unsigned i = 1; i < NumMemOps; i++)
6376     if (MemOps[i].bitsGT(LargestVT))
6377       LargestVT = MemOps[i];
6378   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6379 
6380   for (unsigned i = 0; i < NumMemOps; i++) {
6381     EVT VT = MemOps[i];
6382     unsigned VTSize = VT.getSizeInBits() / 8;
6383     if (VTSize > Size) {
6384       // Issuing an unaligned load / store pair  that overlaps with the previous
6385       // pair. Adjust the offset accordingly.
6386       assert(i == NumMemOps-1 && i != 0);
6387       DstOff -= VTSize - Size;
6388     }
6389 
6390     // If this store is smaller than the largest store see whether we can get
6391     // the smaller value for free with a truncate.
6392     SDValue Value = MemSetValue;
6393     if (VT.bitsLT(LargestVT)) {
6394       if (!LargestVT.isVector() && !VT.isVector() &&
6395           TLI.isTruncateFree(LargestVT, VT))
6396         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6397       else
6398         Value = getMemsetValue(Src, VT, DAG, dl);
6399     }
6400     assert(Value.getValueType() == VT && "Value with wrong type.");
6401     SDValue Store = DAG.getStore(
6402         Chain, dl, Value,
6403         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6404         DstPtrInfo.getWithOffset(DstOff), Alignment,
6405         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
6406     OutChains.push_back(Store);
6407     DstOff += VT.getSizeInBits() / 8;
6408     Size -= VTSize;
6409   }
6410 
6411   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6412 }
6413 
6414 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6415                                             unsigned AS) {
6416   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6417   // pointer operands can be losslessly bitcasted to pointers of address space 0
6418   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6419     report_fatal_error("cannot lower memory intrinsic in address space " +
6420                        Twine(AS));
6421   }
6422 }
6423 
6424 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6425                                 SDValue Src, SDValue Size, Align Alignment,
6426                                 bool isVol, bool AlwaysInline, bool isTailCall,
6427                                 MachinePointerInfo DstPtrInfo,
6428                                 MachinePointerInfo SrcPtrInfo) {
6429   // Check to see if we should lower the memcpy to loads and stores first.
6430   // For cases within the target-specified limits, this is the best choice.
6431   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6432   if (ConstantSize) {
6433     // Memcpy with size zero? Just return the original chain.
6434     if (ConstantSize->isNullValue())
6435       return Chain;
6436 
6437     SDValue Result = getMemcpyLoadsAndStores(
6438         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6439         isVol, false, DstPtrInfo, SrcPtrInfo);
6440     if (Result.getNode())
6441       return Result;
6442   }
6443 
6444   // Then check to see if we should lower the memcpy with target-specific
6445   // code. If the target chooses to do this, this is the next best.
6446   if (TSI) {
6447     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6448         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6449         DstPtrInfo, SrcPtrInfo);
6450     if (Result.getNode())
6451       return Result;
6452   }
6453 
6454   // If we really need inline code and the target declined to provide it,
6455   // use a (potentially long) sequence of loads and stores.
6456   if (AlwaysInline) {
6457     assert(ConstantSize && "AlwaysInline requires a constant size!");
6458     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6459                                    ConstantSize->getZExtValue(), Alignment,
6460                                    isVol, true, DstPtrInfo, SrcPtrInfo);
6461   }
6462 
6463   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6464   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6465 
6466   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6467   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6468   // respect volatile, so they may do things like read or write memory
6469   // beyond the given memory regions. But fixing this isn't easy, and most
6470   // people don't care.
6471 
6472   // Emit a library call.
6473   TargetLowering::ArgListTy Args;
6474   TargetLowering::ArgListEntry Entry;
6475   Entry.Ty = Type::getInt8PtrTy(*getContext());
6476   Entry.Node = Dst; Args.push_back(Entry);
6477   Entry.Node = Src; Args.push_back(Entry);
6478 
6479   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6480   Entry.Node = Size; Args.push_back(Entry);
6481   // FIXME: pass in SDLoc
6482   TargetLowering::CallLoweringInfo CLI(*this);
6483   CLI.setDebugLoc(dl)
6484       .setChain(Chain)
6485       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6486                     Dst.getValueType().getTypeForEVT(*getContext()),
6487                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6488                                       TLI->getPointerTy(getDataLayout())),
6489                     std::move(Args))
6490       .setDiscardResult()
6491       .setTailCall(isTailCall);
6492 
6493   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6494   return CallResult.second;
6495 }
6496 
6497 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6498                                       SDValue Dst, unsigned DstAlign,
6499                                       SDValue Src, unsigned SrcAlign,
6500                                       SDValue Size, Type *SizeTy,
6501                                       unsigned ElemSz, bool isTailCall,
6502                                       MachinePointerInfo DstPtrInfo,
6503                                       MachinePointerInfo SrcPtrInfo) {
6504   // Emit a library call.
6505   TargetLowering::ArgListTy Args;
6506   TargetLowering::ArgListEntry Entry;
6507   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6508   Entry.Node = Dst;
6509   Args.push_back(Entry);
6510 
6511   Entry.Node = Src;
6512   Args.push_back(Entry);
6513 
6514   Entry.Ty = SizeTy;
6515   Entry.Node = Size;
6516   Args.push_back(Entry);
6517 
6518   RTLIB::Libcall LibraryCall =
6519       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6520   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6521     report_fatal_error("Unsupported element size");
6522 
6523   TargetLowering::CallLoweringInfo CLI(*this);
6524   CLI.setDebugLoc(dl)
6525       .setChain(Chain)
6526       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6527                     Type::getVoidTy(*getContext()),
6528                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6529                                       TLI->getPointerTy(getDataLayout())),
6530                     std::move(Args))
6531       .setDiscardResult()
6532       .setTailCall(isTailCall);
6533 
6534   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6535   return CallResult.second;
6536 }
6537 
6538 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6539                                  SDValue Src, SDValue Size, Align Alignment,
6540                                  bool isVol, bool isTailCall,
6541                                  MachinePointerInfo DstPtrInfo,
6542                                  MachinePointerInfo SrcPtrInfo) {
6543   // Check to see if we should lower the memmove to loads and stores first.
6544   // For cases within the target-specified limits, this is the best choice.
6545   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6546   if (ConstantSize) {
6547     // Memmove with size zero? Just return the original chain.
6548     if (ConstantSize->isNullValue())
6549       return Chain;
6550 
6551     SDValue Result = getMemmoveLoadsAndStores(
6552         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6553         isVol, false, DstPtrInfo, SrcPtrInfo);
6554     if (Result.getNode())
6555       return Result;
6556   }
6557 
6558   // Then check to see if we should lower the memmove with target-specific
6559   // code. If the target chooses to do this, this is the next best.
6560   if (TSI) {
6561     SDValue Result =
6562         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6563                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6564     if (Result.getNode())
6565       return Result;
6566   }
6567 
6568   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6569   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6570 
6571   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6572   // not be safe.  See memcpy above for more details.
6573 
6574   // Emit a library call.
6575   TargetLowering::ArgListTy Args;
6576   TargetLowering::ArgListEntry Entry;
6577   Entry.Ty = Type::getInt8PtrTy(*getContext());
6578   Entry.Node = Dst; Args.push_back(Entry);
6579   Entry.Node = Src; Args.push_back(Entry);
6580 
6581   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6582   Entry.Node = Size; Args.push_back(Entry);
6583   // FIXME:  pass in SDLoc
6584   TargetLowering::CallLoweringInfo CLI(*this);
6585   CLI.setDebugLoc(dl)
6586       .setChain(Chain)
6587       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6588                     Dst.getValueType().getTypeForEVT(*getContext()),
6589                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6590                                       TLI->getPointerTy(getDataLayout())),
6591                     std::move(Args))
6592       .setDiscardResult()
6593       .setTailCall(isTailCall);
6594 
6595   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6596   return CallResult.second;
6597 }
6598 
6599 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6600                                        SDValue Dst, unsigned DstAlign,
6601                                        SDValue Src, unsigned SrcAlign,
6602                                        SDValue Size, Type *SizeTy,
6603                                        unsigned ElemSz, bool isTailCall,
6604                                        MachinePointerInfo DstPtrInfo,
6605                                        MachinePointerInfo SrcPtrInfo) {
6606   // Emit a library call.
6607   TargetLowering::ArgListTy Args;
6608   TargetLowering::ArgListEntry Entry;
6609   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6610   Entry.Node = Dst;
6611   Args.push_back(Entry);
6612 
6613   Entry.Node = Src;
6614   Args.push_back(Entry);
6615 
6616   Entry.Ty = SizeTy;
6617   Entry.Node = Size;
6618   Args.push_back(Entry);
6619 
6620   RTLIB::Libcall LibraryCall =
6621       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6622   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6623     report_fatal_error("Unsupported element size");
6624 
6625   TargetLowering::CallLoweringInfo CLI(*this);
6626   CLI.setDebugLoc(dl)
6627       .setChain(Chain)
6628       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6629                     Type::getVoidTy(*getContext()),
6630                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6631                                       TLI->getPointerTy(getDataLayout())),
6632                     std::move(Args))
6633       .setDiscardResult()
6634       .setTailCall(isTailCall);
6635 
6636   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6637   return CallResult.second;
6638 }
6639 
6640 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6641                                 SDValue Src, SDValue Size, Align Alignment,
6642                                 bool isVol, bool isTailCall,
6643                                 MachinePointerInfo DstPtrInfo) {
6644   // Check to see if we should lower the memset to stores first.
6645   // For cases within the target-specified limits, this is the best choice.
6646   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6647   if (ConstantSize) {
6648     // Memset with size zero? Just return the original chain.
6649     if (ConstantSize->isNullValue())
6650       return Chain;
6651 
6652     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
6653                                      ConstantSize->getZExtValue(), Alignment,
6654                                      isVol, DstPtrInfo);
6655 
6656     if (Result.getNode())
6657       return Result;
6658   }
6659 
6660   // Then check to see if we should lower the memset with target-specific
6661   // code. If the target chooses to do this, this is the next best.
6662   if (TSI) {
6663     SDValue Result = TSI->EmitTargetCodeForMemset(
6664         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
6665     if (Result.getNode())
6666       return Result;
6667   }
6668 
6669   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6670 
6671   // Emit a library call.
6672   TargetLowering::ArgListTy Args;
6673   TargetLowering::ArgListEntry Entry;
6674   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
6675   Args.push_back(Entry);
6676   Entry.Node = Src;
6677   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6678   Args.push_back(Entry);
6679   Entry.Node = Size;
6680   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6681   Args.push_back(Entry);
6682 
6683   // FIXME: pass in SDLoc
6684   TargetLowering::CallLoweringInfo CLI(*this);
6685   CLI.setDebugLoc(dl)
6686       .setChain(Chain)
6687       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
6688                     Dst.getValueType().getTypeForEVT(*getContext()),
6689                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
6690                                       TLI->getPointerTy(getDataLayout())),
6691                     std::move(Args))
6692       .setDiscardResult()
6693       .setTailCall(isTailCall);
6694 
6695   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6696   return CallResult.second;
6697 }
6698 
6699 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6700                                       SDValue Dst, unsigned DstAlign,
6701                                       SDValue Value, SDValue Size, Type *SizeTy,
6702                                       unsigned ElemSz, bool isTailCall,
6703                                       MachinePointerInfo DstPtrInfo) {
6704   // Emit a library call.
6705   TargetLowering::ArgListTy Args;
6706   TargetLowering::ArgListEntry Entry;
6707   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6708   Entry.Node = Dst;
6709   Args.push_back(Entry);
6710 
6711   Entry.Ty = Type::getInt8Ty(*getContext());
6712   Entry.Node = Value;
6713   Args.push_back(Entry);
6714 
6715   Entry.Ty = SizeTy;
6716   Entry.Node = Size;
6717   Args.push_back(Entry);
6718 
6719   RTLIB::Libcall LibraryCall =
6720       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6721   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6722     report_fatal_error("Unsupported element size");
6723 
6724   TargetLowering::CallLoweringInfo CLI(*this);
6725   CLI.setDebugLoc(dl)
6726       .setChain(Chain)
6727       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6728                     Type::getVoidTy(*getContext()),
6729                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6730                                       TLI->getPointerTy(getDataLayout())),
6731                     std::move(Args))
6732       .setDiscardResult()
6733       .setTailCall(isTailCall);
6734 
6735   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6736   return CallResult.second;
6737 }
6738 
6739 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6740                                 SDVTList VTList, ArrayRef<SDValue> Ops,
6741                                 MachineMemOperand *MMO) {
6742   FoldingSetNodeID ID;
6743   ID.AddInteger(MemVT.getRawBits());
6744   AddNodeIDNode(ID, Opcode, VTList, Ops);
6745   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6746   void* IP = nullptr;
6747   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6748     cast<AtomicSDNode>(E)->refineAlignment(MMO);
6749     return SDValue(E, 0);
6750   }
6751 
6752   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6753                                     VTList, MemVT, MMO);
6754   createOperands(N, Ops);
6755 
6756   CSEMap.InsertNode(N, IP);
6757   InsertNode(N);
6758   return SDValue(N, 0);
6759 }
6760 
6761 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6762                                        EVT MemVT, SDVTList VTs, SDValue Chain,
6763                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
6764                                        MachineMemOperand *MMO) {
6765   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6766          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6767   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6768 
6769   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6770   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6771 }
6772 
6773 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6774                                 SDValue Chain, SDValue Ptr, SDValue Val,
6775                                 MachineMemOperand *MMO) {
6776   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6777           Opcode == ISD::ATOMIC_LOAD_SUB ||
6778           Opcode == ISD::ATOMIC_LOAD_AND ||
6779           Opcode == ISD::ATOMIC_LOAD_CLR ||
6780           Opcode == ISD::ATOMIC_LOAD_OR ||
6781           Opcode == ISD::ATOMIC_LOAD_XOR ||
6782           Opcode == ISD::ATOMIC_LOAD_NAND ||
6783           Opcode == ISD::ATOMIC_LOAD_MIN ||
6784           Opcode == ISD::ATOMIC_LOAD_MAX ||
6785           Opcode == ISD::ATOMIC_LOAD_UMIN ||
6786           Opcode == ISD::ATOMIC_LOAD_UMAX ||
6787           Opcode == ISD::ATOMIC_LOAD_FADD ||
6788           Opcode == ISD::ATOMIC_LOAD_FSUB ||
6789           Opcode == ISD::ATOMIC_SWAP ||
6790           Opcode == ISD::ATOMIC_STORE) &&
6791          "Invalid Atomic Op");
6792 
6793   EVT VT = Val.getValueType();
6794 
6795   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
6796                                                getVTList(VT, MVT::Other);
6797   SDValue Ops[] = {Chain, Ptr, Val};
6798   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6799 }
6800 
6801 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6802                                 EVT VT, SDValue Chain, SDValue Ptr,
6803                                 MachineMemOperand *MMO) {
6804   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
6805 
6806   SDVTList VTs = getVTList(VT, MVT::Other);
6807   SDValue Ops[] = {Chain, Ptr};
6808   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6809 }
6810 
6811 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
6812 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
6813   if (Ops.size() == 1)
6814     return Ops[0];
6815 
6816   SmallVector<EVT, 4> VTs;
6817   VTs.reserve(Ops.size());
6818   for (unsigned i = 0; i < Ops.size(); ++i)
6819     VTs.push_back(Ops[i].getValueType());
6820   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
6821 }
6822 
6823 SDValue SelectionDAG::getMemIntrinsicNode(
6824     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
6825     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
6826     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
6827   if (!Size && MemVT.isScalableVector())
6828     Size = MemoryLocation::UnknownSize;
6829   else if (!Size)
6830     Size = MemVT.getStoreSize();
6831 
6832   MachineFunction &MF = getMachineFunction();
6833   MachineMemOperand *MMO =
6834       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
6835 
6836   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
6837 }
6838 
6839 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
6840                                           SDVTList VTList,
6841                                           ArrayRef<SDValue> Ops, EVT MemVT,
6842                                           MachineMemOperand *MMO) {
6843   assert((Opcode == ISD::INTRINSIC_VOID ||
6844           Opcode == ISD::INTRINSIC_W_CHAIN ||
6845           Opcode == ISD::PREFETCH ||
6846           ((int)Opcode <= std::numeric_limits<int>::max() &&
6847            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
6848          "Opcode is not a memory-accessing opcode!");
6849 
6850   // Memoize the node unless it returns a flag.
6851   MemIntrinsicSDNode *N;
6852   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6853     FoldingSetNodeID ID;
6854     AddNodeIDNode(ID, Opcode, VTList, Ops);
6855     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
6856         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
6857     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6858     void *IP = nullptr;
6859     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6860       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
6861       return SDValue(E, 0);
6862     }
6863 
6864     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6865                                       VTList, MemVT, MMO);
6866     createOperands(N, Ops);
6867 
6868   CSEMap.InsertNode(N, IP);
6869   } else {
6870     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6871                                       VTList, MemVT, MMO);
6872     createOperands(N, Ops);
6873   }
6874   InsertNode(N);
6875   SDValue V(N, 0);
6876   NewSDValueDbgMsg(V, "Creating new node: ", this);
6877   return V;
6878 }
6879 
6880 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
6881                                       SDValue Chain, int FrameIndex,
6882                                       int64_t Size, int64_t Offset) {
6883   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
6884   const auto VTs = getVTList(MVT::Other);
6885   SDValue Ops[2] = {
6886       Chain,
6887       getFrameIndex(FrameIndex,
6888                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
6889                     true)};
6890 
6891   FoldingSetNodeID ID;
6892   AddNodeIDNode(ID, Opcode, VTs, Ops);
6893   ID.AddInteger(FrameIndex);
6894   ID.AddInteger(Size);
6895   ID.AddInteger(Offset);
6896   void *IP = nullptr;
6897   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6898     return SDValue(E, 0);
6899 
6900   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
6901       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
6902   createOperands(N, Ops);
6903   CSEMap.InsertNode(N, IP);
6904   InsertNode(N);
6905   SDValue V(N, 0);
6906   NewSDValueDbgMsg(V, "Creating new node: ", this);
6907   return V;
6908 }
6909 
6910 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
6911                                          uint64_t Guid, uint64_t Index,
6912                                          uint32_t Attr) {
6913   const unsigned Opcode = ISD::PSEUDO_PROBE;
6914   const auto VTs = getVTList(MVT::Other);
6915   SDValue Ops[] = {Chain};
6916   FoldingSetNodeID ID;
6917   AddNodeIDNode(ID, Opcode, VTs, Ops);
6918   ID.AddInteger(Guid);
6919   ID.AddInteger(Index);
6920   void *IP = nullptr;
6921   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
6922     return SDValue(E, 0);
6923 
6924   auto *N = newSDNode<PseudoProbeSDNode>(
6925       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
6926   createOperands(N, Ops);
6927   CSEMap.InsertNode(N, IP);
6928   InsertNode(N);
6929   SDValue V(N, 0);
6930   NewSDValueDbgMsg(V, "Creating new node: ", this);
6931   return V;
6932 }
6933 
6934 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6935 /// MachinePointerInfo record from it.  This is particularly useful because the
6936 /// code generator has many cases where it doesn't bother passing in a
6937 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6938 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6939                                            SelectionDAG &DAG, SDValue Ptr,
6940                                            int64_t Offset = 0) {
6941   // If this is FI+Offset, we can model it.
6942   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
6943     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
6944                                              FI->getIndex(), Offset);
6945 
6946   // If this is (FI+Offset1)+Offset2, we can model it.
6947   if (Ptr.getOpcode() != ISD::ADD ||
6948       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
6949       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
6950     return Info;
6951 
6952   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6953   return MachinePointerInfo::getFixedStack(
6954       DAG.getMachineFunction(), FI,
6955       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
6956 }
6957 
6958 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6959 /// MachinePointerInfo record from it.  This is particularly useful because the
6960 /// code generator has many cases where it doesn't bother passing in a
6961 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6962 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6963                                            SelectionDAG &DAG, SDValue Ptr,
6964                                            SDValue OffsetOp) {
6965   // If the 'Offset' value isn't a constant, we can't handle this.
6966   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
6967     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
6968   if (OffsetOp.isUndef())
6969     return InferPointerInfo(Info, DAG, Ptr);
6970   return Info;
6971 }
6972 
6973 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6974                               EVT VT, const SDLoc &dl, SDValue Chain,
6975                               SDValue Ptr, SDValue Offset,
6976                               MachinePointerInfo PtrInfo, EVT MemVT,
6977                               Align Alignment,
6978                               MachineMemOperand::Flags MMOFlags,
6979                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
6980   assert(Chain.getValueType() == MVT::Other &&
6981         "Invalid chain type");
6982 
6983   MMOFlags |= MachineMemOperand::MOLoad;
6984   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
6985   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
6986   // clients.
6987   if (PtrInfo.V.isNull())
6988     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
6989 
6990   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
6991   MachineFunction &MF = getMachineFunction();
6992   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
6993                                                    Alignment, AAInfo, Ranges);
6994   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
6995 }
6996 
6997 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6998                               EVT VT, const SDLoc &dl, SDValue Chain,
6999                               SDValue Ptr, SDValue Offset, EVT MemVT,
7000                               MachineMemOperand *MMO) {
7001   if (VT == MemVT) {
7002     ExtType = ISD::NON_EXTLOAD;
7003   } else if (ExtType == ISD::NON_EXTLOAD) {
7004     assert(VT == MemVT && "Non-extending load from different memory type!");
7005   } else {
7006     // Extending load.
7007     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7008            "Should only be an extending load, not truncating!");
7009     assert(VT.isInteger() == MemVT.isInteger() &&
7010            "Cannot convert from FP to Int or Int -> FP!");
7011     assert(VT.isVector() == MemVT.isVector() &&
7012            "Cannot use an ext load to convert to or from a vector!");
7013     assert((!VT.isVector() ||
7014             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7015            "Cannot use an ext load to change the number of vector elements!");
7016   }
7017 
7018   bool Indexed = AM != ISD::UNINDEXED;
7019   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7020 
7021   SDVTList VTs = Indexed ?
7022     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7023   SDValue Ops[] = { Chain, Ptr, Offset };
7024   FoldingSetNodeID ID;
7025   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7026   ID.AddInteger(MemVT.getRawBits());
7027   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7028       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7029   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7030   void *IP = nullptr;
7031   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7032     cast<LoadSDNode>(E)->refineAlignment(MMO);
7033     return SDValue(E, 0);
7034   }
7035   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7036                                   ExtType, MemVT, MMO);
7037   createOperands(N, Ops);
7038 
7039   CSEMap.InsertNode(N, IP);
7040   InsertNode(N);
7041   SDValue V(N, 0);
7042   NewSDValueDbgMsg(V, "Creating new node: ", this);
7043   return V;
7044 }
7045 
7046 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7047                               SDValue Ptr, MachinePointerInfo PtrInfo,
7048                               MaybeAlign Alignment,
7049                               MachineMemOperand::Flags MMOFlags,
7050                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7051   SDValue Undef = getUNDEF(Ptr.getValueType());
7052   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7053                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7054 }
7055 
7056 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7057                               SDValue Ptr, MachineMemOperand *MMO) {
7058   SDValue Undef = getUNDEF(Ptr.getValueType());
7059   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7060                  VT, MMO);
7061 }
7062 
7063 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7064                                  EVT VT, SDValue Chain, SDValue Ptr,
7065                                  MachinePointerInfo PtrInfo, EVT MemVT,
7066                                  MaybeAlign Alignment,
7067                                  MachineMemOperand::Flags MMOFlags,
7068                                  const AAMDNodes &AAInfo) {
7069   SDValue Undef = getUNDEF(Ptr.getValueType());
7070   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7071                  MemVT, Alignment, MMOFlags, AAInfo);
7072 }
7073 
7074 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7075                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7076                                  MachineMemOperand *MMO) {
7077   SDValue Undef = getUNDEF(Ptr.getValueType());
7078   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7079                  MemVT, MMO);
7080 }
7081 
7082 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7083                                      SDValue Base, SDValue Offset,
7084                                      ISD::MemIndexedMode AM) {
7085   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7086   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7087   // Don't propagate the invariant or dereferenceable flags.
7088   auto MMOFlags =
7089       LD->getMemOperand()->getFlags() &
7090       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7091   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7092                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7093                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7094 }
7095 
7096 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7097                                SDValue Ptr, MachinePointerInfo PtrInfo,
7098                                Align Alignment,
7099                                MachineMemOperand::Flags MMOFlags,
7100                                const AAMDNodes &AAInfo) {
7101   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7102 
7103   MMOFlags |= MachineMemOperand::MOStore;
7104   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7105 
7106   if (PtrInfo.V.isNull())
7107     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7108 
7109   MachineFunction &MF = getMachineFunction();
7110   uint64_t Size =
7111       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7112   MachineMemOperand *MMO =
7113       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7114   return getStore(Chain, dl, Val, Ptr, MMO);
7115 }
7116 
7117 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7118                                SDValue Ptr, MachineMemOperand *MMO) {
7119   assert(Chain.getValueType() == MVT::Other &&
7120         "Invalid chain type");
7121   EVT VT = Val.getValueType();
7122   SDVTList VTs = getVTList(MVT::Other);
7123   SDValue Undef = getUNDEF(Ptr.getValueType());
7124   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7125   FoldingSetNodeID ID;
7126   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7127   ID.AddInteger(VT.getRawBits());
7128   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7129       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7130   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7131   void *IP = nullptr;
7132   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7133     cast<StoreSDNode>(E)->refineAlignment(MMO);
7134     return SDValue(E, 0);
7135   }
7136   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7137                                    ISD::UNINDEXED, false, VT, MMO);
7138   createOperands(N, Ops);
7139 
7140   CSEMap.InsertNode(N, IP);
7141   InsertNode(N);
7142   SDValue V(N, 0);
7143   NewSDValueDbgMsg(V, "Creating new node: ", this);
7144   return V;
7145 }
7146 
7147 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7148                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7149                                     EVT SVT, Align Alignment,
7150                                     MachineMemOperand::Flags MMOFlags,
7151                                     const AAMDNodes &AAInfo) {
7152   assert(Chain.getValueType() == MVT::Other &&
7153         "Invalid chain type");
7154 
7155   MMOFlags |= MachineMemOperand::MOStore;
7156   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7157 
7158   if (PtrInfo.V.isNull())
7159     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7160 
7161   MachineFunction &MF = getMachineFunction();
7162   MachineMemOperand *MMO = MF.getMachineMemOperand(
7163       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7164       Alignment, AAInfo);
7165   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7166 }
7167 
7168 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7169                                     SDValue Ptr, EVT SVT,
7170                                     MachineMemOperand *MMO) {
7171   EVT VT = Val.getValueType();
7172 
7173   assert(Chain.getValueType() == MVT::Other &&
7174         "Invalid chain type");
7175   if (VT == SVT)
7176     return getStore(Chain, dl, Val, Ptr, MMO);
7177 
7178   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7179          "Should only be a truncating store, not extending!");
7180   assert(VT.isInteger() == SVT.isInteger() &&
7181          "Can't do FP-INT conversion!");
7182   assert(VT.isVector() == SVT.isVector() &&
7183          "Cannot use trunc store to convert to or from a vector!");
7184   assert((!VT.isVector() ||
7185           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7186          "Cannot use trunc store to change the number of vector elements!");
7187 
7188   SDVTList VTs = getVTList(MVT::Other);
7189   SDValue Undef = getUNDEF(Ptr.getValueType());
7190   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7191   FoldingSetNodeID ID;
7192   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7193   ID.AddInteger(SVT.getRawBits());
7194   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7195       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7196   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7197   void *IP = nullptr;
7198   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7199     cast<StoreSDNode>(E)->refineAlignment(MMO);
7200     return SDValue(E, 0);
7201   }
7202   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7203                                    ISD::UNINDEXED, true, SVT, MMO);
7204   createOperands(N, Ops);
7205 
7206   CSEMap.InsertNode(N, IP);
7207   InsertNode(N);
7208   SDValue V(N, 0);
7209   NewSDValueDbgMsg(V, "Creating new node: ", this);
7210   return V;
7211 }
7212 
7213 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7214                                       SDValue Base, SDValue Offset,
7215                                       ISD::MemIndexedMode AM) {
7216   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7217   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7218   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7219   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7220   FoldingSetNodeID ID;
7221   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7222   ID.AddInteger(ST->getMemoryVT().getRawBits());
7223   ID.AddInteger(ST->getRawSubclassData());
7224   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7225   void *IP = nullptr;
7226   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7227     return SDValue(E, 0);
7228 
7229   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7230                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7231                                    ST->getMemOperand());
7232   createOperands(N, Ops);
7233 
7234   CSEMap.InsertNode(N, IP);
7235   InsertNode(N);
7236   SDValue V(N, 0);
7237   NewSDValueDbgMsg(V, "Creating new node: ", this);
7238   return V;
7239 }
7240 
7241 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7242                                     SDValue Base, SDValue Offset, SDValue Mask,
7243                                     SDValue PassThru, EVT MemVT,
7244                                     MachineMemOperand *MMO,
7245                                     ISD::MemIndexedMode AM,
7246                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7247   bool Indexed = AM != ISD::UNINDEXED;
7248   assert((Indexed || Offset.isUndef()) &&
7249          "Unindexed masked load with an offset!");
7250   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
7251                          : getVTList(VT, MVT::Other);
7252   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
7253   FoldingSetNodeID ID;
7254   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
7255   ID.AddInteger(MemVT.getRawBits());
7256   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
7257       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
7258   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7259   void *IP = nullptr;
7260   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7261     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
7262     return SDValue(E, 0);
7263   }
7264   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7265                                         AM, ExtTy, isExpanding, MemVT, MMO);
7266   createOperands(N, Ops);
7267 
7268   CSEMap.InsertNode(N, IP);
7269   InsertNode(N);
7270   SDValue V(N, 0);
7271   NewSDValueDbgMsg(V, "Creating new node: ", this);
7272   return V;
7273 }
7274 
7275 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
7276                                            SDValue Base, SDValue Offset,
7277                                            ISD::MemIndexedMode AM) {
7278   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
7279   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
7280   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
7281                        Offset, LD->getMask(), LD->getPassThru(),
7282                        LD->getMemoryVT(), LD->getMemOperand(), AM,
7283                        LD->getExtensionType(), LD->isExpandingLoad());
7284 }
7285 
7286 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
7287                                      SDValue Val, SDValue Base, SDValue Offset,
7288                                      SDValue Mask, EVT MemVT,
7289                                      MachineMemOperand *MMO,
7290                                      ISD::MemIndexedMode AM, bool IsTruncating,
7291                                      bool IsCompressing) {
7292   assert(Chain.getValueType() == MVT::Other &&
7293         "Invalid chain type");
7294   bool Indexed = AM != ISD::UNINDEXED;
7295   assert((Indexed || Offset.isUndef()) &&
7296          "Unindexed masked store with an offset!");
7297   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
7298                          : getVTList(MVT::Other);
7299   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
7300   FoldingSetNodeID ID;
7301   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
7302   ID.AddInteger(MemVT.getRawBits());
7303   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
7304       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7305   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7306   void *IP = nullptr;
7307   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7308     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
7309     return SDValue(E, 0);
7310   }
7311   auto *N =
7312       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7313                                    IsTruncating, IsCompressing, MemVT, MMO);
7314   createOperands(N, Ops);
7315 
7316   CSEMap.InsertNode(N, IP);
7317   InsertNode(N);
7318   SDValue V(N, 0);
7319   NewSDValueDbgMsg(V, "Creating new node: ", this);
7320   return V;
7321 }
7322 
7323 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
7324                                             SDValue Base, SDValue Offset,
7325                                             ISD::MemIndexedMode AM) {
7326   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
7327   assert(ST->getOffset().isUndef() &&
7328          "Masked store is already a indexed store!");
7329   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
7330                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
7331                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
7332 }
7333 
7334 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
7335                                       ArrayRef<SDValue> Ops,
7336                                       MachineMemOperand *MMO,
7337                                       ISD::MemIndexType IndexType,
7338                                       ISD::LoadExtType ExtTy) {
7339   assert(Ops.size() == 6 && "Incompatible number of operands");
7340 
7341   FoldingSetNodeID ID;
7342   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7343   ID.AddInteger(VT.getRawBits());
7344   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7345       dl.getIROrder(), VTs, VT, MMO, IndexType, ExtTy));
7346   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7347   void *IP = nullptr;
7348   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7349     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7350     return SDValue(E, 0);
7351   }
7352 
7353   IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]);
7354   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7355                                           VTs, VT, MMO, IndexType, ExtTy);
7356   createOperands(N, Ops);
7357 
7358   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7359          "Incompatible type of the PassThru value in MaskedGatherSDNode");
7360   assert(N->getMask().getValueType().getVectorElementCount() ==
7361              N->getValueType(0).getVectorElementCount() &&
7362          "Vector width mismatch between mask and data");
7363   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7364              N->getValueType(0).getVectorElementCount().isScalable() &&
7365          "Scalable flags of index and data do not match");
7366   assert(ElementCount::isKnownGE(
7367              N->getIndex().getValueType().getVectorElementCount(),
7368              N->getValueType(0).getVectorElementCount()) &&
7369          "Vector width mismatch between index and data");
7370   assert(isa<ConstantSDNode>(N->getScale()) &&
7371          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7372          "Scale should be a constant power of 2");
7373 
7374   CSEMap.InsertNode(N, IP);
7375   InsertNode(N);
7376   SDValue V(N, 0);
7377   NewSDValueDbgMsg(V, "Creating new node: ", this);
7378   return V;
7379 }
7380 
7381 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
7382                                        ArrayRef<SDValue> Ops,
7383                                        MachineMemOperand *MMO,
7384                                        ISD::MemIndexType IndexType,
7385                                        bool IsTrunc) {
7386   assert(Ops.size() == 6 && "Incompatible number of operands");
7387 
7388   FoldingSetNodeID ID;
7389   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7390   ID.AddInteger(VT.getRawBits());
7391   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7392       dl.getIROrder(), VTs, VT, MMO, IndexType, IsTrunc));
7393   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7394   void *IP = nullptr;
7395   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7396     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7397     return SDValue(E, 0);
7398   }
7399 
7400   IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]);
7401   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7402                                            VTs, VT, MMO, IndexType, IsTrunc);
7403   createOperands(N, Ops);
7404 
7405   assert(N->getMask().getValueType().getVectorElementCount() ==
7406              N->getValue().getValueType().getVectorElementCount() &&
7407          "Vector width mismatch between mask and data");
7408   assert(
7409       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7410           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7411       "Scalable flags of index and data do not match");
7412   assert(ElementCount::isKnownGE(
7413              N->getIndex().getValueType().getVectorElementCount(),
7414              N->getValue().getValueType().getVectorElementCount()) &&
7415          "Vector width mismatch between index and data");
7416   assert(isa<ConstantSDNode>(N->getScale()) &&
7417          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7418          "Scale should be a constant power of 2");
7419 
7420   CSEMap.InsertNode(N, IP);
7421   InsertNode(N);
7422   SDValue V(N, 0);
7423   NewSDValueDbgMsg(V, "Creating new node: ", this);
7424   return V;
7425 }
7426 
7427 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7428   // select undef, T, F --> T (if T is a constant), otherwise F
7429   // select, ?, undef, F --> F
7430   // select, ?, T, undef --> T
7431   if (Cond.isUndef())
7432     return isConstantValueOfAnyType(T) ? T : F;
7433   if (T.isUndef())
7434     return F;
7435   if (F.isUndef())
7436     return T;
7437 
7438   // select true, T, F --> T
7439   // select false, T, F --> F
7440   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7441     return CondC->isNullValue() ? F : T;
7442 
7443   // TODO: This should simplify VSELECT with constant condition using something
7444   // like this (but check boolean contents to be complete?):
7445   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7446   //    return T;
7447   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7448   //    return F;
7449 
7450   // select ?, T, T --> T
7451   if (T == F)
7452     return T;
7453 
7454   return SDValue();
7455 }
7456 
7457 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7458   // shift undef, Y --> 0 (can always assume that the undef value is 0)
7459   if (X.isUndef())
7460     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7461   // shift X, undef --> undef (because it may shift by the bitwidth)
7462   if (Y.isUndef())
7463     return getUNDEF(X.getValueType());
7464 
7465   // shift 0, Y --> 0
7466   // shift X, 0 --> X
7467   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7468     return X;
7469 
7470   // shift X, C >= bitwidth(X) --> undef
7471   // All vector elements must be too big (or undef) to avoid partial undefs.
7472   auto isShiftTooBig = [X](ConstantSDNode *Val) {
7473     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7474   };
7475   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7476     return getUNDEF(X.getValueType());
7477 
7478   return SDValue();
7479 }
7480 
7481 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
7482                                       SDNodeFlags Flags) {
7483   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
7484   // (an undef operand can be chosen to be Nan/Inf), then the result of this
7485   // operation is poison. That result can be relaxed to undef.
7486   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
7487   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7488   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
7489                 (YC && YC->getValueAPF().isNaN());
7490   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
7491                 (YC && YC->getValueAPF().isInfinity());
7492 
7493   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
7494     return getUNDEF(X.getValueType());
7495 
7496   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
7497     return getUNDEF(X.getValueType());
7498 
7499   if (!YC)
7500     return SDValue();
7501 
7502   // X + -0.0 --> X
7503   if (Opcode == ISD::FADD)
7504     if (YC->getValueAPF().isNegZero())
7505       return X;
7506 
7507   // X - +0.0 --> X
7508   if (Opcode == ISD::FSUB)
7509     if (YC->getValueAPF().isPosZero())
7510       return X;
7511 
7512   // X * 1.0 --> X
7513   // X / 1.0 --> X
7514   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7515     if (YC->getValueAPF().isExactlyValue(1.0))
7516       return X;
7517 
7518   // X * 0.0 --> 0.0
7519   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
7520     if (YC->getValueAPF().isZero())
7521       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
7522 
7523   return SDValue();
7524 }
7525 
7526 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7527                                SDValue Ptr, SDValue SV, unsigned Align) {
7528   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7529   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7530 }
7531 
7532 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7533                               ArrayRef<SDUse> Ops) {
7534   switch (Ops.size()) {
7535   case 0: return getNode(Opcode, DL, VT);
7536   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7537   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7538   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7539   default: break;
7540   }
7541 
7542   // Copy from an SDUse array into an SDValue array for use with
7543   // the regular getNode logic.
7544   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7545   return getNode(Opcode, DL, VT, NewOps);
7546 }
7547 
7548 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7549                               ArrayRef<SDValue> Ops) {
7550   SDNodeFlags Flags;
7551   if (Inserter)
7552     Flags = Inserter->getFlags();
7553   return getNode(Opcode, DL, VT, Ops, Flags);
7554 }
7555 
7556 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7557                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7558   unsigned NumOps = Ops.size();
7559   switch (NumOps) {
7560   case 0: return getNode(Opcode, DL, VT);
7561   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7562   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7563   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7564   default: break;
7565   }
7566 
7567   switch (Opcode) {
7568   default: break;
7569   case ISD::BUILD_VECTOR:
7570     // Attempt to simplify BUILD_VECTOR.
7571     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7572       return V;
7573     break;
7574   case ISD::CONCAT_VECTORS:
7575     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7576       return V;
7577     break;
7578   case ISD::SELECT_CC:
7579     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7580     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7581            "LHS and RHS of condition must have same type!");
7582     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7583            "True and False arms of SelectCC must have same type!");
7584     assert(Ops[2].getValueType() == VT &&
7585            "select_cc node must be of same type as true and false value!");
7586     break;
7587   case ISD::BR_CC:
7588     assert(NumOps == 5 && "BR_CC takes 5 operands!");
7589     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7590            "LHS/RHS of comparison should match types!");
7591     break;
7592   }
7593 
7594   // Memoize nodes.
7595   SDNode *N;
7596   SDVTList VTs = getVTList(VT);
7597 
7598   if (VT != MVT::Glue) {
7599     FoldingSetNodeID ID;
7600     AddNodeIDNode(ID, Opcode, VTs, Ops);
7601     void *IP = nullptr;
7602 
7603     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7604       return SDValue(E, 0);
7605 
7606     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7607     createOperands(N, Ops);
7608 
7609     CSEMap.InsertNode(N, IP);
7610   } else {
7611     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7612     createOperands(N, Ops);
7613   }
7614 
7615   N->setFlags(Flags);
7616   InsertNode(N);
7617   SDValue V(N, 0);
7618   NewSDValueDbgMsg(V, "Creating new node: ", this);
7619   return V;
7620 }
7621 
7622 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7623                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7624   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7625 }
7626 
7627 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7628                               ArrayRef<SDValue> Ops) {
7629   SDNodeFlags Flags;
7630   if (Inserter)
7631     Flags = Inserter->getFlags();
7632   return getNode(Opcode, DL, VTList, Ops, Flags);
7633 }
7634 
7635 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7636                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7637   if (VTList.NumVTs == 1)
7638     return getNode(Opcode, DL, VTList.VTs[0], Ops);
7639 
7640   switch (Opcode) {
7641   case ISD::STRICT_FP_EXTEND:
7642     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
7643            "Invalid STRICT_FP_EXTEND!");
7644     assert(VTList.VTs[0].isFloatingPoint() &&
7645            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
7646     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7647            "STRICT_FP_EXTEND result type should be vector iff the operand "
7648            "type is vector!");
7649     assert((!VTList.VTs[0].isVector() ||
7650             VTList.VTs[0].getVectorNumElements() ==
7651             Ops[1].getValueType().getVectorNumElements()) &&
7652            "Vector element count mismatch!");
7653     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
7654            "Invalid fpext node, dst <= src!");
7655     break;
7656   case ISD::STRICT_FP_ROUND:
7657     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
7658     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7659            "STRICT_FP_ROUND result type should be vector iff the operand "
7660            "type is vector!");
7661     assert((!VTList.VTs[0].isVector() ||
7662             VTList.VTs[0].getVectorNumElements() ==
7663             Ops[1].getValueType().getVectorNumElements()) &&
7664            "Vector element count mismatch!");
7665     assert(VTList.VTs[0].isFloatingPoint() &&
7666            Ops[1].getValueType().isFloatingPoint() &&
7667            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
7668            isa<ConstantSDNode>(Ops[2]) &&
7669            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
7670             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
7671            "Invalid STRICT_FP_ROUND!");
7672     break;
7673 #if 0
7674   // FIXME: figure out how to safely handle things like
7675   // int foo(int x) { return 1 << (x & 255); }
7676   // int bar() { return foo(256); }
7677   case ISD::SRA_PARTS:
7678   case ISD::SRL_PARTS:
7679   case ISD::SHL_PARTS:
7680     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7681         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
7682       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7683     else if (N3.getOpcode() == ISD::AND)
7684       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
7685         // If the and is only masking out bits that cannot effect the shift,
7686         // eliminate the and.
7687         unsigned NumBits = VT.getScalarSizeInBits()*2;
7688         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
7689           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7690       }
7691     break;
7692 #endif
7693   }
7694 
7695   // Memoize the node unless it returns a flag.
7696   SDNode *N;
7697   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7698     FoldingSetNodeID ID;
7699     AddNodeIDNode(ID, Opcode, VTList, Ops);
7700     void *IP = nullptr;
7701     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7702       return SDValue(E, 0);
7703 
7704     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7705     createOperands(N, Ops);
7706     CSEMap.InsertNode(N, IP);
7707   } else {
7708     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7709     createOperands(N, Ops);
7710   }
7711 
7712   N->setFlags(Flags);
7713   InsertNode(N);
7714   SDValue V(N, 0);
7715   NewSDValueDbgMsg(V, "Creating new node: ", this);
7716   return V;
7717 }
7718 
7719 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7720                               SDVTList VTList) {
7721   return getNode(Opcode, DL, VTList, None);
7722 }
7723 
7724 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7725                               SDValue N1) {
7726   SDValue Ops[] = { N1 };
7727   return getNode(Opcode, DL, VTList, Ops);
7728 }
7729 
7730 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7731                               SDValue N1, SDValue N2) {
7732   SDValue Ops[] = { N1, N2 };
7733   return getNode(Opcode, DL, VTList, Ops);
7734 }
7735 
7736 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7737                               SDValue N1, SDValue N2, SDValue N3) {
7738   SDValue Ops[] = { N1, N2, N3 };
7739   return getNode(Opcode, DL, VTList, Ops);
7740 }
7741 
7742 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7743                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7744   SDValue Ops[] = { N1, N2, N3, N4 };
7745   return getNode(Opcode, DL, VTList, Ops);
7746 }
7747 
7748 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7749                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7750                               SDValue N5) {
7751   SDValue Ops[] = { N1, N2, N3, N4, N5 };
7752   return getNode(Opcode, DL, VTList, Ops);
7753 }
7754 
7755 SDVTList SelectionDAG::getVTList(EVT VT) {
7756   return makeVTList(SDNode::getValueTypeList(VT), 1);
7757 }
7758 
7759 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
7760   FoldingSetNodeID ID;
7761   ID.AddInteger(2U);
7762   ID.AddInteger(VT1.getRawBits());
7763   ID.AddInteger(VT2.getRawBits());
7764 
7765   void *IP = nullptr;
7766   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7767   if (!Result) {
7768     EVT *Array = Allocator.Allocate<EVT>(2);
7769     Array[0] = VT1;
7770     Array[1] = VT2;
7771     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
7772     VTListMap.InsertNode(Result, IP);
7773   }
7774   return Result->getSDVTList();
7775 }
7776 
7777 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
7778   FoldingSetNodeID ID;
7779   ID.AddInteger(3U);
7780   ID.AddInteger(VT1.getRawBits());
7781   ID.AddInteger(VT2.getRawBits());
7782   ID.AddInteger(VT3.getRawBits());
7783 
7784   void *IP = nullptr;
7785   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7786   if (!Result) {
7787     EVT *Array = Allocator.Allocate<EVT>(3);
7788     Array[0] = VT1;
7789     Array[1] = VT2;
7790     Array[2] = VT3;
7791     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
7792     VTListMap.InsertNode(Result, IP);
7793   }
7794   return Result->getSDVTList();
7795 }
7796 
7797 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
7798   FoldingSetNodeID ID;
7799   ID.AddInteger(4U);
7800   ID.AddInteger(VT1.getRawBits());
7801   ID.AddInteger(VT2.getRawBits());
7802   ID.AddInteger(VT3.getRawBits());
7803   ID.AddInteger(VT4.getRawBits());
7804 
7805   void *IP = nullptr;
7806   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7807   if (!Result) {
7808     EVT *Array = Allocator.Allocate<EVT>(4);
7809     Array[0] = VT1;
7810     Array[1] = VT2;
7811     Array[2] = VT3;
7812     Array[3] = VT4;
7813     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
7814     VTListMap.InsertNode(Result, IP);
7815   }
7816   return Result->getSDVTList();
7817 }
7818 
7819 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
7820   unsigned NumVTs = VTs.size();
7821   FoldingSetNodeID ID;
7822   ID.AddInteger(NumVTs);
7823   for (unsigned index = 0; index < NumVTs; index++) {
7824     ID.AddInteger(VTs[index].getRawBits());
7825   }
7826 
7827   void *IP = nullptr;
7828   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7829   if (!Result) {
7830     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
7831     llvm::copy(VTs, Array);
7832     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
7833     VTListMap.InsertNode(Result, IP);
7834   }
7835   return Result->getSDVTList();
7836 }
7837 
7838 
7839 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
7840 /// specified operands.  If the resultant node already exists in the DAG,
7841 /// this does not modify the specified node, instead it returns the node that
7842 /// already exists.  If the resultant node does not exist in the DAG, the
7843 /// input node is returned.  As a degenerate case, if you specify the same
7844 /// input operands as the node already has, the input node is returned.
7845 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
7846   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
7847 
7848   // Check to see if there is no change.
7849   if (Op == N->getOperand(0)) return N;
7850 
7851   // See if the modified node already exists.
7852   void *InsertPos = nullptr;
7853   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
7854     return Existing;
7855 
7856   // Nope it doesn't.  Remove the node from its current place in the maps.
7857   if (InsertPos)
7858     if (!RemoveNodeFromCSEMaps(N))
7859       InsertPos = nullptr;
7860 
7861   // Now we update the operands.
7862   N->OperandList[0].set(Op);
7863 
7864   updateDivergence(N);
7865   // If this gets put into a CSE map, add it.
7866   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7867   return N;
7868 }
7869 
7870 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
7871   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
7872 
7873   // Check to see if there is no change.
7874   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
7875     return N;   // No operands changed, just return the input node.
7876 
7877   // See if the modified node already exists.
7878   void *InsertPos = nullptr;
7879   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
7880     return Existing;
7881 
7882   // Nope it doesn't.  Remove the node from its current place in the maps.
7883   if (InsertPos)
7884     if (!RemoveNodeFromCSEMaps(N))
7885       InsertPos = nullptr;
7886 
7887   // Now we update the operands.
7888   if (N->OperandList[0] != Op1)
7889     N->OperandList[0].set(Op1);
7890   if (N->OperandList[1] != Op2)
7891     N->OperandList[1].set(Op2);
7892 
7893   updateDivergence(N);
7894   // If this gets put into a CSE map, add it.
7895   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7896   return N;
7897 }
7898 
7899 SDNode *SelectionDAG::
7900 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
7901   SDValue Ops[] = { Op1, Op2, Op3 };
7902   return UpdateNodeOperands(N, Ops);
7903 }
7904 
7905 SDNode *SelectionDAG::
7906 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7907                    SDValue Op3, SDValue Op4) {
7908   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
7909   return UpdateNodeOperands(N, Ops);
7910 }
7911 
7912 SDNode *SelectionDAG::
7913 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7914                    SDValue Op3, SDValue Op4, SDValue Op5) {
7915   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
7916   return UpdateNodeOperands(N, Ops);
7917 }
7918 
7919 SDNode *SelectionDAG::
7920 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
7921   unsigned NumOps = Ops.size();
7922   assert(N->getNumOperands() == NumOps &&
7923          "Update with wrong number of operands");
7924 
7925   // If no operands changed just return the input node.
7926   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
7927     return N;
7928 
7929   // See if the modified node already exists.
7930   void *InsertPos = nullptr;
7931   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
7932     return Existing;
7933 
7934   // Nope it doesn't.  Remove the node from its current place in the maps.
7935   if (InsertPos)
7936     if (!RemoveNodeFromCSEMaps(N))
7937       InsertPos = nullptr;
7938 
7939   // Now we update the operands.
7940   for (unsigned i = 0; i != NumOps; ++i)
7941     if (N->OperandList[i] != Ops[i])
7942       N->OperandList[i].set(Ops[i]);
7943 
7944   updateDivergence(N);
7945   // If this gets put into a CSE map, add it.
7946   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7947   return N;
7948 }
7949 
7950 /// DropOperands - Release the operands and set this node to have
7951 /// zero operands.
7952 void SDNode::DropOperands() {
7953   // Unlike the code in MorphNodeTo that does this, we don't need to
7954   // watch for dead nodes here.
7955   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
7956     SDUse &Use = *I++;
7957     Use.set(SDValue());
7958   }
7959 }
7960 
7961 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
7962                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
7963   if (NewMemRefs.empty()) {
7964     N->clearMemRefs();
7965     return;
7966   }
7967 
7968   // Check if we can avoid allocating by storing a single reference directly.
7969   if (NewMemRefs.size() == 1) {
7970     N->MemRefs = NewMemRefs[0];
7971     N->NumMemRefs = 1;
7972     return;
7973   }
7974 
7975   MachineMemOperand **MemRefsBuffer =
7976       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
7977   llvm::copy(NewMemRefs, MemRefsBuffer);
7978   N->MemRefs = MemRefsBuffer;
7979   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
7980 }
7981 
7982 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
7983 /// machine opcode.
7984 ///
7985 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7986                                    EVT VT) {
7987   SDVTList VTs = getVTList(VT);
7988   return SelectNodeTo(N, MachineOpc, VTs, None);
7989 }
7990 
7991 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7992                                    EVT VT, SDValue Op1) {
7993   SDVTList VTs = getVTList(VT);
7994   SDValue Ops[] = { Op1 };
7995   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7996 }
7997 
7998 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7999                                    EVT VT, SDValue Op1,
8000                                    SDValue Op2) {
8001   SDVTList VTs = getVTList(VT);
8002   SDValue Ops[] = { Op1, Op2 };
8003   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8004 }
8005 
8006 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8007                                    EVT VT, SDValue Op1,
8008                                    SDValue Op2, SDValue Op3) {
8009   SDVTList VTs = getVTList(VT);
8010   SDValue Ops[] = { Op1, Op2, Op3 };
8011   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8012 }
8013 
8014 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8015                                    EVT VT, ArrayRef<SDValue> Ops) {
8016   SDVTList VTs = getVTList(VT);
8017   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8018 }
8019 
8020 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8021                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8022   SDVTList VTs = getVTList(VT1, VT2);
8023   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8024 }
8025 
8026 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8027                                    EVT VT1, EVT VT2) {
8028   SDVTList VTs = getVTList(VT1, VT2);
8029   return SelectNodeTo(N, MachineOpc, VTs, None);
8030 }
8031 
8032 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8033                                    EVT VT1, EVT VT2, EVT VT3,
8034                                    ArrayRef<SDValue> Ops) {
8035   SDVTList VTs = getVTList(VT1, VT2, VT3);
8036   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8037 }
8038 
8039 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8040                                    EVT VT1, EVT VT2,
8041                                    SDValue Op1, SDValue Op2) {
8042   SDVTList VTs = getVTList(VT1, VT2);
8043   SDValue Ops[] = { Op1, Op2 };
8044   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8045 }
8046 
8047 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8048                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8049   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8050   // Reset the NodeID to -1.
8051   New->setNodeId(-1);
8052   if (New != N) {
8053     ReplaceAllUsesWith(N, New);
8054     RemoveDeadNode(N);
8055   }
8056   return New;
8057 }
8058 
8059 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8060 /// the line number information on the merged node since it is not possible to
8061 /// preserve the information that operation is associated with multiple lines.
8062 /// This will make the debugger working better at -O0, were there is a higher
8063 /// probability having other instructions associated with that line.
8064 ///
8065 /// For IROrder, we keep the smaller of the two
8066 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8067   DebugLoc NLoc = N->getDebugLoc();
8068   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8069     N->setDebugLoc(DebugLoc());
8070   }
8071   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8072   N->setIROrder(Order);
8073   return N;
8074 }
8075 
8076 /// MorphNodeTo - This *mutates* the specified node to have the specified
8077 /// return type, opcode, and operands.
8078 ///
8079 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8080 /// node of the specified opcode and operands, it returns that node instead of
8081 /// the current one.  Note that the SDLoc need not be the same.
8082 ///
8083 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8084 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8085 /// node, and because it doesn't require CSE recalculation for any of
8086 /// the node's users.
8087 ///
8088 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8089 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8090 /// the legalizer which maintain worklists that would need to be updated when
8091 /// deleting things.
8092 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8093                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8094   // If an identical node already exists, use it.
8095   void *IP = nullptr;
8096   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8097     FoldingSetNodeID ID;
8098     AddNodeIDNode(ID, Opc, VTs, Ops);
8099     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8100       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8101   }
8102 
8103   if (!RemoveNodeFromCSEMaps(N))
8104     IP = nullptr;
8105 
8106   // Start the morphing.
8107   N->NodeType = Opc;
8108   N->ValueList = VTs.VTs;
8109   N->NumValues = VTs.NumVTs;
8110 
8111   // Clear the operands list, updating used nodes to remove this from their
8112   // use list.  Keep track of any operands that become dead as a result.
8113   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8114   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8115     SDUse &Use = *I++;
8116     SDNode *Used = Use.getNode();
8117     Use.set(SDValue());
8118     if (Used->use_empty())
8119       DeadNodeSet.insert(Used);
8120   }
8121 
8122   // For MachineNode, initialize the memory references information.
8123   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8124     MN->clearMemRefs();
8125 
8126   // Swap for an appropriately sized array from the recycler.
8127   removeOperands(N);
8128   createOperands(N, Ops);
8129 
8130   // Delete any nodes that are still dead after adding the uses for the
8131   // new operands.
8132   if (!DeadNodeSet.empty()) {
8133     SmallVector<SDNode *, 16> DeadNodes;
8134     for (SDNode *N : DeadNodeSet)
8135       if (N->use_empty())
8136         DeadNodes.push_back(N);
8137     RemoveDeadNodes(DeadNodes);
8138   }
8139 
8140   if (IP)
8141     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8142   return N;
8143 }
8144 
8145 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8146   unsigned OrigOpc = Node->getOpcode();
8147   unsigned NewOpc;
8148   switch (OrigOpc) {
8149   default:
8150     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8151 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8152   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8153 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8154   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8155 #include "llvm/IR/ConstrainedOps.def"
8156   }
8157 
8158   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8159 
8160   // We're taking this node out of the chain, so we need to re-link things.
8161   SDValue InputChain = Node->getOperand(0);
8162   SDValue OutputChain = SDValue(Node, 1);
8163   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8164 
8165   SmallVector<SDValue, 3> Ops;
8166   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8167     Ops.push_back(Node->getOperand(i));
8168 
8169   SDVTList VTs = getVTList(Node->getValueType(0));
8170   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8171 
8172   // MorphNodeTo can operate in two ways: if an existing node with the
8173   // specified operands exists, it can just return it.  Otherwise, it
8174   // updates the node in place to have the requested operands.
8175   if (Res == Node) {
8176     // If we updated the node in place, reset the node ID.  To the isel,
8177     // this should be just like a newly allocated machine node.
8178     Res->setNodeId(-1);
8179   } else {
8180     ReplaceAllUsesWith(Node, Res);
8181     RemoveDeadNode(Node);
8182   }
8183 
8184   return Res;
8185 }
8186 
8187 /// getMachineNode - These are used for target selectors to create a new node
8188 /// with specified return type(s), MachineInstr opcode, and operands.
8189 ///
8190 /// Note that getMachineNode returns the resultant node.  If there is already a
8191 /// node of the specified opcode and operands, it returns that node instead of
8192 /// the current one.
8193 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8194                                             EVT VT) {
8195   SDVTList VTs = getVTList(VT);
8196   return getMachineNode(Opcode, dl, VTs, None);
8197 }
8198 
8199 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8200                                             EVT VT, SDValue Op1) {
8201   SDVTList VTs = getVTList(VT);
8202   SDValue Ops[] = { Op1 };
8203   return getMachineNode(Opcode, dl, VTs, Ops);
8204 }
8205 
8206 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8207                                             EVT VT, SDValue Op1, SDValue Op2) {
8208   SDVTList VTs = getVTList(VT);
8209   SDValue Ops[] = { Op1, Op2 };
8210   return getMachineNode(Opcode, dl, VTs, Ops);
8211 }
8212 
8213 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8214                                             EVT VT, SDValue Op1, SDValue Op2,
8215                                             SDValue Op3) {
8216   SDVTList VTs = getVTList(VT);
8217   SDValue Ops[] = { Op1, Op2, Op3 };
8218   return getMachineNode(Opcode, dl, VTs, Ops);
8219 }
8220 
8221 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8222                                             EVT VT, ArrayRef<SDValue> Ops) {
8223   SDVTList VTs = getVTList(VT);
8224   return getMachineNode(Opcode, dl, VTs, Ops);
8225 }
8226 
8227 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8228                                             EVT VT1, EVT VT2, SDValue Op1,
8229                                             SDValue Op2) {
8230   SDVTList VTs = getVTList(VT1, VT2);
8231   SDValue Ops[] = { Op1, Op2 };
8232   return getMachineNode(Opcode, dl, VTs, Ops);
8233 }
8234 
8235 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8236                                             EVT VT1, EVT VT2, SDValue Op1,
8237                                             SDValue Op2, SDValue Op3) {
8238   SDVTList VTs = getVTList(VT1, VT2);
8239   SDValue Ops[] = { Op1, Op2, Op3 };
8240   return getMachineNode(Opcode, dl, VTs, Ops);
8241 }
8242 
8243 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8244                                             EVT VT1, EVT VT2,
8245                                             ArrayRef<SDValue> Ops) {
8246   SDVTList VTs = getVTList(VT1, VT2);
8247   return getMachineNode(Opcode, dl, VTs, Ops);
8248 }
8249 
8250 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8251                                             EVT VT1, EVT VT2, EVT VT3,
8252                                             SDValue Op1, SDValue Op2) {
8253   SDVTList VTs = getVTList(VT1, VT2, VT3);
8254   SDValue Ops[] = { Op1, Op2 };
8255   return getMachineNode(Opcode, dl, VTs, Ops);
8256 }
8257 
8258 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8259                                             EVT VT1, EVT VT2, EVT VT3,
8260                                             SDValue Op1, SDValue Op2,
8261                                             SDValue Op3) {
8262   SDVTList VTs = getVTList(VT1, VT2, VT3);
8263   SDValue Ops[] = { Op1, Op2, Op3 };
8264   return getMachineNode(Opcode, dl, VTs, Ops);
8265 }
8266 
8267 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8268                                             EVT VT1, EVT VT2, EVT VT3,
8269                                             ArrayRef<SDValue> Ops) {
8270   SDVTList VTs = getVTList(VT1, VT2, VT3);
8271   return getMachineNode(Opcode, dl, VTs, Ops);
8272 }
8273 
8274 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8275                                             ArrayRef<EVT> ResultTys,
8276                                             ArrayRef<SDValue> Ops) {
8277   SDVTList VTs = getVTList(ResultTys);
8278   return getMachineNode(Opcode, dl, VTs, Ops);
8279 }
8280 
8281 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
8282                                             SDVTList VTs,
8283                                             ArrayRef<SDValue> Ops) {
8284   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
8285   MachineSDNode *N;
8286   void *IP = nullptr;
8287 
8288   if (DoCSE) {
8289     FoldingSetNodeID ID;
8290     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
8291     IP = nullptr;
8292     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8293       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
8294     }
8295   }
8296 
8297   // Allocate a new MachineSDNode.
8298   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8299   createOperands(N, Ops);
8300 
8301   if (DoCSE)
8302     CSEMap.InsertNode(N, IP);
8303 
8304   InsertNode(N);
8305   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
8306   return N;
8307 }
8308 
8309 /// getTargetExtractSubreg - A convenience function for creating
8310 /// TargetOpcode::EXTRACT_SUBREG nodes.
8311 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8312                                              SDValue Operand) {
8313   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8314   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
8315                                   VT, Operand, SRIdxVal);
8316   return SDValue(Subreg, 0);
8317 }
8318 
8319 /// getTargetInsertSubreg - A convenience function for creating
8320 /// TargetOpcode::INSERT_SUBREG nodes.
8321 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8322                                             SDValue Operand, SDValue Subreg) {
8323   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8324   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
8325                                   VT, Operand, Subreg, SRIdxVal);
8326   return SDValue(Result, 0);
8327 }
8328 
8329 /// getNodeIfExists - Get the specified node if it's already available, or
8330 /// else return NULL.
8331 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8332                                       ArrayRef<SDValue> Ops) {
8333   SDNodeFlags Flags;
8334   if (Inserter)
8335     Flags = Inserter->getFlags();
8336   return getNodeIfExists(Opcode, VTList, Ops, Flags);
8337 }
8338 
8339 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8340                                       ArrayRef<SDValue> Ops,
8341                                       const SDNodeFlags Flags) {
8342   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8343     FoldingSetNodeID ID;
8344     AddNodeIDNode(ID, Opcode, VTList, Ops);
8345     void *IP = nullptr;
8346     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
8347       E->intersectFlagsWith(Flags);
8348       return E;
8349     }
8350   }
8351   return nullptr;
8352 }
8353 
8354 /// doesNodeExist - Check if a node exists without modifying its flags.
8355 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
8356                                  ArrayRef<SDValue> Ops) {
8357   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8358     FoldingSetNodeID ID;
8359     AddNodeIDNode(ID, Opcode, VTList, Ops);
8360     void *IP = nullptr;
8361     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
8362       return true;
8363   }
8364   return false;
8365 }
8366 
8367 /// getDbgValue - Creates a SDDbgValue node.
8368 ///
8369 /// SDNode
8370 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
8371                                       SDNode *N, unsigned R, bool IsIndirect,
8372                                       const DebugLoc &DL, unsigned O) {
8373   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8374          "Expected inlined-at fields to agree");
8375   return new (DbgInfo->getAlloc())
8376       SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O);
8377 }
8378 
8379 /// Constant
8380 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
8381                                               DIExpression *Expr,
8382                                               const Value *C,
8383                                               const DebugLoc &DL, unsigned O) {
8384   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8385          "Expected inlined-at fields to agree");
8386   return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O);
8387 }
8388 
8389 /// FrameIndex
8390 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8391                                                 DIExpression *Expr, unsigned FI,
8392                                                 bool IsIndirect,
8393                                                 const DebugLoc &DL,
8394                                                 unsigned O) {
8395   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8396          "Expected inlined-at fields to agree");
8397   return new (DbgInfo->getAlloc())
8398       SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX);
8399 }
8400 
8401 /// VReg
8402 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var,
8403                                           DIExpression *Expr,
8404                                           unsigned VReg, bool IsIndirect,
8405                                           const DebugLoc &DL, unsigned O) {
8406   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8407          "Expected inlined-at fields to agree");
8408   return new (DbgInfo->getAlloc())
8409       SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG);
8410 }
8411 
8412 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8413                                      unsigned OffsetInBits, unsigned SizeInBits,
8414                                      bool InvalidateDbg) {
8415   SDNode *FromNode = From.getNode();
8416   SDNode *ToNode = To.getNode();
8417   assert(FromNode && ToNode && "Can't modify dbg values");
8418 
8419   // PR35338
8420   // TODO: assert(From != To && "Redundant dbg value transfer");
8421   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8422   if (From == To || FromNode == ToNode)
8423     return;
8424 
8425   if (!FromNode->getHasDebugValue())
8426     return;
8427 
8428   SmallVector<SDDbgValue *, 2> ClonedDVs;
8429   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8430     if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated())
8431       continue;
8432 
8433     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8434 
8435     // Just transfer the dbg value attached to From.
8436     if (Dbg->getResNo() != From.getResNo())
8437       continue;
8438 
8439     DIVariable *Var = Dbg->getVariable();
8440     auto *Expr = Dbg->getExpression();
8441     // If a fragment is requested, update the expression.
8442     if (SizeInBits) {
8443       // When splitting a larger (e.g., sign-extended) value whose
8444       // lower bits are described with an SDDbgValue, do not attempt
8445       // to transfer the SDDbgValue to the upper bits.
8446       if (auto FI = Expr->getFragmentInfo())
8447         if (OffsetInBits + SizeInBits > FI->SizeInBits)
8448           continue;
8449       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8450                                                              SizeInBits);
8451       if (!Fragment)
8452         continue;
8453       Expr = *Fragment;
8454     }
8455     // Clone the SDDbgValue and move it to To.
8456     SDDbgValue *Clone = getDbgValue(
8457         Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(), Dbg->getDebugLoc(),
8458         std::max(ToNode->getIROrder(), Dbg->getOrder()));
8459     ClonedDVs.push_back(Clone);
8460 
8461     if (InvalidateDbg) {
8462       // Invalidate value and indicate the SDDbgValue should not be emitted.
8463       Dbg->setIsInvalidated();
8464       Dbg->setIsEmitted();
8465     }
8466   }
8467 
8468   for (SDDbgValue *Dbg : ClonedDVs)
8469     AddDbgValue(Dbg, ToNode, false);
8470 }
8471 
8472 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8473   if (!N.getHasDebugValue())
8474     return;
8475 
8476   SmallVector<SDDbgValue *, 2> ClonedDVs;
8477   for (auto DV : GetDbgValues(&N)) {
8478     if (DV->isInvalidated())
8479       continue;
8480     switch (N.getOpcode()) {
8481     default:
8482       break;
8483     case ISD::ADD:
8484       SDValue N0 = N.getOperand(0);
8485       SDValue N1 = N.getOperand(1);
8486       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8487           isConstantIntBuildVectorOrConstantInt(N1)) {
8488         uint64_t Offset = N.getConstantOperandVal(1);
8489         // Rewrite an ADD constant node into a DIExpression. Since we are
8490         // performing arithmetic to compute the variable's *value* in the
8491         // DIExpression, we need to mark the expression with a
8492         // DW_OP_stack_value.
8493         auto *DIExpr = DV->getExpression();
8494         DIExpr =
8495             DIExpression::prepend(DIExpr, DIExpression::StackValue, Offset);
8496         SDDbgValue *Clone =
8497             getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(),
8498                         DV->isIndirect(), DV->getDebugLoc(), DV->getOrder());
8499         ClonedDVs.push_back(Clone);
8500         DV->setIsInvalidated();
8501         DV->setIsEmitted();
8502         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8503                    N0.getNode()->dumprFull(this);
8504                    dbgs() << " into " << *DIExpr << '\n');
8505       }
8506     }
8507   }
8508 
8509   for (SDDbgValue *Dbg : ClonedDVs)
8510     AddDbgValue(Dbg, Dbg->getSDNode(), false);
8511 }
8512 
8513 /// Creates a SDDbgLabel node.
8514 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8515                                       const DebugLoc &DL, unsigned O) {
8516   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8517          "Expected inlined-at fields to agree");
8518   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8519 }
8520 
8521 namespace {
8522 
8523 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8524 /// pointed to by a use iterator is deleted, increment the use iterator
8525 /// so that it doesn't dangle.
8526 ///
8527 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8528   SDNode::use_iterator &UI;
8529   SDNode::use_iterator &UE;
8530 
8531   void NodeDeleted(SDNode *N, SDNode *E) override {
8532     // Increment the iterator as needed.
8533     while (UI != UE && N == *UI)
8534       ++UI;
8535   }
8536 
8537 public:
8538   RAUWUpdateListener(SelectionDAG &d,
8539                      SDNode::use_iterator &ui,
8540                      SDNode::use_iterator &ue)
8541     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8542 };
8543 
8544 } // end anonymous namespace
8545 
8546 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8547 /// This can cause recursive merging of nodes in the DAG.
8548 ///
8549 /// This version assumes From has a single result value.
8550 ///
8551 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8552   SDNode *From = FromN.getNode();
8553   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8554          "Cannot replace with this method!");
8555   assert(From != To.getNode() && "Cannot replace uses of with self");
8556 
8557   // Preserve Debug Values
8558   transferDbgValues(FromN, To);
8559 
8560   // Iterate over all the existing uses of From. New uses will be added
8561   // to the beginning of the use list, which we avoid visiting.
8562   // This specifically avoids visiting uses of From that arise while the
8563   // replacement is happening, because any such uses would be the result
8564   // of CSE: If an existing node looks like From after one of its operands
8565   // is replaced by To, we don't want to replace of all its users with To
8566   // too. See PR3018 for more info.
8567   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8568   RAUWUpdateListener Listener(*this, UI, UE);
8569   while (UI != UE) {
8570     SDNode *User = *UI;
8571 
8572     // This node is about to morph, remove its old self from the CSE maps.
8573     RemoveNodeFromCSEMaps(User);
8574 
8575     // A user can appear in a use list multiple times, and when this
8576     // happens the uses are usually next to each other in the list.
8577     // To help reduce the number of CSE recomputations, process all
8578     // the uses of this user that we can find this way.
8579     do {
8580       SDUse &Use = UI.getUse();
8581       ++UI;
8582       Use.set(To);
8583       if (To->isDivergent() != From->isDivergent())
8584         updateDivergence(User);
8585     } while (UI != UE && *UI == User);
8586     // Now that we have modified User, add it back to the CSE maps.  If it
8587     // already exists there, recursively merge the results together.
8588     AddModifiedNodeToCSEMaps(User);
8589   }
8590 
8591   // If we just RAUW'd the root, take note.
8592   if (FromN == getRoot())
8593     setRoot(To);
8594 }
8595 
8596 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8597 /// This can cause recursive merging of nodes in the DAG.
8598 ///
8599 /// This version assumes that for each value of From, there is a
8600 /// corresponding value in To in the same position with the same type.
8601 ///
8602 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
8603 #ifndef NDEBUG
8604   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8605     assert((!From->hasAnyUseOfValue(i) ||
8606             From->getValueType(i) == To->getValueType(i)) &&
8607            "Cannot use this version of ReplaceAllUsesWith!");
8608 #endif
8609 
8610   // Handle the trivial case.
8611   if (From == To)
8612     return;
8613 
8614   // Preserve Debug Info. Only do this if there's a use.
8615   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8616     if (From->hasAnyUseOfValue(i)) {
8617       assert((i < To->getNumValues()) && "Invalid To location");
8618       transferDbgValues(SDValue(From, i), SDValue(To, i));
8619     }
8620 
8621   // Iterate over just the existing users of From. See the comments in
8622   // the ReplaceAllUsesWith above.
8623   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8624   RAUWUpdateListener Listener(*this, UI, UE);
8625   while (UI != UE) {
8626     SDNode *User = *UI;
8627 
8628     // This node is about to morph, remove its old self from the CSE maps.
8629     RemoveNodeFromCSEMaps(User);
8630 
8631     // A user can appear in a use list multiple times, and when this
8632     // happens the uses are usually next to each other in the list.
8633     // To help reduce the number of CSE recomputations, process all
8634     // the uses of this user that we can find this way.
8635     do {
8636       SDUse &Use = UI.getUse();
8637       ++UI;
8638       Use.setNode(To);
8639       if (To->isDivergent() != From->isDivergent())
8640         updateDivergence(User);
8641     } while (UI != UE && *UI == User);
8642 
8643     // Now that we have modified User, add it back to the CSE maps.  If it
8644     // already exists there, recursively merge the results together.
8645     AddModifiedNodeToCSEMaps(User);
8646   }
8647 
8648   // If we just RAUW'd the root, take note.
8649   if (From == getRoot().getNode())
8650     setRoot(SDValue(To, getRoot().getResNo()));
8651 }
8652 
8653 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8654 /// This can cause recursive merging of nodes in the DAG.
8655 ///
8656 /// This version can replace From with any result values.  To must match the
8657 /// number and types of values returned by From.
8658 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
8659   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
8660     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
8661 
8662   // Preserve Debug Info.
8663   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8664     transferDbgValues(SDValue(From, i), To[i]);
8665 
8666   // Iterate over just the existing users of From. See the comments in
8667   // the ReplaceAllUsesWith above.
8668   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8669   RAUWUpdateListener Listener(*this, UI, UE);
8670   while (UI != UE) {
8671     SDNode *User = *UI;
8672 
8673     // This node is about to morph, remove its old self from the CSE maps.
8674     RemoveNodeFromCSEMaps(User);
8675 
8676     // A user can appear in a use list multiple times, and when this happens the
8677     // uses are usually next to each other in the list.  To help reduce the
8678     // number of CSE and divergence recomputations, process all the uses of this
8679     // user that we can find this way.
8680     bool To_IsDivergent = false;
8681     do {
8682       SDUse &Use = UI.getUse();
8683       const SDValue &ToOp = To[Use.getResNo()];
8684       ++UI;
8685       Use.set(ToOp);
8686       To_IsDivergent |= ToOp->isDivergent();
8687     } while (UI != UE && *UI == User);
8688 
8689     if (To_IsDivergent != From->isDivergent())
8690       updateDivergence(User);
8691 
8692     // Now that we have modified User, add it back to the CSE maps.  If it
8693     // already exists there, recursively merge the results together.
8694     AddModifiedNodeToCSEMaps(User);
8695   }
8696 
8697   // If we just RAUW'd the root, take note.
8698   if (From == getRoot().getNode())
8699     setRoot(SDValue(To[getRoot().getResNo()]));
8700 }
8701 
8702 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8703 /// uses of other values produced by From.getNode() alone.  The Deleted
8704 /// vector is handled the same way as for ReplaceAllUsesWith.
8705 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
8706   // Handle the really simple, really trivial case efficiently.
8707   if (From == To) return;
8708 
8709   // Handle the simple, trivial, case efficiently.
8710   if (From.getNode()->getNumValues() == 1) {
8711     ReplaceAllUsesWith(From, To);
8712     return;
8713   }
8714 
8715   // Preserve Debug Info.
8716   transferDbgValues(From, To);
8717 
8718   // Iterate over just the existing users of From. See the comments in
8719   // the ReplaceAllUsesWith above.
8720   SDNode::use_iterator UI = From.getNode()->use_begin(),
8721                        UE = From.getNode()->use_end();
8722   RAUWUpdateListener Listener(*this, UI, UE);
8723   while (UI != UE) {
8724     SDNode *User = *UI;
8725     bool UserRemovedFromCSEMaps = false;
8726 
8727     // A user can appear in a use list multiple times, and when this
8728     // happens the uses are usually next to each other in the list.
8729     // To help reduce the number of CSE recomputations, process all
8730     // the uses of this user that we can find this way.
8731     do {
8732       SDUse &Use = UI.getUse();
8733 
8734       // Skip uses of different values from the same node.
8735       if (Use.getResNo() != From.getResNo()) {
8736         ++UI;
8737         continue;
8738       }
8739 
8740       // If this node hasn't been modified yet, it's still in the CSE maps,
8741       // so remove its old self from the CSE maps.
8742       if (!UserRemovedFromCSEMaps) {
8743         RemoveNodeFromCSEMaps(User);
8744         UserRemovedFromCSEMaps = true;
8745       }
8746 
8747       ++UI;
8748       Use.set(To);
8749       if (To->isDivergent() != From->isDivergent())
8750         updateDivergence(User);
8751     } while (UI != UE && *UI == User);
8752     // We are iterating over all uses of the From node, so if a use
8753     // doesn't use the specific value, no changes are made.
8754     if (!UserRemovedFromCSEMaps)
8755       continue;
8756 
8757     // Now that we have modified User, add it back to the CSE maps.  If it
8758     // already exists there, recursively merge the results together.
8759     AddModifiedNodeToCSEMaps(User);
8760   }
8761 
8762   // If we just RAUW'd the root, take note.
8763   if (From == getRoot())
8764     setRoot(To);
8765 }
8766 
8767 namespace {
8768 
8769   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
8770   /// to record information about a use.
8771   struct UseMemo {
8772     SDNode *User;
8773     unsigned Index;
8774     SDUse *Use;
8775   };
8776 
8777   /// operator< - Sort Memos by User.
8778   bool operator<(const UseMemo &L, const UseMemo &R) {
8779     return (intptr_t)L.User < (intptr_t)R.User;
8780   }
8781 
8782 } // end anonymous namespace
8783 
8784 bool SelectionDAG::calculateDivergence(SDNode *N) {
8785   if (TLI->isSDNodeAlwaysUniform(N)) {
8786     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
8787            "Conflicting divergence information!");
8788     return false;
8789   }
8790   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
8791     return true;
8792   for (auto &Op : N->ops()) {
8793     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
8794       return true;
8795   }
8796   return false;
8797 }
8798 
8799 void SelectionDAG::updateDivergence(SDNode *N) {
8800   SmallVector<SDNode *, 16> Worklist(1, N);
8801   do {
8802     N = Worklist.pop_back_val();
8803     bool IsDivergent = calculateDivergence(N);
8804     if (N->SDNodeBits.IsDivergent != IsDivergent) {
8805       N->SDNodeBits.IsDivergent = IsDivergent;
8806       llvm::append_range(Worklist, N->uses());
8807     }
8808   } while (!Worklist.empty());
8809 }
8810 
8811 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
8812   DenseMap<SDNode *, unsigned> Degree;
8813   Order.reserve(AllNodes.size());
8814   for (auto &N : allnodes()) {
8815     unsigned NOps = N.getNumOperands();
8816     Degree[&N] = NOps;
8817     if (0 == NOps)
8818       Order.push_back(&N);
8819   }
8820   for (size_t I = 0; I != Order.size(); ++I) {
8821     SDNode *N = Order[I];
8822     for (auto U : N->uses()) {
8823       unsigned &UnsortedOps = Degree[U];
8824       if (0 == --UnsortedOps)
8825         Order.push_back(U);
8826     }
8827   }
8828 }
8829 
8830 #ifndef NDEBUG
8831 void SelectionDAG::VerifyDAGDiverence() {
8832   std::vector<SDNode *> TopoOrder;
8833   CreateTopologicalOrder(TopoOrder);
8834   for (auto *N : TopoOrder) {
8835     assert(calculateDivergence(N) == N->isDivergent() &&
8836            "Divergence bit inconsistency detected");
8837   }
8838 }
8839 #endif
8840 
8841 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
8842 /// uses of other values produced by From.getNode() alone.  The same value
8843 /// may appear in both the From and To list.  The Deleted vector is
8844 /// handled the same way as for ReplaceAllUsesWith.
8845 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
8846                                               const SDValue *To,
8847                                               unsigned Num){
8848   // Handle the simple, trivial case efficiently.
8849   if (Num == 1)
8850     return ReplaceAllUsesOfValueWith(*From, *To);
8851 
8852   transferDbgValues(*From, *To);
8853 
8854   // Read up all the uses and make records of them. This helps
8855   // processing new uses that are introduced during the
8856   // replacement process.
8857   SmallVector<UseMemo, 4> Uses;
8858   for (unsigned i = 0; i != Num; ++i) {
8859     unsigned FromResNo = From[i].getResNo();
8860     SDNode *FromNode = From[i].getNode();
8861     for (SDNode::use_iterator UI = FromNode->use_begin(),
8862          E = FromNode->use_end(); UI != E; ++UI) {
8863       SDUse &Use = UI.getUse();
8864       if (Use.getResNo() == FromResNo) {
8865         UseMemo Memo = { *UI, i, &Use };
8866         Uses.push_back(Memo);
8867       }
8868     }
8869   }
8870 
8871   // Sort the uses, so that all the uses from a given User are together.
8872   llvm::sort(Uses);
8873 
8874   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
8875        UseIndex != UseIndexEnd; ) {
8876     // We know that this user uses some value of From.  If it is the right
8877     // value, update it.
8878     SDNode *User = Uses[UseIndex].User;
8879 
8880     // This node is about to morph, remove its old self from the CSE maps.
8881     RemoveNodeFromCSEMaps(User);
8882 
8883     // The Uses array is sorted, so all the uses for a given User
8884     // are next to each other in the list.
8885     // To help reduce the number of CSE recomputations, process all
8886     // the uses of this user that we can find this way.
8887     do {
8888       unsigned i = Uses[UseIndex].Index;
8889       SDUse &Use = *Uses[UseIndex].Use;
8890       ++UseIndex;
8891 
8892       Use.set(To[i]);
8893     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
8894 
8895     // Now that we have modified User, add it back to the CSE maps.  If it
8896     // already exists there, recursively merge the results together.
8897     AddModifiedNodeToCSEMaps(User);
8898   }
8899 }
8900 
8901 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
8902 /// based on their topological order. It returns the maximum id and a vector
8903 /// of the SDNodes* in assigned order by reference.
8904 unsigned SelectionDAG::AssignTopologicalOrder() {
8905   unsigned DAGSize = 0;
8906 
8907   // SortedPos tracks the progress of the algorithm. Nodes before it are
8908   // sorted, nodes after it are unsorted. When the algorithm completes
8909   // it is at the end of the list.
8910   allnodes_iterator SortedPos = allnodes_begin();
8911 
8912   // Visit all the nodes. Move nodes with no operands to the front of
8913   // the list immediately. Annotate nodes that do have operands with their
8914   // operand count. Before we do this, the Node Id fields of the nodes
8915   // may contain arbitrary values. After, the Node Id fields for nodes
8916   // before SortedPos will contain the topological sort index, and the
8917   // Node Id fields for nodes At SortedPos and after will contain the
8918   // count of outstanding operands.
8919   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
8920     SDNode *N = &*I++;
8921     checkForCycles(N, this);
8922     unsigned Degree = N->getNumOperands();
8923     if (Degree == 0) {
8924       // A node with no uses, add it to the result array immediately.
8925       N->setNodeId(DAGSize++);
8926       allnodes_iterator Q(N);
8927       if (Q != SortedPos)
8928         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
8929       assert(SortedPos != AllNodes.end() && "Overran node list");
8930       ++SortedPos;
8931     } else {
8932       // Temporarily use the Node Id as scratch space for the degree count.
8933       N->setNodeId(Degree);
8934     }
8935   }
8936 
8937   // Visit all the nodes. As we iterate, move nodes into sorted order,
8938   // such that by the time the end is reached all nodes will be sorted.
8939   for (SDNode &Node : allnodes()) {
8940     SDNode *N = &Node;
8941     checkForCycles(N, this);
8942     // N is in sorted position, so all its uses have one less operand
8943     // that needs to be sorted.
8944     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8945          UI != UE; ++UI) {
8946       SDNode *P = *UI;
8947       unsigned Degree = P->getNodeId();
8948       assert(Degree != 0 && "Invalid node degree");
8949       --Degree;
8950       if (Degree == 0) {
8951         // All of P's operands are sorted, so P may sorted now.
8952         P->setNodeId(DAGSize++);
8953         if (P->getIterator() != SortedPos)
8954           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
8955         assert(SortedPos != AllNodes.end() && "Overran node list");
8956         ++SortedPos;
8957       } else {
8958         // Update P's outstanding operand count.
8959         P->setNodeId(Degree);
8960       }
8961     }
8962     if (Node.getIterator() == SortedPos) {
8963 #ifndef NDEBUG
8964       allnodes_iterator I(N);
8965       SDNode *S = &*++I;
8966       dbgs() << "Overran sorted position:\n";
8967       S->dumprFull(this); dbgs() << "\n";
8968       dbgs() << "Checking if this is due to cycles\n";
8969       checkForCycles(this, true);
8970 #endif
8971       llvm_unreachable(nullptr);
8972     }
8973   }
8974 
8975   assert(SortedPos == AllNodes.end() &&
8976          "Topological sort incomplete!");
8977   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
8978          "First node in topological sort is not the entry token!");
8979   assert(AllNodes.front().getNodeId() == 0 &&
8980          "First node in topological sort has non-zero id!");
8981   assert(AllNodes.front().getNumOperands() == 0 &&
8982          "First node in topological sort has operands!");
8983   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
8984          "Last node in topologic sort has unexpected id!");
8985   assert(AllNodes.back().use_empty() &&
8986          "Last node in topologic sort has users!");
8987   assert(DAGSize == allnodes_size() && "Node count mismatch!");
8988   return DAGSize;
8989 }
8990 
8991 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
8992 /// value is produced by SD.
8993 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
8994   if (SD) {
8995     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
8996     SD->setHasDebugValue(true);
8997   }
8998   DbgInfo->add(DB, SD, isParameter);
8999 }
9000 
9001 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) {
9002   DbgInfo->add(DB);
9003 }
9004 
9005 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9006                                                    SDValue NewMemOpChain) {
9007   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9008   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9009   // The new memory operation must have the same position as the old load in
9010   // terms of memory dependency. Create a TokenFactor for the old load and new
9011   // memory operation and update uses of the old load's output chain to use that
9012   // TokenFactor.
9013   if (OldChain == NewMemOpChain || OldChain.use_empty())
9014     return NewMemOpChain;
9015 
9016   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9017                                 OldChain, NewMemOpChain);
9018   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9019   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9020   return TokenFactor;
9021 }
9022 
9023 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9024                                                    SDValue NewMemOp) {
9025   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9026   SDValue OldChain = SDValue(OldLoad, 1);
9027   SDValue NewMemOpChain = NewMemOp.getValue(1);
9028   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9029 }
9030 
9031 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9032                                                      Function **OutFunction) {
9033   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9034 
9035   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9036   auto *Module = MF->getFunction().getParent();
9037   auto *Function = Module->getFunction(Symbol);
9038 
9039   if (OutFunction != nullptr)
9040       *OutFunction = Function;
9041 
9042   if (Function != nullptr) {
9043     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9044     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9045   }
9046 
9047   std::string ErrorStr;
9048   raw_string_ostream ErrorFormatter(ErrorStr);
9049 
9050   ErrorFormatter << "Undefined external symbol ";
9051   ErrorFormatter << '"' << Symbol << '"';
9052   ErrorFormatter.flush();
9053 
9054   report_fatal_error(ErrorStr);
9055 }
9056 
9057 //===----------------------------------------------------------------------===//
9058 //                              SDNode Class
9059 //===----------------------------------------------------------------------===//
9060 
9061 bool llvm::isNullConstant(SDValue V) {
9062   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9063   return Const != nullptr && Const->isNullValue();
9064 }
9065 
9066 bool llvm::isNullFPConstant(SDValue V) {
9067   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9068   return Const != nullptr && Const->isZero() && !Const->isNegative();
9069 }
9070 
9071 bool llvm::isAllOnesConstant(SDValue V) {
9072   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9073   return Const != nullptr && Const->isAllOnesValue();
9074 }
9075 
9076 bool llvm::isOneConstant(SDValue V) {
9077   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9078   return Const != nullptr && Const->isOne();
9079 }
9080 
9081 SDValue llvm::peekThroughBitcasts(SDValue V) {
9082   while (V.getOpcode() == ISD::BITCAST)
9083     V = V.getOperand(0);
9084   return V;
9085 }
9086 
9087 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9088   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9089     V = V.getOperand(0);
9090   return V;
9091 }
9092 
9093 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9094   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9095     V = V.getOperand(0);
9096   return V;
9097 }
9098 
9099 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9100   if (V.getOpcode() != ISD::XOR)
9101     return false;
9102   V = peekThroughBitcasts(V.getOperand(1));
9103   unsigned NumBits = V.getScalarValueSizeInBits();
9104   ConstantSDNode *C =
9105       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9106   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9107 }
9108 
9109 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9110                                           bool AllowTruncation) {
9111   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9112     return CN;
9113 
9114   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9115     BitVector UndefElements;
9116     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9117 
9118     // BuildVectors can truncate their operands. Ignore that case here unless
9119     // AllowTruncation is set.
9120     if (CN && (UndefElements.none() || AllowUndefs)) {
9121       EVT CVT = CN->getValueType(0);
9122       EVT NSVT = N.getValueType().getScalarType();
9123       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9124       if (AllowTruncation || (CVT == NSVT))
9125         return CN;
9126     }
9127   }
9128 
9129   return nullptr;
9130 }
9131 
9132 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9133                                           bool AllowUndefs,
9134                                           bool AllowTruncation) {
9135   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9136     return CN;
9137 
9138   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9139     BitVector UndefElements;
9140     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9141 
9142     // BuildVectors can truncate their operands. Ignore that case here unless
9143     // AllowTruncation is set.
9144     if (CN && (UndefElements.none() || AllowUndefs)) {
9145       EVT CVT = CN->getValueType(0);
9146       EVT NSVT = N.getValueType().getScalarType();
9147       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9148       if (AllowTruncation || (CVT == NSVT))
9149         return CN;
9150     }
9151   }
9152 
9153   return nullptr;
9154 }
9155 
9156 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
9157   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9158     return CN;
9159 
9160   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9161     BitVector UndefElements;
9162     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
9163     if (CN && (UndefElements.none() || AllowUndefs))
9164       return CN;
9165   }
9166 
9167   if (N.getOpcode() == ISD::SPLAT_VECTOR)
9168     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
9169       return CN;
9170 
9171   return nullptr;
9172 }
9173 
9174 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
9175                                               const APInt &DemandedElts,
9176                                               bool AllowUndefs) {
9177   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9178     return CN;
9179 
9180   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9181     BitVector UndefElements;
9182     ConstantFPSDNode *CN =
9183         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
9184     if (CN && (UndefElements.none() || AllowUndefs))
9185       return CN;
9186   }
9187 
9188   return nullptr;
9189 }
9190 
9191 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
9192   // TODO: may want to use peekThroughBitcast() here.
9193   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9194   return C && C->isNullValue();
9195 }
9196 
9197 bool llvm::isOneOrOneSplat(SDValue N) {
9198   // TODO: may want to use peekThroughBitcast() here.
9199   unsigned BitWidth = N.getScalarValueSizeInBits();
9200   ConstantSDNode *C = isConstOrConstSplat(N);
9201   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
9202 }
9203 
9204 bool llvm::isAllOnesOrAllOnesSplat(SDValue N) {
9205   N = peekThroughBitcasts(N);
9206   unsigned BitWidth = N.getScalarValueSizeInBits();
9207   ConstantSDNode *C = isConstOrConstSplat(N);
9208   return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
9209 }
9210 
9211 HandleSDNode::~HandleSDNode() {
9212   DropOperands();
9213 }
9214 
9215 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
9216                                          const DebugLoc &DL,
9217                                          const GlobalValue *GA, EVT VT,
9218                                          int64_t o, unsigned TF)
9219     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
9220   TheGlobal = GA;
9221 }
9222 
9223 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
9224                                          EVT VT, unsigned SrcAS,
9225                                          unsigned DestAS)
9226     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
9227       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
9228 
9229 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
9230                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
9231     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
9232   MemSDNodeBits.IsVolatile = MMO->isVolatile();
9233   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
9234   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
9235   MemSDNodeBits.IsInvariant = MMO->isInvariant();
9236 
9237   // We check here that the size of the memory operand fits within the size of
9238   // the MMO. This is because the MMO might indicate only a possible address
9239   // range instead of specifying the affected memory addresses precisely.
9240   // TODO: Make MachineMemOperands aware of scalable vectors.
9241   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
9242          "Size mismatch!");
9243 }
9244 
9245 /// Profile - Gather unique data for the node.
9246 ///
9247 void SDNode::Profile(FoldingSetNodeID &ID) const {
9248   AddNodeIDNode(ID, this);
9249 }
9250 
9251 namespace {
9252 
9253   struct EVTArray {
9254     std::vector<EVT> VTs;
9255 
9256     EVTArray() {
9257       VTs.reserve(MVT::LAST_VALUETYPE);
9258       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
9259         VTs.push_back(MVT((MVT::SimpleValueType)i));
9260     }
9261   };
9262 
9263 } // end anonymous namespace
9264 
9265 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
9266 static ManagedStatic<EVTArray> SimpleVTArray;
9267 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
9268 
9269 /// getValueTypeList - Return a pointer to the specified value type.
9270 ///
9271 const EVT *SDNode::getValueTypeList(EVT VT) {
9272   if (VT.isExtended()) {
9273     sys::SmartScopedLock<true> Lock(*VTMutex);
9274     return &(*EVTs->insert(VT).first);
9275   } else {
9276     assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
9277            "Value type out of range!");
9278     return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
9279   }
9280 }
9281 
9282 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
9283 /// indicated value.  This method ignores uses of other values defined by this
9284 /// operation.
9285 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
9286   assert(Value < getNumValues() && "Bad value!");
9287 
9288   // TODO: Only iterate over uses of a given value of the node
9289   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
9290     if (UI.getUse().getResNo() == Value) {
9291       if (NUses == 0)
9292         return false;
9293       --NUses;
9294     }
9295   }
9296 
9297   // Found exactly the right number of uses?
9298   return NUses == 0;
9299 }
9300 
9301 /// hasAnyUseOfValue - Return true if there are any use of the indicated
9302 /// value. This method ignores uses of other values defined by this operation.
9303 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
9304   assert(Value < getNumValues() && "Bad value!");
9305 
9306   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
9307     if (UI.getUse().getResNo() == Value)
9308       return true;
9309 
9310   return false;
9311 }
9312 
9313 /// isOnlyUserOf - Return true if this node is the only use of N.
9314 bool SDNode::isOnlyUserOf(const SDNode *N) const {
9315   bool Seen = false;
9316   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9317     SDNode *User = *I;
9318     if (User == this)
9319       Seen = true;
9320     else
9321       return false;
9322   }
9323 
9324   return Seen;
9325 }
9326 
9327 /// Return true if the only users of N are contained in Nodes.
9328 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
9329   bool Seen = false;
9330   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9331     SDNode *User = *I;
9332     if (llvm::is_contained(Nodes, User))
9333       Seen = true;
9334     else
9335       return false;
9336   }
9337 
9338   return Seen;
9339 }
9340 
9341 /// isOperand - Return true if this node is an operand of N.
9342 bool SDValue::isOperandOf(const SDNode *N) const {
9343   return is_contained(N->op_values(), *this);
9344 }
9345 
9346 bool SDNode::isOperandOf(const SDNode *N) const {
9347   return any_of(N->op_values(),
9348                 [this](SDValue Op) { return this == Op.getNode(); });
9349 }
9350 
9351 /// reachesChainWithoutSideEffects - Return true if this operand (which must
9352 /// be a chain) reaches the specified operand without crossing any
9353 /// side-effecting instructions on any chain path.  In practice, this looks
9354 /// through token factors and non-volatile loads.  In order to remain efficient,
9355 /// this only looks a couple of nodes in, it does not do an exhaustive search.
9356 ///
9357 /// Note that we only need to examine chains when we're searching for
9358 /// side-effects; SelectionDAG requires that all side-effects are represented
9359 /// by chains, even if another operand would force a specific ordering. This
9360 /// constraint is necessary to allow transformations like splitting loads.
9361 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
9362                                              unsigned Depth) const {
9363   if (*this == Dest) return true;
9364 
9365   // Don't search too deeply, we just want to be able to see through
9366   // TokenFactor's etc.
9367   if (Depth == 0) return false;
9368 
9369   // If this is a token factor, all inputs to the TF happen in parallel.
9370   if (getOpcode() == ISD::TokenFactor) {
9371     // First, try a shallow search.
9372     if (is_contained((*this)->ops(), Dest)) {
9373       // We found the chain we want as an operand of this TokenFactor.
9374       // Essentially, we reach the chain without side-effects if we could
9375       // serialize the TokenFactor into a simple chain of operations with
9376       // Dest as the last operation. This is automatically true if the
9377       // chain has one use: there are no other ordering constraints.
9378       // If the chain has more than one use, we give up: some other
9379       // use of Dest might force a side-effect between Dest and the current
9380       // node.
9381       if (Dest.hasOneUse())
9382         return true;
9383     }
9384     // Next, try a deep search: check whether every operand of the TokenFactor
9385     // reaches Dest.
9386     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
9387       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
9388     });
9389   }
9390 
9391   // Loads don't have side effects, look through them.
9392   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
9393     if (Ld->isUnordered())
9394       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
9395   }
9396   return false;
9397 }
9398 
9399 bool SDNode::hasPredecessor(const SDNode *N) const {
9400   SmallPtrSet<const SDNode *, 32> Visited;
9401   SmallVector<const SDNode *, 16> Worklist;
9402   Worklist.push_back(this);
9403   return hasPredecessorHelper(N, Visited, Worklist);
9404 }
9405 
9406 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
9407   this->Flags.intersectWith(Flags);
9408 }
9409 
9410 SDValue
9411 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
9412                                   ArrayRef<ISD::NodeType> CandidateBinOps,
9413                                   bool AllowPartials) {
9414   // The pattern must end in an extract from index 0.
9415   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9416       !isNullConstant(Extract->getOperand(1)))
9417     return SDValue();
9418 
9419   // Match against one of the candidate binary ops.
9420   SDValue Op = Extract->getOperand(0);
9421   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9422         return Op.getOpcode() == unsigned(BinOp);
9423       }))
9424     return SDValue();
9425 
9426   // Floating-point reductions may require relaxed constraints on the final step
9427   // of the reduction because they may reorder intermediate operations.
9428   unsigned CandidateBinOp = Op.getOpcode();
9429   if (Op.getValueType().isFloatingPoint()) {
9430     SDNodeFlags Flags = Op->getFlags();
9431     switch (CandidateBinOp) {
9432     case ISD::FADD:
9433       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
9434         return SDValue();
9435       break;
9436     default:
9437       llvm_unreachable("Unhandled FP opcode for binop reduction");
9438     }
9439   }
9440 
9441   // Matching failed - attempt to see if we did enough stages that a partial
9442   // reduction from a subvector is possible.
9443   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
9444     if (!AllowPartials || !Op)
9445       return SDValue();
9446     EVT OpVT = Op.getValueType();
9447     EVT OpSVT = OpVT.getScalarType();
9448     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
9449     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
9450       return SDValue();
9451     BinOp = (ISD::NodeType)CandidateBinOp;
9452     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
9453                    getVectorIdxConstant(0, SDLoc(Op)));
9454   };
9455 
9456   // At each stage, we're looking for something that looks like:
9457   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9458   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9459   //                               i32 undef, i32 undef, i32 undef, i32 undef>
9460   // %a = binop <8 x i32> %op, %s
9461   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9462   // we expect something like:
9463   // <4,5,6,7,u,u,u,u>
9464   // <2,3,u,u,u,u,u,u>
9465   // <1,u,u,u,u,u,u,u>
9466   // While a partial reduction match would be:
9467   // <2,3,u,u,u,u,u,u>
9468   // <1,u,u,u,u,u,u,u>
9469   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9470   SDValue PrevOp;
9471   for (unsigned i = 0; i < Stages; ++i) {
9472     unsigned MaskEnd = (1 << i);
9473 
9474     if (Op.getOpcode() != CandidateBinOp)
9475       return PartialReduction(PrevOp, MaskEnd);
9476 
9477     SDValue Op0 = Op.getOperand(0);
9478     SDValue Op1 = Op.getOperand(1);
9479 
9480     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9481     if (Shuffle) {
9482       Op = Op1;
9483     } else {
9484       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9485       Op = Op0;
9486     }
9487 
9488     // The first operand of the shuffle should be the same as the other operand
9489     // of the binop.
9490     if (!Shuffle || Shuffle->getOperand(0) != Op)
9491       return PartialReduction(PrevOp, MaskEnd);
9492 
9493     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9494     for (int Index = 0; Index < (int)MaskEnd; ++Index)
9495       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
9496         return PartialReduction(PrevOp, MaskEnd);
9497 
9498     PrevOp = Op;
9499   }
9500 
9501   // Handle subvector reductions, which tend to appear after the shuffle
9502   // reduction stages.
9503   while (Op.getOpcode() == CandidateBinOp) {
9504     unsigned NumElts = Op.getValueType().getVectorNumElements();
9505     SDValue Op0 = Op.getOperand(0);
9506     SDValue Op1 = Op.getOperand(1);
9507     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9508         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9509         Op0.getOperand(0) != Op1.getOperand(0))
9510       break;
9511     SDValue Src = Op0.getOperand(0);
9512     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
9513     if (NumSrcElts != (2 * NumElts))
9514       break;
9515     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
9516           Op1.getConstantOperandAPInt(1) == NumElts) &&
9517         !(Op1.getConstantOperandAPInt(1) == 0 &&
9518           Op0.getConstantOperandAPInt(1) == NumElts))
9519       break;
9520     Op = Src;
9521   }
9522 
9523   BinOp = (ISD::NodeType)CandidateBinOp;
9524   return Op;
9525 }
9526 
9527 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9528   assert(N->getNumValues() == 1 &&
9529          "Can't unroll a vector with multiple results!");
9530 
9531   EVT VT = N->getValueType(0);
9532   unsigned NE = VT.getVectorNumElements();
9533   EVT EltVT = VT.getVectorElementType();
9534   SDLoc dl(N);
9535 
9536   SmallVector<SDValue, 8> Scalars;
9537   SmallVector<SDValue, 4> Operands(N->getNumOperands());
9538 
9539   // If ResNE is 0, fully unroll the vector op.
9540   if (ResNE == 0)
9541     ResNE = NE;
9542   else if (NE > ResNE)
9543     NE = ResNE;
9544 
9545   unsigned i;
9546   for (i= 0; i != NE; ++i) {
9547     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9548       SDValue Operand = N->getOperand(j);
9549       EVT OperandVT = Operand.getValueType();
9550       if (OperandVT.isVector()) {
9551         // A vector operand; extract a single element.
9552         EVT OperandEltVT = OperandVT.getVectorElementType();
9553         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
9554                               Operand, getVectorIdxConstant(i, dl));
9555       } else {
9556         // A scalar operand; just use it as is.
9557         Operands[j] = Operand;
9558       }
9559     }
9560 
9561     switch (N->getOpcode()) {
9562     default: {
9563       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9564                                 N->getFlags()));
9565       break;
9566     }
9567     case ISD::VSELECT:
9568       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
9569       break;
9570     case ISD::SHL:
9571     case ISD::SRA:
9572     case ISD::SRL:
9573     case ISD::ROTL:
9574     case ISD::ROTR:
9575       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
9576                                getShiftAmountOperand(Operands[0].getValueType(),
9577                                                      Operands[1])));
9578       break;
9579     case ISD::SIGN_EXTEND_INREG: {
9580       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
9581       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
9582                                 Operands[0],
9583                                 getValueType(ExtVT)));
9584     }
9585     }
9586   }
9587 
9588   for (; i < ResNE; ++i)
9589     Scalars.push_back(getUNDEF(EltVT));
9590 
9591   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
9592   return getBuildVector(VecVT, dl, Scalars);
9593 }
9594 
9595 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
9596     SDNode *N, unsigned ResNE) {
9597   unsigned Opcode = N->getOpcode();
9598   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
9599           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
9600           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
9601          "Expected an overflow opcode");
9602 
9603   EVT ResVT = N->getValueType(0);
9604   EVT OvVT = N->getValueType(1);
9605   EVT ResEltVT = ResVT.getVectorElementType();
9606   EVT OvEltVT = OvVT.getVectorElementType();
9607   SDLoc dl(N);
9608 
9609   // If ResNE is 0, fully unroll the vector op.
9610   unsigned NE = ResVT.getVectorNumElements();
9611   if (ResNE == 0)
9612     ResNE = NE;
9613   else if (NE > ResNE)
9614     NE = ResNE;
9615 
9616   SmallVector<SDValue, 8> LHSScalars;
9617   SmallVector<SDValue, 8> RHSScalars;
9618   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
9619   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
9620 
9621   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
9622   SDVTList VTs = getVTList(ResEltVT, SVT);
9623   SmallVector<SDValue, 8> ResScalars;
9624   SmallVector<SDValue, 8> OvScalars;
9625   for (unsigned i = 0; i < NE; ++i) {
9626     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
9627     SDValue Ov =
9628         getSelect(dl, OvEltVT, Res.getValue(1),
9629                   getBoolConstant(true, dl, OvEltVT, ResVT),
9630                   getConstant(0, dl, OvEltVT));
9631 
9632     ResScalars.push_back(Res);
9633     OvScalars.push_back(Ov);
9634   }
9635 
9636   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
9637   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
9638 
9639   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
9640   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
9641   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
9642                         getBuildVector(NewOvVT, dl, OvScalars));
9643 }
9644 
9645 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
9646                                                   LoadSDNode *Base,
9647                                                   unsigned Bytes,
9648                                                   int Dist) const {
9649   if (LD->isVolatile() || Base->isVolatile())
9650     return false;
9651   // TODO: probably too restrictive for atomics, revisit
9652   if (!LD->isSimple())
9653     return false;
9654   if (LD->isIndexed() || Base->isIndexed())
9655     return false;
9656   if (LD->getChain() != Base->getChain())
9657     return false;
9658   EVT VT = LD->getValueType(0);
9659   if (VT.getSizeInBits() / 8 != Bytes)
9660     return false;
9661 
9662   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
9663   auto LocDecomp = BaseIndexOffset::match(LD, *this);
9664 
9665   int64_t Offset = 0;
9666   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
9667     return (Dist * Bytes == Offset);
9668   return false;
9669 }
9670 
9671 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
9672 /// if it cannot be inferred.
9673 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
9674   // If this is a GlobalAddress + cst, return the alignment.
9675   const GlobalValue *GV = nullptr;
9676   int64_t GVOffset = 0;
9677   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
9678     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
9679     KnownBits Known(PtrWidth);
9680     llvm::computeKnownBits(GV, Known, getDataLayout());
9681     unsigned AlignBits = Known.countMinTrailingZeros();
9682     if (AlignBits)
9683       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
9684   }
9685 
9686   // If this is a direct reference to a stack slot, use information about the
9687   // stack slot's alignment.
9688   int FrameIdx = INT_MIN;
9689   int64_t FrameOffset = 0;
9690   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
9691     FrameIdx = FI->getIndex();
9692   } else if (isBaseWithConstantOffset(Ptr) &&
9693              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
9694     // Handle FI+Cst
9695     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9696     FrameOffset = Ptr.getConstantOperandVal(1);
9697   }
9698 
9699   if (FrameIdx != INT_MIN) {
9700     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
9701     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
9702   }
9703 
9704   return None;
9705 }
9706 
9707 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
9708 /// which is split (or expanded) into two not necessarily identical pieces.
9709 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
9710   // Currently all types are split in half.
9711   EVT LoVT, HiVT;
9712   if (!VT.isVector())
9713     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
9714   else
9715     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
9716 
9717   return std::make_pair(LoVT, HiVT);
9718 }
9719 
9720 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
9721 /// type, dependent on an enveloping VT that has been split into two identical
9722 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
9723 std::pair<EVT, EVT>
9724 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
9725                                        bool *HiIsEmpty) const {
9726   EVT EltTp = VT.getVectorElementType();
9727   // Examples:
9728   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
9729   //   custom VL=9  with enveloping VL=8/8 yields 8/1
9730   //   custom VL=10 with enveloping VL=8/8 yields 8/2
9731   //   etc.
9732   ElementCount VTNumElts = VT.getVectorElementCount();
9733   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
9734   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
9735          "Mixing fixed width and scalable vectors when enveloping a type");
9736   EVT LoVT, HiVT;
9737   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
9738     LoVT = EnvVT;
9739     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
9740     *HiIsEmpty = false;
9741   } else {
9742     // Flag that hi type has zero storage size, but return split envelop type
9743     // (this would be easier if vector types with zero elements were allowed).
9744     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
9745     HiVT = EnvVT;
9746     *HiIsEmpty = true;
9747   }
9748   return std::make_pair(LoVT, HiVT);
9749 }
9750 
9751 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
9752 /// low/high part.
9753 std::pair<SDValue, SDValue>
9754 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
9755                           const EVT &HiVT) {
9756   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
9757          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
9758          "Splitting vector with an invalid mixture of fixed and scalable "
9759          "vector types");
9760   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
9761              N.getValueType().getVectorMinNumElements() &&
9762          "More vector elements requested than available!");
9763   SDValue Lo, Hi;
9764   Lo =
9765       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
9766   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
9767   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
9768   // IDX with the runtime scaling factor of the result vector type. For
9769   // fixed-width result vectors, that runtime scaling factor is 1.
9770   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
9771                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
9772   return std::make_pair(Lo, Hi);
9773 }
9774 
9775 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
9776 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
9777   EVT VT = N.getValueType();
9778   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
9779                                 NextPowerOf2(VT.getVectorNumElements()));
9780   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
9781                  getVectorIdxConstant(0, DL));
9782 }
9783 
9784 void SelectionDAG::ExtractVectorElements(SDValue Op,
9785                                          SmallVectorImpl<SDValue> &Args,
9786                                          unsigned Start, unsigned Count,
9787                                          EVT EltVT) {
9788   EVT VT = Op.getValueType();
9789   if (Count == 0)
9790     Count = VT.getVectorNumElements();
9791   if (EltVT == EVT())
9792     EltVT = VT.getVectorElementType();
9793   SDLoc SL(Op);
9794   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
9795     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
9796                            getVectorIdxConstant(i, SL)));
9797   }
9798 }
9799 
9800 // getAddressSpace - Return the address space this GlobalAddress belongs to.
9801 unsigned GlobalAddressSDNode::getAddressSpace() const {
9802   return getGlobal()->getType()->getAddressSpace();
9803 }
9804 
9805 Type *ConstantPoolSDNode::getType() const {
9806   if (isMachineConstantPoolEntry())
9807     return Val.MachineCPVal->getType();
9808   return Val.ConstVal->getType();
9809 }
9810 
9811 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
9812                                         unsigned &SplatBitSize,
9813                                         bool &HasAnyUndefs,
9814                                         unsigned MinSplatBits,
9815                                         bool IsBigEndian) const {
9816   EVT VT = getValueType(0);
9817   assert(VT.isVector() && "Expected a vector type");
9818   unsigned VecWidth = VT.getSizeInBits();
9819   if (MinSplatBits > VecWidth)
9820     return false;
9821 
9822   // FIXME: The widths are based on this node's type, but build vectors can
9823   // truncate their operands.
9824   SplatValue = APInt(VecWidth, 0);
9825   SplatUndef = APInt(VecWidth, 0);
9826 
9827   // Get the bits. Bits with undefined values (when the corresponding element
9828   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
9829   // in SplatValue. If any of the values are not constant, give up and return
9830   // false.
9831   unsigned int NumOps = getNumOperands();
9832   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
9833   unsigned EltWidth = VT.getScalarSizeInBits();
9834 
9835   for (unsigned j = 0; j < NumOps; ++j) {
9836     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
9837     SDValue OpVal = getOperand(i);
9838     unsigned BitPos = j * EltWidth;
9839 
9840     if (OpVal.isUndef())
9841       SplatUndef.setBits(BitPos, BitPos + EltWidth);
9842     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
9843       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
9844     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
9845       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
9846     else
9847       return false;
9848   }
9849 
9850   // The build_vector is all constants or undefs. Find the smallest element
9851   // size that splats the vector.
9852   HasAnyUndefs = (SplatUndef != 0);
9853 
9854   // FIXME: This does not work for vectors with elements less than 8 bits.
9855   while (VecWidth > 8) {
9856     unsigned HalfSize = VecWidth / 2;
9857     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
9858     APInt LowValue = SplatValue.trunc(HalfSize);
9859     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
9860     APInt LowUndef = SplatUndef.trunc(HalfSize);
9861 
9862     // If the two halves do not match (ignoring undef bits), stop here.
9863     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
9864         MinSplatBits > HalfSize)
9865       break;
9866 
9867     SplatValue = HighValue | LowValue;
9868     SplatUndef = HighUndef & LowUndef;
9869 
9870     VecWidth = HalfSize;
9871   }
9872 
9873   SplatBitSize = VecWidth;
9874   return true;
9875 }
9876 
9877 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
9878                                          BitVector *UndefElements) const {
9879   unsigned NumOps = getNumOperands();
9880   if (UndefElements) {
9881     UndefElements->clear();
9882     UndefElements->resize(NumOps);
9883   }
9884   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
9885   if (!DemandedElts)
9886     return SDValue();
9887   SDValue Splatted;
9888   for (unsigned i = 0; i != NumOps; ++i) {
9889     if (!DemandedElts[i])
9890       continue;
9891     SDValue Op = getOperand(i);
9892     if (Op.isUndef()) {
9893       if (UndefElements)
9894         (*UndefElements)[i] = true;
9895     } else if (!Splatted) {
9896       Splatted = Op;
9897     } else if (Splatted != Op) {
9898       return SDValue();
9899     }
9900   }
9901 
9902   if (!Splatted) {
9903     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
9904     assert(getOperand(FirstDemandedIdx).isUndef() &&
9905            "Can only have a splat without a constant for all undefs.");
9906     return getOperand(FirstDemandedIdx);
9907   }
9908 
9909   return Splatted;
9910 }
9911 
9912 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
9913   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
9914   return getSplatValue(DemandedElts, UndefElements);
9915 }
9916 
9917 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
9918                                             SmallVectorImpl<SDValue> &Sequence,
9919                                             BitVector *UndefElements) const {
9920   unsigned NumOps = getNumOperands();
9921   Sequence.clear();
9922   if (UndefElements) {
9923     UndefElements->clear();
9924     UndefElements->resize(NumOps);
9925   }
9926   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
9927   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
9928     return false;
9929 
9930   // Set the undefs even if we don't find a sequence (like getSplatValue).
9931   if (UndefElements)
9932     for (unsigned I = 0; I != NumOps; ++I)
9933       if (DemandedElts[I] && getOperand(I).isUndef())
9934         (*UndefElements)[I] = true;
9935 
9936   // Iteratively widen the sequence length looking for repetitions.
9937   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
9938     Sequence.append(SeqLen, SDValue());
9939     for (unsigned I = 0; I != NumOps; ++I) {
9940       if (!DemandedElts[I])
9941         continue;
9942       SDValue &SeqOp = Sequence[I % SeqLen];
9943       SDValue Op = getOperand(I);
9944       if (Op.isUndef()) {
9945         if (!SeqOp)
9946           SeqOp = Op;
9947         continue;
9948       }
9949       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
9950         Sequence.clear();
9951         break;
9952       }
9953       SeqOp = Op;
9954     }
9955     if (!Sequence.empty())
9956       return true;
9957   }
9958 
9959   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
9960   return false;
9961 }
9962 
9963 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
9964                                             BitVector *UndefElements) const {
9965   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
9966   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
9967 }
9968 
9969 ConstantSDNode *
9970 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
9971                                         BitVector *UndefElements) const {
9972   return dyn_cast_or_null<ConstantSDNode>(
9973       getSplatValue(DemandedElts, UndefElements));
9974 }
9975 
9976 ConstantSDNode *
9977 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
9978   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
9979 }
9980 
9981 ConstantFPSDNode *
9982 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
9983                                           BitVector *UndefElements) const {
9984   return dyn_cast_or_null<ConstantFPSDNode>(
9985       getSplatValue(DemandedElts, UndefElements));
9986 }
9987 
9988 ConstantFPSDNode *
9989 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
9990   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
9991 }
9992 
9993 int32_t
9994 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
9995                                                    uint32_t BitWidth) const {
9996   if (ConstantFPSDNode *CN =
9997           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
9998     bool IsExact;
9999     APSInt IntVal(BitWidth);
10000     const APFloat &APF = CN->getValueAPF();
10001     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10002             APFloat::opOK ||
10003         !IsExact)
10004       return -1;
10005 
10006     return IntVal.exactLogBase2();
10007   }
10008   return -1;
10009 }
10010 
10011 bool BuildVectorSDNode::isConstant() const {
10012   for (const SDValue &Op : op_values()) {
10013     unsigned Opc = Op.getOpcode();
10014     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10015       return false;
10016   }
10017   return true;
10018 }
10019 
10020 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10021   // Find the first non-undef value in the shuffle mask.
10022   unsigned i, e;
10023   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10024     /* search */;
10025 
10026   // If all elements are undefined, this shuffle can be considered a splat
10027   // (although it should eventually get simplified away completely).
10028   if (i == e)
10029     return true;
10030 
10031   // Make sure all remaining elements are either undef or the same as the first
10032   // non-undef value.
10033   for (int Idx = Mask[i]; i != e; ++i)
10034     if (Mask[i] >= 0 && Mask[i] != Idx)
10035       return false;
10036   return true;
10037 }
10038 
10039 // Returns the SDNode if it is a constant integer BuildVector
10040 // or constant integer.
10041 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
10042   if (isa<ConstantSDNode>(N))
10043     return N.getNode();
10044   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10045     return N.getNode();
10046   // Treat a GlobalAddress supporting constant offset folding as a
10047   // constant integer.
10048   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10049     if (GA->getOpcode() == ISD::GlobalAddress &&
10050         TLI->isOffsetFoldingLegal(GA))
10051       return GA;
10052   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10053       isa<ConstantSDNode>(N.getOperand(0)))
10054     return N.getNode();
10055   return nullptr;
10056 }
10057 
10058 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
10059   if (isa<ConstantFPSDNode>(N))
10060     return N.getNode();
10061 
10062   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10063     return N.getNode();
10064 
10065   return nullptr;
10066 }
10067 
10068 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10069   assert(!Node->OperandList && "Node already has operands");
10070   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
10071          "too many operands to fit into SDNode");
10072   SDUse *Ops = OperandRecycler.allocate(
10073       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10074 
10075   bool IsDivergent = false;
10076   for (unsigned I = 0; I != Vals.size(); ++I) {
10077     Ops[I].setUser(Node);
10078     Ops[I].setInitial(Vals[I]);
10079     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10080       IsDivergent |= Ops[I].getNode()->isDivergent();
10081   }
10082   Node->NumOperands = Vals.size();
10083   Node->OperandList = Ops;
10084   if (!TLI->isSDNodeAlwaysUniform(Node)) {
10085     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10086     Node->SDNodeBits.IsDivergent = IsDivergent;
10087   }
10088   checkForCycles(Node);
10089 }
10090 
10091 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10092                                      SmallVectorImpl<SDValue> &Vals) {
10093   size_t Limit = SDNode::getMaxNumOperands();
10094   while (Vals.size() > Limit) {
10095     unsigned SliceIdx = Vals.size() - Limit;
10096     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
10097     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
10098     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
10099     Vals.emplace_back(NewTF);
10100   }
10101   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
10102 }
10103 
10104 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
10105                                         EVT VT, SDNodeFlags Flags) {
10106   switch (Opcode) {
10107   default:
10108     return SDValue();
10109   case ISD::ADD:
10110   case ISD::OR:
10111   case ISD::XOR:
10112   case ISD::UMAX:
10113     return getConstant(0, DL, VT);
10114   case ISD::MUL:
10115     return getConstant(1, DL, VT);
10116   case ISD::AND:
10117   case ISD::UMIN:
10118     return getAllOnesConstant(DL, VT);
10119   case ISD::SMAX:
10120     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
10121   case ISD::SMIN:
10122     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
10123   case ISD::FADD:
10124     return getConstantFP(-0.0, DL, VT);
10125   case ISD::FMUL:
10126     return getConstantFP(1.0, DL, VT);
10127   case ISD::FMINNUM:
10128   case ISD::FMAXNUM: {
10129     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
10130     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
10131     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
10132                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
10133                         APFloat::getLargest(Semantics);
10134     if (Opcode == ISD::FMAXNUM)
10135       NeutralAF.changeSign();
10136 
10137     return getConstantFP(NeutralAF, DL, VT);
10138   }
10139   }
10140 }
10141 
10142 #ifndef NDEBUG
10143 static void checkForCyclesHelper(const SDNode *N,
10144                                  SmallPtrSetImpl<const SDNode*> &Visited,
10145                                  SmallPtrSetImpl<const SDNode*> &Checked,
10146                                  const llvm::SelectionDAG *DAG) {
10147   // If this node has already been checked, don't check it again.
10148   if (Checked.count(N))
10149     return;
10150 
10151   // If a node has already been visited on this depth-first walk, reject it as
10152   // a cycle.
10153   if (!Visited.insert(N).second) {
10154     errs() << "Detected cycle in SelectionDAG\n";
10155     dbgs() << "Offending node:\n";
10156     N->dumprFull(DAG); dbgs() << "\n";
10157     abort();
10158   }
10159 
10160   for (const SDValue &Op : N->op_values())
10161     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
10162 
10163   Checked.insert(N);
10164   Visited.erase(N);
10165 }
10166 #endif
10167 
10168 void llvm::checkForCycles(const llvm::SDNode *N,
10169                           const llvm::SelectionDAG *DAG,
10170                           bool force) {
10171 #ifndef NDEBUG
10172   bool check = force;
10173 #ifdef EXPENSIVE_CHECKS
10174   check = true;
10175 #endif  // EXPENSIVE_CHECKS
10176   if (check) {
10177     assert(N && "Checking nonexistent SDNode");
10178     SmallPtrSet<const SDNode*, 32> visited;
10179     SmallPtrSet<const SDNode*, 32> checked;
10180     checkForCyclesHelper(N, visited, checked, DAG);
10181   }
10182 #endif  // !NDEBUG
10183 }
10184 
10185 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
10186   checkForCycles(DAG->getRoot().getNode(), DAG, force);
10187 }
10188