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