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