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