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