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