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