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