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