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