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