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