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