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