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