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