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/APSInt.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/ManagedStatic.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/Mutex.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetIntrinsicInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Target/TargetRegisterInfo.h"
49 #include "llvm/Target/TargetSubtargetInfo.h"
50 #include <algorithm>
51 #include <cmath>
52 #include <utility>
53 
54 using namespace llvm;
55 
56 /// makeVTList - Return an instance of the SDVTList struct initialized with the
57 /// specified members.
58 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
59   SDVTList Res = {VTs, NumVTs};
60   return Res;
61 }
62 
63 // Default null implementations of the callbacks.
64 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
65 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
66 
67 //===----------------------------------------------------------------------===//
68 //                              ConstantFPSDNode Class
69 //===----------------------------------------------------------------------===//
70 
71 /// isExactlyValue - We don't rely on operator== working on double values, as
72 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
73 /// As such, this method can be used to do an exact bit-for-bit comparison of
74 /// two floating point values.
75 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
76   return getValueAPF().bitwiseIsEqual(V);
77 }
78 
79 bool ConstantFPSDNode::isValueValidForType(EVT VT,
80                                            const APFloat& Val) {
81   assert(VT.isFloatingPoint() && "Can only convert between FP types");
82 
83   // convert modifies in place, so make a copy.
84   APFloat Val2 = APFloat(Val);
85   bool losesInfo;
86   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
87                       APFloat::rmNearestTiesToEven,
88                       &losesInfo);
89   return !losesInfo;
90 }
91 
92 //===----------------------------------------------------------------------===//
93 //                              ISD Namespace
94 //===----------------------------------------------------------------------===//
95 
96 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
97   auto *BV = dyn_cast<BuildVectorSDNode>(N);
98   if (!BV)
99     return false;
100 
101   APInt SplatUndef;
102   unsigned SplatBitSize;
103   bool HasUndefs;
104   EVT EltVT = N->getValueType(0).getVectorElementType();
105   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs) &&
106          EltVT.getSizeInBits() >= SplatBitSize;
107 }
108 
109 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
110 // specializations of the more general isConstantSplatVector()?
111 
112 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
113   // Look through a bit convert.
114   while (N->getOpcode() == ISD::BITCAST)
115     N = N->getOperand(0).getNode();
116 
117   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
118 
119   unsigned i = 0, e = N->getNumOperands();
120 
121   // Skip over all of the undef values.
122   while (i != e && N->getOperand(i).isUndef())
123     ++i;
124 
125   // Do not accept an all-undef vector.
126   if (i == e) return false;
127 
128   // Do not accept build_vectors that aren't all constants or which have non-~0
129   // elements. We have to be a bit careful here, as the type of the constant
130   // may not be the same as the type of the vector elements due to type
131   // legalization (the elements are promoted to a legal type for the target and
132   // a vector of a type may be legal when the base element type is not).
133   // We only want to check enough bits to cover the vector elements, because
134   // we care if the resultant vector is all ones, not whether the individual
135   // constants are.
136   SDValue NotZero = N->getOperand(i);
137   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
138   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
139     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
140       return false;
141   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
142     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
143       return false;
144   } else
145     return false;
146 
147   // Okay, we have at least one ~0 value, check to see if the rest match or are
148   // undefs. Even with the above element type twiddling, this should be OK, as
149   // the same type legalization should have applied to all the elements.
150   for (++i; i != e; ++i)
151     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
152       return false;
153   return true;
154 }
155 
156 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
157   // Look through a bit convert.
158   while (N->getOpcode() == ISD::BITCAST)
159     N = N->getOperand(0).getNode();
160 
161   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
162 
163   bool IsAllUndef = true;
164   for (const SDValue &Op : N->op_values()) {
165     if (Op.isUndef())
166       continue;
167     IsAllUndef = false;
168     // Do not accept build_vectors that aren't all constants or which have non-0
169     // elements. We have to be a bit careful here, as the type of the constant
170     // may not be the same as the type of the vector elements due to type
171     // legalization (the elements are promoted to a legal type for the target
172     // and a vector of a type may be legal when the base element type is not).
173     // We only want to check enough bits to cover the vector elements, because
174     // we care if the resultant vector is all zeros, not whether the individual
175     // constants are.
176     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
177     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
178       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
179         return false;
180     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
181       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
182         return false;
183     } else
184       return false;
185   }
186 
187   // Do not accept an all-undef vector.
188   if (IsAllUndef)
189     return false;
190   return true;
191 }
192 
193 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
194   if (N->getOpcode() != ISD::BUILD_VECTOR)
195     return false;
196 
197   for (const SDValue &Op : N->op_values()) {
198     if (Op.isUndef())
199       continue;
200     if (!isa<ConstantSDNode>(Op))
201       return false;
202   }
203   return true;
204 }
205 
206 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
207   if (N->getOpcode() != ISD::BUILD_VECTOR)
208     return false;
209 
210   for (const SDValue &Op : N->op_values()) {
211     if (Op.isUndef())
212       continue;
213     if (!isa<ConstantFPSDNode>(Op))
214       return false;
215   }
216   return true;
217 }
218 
219 bool ISD::allOperandsUndef(const SDNode *N) {
220   // Return false if the node has no operands.
221   // This is "logically inconsistent" with the definition of "all" but
222   // is probably the desired behavior.
223   if (N->getNumOperands() == 0)
224     return false;
225 
226   for (const SDValue &Op : N->op_values())
227     if (!Op.isUndef())
228       return false;
229 
230   return true;
231 }
232 
233 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
234   switch (ExtType) {
235   case ISD::EXTLOAD:
236     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
237   case ISD::SEXTLOAD:
238     return ISD::SIGN_EXTEND;
239   case ISD::ZEXTLOAD:
240     return ISD::ZERO_EXTEND;
241   default:
242     break;
243   }
244 
245   llvm_unreachable("Invalid LoadExtType");
246 }
247 
248 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
249   // To perform this operation, we just need to swap the L and G bits of the
250   // operation.
251   unsigned OldL = (Operation >> 2) & 1;
252   unsigned OldG = (Operation >> 1) & 1;
253   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
254                        (OldL << 1) |       // New G bit
255                        (OldG << 2));       // New L bit.
256 }
257 
258 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
259   unsigned Operation = Op;
260   if (isInteger)
261     Operation ^= 7;   // Flip L, G, E bits, but not U.
262   else
263     Operation ^= 15;  // Flip all of the condition bits.
264 
265   if (Operation > ISD::SETTRUE2)
266     Operation &= ~8;  // Don't let N and U bits get set.
267 
268   return ISD::CondCode(Operation);
269 }
270 
271 
272 /// For an integer comparison, return 1 if the comparison is a signed operation
273 /// and 2 if the result is an unsigned comparison. Return zero if the operation
274 /// does not depend on the sign of the input (setne and seteq).
275 static int isSignedOp(ISD::CondCode Opcode) {
276   switch (Opcode) {
277   default: llvm_unreachable("Illegal integer setcc operation!");
278   case ISD::SETEQ:
279   case ISD::SETNE: return 0;
280   case ISD::SETLT:
281   case ISD::SETLE:
282   case ISD::SETGT:
283   case ISD::SETGE: return 1;
284   case ISD::SETULT:
285   case ISD::SETULE:
286   case ISD::SETUGT:
287   case ISD::SETUGE: return 2;
288   }
289 }
290 
291 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
292                                        bool isInteger) {
293   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
294     // Cannot fold a signed integer setcc with an unsigned integer setcc.
295     return ISD::SETCC_INVALID;
296 
297   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
298 
299   // If the N and U bits get set then the resultant comparison DOES suddenly
300   // care about orderedness, and is true when ordered.
301   if (Op > ISD::SETTRUE2)
302     Op &= ~16;     // Clear the U bit if the N bit is set.
303 
304   // Canonicalize illegal integer setcc's.
305   if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
306     Op = ISD::SETNE;
307 
308   return ISD::CondCode(Op);
309 }
310 
311 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
312                                         bool isInteger) {
313   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
314     // Cannot fold a signed setcc with an unsigned setcc.
315     return ISD::SETCC_INVALID;
316 
317   // Combine all of the condition bits.
318   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
319 
320   // Canonicalize illegal integer setcc's.
321   if (isInteger) {
322     switch (Result) {
323     default: break;
324     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
325     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
326     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
327     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
328     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
329     }
330   }
331 
332   return Result;
333 }
334 
335 //===----------------------------------------------------------------------===//
336 //                           SDNode Profile Support
337 //===----------------------------------------------------------------------===//
338 
339 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
340 ///
341 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
342   ID.AddInteger(OpC);
343 }
344 
345 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
346 /// solely with their pointer.
347 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
348   ID.AddPointer(VTList.VTs);
349 }
350 
351 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
352 ///
353 static void AddNodeIDOperands(FoldingSetNodeID &ID,
354                               ArrayRef<SDValue> Ops) {
355   for (auto& Op : Ops) {
356     ID.AddPointer(Op.getNode());
357     ID.AddInteger(Op.getResNo());
358   }
359 }
360 
361 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
362 ///
363 static void AddNodeIDOperands(FoldingSetNodeID &ID,
364                               ArrayRef<SDUse> Ops) {
365   for (auto& Op : Ops) {
366     ID.AddPointer(Op.getNode());
367     ID.AddInteger(Op.getResNo());
368   }
369 }
370 
371 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
372                           SDVTList VTList, ArrayRef<SDValue> OpList) {
373   AddNodeIDOpcode(ID, OpC);
374   AddNodeIDValueTypes(ID, VTList);
375   AddNodeIDOperands(ID, OpList);
376 }
377 
378 /// If this is an SDNode with special info, add this info to the NodeID data.
379 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
380   switch (N->getOpcode()) {
381   case ISD::TargetExternalSymbol:
382   case ISD::ExternalSymbol:
383   case ISD::MCSymbol:
384     llvm_unreachable("Should only be used on nodes with operands");
385   default: break;  // Normal nodes don't need extra info.
386   case ISD::TargetConstant:
387   case ISD::Constant: {
388     const ConstantSDNode *C = cast<ConstantSDNode>(N);
389     ID.AddPointer(C->getConstantIntValue());
390     ID.AddBoolean(C->isOpaque());
391     break;
392   }
393   case ISD::TargetConstantFP:
394   case ISD::ConstantFP: {
395     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
396     break;
397   }
398   case ISD::TargetGlobalAddress:
399   case ISD::GlobalAddress:
400   case ISD::TargetGlobalTLSAddress:
401   case ISD::GlobalTLSAddress: {
402     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
403     ID.AddPointer(GA->getGlobal());
404     ID.AddInteger(GA->getOffset());
405     ID.AddInteger(GA->getTargetFlags());
406     break;
407   }
408   case ISD::BasicBlock:
409     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
410     break;
411   case ISD::Register:
412     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
413     break;
414   case ISD::RegisterMask:
415     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
416     break;
417   case ISD::SRCVALUE:
418     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
419     break;
420   case ISD::FrameIndex:
421   case ISD::TargetFrameIndex:
422     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
423     break;
424   case ISD::JumpTable:
425   case ISD::TargetJumpTable:
426     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
427     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
428     break;
429   case ISD::ConstantPool:
430   case ISD::TargetConstantPool: {
431     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
432     ID.AddInteger(CP->getAlignment());
433     ID.AddInteger(CP->getOffset());
434     if (CP->isMachineConstantPoolEntry())
435       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
436     else
437       ID.AddPointer(CP->getConstVal());
438     ID.AddInteger(CP->getTargetFlags());
439     break;
440   }
441   case ISD::TargetIndex: {
442     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
443     ID.AddInteger(TI->getIndex());
444     ID.AddInteger(TI->getOffset());
445     ID.AddInteger(TI->getTargetFlags());
446     break;
447   }
448   case ISD::LOAD: {
449     const LoadSDNode *LD = cast<LoadSDNode>(N);
450     ID.AddInteger(LD->getMemoryVT().getRawBits());
451     ID.AddInteger(LD->getRawSubclassData());
452     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
453     break;
454   }
455   case ISD::STORE: {
456     const StoreSDNode *ST = cast<StoreSDNode>(N);
457     ID.AddInteger(ST->getMemoryVT().getRawBits());
458     ID.AddInteger(ST->getRawSubclassData());
459     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
460     break;
461   }
462   case ISD::ATOMIC_CMP_SWAP:
463   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
464   case ISD::ATOMIC_SWAP:
465   case ISD::ATOMIC_LOAD_ADD:
466   case ISD::ATOMIC_LOAD_SUB:
467   case ISD::ATOMIC_LOAD_AND:
468   case ISD::ATOMIC_LOAD_OR:
469   case ISD::ATOMIC_LOAD_XOR:
470   case ISD::ATOMIC_LOAD_NAND:
471   case ISD::ATOMIC_LOAD_MIN:
472   case ISD::ATOMIC_LOAD_MAX:
473   case ISD::ATOMIC_LOAD_UMIN:
474   case ISD::ATOMIC_LOAD_UMAX:
475   case ISD::ATOMIC_LOAD:
476   case ISD::ATOMIC_STORE: {
477     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
478     ID.AddInteger(AT->getMemoryVT().getRawBits());
479     ID.AddInteger(AT->getRawSubclassData());
480     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
481     break;
482   }
483   case ISD::PREFETCH: {
484     const MemSDNode *PF = cast<MemSDNode>(N);
485     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
486     break;
487   }
488   case ISD::VECTOR_SHUFFLE: {
489     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
490     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
491          i != e; ++i)
492       ID.AddInteger(SVN->getMaskElt(i));
493     break;
494   }
495   case ISD::TargetBlockAddress:
496   case ISD::BlockAddress: {
497     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
498     ID.AddPointer(BA->getBlockAddress());
499     ID.AddInteger(BA->getOffset());
500     ID.AddInteger(BA->getTargetFlags());
501     break;
502   }
503   } // end switch (N->getOpcode())
504 
505   // Target specific memory nodes could also have address spaces to check.
506   if (N->isTargetMemoryOpcode())
507     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
508 }
509 
510 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
511 /// data.
512 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
513   AddNodeIDOpcode(ID, N->getOpcode());
514   // Add the return value info.
515   AddNodeIDValueTypes(ID, N->getVTList());
516   // Add the operand info.
517   AddNodeIDOperands(ID, N->ops());
518 
519   // Handle SDNode leafs with special info.
520   AddNodeIDCustom(ID, N);
521 }
522 
523 //===----------------------------------------------------------------------===//
524 //                              SelectionDAG Class
525 //===----------------------------------------------------------------------===//
526 
527 /// doNotCSE - Return true if CSE should not be performed for this node.
528 static bool doNotCSE(SDNode *N) {
529   if (N->getValueType(0) == MVT::Glue)
530     return true; // Never CSE anything that produces a flag.
531 
532   switch (N->getOpcode()) {
533   default: break;
534   case ISD::HANDLENODE:
535   case ISD::EH_LABEL:
536     return true;   // Never CSE these nodes.
537   }
538 
539   // Check that remaining values produced are not flags.
540   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
541     if (N->getValueType(i) == MVT::Glue)
542       return true; // Never CSE anything that produces a flag.
543 
544   return false;
545 }
546 
547 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
548 /// SelectionDAG.
549 void SelectionDAG::RemoveDeadNodes() {
550   // Create a dummy node (which is not added to allnodes), that adds a reference
551   // to the root node, preventing it from being deleted.
552   HandleSDNode Dummy(getRoot());
553 
554   SmallVector<SDNode*, 128> DeadNodes;
555 
556   // Add all obviously-dead nodes to the DeadNodes worklist.
557   for (SDNode &Node : allnodes())
558     if (Node.use_empty())
559       DeadNodes.push_back(&Node);
560 
561   RemoveDeadNodes(DeadNodes);
562 
563   // If the root changed (e.g. it was a dead load, update the root).
564   setRoot(Dummy.getValue());
565 }
566 
567 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
568 /// given list, and any nodes that become unreachable as a result.
569 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
570 
571   // Process the worklist, deleting the nodes and adding their uses to the
572   // worklist.
573   while (!DeadNodes.empty()) {
574     SDNode *N = DeadNodes.pop_back_val();
575 
576     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
577       DUL->NodeDeleted(N, nullptr);
578 
579     // Take the node out of the appropriate CSE map.
580     RemoveNodeFromCSEMaps(N);
581 
582     // Next, brutally remove the operand list.  This is safe to do, as there are
583     // no cycles in the graph.
584     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
585       SDUse &Use = *I++;
586       SDNode *Operand = Use.getNode();
587       Use.set(SDValue());
588 
589       // Now that we removed this operand, see if there are no uses of it left.
590       if (Operand->use_empty())
591         DeadNodes.push_back(Operand);
592     }
593 
594     DeallocateNode(N);
595   }
596 }
597 
598 void SelectionDAG::RemoveDeadNode(SDNode *N){
599   SmallVector<SDNode*, 16> DeadNodes(1, N);
600 
601   // Create a dummy node that adds a reference to the root node, preventing
602   // it from being deleted.  (This matters if the root is an operand of the
603   // dead node.)
604   HandleSDNode Dummy(getRoot());
605 
606   RemoveDeadNodes(DeadNodes);
607 }
608 
609 void SelectionDAG::DeleteNode(SDNode *N) {
610   // First take this out of the appropriate CSE map.
611   RemoveNodeFromCSEMaps(N);
612 
613   // Finally, remove uses due to operands of this node, remove from the
614   // AllNodes list, and delete the node.
615   DeleteNodeNotInCSEMaps(N);
616 }
617 
618 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
619   assert(N->getIterator() != AllNodes.begin() &&
620          "Cannot delete the entry node!");
621   assert(N->use_empty() && "Cannot delete a node that is not dead!");
622 
623   // Drop all of the operands and decrement used node's use counts.
624   N->DropOperands();
625 
626   DeallocateNode(N);
627 }
628 
629 void SDDbgInfo::erase(const SDNode *Node) {
630   DbgValMapType::iterator I = DbgValMap.find(Node);
631   if (I == DbgValMap.end())
632     return;
633   for (auto &Val: I->second)
634     Val->setIsInvalidated();
635   DbgValMap.erase(I);
636 }
637 
638 void SelectionDAG::DeallocateNode(SDNode *N) {
639   // If we have operands, deallocate them.
640   removeOperands(N);
641 
642   // Set the opcode to DELETED_NODE to help catch bugs when node
643   // memory is reallocated.
644   N->NodeType = ISD::DELETED_NODE;
645 
646   NodeAllocator.Deallocate(AllNodes.remove(N));
647 
648   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
649   // them and forget about that node.
650   DbgInfo->erase(N);
651 }
652 
653 #ifndef NDEBUG
654 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
655 static void VerifySDNode(SDNode *N) {
656   switch (N->getOpcode()) {
657   default:
658     break;
659   case ISD::BUILD_PAIR: {
660     EVT VT = N->getValueType(0);
661     assert(N->getNumValues() == 1 && "Too many results!");
662     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
663            "Wrong return type!");
664     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
665     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
666            "Mismatched operand types!");
667     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
668            "Wrong operand type!");
669     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
670            "Wrong return type size");
671     break;
672   }
673   case ISD::BUILD_VECTOR: {
674     assert(N->getNumValues() == 1 && "Too many results!");
675     assert(N->getValueType(0).isVector() && "Wrong return type!");
676     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
677            "Wrong number of operands!");
678     EVT EltVT = N->getValueType(0).getVectorElementType();
679     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
680       assert((I->getValueType() == EltVT ||
681              (EltVT.isInteger() && I->getValueType().isInteger() &&
682               EltVT.bitsLE(I->getValueType()))) &&
683             "Wrong operand type!");
684       assert(I->getValueType() == N->getOperand(0).getValueType() &&
685              "Operands must all have the same type");
686     }
687     break;
688   }
689   }
690 }
691 #endif // NDEBUG
692 
693 /// \brief Insert a newly allocated node into the DAG.
694 ///
695 /// Handles insertion into the all nodes list and CSE map, as well as
696 /// verification and other common operations when a new node is allocated.
697 void SelectionDAG::InsertNode(SDNode *N) {
698   AllNodes.push_back(N);
699 #ifndef NDEBUG
700   N->PersistentId = NextPersistentId++;
701   VerifySDNode(N);
702 #endif
703 }
704 
705 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
706 /// correspond to it.  This is useful when we're about to delete or repurpose
707 /// the node.  We don't want future request for structurally identical nodes
708 /// to return N anymore.
709 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
710   bool Erased = false;
711   switch (N->getOpcode()) {
712   case ISD::HANDLENODE: return false;  // noop.
713   case ISD::CONDCODE:
714     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
715            "Cond code doesn't exist!");
716     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
717     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
718     break;
719   case ISD::ExternalSymbol:
720     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
721     break;
722   case ISD::TargetExternalSymbol: {
723     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
724     Erased = TargetExternalSymbols.erase(
725                std::pair<std::string,unsigned char>(ESN->getSymbol(),
726                                                     ESN->getTargetFlags()));
727     break;
728   }
729   case ISD::MCSymbol: {
730     auto *MCSN = cast<MCSymbolSDNode>(N);
731     Erased = MCSymbols.erase(MCSN->getMCSymbol());
732     break;
733   }
734   case ISD::VALUETYPE: {
735     EVT VT = cast<VTSDNode>(N)->getVT();
736     if (VT.isExtended()) {
737       Erased = ExtendedValueTypeNodes.erase(VT);
738     } else {
739       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
740       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
741     }
742     break;
743   }
744   default:
745     // Remove it from the CSE Map.
746     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
747     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
748     Erased = CSEMap.RemoveNode(N);
749     break;
750   }
751 #ifndef NDEBUG
752   // Verify that the node was actually in one of the CSE maps, unless it has a
753   // flag result (which cannot be CSE'd) or is one of the special cases that are
754   // not subject to CSE.
755   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
756       !N->isMachineOpcode() && !doNotCSE(N)) {
757     N->dump(this);
758     dbgs() << "\n";
759     llvm_unreachable("Node is not in map!");
760   }
761 #endif
762   return Erased;
763 }
764 
765 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
766 /// maps and modified in place. Add it back to the CSE maps, unless an identical
767 /// node already exists, in which case transfer all its users to the existing
768 /// node. This transfer can potentially trigger recursive merging.
769 ///
770 void
771 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
772   // For node types that aren't CSE'd, just act as if no identical node
773   // already exists.
774   if (!doNotCSE(N)) {
775     SDNode *Existing = CSEMap.GetOrInsertNode(N);
776     if (Existing != N) {
777       // If there was already an existing matching node, use ReplaceAllUsesWith
778       // to replace the dead one with the existing one.  This can cause
779       // recursive merging of other unrelated nodes down the line.
780       ReplaceAllUsesWith(N, Existing);
781 
782       // N is now dead. Inform the listeners and delete it.
783       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
784         DUL->NodeDeleted(N, Existing);
785       DeleteNodeNotInCSEMaps(N);
786       return;
787     }
788   }
789 
790   // If the node doesn't already exist, we updated it.  Inform listeners.
791   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
792     DUL->NodeUpdated(N);
793 }
794 
795 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
796 /// were replaced with those specified.  If this node is never memoized,
797 /// return null, otherwise return a pointer to the slot it would take.  If a
798 /// node already exists with these operands, the slot will be non-null.
799 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
800                                            void *&InsertPos) {
801   if (doNotCSE(N))
802     return nullptr;
803 
804   SDValue Ops[] = { Op };
805   FoldingSetNodeID ID;
806   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
807   AddNodeIDCustom(ID, N);
808   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
809   if (Node)
810     if (const SDNodeFlags *Flags = N->getFlags())
811       Node->intersectFlagsWith(Flags);
812   return Node;
813 }
814 
815 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
816 /// were replaced with those specified.  If this node is never memoized,
817 /// return null, otherwise return a pointer to the slot it would take.  If a
818 /// node already exists with these operands, the slot will be non-null.
819 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
820                                            SDValue Op1, SDValue Op2,
821                                            void *&InsertPos) {
822   if (doNotCSE(N))
823     return nullptr;
824 
825   SDValue Ops[] = { Op1, Op2 };
826   FoldingSetNodeID ID;
827   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
828   AddNodeIDCustom(ID, N);
829   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
830   if (Node)
831     if (const SDNodeFlags *Flags = N->getFlags())
832       Node->intersectFlagsWith(Flags);
833   return Node;
834 }
835 
836 
837 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
838 /// were replaced with those specified.  If this node is never memoized,
839 /// return null, otherwise return a pointer to the slot it would take.  If a
840 /// node already exists with these operands, the slot will be non-null.
841 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
842                                            void *&InsertPos) {
843   if (doNotCSE(N))
844     return nullptr;
845 
846   FoldingSetNodeID ID;
847   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
848   AddNodeIDCustom(ID, N);
849   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
850   if (Node)
851     if (const SDNodeFlags *Flags = N->getFlags())
852       Node->intersectFlagsWith(Flags);
853   return Node;
854 }
855 
856 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
857   Type *Ty = VT == MVT::iPTR ?
858                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
859                    VT.getTypeForEVT(*getContext());
860 
861   return getDataLayout().getABITypeAlignment(Ty);
862 }
863 
864 // EntryNode could meaningfully have debug info if we can find it...
865 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
866     : TM(tm), TSI(nullptr), TLI(nullptr), OptLevel(OL),
867       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
868       Root(getEntryNode()), NewNodesMustHaveLegalTypes(false),
869       UpdateListeners(nullptr) {
870   InsertNode(&EntryNode);
871   DbgInfo = new SDDbgInfo();
872 }
873 
874 void SelectionDAG::init(MachineFunction &mf) {
875   MF = &mf;
876   TLI = getSubtarget().getTargetLowering();
877   TSI = getSubtarget().getSelectionDAGInfo();
878   Context = &mf.getFunction()->getContext();
879 }
880 
881 SelectionDAG::~SelectionDAG() {
882   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
883   allnodes_clear();
884   OperandRecycler.clear(OperandAllocator);
885   delete DbgInfo;
886 }
887 
888 void SelectionDAG::allnodes_clear() {
889   assert(&*AllNodes.begin() == &EntryNode);
890   AllNodes.remove(AllNodes.begin());
891   while (!AllNodes.empty())
892     DeallocateNode(&AllNodes.front());
893 #ifndef NDEBUG
894   NextPersistentId = 0;
895 #endif
896 }
897 
898 SDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, const SDLoc &DL,
899                                       SDVTList VTs, SDValue N1, SDValue N2,
900                                       const SDNodeFlags *Flags) {
901   SDValue Ops[] = {N1, N2};
902 
903   if (isBinOpWithFlags(Opcode)) {
904     // If no flags were passed in, use a default flags object.
905     SDNodeFlags F;
906     if (Flags == nullptr)
907       Flags = &F;
908 
909     auto *FN = newSDNode<BinaryWithFlagsSDNode>(Opcode, DL.getIROrder(),
910                                                 DL.getDebugLoc(), VTs, *Flags);
911     createOperands(FN, Ops);
912 
913     return FN;
914   }
915 
916   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
917   createOperands(N, Ops);
918   return N;
919 }
920 
921 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
922                                           void *&InsertPos) {
923   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
924   if (N) {
925     switch (N->getOpcode()) {
926     default: break;
927     case ISD::Constant:
928     case ISD::ConstantFP:
929       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
930                        "debug location.  Use another overload.");
931     }
932   }
933   return N;
934 }
935 
936 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
937                                           const SDLoc &DL, void *&InsertPos) {
938   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
939   if (N) {
940     switch (N->getOpcode()) {
941     case ISD::Constant:
942     case ISD::ConstantFP:
943       // Erase debug location from the node if the node is used at several
944       // different places. Do not propagate one location to all uses as it
945       // will cause a worse single stepping debugging experience.
946       if (N->getDebugLoc() != DL.getDebugLoc())
947         N->setDebugLoc(DebugLoc());
948       break;
949     default:
950       // When the node's point of use is located earlier in the instruction
951       // sequence than its prior point of use, update its debug info to the
952       // earlier location.
953       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
954         N->setDebugLoc(DL.getDebugLoc());
955       break;
956     }
957   }
958   return N;
959 }
960 
961 void SelectionDAG::clear() {
962   allnodes_clear();
963   OperandRecycler.clear(OperandAllocator);
964   OperandAllocator.Reset();
965   CSEMap.clear();
966 
967   ExtendedValueTypeNodes.clear();
968   ExternalSymbols.clear();
969   TargetExternalSymbols.clear();
970   MCSymbols.clear();
971   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
972             static_cast<CondCodeSDNode*>(nullptr));
973   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
974             static_cast<SDNode*>(nullptr));
975 
976   EntryNode.UseList = nullptr;
977   InsertNode(&EntryNode);
978   Root = getEntryNode();
979   DbgInfo->clear();
980 }
981 
982 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
983   return VT.bitsGT(Op.getValueType()) ?
984     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
985     getNode(ISD::TRUNCATE, DL, VT, Op);
986 }
987 
988 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
989   return VT.bitsGT(Op.getValueType()) ?
990     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
991     getNode(ISD::TRUNCATE, DL, VT, Op);
992 }
993 
994 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
995   return VT.bitsGT(Op.getValueType()) ?
996     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
997     getNode(ISD::TRUNCATE, DL, VT, Op);
998 }
999 
1000 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1001                                         EVT OpVT) {
1002   if (VT.bitsLE(Op.getValueType()))
1003     return getNode(ISD::TRUNCATE, SL, VT, Op);
1004 
1005   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1006   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1007 }
1008 
1009 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1010   assert(!VT.isVector() &&
1011          "getZeroExtendInReg should use the vector element type instead of "
1012          "the vector type!");
1013   if (Op.getValueType() == VT) return Op;
1014   unsigned BitWidth = Op.getScalarValueSizeInBits();
1015   APInt Imm = APInt::getLowBitsSet(BitWidth,
1016                                    VT.getSizeInBits());
1017   return getNode(ISD::AND, DL, Op.getValueType(), Op,
1018                  getConstant(Imm, DL, Op.getValueType()));
1019 }
1020 
1021 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL,
1022                                               EVT VT) {
1023   assert(VT.isVector() && "This DAG node is restricted to vector types.");
1024   assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1025          "The sizes of the input and result must match in order to perform the "
1026          "extend in-register.");
1027   assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1028          "The destination vector type must have fewer lanes than the input.");
1029   return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op);
1030 }
1031 
1032 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, const SDLoc &DL,
1033                                                EVT VT) {
1034   assert(VT.isVector() && "This DAG node is restricted to vector types.");
1035   assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1036          "The sizes of the input and result must match in order to perform the "
1037          "extend in-register.");
1038   assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1039          "The destination vector type must have fewer lanes than the input.");
1040   return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op);
1041 }
1042 
1043 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL,
1044                                                EVT VT) {
1045   assert(VT.isVector() && "This DAG node is restricted to vector types.");
1046   assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1047          "The sizes of the input and result must match in order to perform the "
1048          "extend in-register.");
1049   assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1050          "The destination vector type must have fewer lanes than the input.");
1051   return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op);
1052 }
1053 
1054 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1055 ///
1056 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1057   EVT EltVT = VT.getScalarType();
1058   SDValue NegOne =
1059     getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1060   return getNode(ISD::XOR, DL, VT, Val, NegOne);
1061 }
1062 
1063 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1064   EVT EltVT = VT.getScalarType();
1065   SDValue TrueValue;
1066   switch (TLI->getBooleanContents(VT)) {
1067     case TargetLowering::ZeroOrOneBooleanContent:
1068     case TargetLowering::UndefinedBooleanContent:
1069       TrueValue = getConstant(1, DL, VT);
1070       break;
1071     case TargetLowering::ZeroOrNegativeOneBooleanContent:
1072       TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL,
1073                               VT);
1074       break;
1075   }
1076   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1077 }
1078 
1079 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1080                                   bool isT, bool isO) {
1081   EVT EltVT = VT.getScalarType();
1082   assert((EltVT.getSizeInBits() >= 64 ||
1083          (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1084          "getConstant with a uint64_t value that doesn't fit in the type!");
1085   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1086 }
1087 
1088 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1089                                   bool isT, bool isO) {
1090   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1091 }
1092 
1093 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1094                                   EVT VT, bool isT, bool isO) {
1095   assert(VT.isInteger() && "Cannot create FP integer constant!");
1096 
1097   EVT EltVT = VT.getScalarType();
1098   const ConstantInt *Elt = &Val;
1099 
1100   // In some cases the vector type is legal but the element type is illegal and
1101   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1102   // inserted value (the type does not need to match the vector element type).
1103   // Any extra bits introduced will be truncated away.
1104   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1105       TargetLowering::TypePromoteInteger) {
1106    EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1107    APInt NewVal = Elt->getValue().zext(EltVT.getSizeInBits());
1108    Elt = ConstantInt::get(*getContext(), NewVal);
1109   }
1110   // In other cases the element type is illegal and needs to be expanded, for
1111   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1112   // the value into n parts and use a vector type with n-times the elements.
1113   // Then bitcast to the type requested.
1114   // Legalizing constants too early makes the DAGCombiner's job harder so we
1115   // only legalize if the DAG tells us we must produce legal types.
1116   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1117            TLI->getTypeAction(*getContext(), EltVT) ==
1118            TargetLowering::TypeExpandInteger) {
1119     const APInt &NewVal = Elt->getValue();
1120     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1121     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1122     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1123     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1124 
1125     // Check the temporary vector is the correct size. If this fails then
1126     // getTypeToTransformTo() probably returned a type whose size (in bits)
1127     // isn't a power-of-2 factor of the requested type size.
1128     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1129 
1130     SmallVector<SDValue, 2> EltParts;
1131     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1132       EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1133                                            .trunc(ViaEltSizeInBits), DL,
1134                                      ViaEltVT, isT, isO));
1135     }
1136 
1137     // EltParts is currently in little endian order. If we actually want
1138     // big-endian order then reverse it now.
1139     if (getDataLayout().isBigEndian())
1140       std::reverse(EltParts.begin(), EltParts.end());
1141 
1142     // The elements must be reversed when the element order is different
1143     // to the endianness of the elements (because the BITCAST is itself a
1144     // vector shuffle in this situation). However, we do not need any code to
1145     // perform this reversal because getConstant() is producing a vector
1146     // splat.
1147     // This situation occurs in MIPS MSA.
1148 
1149     SmallVector<SDValue, 8> Ops;
1150     for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
1151       Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1152 
1153     SDValue Result = getNode(ISD::BITCAST, DL, VT,
1154                              getNode(ISD::BUILD_VECTOR, DL, ViaVecVT, Ops));
1155     return Result;
1156   }
1157 
1158   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1159          "APInt size does not match type size!");
1160   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1161   FoldingSetNodeID ID;
1162   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1163   ID.AddPointer(Elt);
1164   ID.AddBoolean(isO);
1165   void *IP = nullptr;
1166   SDNode *N = nullptr;
1167   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1168     if (!VT.isVector())
1169       return SDValue(N, 0);
1170 
1171   if (!N) {
1172     N = newSDNode<ConstantSDNode>(isT, isO, Elt, DL.getDebugLoc(), EltVT);
1173     CSEMap.InsertNode(N, IP);
1174     InsertNode(N);
1175   }
1176 
1177   SDValue Result(N, 0);
1178   if (VT.isVector())
1179     Result = getSplatBuildVector(VT, DL, Result);
1180   return Result;
1181 }
1182 
1183 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1184                                         bool isTarget) {
1185   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1186 }
1187 
1188 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1189                                     bool isTarget) {
1190   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1191 }
1192 
1193 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1194                                     EVT VT, bool isTarget) {
1195   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1196 
1197   EVT EltVT = VT.getScalarType();
1198 
1199   // Do the map lookup using the actual bit pattern for the floating point
1200   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1201   // we don't have issues with SNANs.
1202   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1203   FoldingSetNodeID ID;
1204   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1205   ID.AddPointer(&V);
1206   void *IP = nullptr;
1207   SDNode *N = nullptr;
1208   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1209     if (!VT.isVector())
1210       return SDValue(N, 0);
1211 
1212   if (!N) {
1213     N = newSDNode<ConstantFPSDNode>(isTarget, &V, DL.getDebugLoc(), EltVT);
1214     CSEMap.InsertNode(N, IP);
1215     InsertNode(N);
1216   }
1217 
1218   SDValue Result(N, 0);
1219   if (VT.isVector())
1220     Result = getSplatBuildVector(VT, DL, Result);
1221   return Result;
1222 }
1223 
1224 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1225                                     bool isTarget) {
1226   EVT EltVT = VT.getScalarType();
1227   if (EltVT == MVT::f32)
1228     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1229   else if (EltVT == MVT::f64)
1230     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1231   else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1232            EltVT == MVT::f16) {
1233     bool Ignored;
1234     APFloat APF = APFloat(Val);
1235     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1236                 &Ignored);
1237     return getConstantFP(APF, DL, VT, isTarget);
1238   } else
1239     llvm_unreachable("Unsupported type in getConstantFP");
1240 }
1241 
1242 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1243                                        EVT VT, int64_t Offset, bool isTargetGA,
1244                                        unsigned char TargetFlags) {
1245   assert((TargetFlags == 0 || isTargetGA) &&
1246          "Cannot set target flags on target-independent globals");
1247 
1248   // Truncate (with sign-extension) the offset value to the pointer size.
1249   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1250   if (BitWidth < 64)
1251     Offset = SignExtend64(Offset, BitWidth);
1252 
1253   unsigned Opc;
1254   if (GV->isThreadLocal())
1255     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1256   else
1257     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1258 
1259   FoldingSetNodeID ID;
1260   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1261   ID.AddPointer(GV);
1262   ID.AddInteger(Offset);
1263   ID.AddInteger(TargetFlags);
1264   void *IP = nullptr;
1265   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1266     return SDValue(E, 0);
1267 
1268   auto *N = newSDNode<GlobalAddressSDNode>(
1269       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1270   CSEMap.InsertNode(N, IP);
1271     InsertNode(N);
1272   return SDValue(N, 0);
1273 }
1274 
1275 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1276   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1277   FoldingSetNodeID ID;
1278   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1279   ID.AddInteger(FI);
1280   void *IP = nullptr;
1281   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1282     return SDValue(E, 0);
1283 
1284   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1285   CSEMap.InsertNode(N, IP);
1286   InsertNode(N);
1287   return SDValue(N, 0);
1288 }
1289 
1290 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1291                                    unsigned char TargetFlags) {
1292   assert((TargetFlags == 0 || isTarget) &&
1293          "Cannot set target flags on target-independent jump tables");
1294   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1295   FoldingSetNodeID ID;
1296   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1297   ID.AddInteger(JTI);
1298   ID.AddInteger(TargetFlags);
1299   void *IP = nullptr;
1300   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1301     return SDValue(E, 0);
1302 
1303   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1304   CSEMap.InsertNode(N, IP);
1305   InsertNode(N);
1306   return SDValue(N, 0);
1307 }
1308 
1309 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1310                                       unsigned Alignment, int Offset,
1311                                       bool isTarget,
1312                                       unsigned char TargetFlags) {
1313   assert((TargetFlags == 0 || isTarget) &&
1314          "Cannot set target flags on target-independent globals");
1315   if (Alignment == 0)
1316     Alignment = MF->getFunction()->optForSize()
1317                     ? getDataLayout().getABITypeAlignment(C->getType())
1318                     : getDataLayout().getPrefTypeAlignment(C->getType());
1319   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1320   FoldingSetNodeID ID;
1321   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1322   ID.AddInteger(Alignment);
1323   ID.AddInteger(Offset);
1324   ID.AddPointer(C);
1325   ID.AddInteger(TargetFlags);
1326   void *IP = nullptr;
1327   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1328     return SDValue(E, 0);
1329 
1330   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1331                                           TargetFlags);
1332   CSEMap.InsertNode(N, IP);
1333   InsertNode(N);
1334   return SDValue(N, 0);
1335 }
1336 
1337 
1338 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1339                                       unsigned Alignment, int Offset,
1340                                       bool isTarget,
1341                                       unsigned char TargetFlags) {
1342   assert((TargetFlags == 0 || isTarget) &&
1343          "Cannot set target flags on target-independent globals");
1344   if (Alignment == 0)
1345     Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1346   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1347   FoldingSetNodeID ID;
1348   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1349   ID.AddInteger(Alignment);
1350   ID.AddInteger(Offset);
1351   C->addSelectionDAGCSEId(ID);
1352   ID.AddInteger(TargetFlags);
1353   void *IP = nullptr;
1354   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1355     return SDValue(E, 0);
1356 
1357   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1358                                           TargetFlags);
1359   CSEMap.InsertNode(N, IP);
1360   InsertNode(N);
1361   return SDValue(N, 0);
1362 }
1363 
1364 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1365                                      unsigned char TargetFlags) {
1366   FoldingSetNodeID ID;
1367   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1368   ID.AddInteger(Index);
1369   ID.AddInteger(Offset);
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<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1376   CSEMap.InsertNode(N, IP);
1377   InsertNode(N);
1378   return SDValue(N, 0);
1379 }
1380 
1381 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1382   FoldingSetNodeID ID;
1383   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1384   ID.AddPointer(MBB);
1385   void *IP = nullptr;
1386   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1387     return SDValue(E, 0);
1388 
1389   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1390   CSEMap.InsertNode(N, IP);
1391   InsertNode(N);
1392   return SDValue(N, 0);
1393 }
1394 
1395 SDValue SelectionDAG::getValueType(EVT VT) {
1396   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1397       ValueTypeNodes.size())
1398     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1399 
1400   SDNode *&N = VT.isExtended() ?
1401     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1402 
1403   if (N) return SDValue(N, 0);
1404   N = newSDNode<VTSDNode>(VT);
1405   InsertNode(N);
1406   return SDValue(N, 0);
1407 }
1408 
1409 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1410   SDNode *&N = ExternalSymbols[Sym];
1411   if (N) return SDValue(N, 0);
1412   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1413   InsertNode(N);
1414   return SDValue(N, 0);
1415 }
1416 
1417 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1418   SDNode *&N = MCSymbols[Sym];
1419   if (N)
1420     return SDValue(N, 0);
1421   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1422   InsertNode(N);
1423   return SDValue(N, 0);
1424 }
1425 
1426 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1427                                               unsigned char TargetFlags) {
1428   SDNode *&N =
1429     TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1430                                                                TargetFlags)];
1431   if (N) return SDValue(N, 0);
1432   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1433   InsertNode(N);
1434   return SDValue(N, 0);
1435 }
1436 
1437 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1438   if ((unsigned)Cond >= CondCodeNodes.size())
1439     CondCodeNodes.resize(Cond+1);
1440 
1441   if (!CondCodeNodes[Cond]) {
1442     auto *N = newSDNode<CondCodeSDNode>(Cond);
1443     CondCodeNodes[Cond] = N;
1444     InsertNode(N);
1445   }
1446 
1447   return SDValue(CondCodeNodes[Cond], 0);
1448 }
1449 
1450 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1451 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1452 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1453   std::swap(N1, N2);
1454   ShuffleVectorSDNode::commuteMask(M);
1455 }
1456 
1457 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1458                                        SDValue N2, ArrayRef<int> Mask) {
1459   assert(VT.getVectorNumElements() == Mask.size() &&
1460            "Must have the same number of vector elements as mask elements!");
1461   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1462          "Invalid VECTOR_SHUFFLE");
1463 
1464   // Canonicalize shuffle undef, undef -> undef
1465   if (N1.isUndef() && N2.isUndef())
1466     return getUNDEF(VT);
1467 
1468   // Validate that all indices in Mask are within the range of the elements
1469   // input to the shuffle.
1470   int NElts = Mask.size();
1471   assert(all_of(Mask, [&](int M) { return M < (NElts * 2); }) &&
1472          "Index out of range");
1473 
1474   // Copy the mask so we can do any needed cleanup.
1475   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1476 
1477   // Canonicalize shuffle v, v -> v, undef
1478   if (N1 == N2) {
1479     N2 = getUNDEF(VT);
1480     for (int i = 0; i != NElts; ++i)
1481       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1482   }
1483 
1484   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1485   if (N1.isUndef())
1486     commuteShuffle(N1, N2, MaskVec);
1487 
1488   // If shuffling a splat, try to blend the splat instead. We do this here so
1489   // that even when this arises during lowering we don't have to re-handle it.
1490   auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1491     BitVector UndefElements;
1492     SDValue Splat = BV->getSplatValue(&UndefElements);
1493     if (!Splat)
1494       return;
1495 
1496     for (int i = 0; i < NElts; ++i) {
1497       if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1498         continue;
1499 
1500       // If this input comes from undef, mark it as such.
1501       if (UndefElements[MaskVec[i] - Offset]) {
1502         MaskVec[i] = -1;
1503         continue;
1504       }
1505 
1506       // If we can blend a non-undef lane, use that instead.
1507       if (!UndefElements[i])
1508         MaskVec[i] = i + Offset;
1509     }
1510   };
1511   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1512     BlendSplat(N1BV, 0);
1513   if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1514     BlendSplat(N2BV, NElts);
1515 
1516   // Canonicalize all index into lhs, -> shuffle lhs, undef
1517   // Canonicalize all index into rhs, -> shuffle rhs, undef
1518   bool AllLHS = true, AllRHS = true;
1519   bool N2Undef = N2.isUndef();
1520   for (int i = 0; i != NElts; ++i) {
1521     if (MaskVec[i] >= NElts) {
1522       if (N2Undef)
1523         MaskVec[i] = -1;
1524       else
1525         AllLHS = false;
1526     } else if (MaskVec[i] >= 0) {
1527       AllRHS = false;
1528     }
1529   }
1530   if (AllLHS && AllRHS)
1531     return getUNDEF(VT);
1532   if (AllLHS && !N2Undef)
1533     N2 = getUNDEF(VT);
1534   if (AllRHS) {
1535     N1 = getUNDEF(VT);
1536     commuteShuffle(N1, N2, MaskVec);
1537   }
1538   // Reset our undef status after accounting for the mask.
1539   N2Undef = N2.isUndef();
1540   // Re-check whether both sides ended up undef.
1541   if (N1.isUndef() && N2Undef)
1542     return getUNDEF(VT);
1543 
1544   // If Identity shuffle return that node.
1545   bool Identity = true, AllSame = true;
1546   for (int i = 0; i != NElts; ++i) {
1547     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1548     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1549   }
1550   if (Identity && NElts)
1551     return N1;
1552 
1553   // Shuffling a constant splat doesn't change the result.
1554   if (N2Undef) {
1555     SDValue V = N1;
1556 
1557     // Look through any bitcasts. We check that these don't change the number
1558     // (and size) of elements and just changes their types.
1559     while (V.getOpcode() == ISD::BITCAST)
1560       V = V->getOperand(0);
1561 
1562     // A splat should always show up as a build vector node.
1563     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1564       BitVector UndefElements;
1565       SDValue Splat = BV->getSplatValue(&UndefElements);
1566       // If this is a splat of an undef, shuffling it is also undef.
1567       if (Splat && Splat.isUndef())
1568         return getUNDEF(VT);
1569 
1570       bool SameNumElts =
1571           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1572 
1573       // We only have a splat which can skip shuffles if there is a splatted
1574       // value and no undef lanes rearranged by the shuffle.
1575       if (Splat && UndefElements.none()) {
1576         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1577         // number of elements match or the value splatted is a zero constant.
1578         if (SameNumElts)
1579           return N1;
1580         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1581           if (C->isNullValue())
1582             return N1;
1583       }
1584 
1585       // If the shuffle itself creates a splat, build the vector directly.
1586       if (AllSame && SameNumElts) {
1587         EVT BuildVT = BV->getValueType(0);
1588         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1589         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1590 
1591         // We may have jumped through bitcasts, so the type of the
1592         // BUILD_VECTOR may not match the type of the shuffle.
1593         if (BuildVT != VT)
1594           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1595         return NewBV;
1596       }
1597     }
1598   }
1599 
1600   FoldingSetNodeID ID;
1601   SDValue Ops[2] = { N1, N2 };
1602   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1603   for (int i = 0; i != NElts; ++i)
1604     ID.AddInteger(MaskVec[i]);
1605 
1606   void* IP = nullptr;
1607   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1608     return SDValue(E, 0);
1609 
1610   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1611   // SDNode doesn't have access to it.  This memory will be "leaked" when
1612   // the node is deallocated, but recovered when the NodeAllocator is released.
1613   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1614   std::copy(MaskVec.begin(), MaskVec.end(), MaskAlloc);
1615 
1616   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1617                                            dl.getDebugLoc(), MaskAlloc);
1618   createOperands(N, Ops);
1619 
1620   CSEMap.InsertNode(N, IP);
1621   InsertNode(N);
1622   return SDValue(N, 0);
1623 }
1624 
1625 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1626   MVT VT = SV.getSimpleValueType(0);
1627   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1628   ShuffleVectorSDNode::commuteMask(MaskVec);
1629 
1630   SDValue Op0 = SV.getOperand(0);
1631   SDValue Op1 = SV.getOperand(1);
1632   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1633 }
1634 
1635 SDValue SelectionDAG::getConvertRndSat(EVT VT, const SDLoc &dl, SDValue Val,
1636                                        SDValue DTy, SDValue STy, SDValue Rnd,
1637                                        SDValue Sat, ISD::CvtCode Code) {
1638   // If the src and dest types are the same and the conversion is between
1639   // integer types of the same sign or two floats, no conversion is necessary.
1640   if (DTy == STy &&
1641       (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1642     return Val;
1643 
1644   FoldingSetNodeID ID;
1645   SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1646   AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), Ops);
1647   void* IP = nullptr;
1648   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1649     return SDValue(E, 0);
1650 
1651   auto *N =
1652       newSDNode<CvtRndSatSDNode>(VT, dl.getIROrder(), dl.getDebugLoc(), Code);
1653   createOperands(N, Ops);
1654 
1655   CSEMap.InsertNode(N, IP);
1656   InsertNode(N);
1657   return SDValue(N, 0);
1658 }
1659 
1660 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1661   FoldingSetNodeID ID;
1662   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1663   ID.AddInteger(RegNo);
1664   void *IP = nullptr;
1665   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1666     return SDValue(E, 0);
1667 
1668   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1669   CSEMap.InsertNode(N, IP);
1670   InsertNode(N);
1671   return SDValue(N, 0);
1672 }
1673 
1674 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1675   FoldingSetNodeID ID;
1676   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1677   ID.AddPointer(RegMask);
1678   void *IP = nullptr;
1679   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1680     return SDValue(E, 0);
1681 
1682   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1683   CSEMap.InsertNode(N, IP);
1684   InsertNode(N);
1685   return SDValue(N, 0);
1686 }
1687 
1688 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1689                                  MCSymbol *Label) {
1690   FoldingSetNodeID ID;
1691   SDValue Ops[] = { Root };
1692   AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops);
1693   ID.AddPointer(Label);
1694   void *IP = nullptr;
1695   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1696     return SDValue(E, 0);
1697 
1698   auto *N = newSDNode<EHLabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
1699   createOperands(N, Ops);
1700 
1701   CSEMap.InsertNode(N, IP);
1702   InsertNode(N);
1703   return SDValue(N, 0);
1704 }
1705 
1706 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1707                                       int64_t Offset,
1708                                       bool isTarget,
1709                                       unsigned char TargetFlags) {
1710   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1711 
1712   FoldingSetNodeID ID;
1713   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1714   ID.AddPointer(BA);
1715   ID.AddInteger(Offset);
1716   ID.AddInteger(TargetFlags);
1717   void *IP = nullptr;
1718   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1719     return SDValue(E, 0);
1720 
1721   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1722   CSEMap.InsertNode(N, IP);
1723   InsertNode(N);
1724   return SDValue(N, 0);
1725 }
1726 
1727 SDValue SelectionDAG::getSrcValue(const Value *V) {
1728   assert((!V || V->getType()->isPointerTy()) &&
1729          "SrcValue is not a pointer?");
1730 
1731   FoldingSetNodeID ID;
1732   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1733   ID.AddPointer(V);
1734 
1735   void *IP = nullptr;
1736   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1737     return SDValue(E, 0);
1738 
1739   auto *N = newSDNode<SrcValueSDNode>(V);
1740   CSEMap.InsertNode(N, IP);
1741   InsertNode(N);
1742   return SDValue(N, 0);
1743 }
1744 
1745 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1746   FoldingSetNodeID ID;
1747   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1748   ID.AddPointer(MD);
1749 
1750   void *IP = nullptr;
1751   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1752     return SDValue(E, 0);
1753 
1754   auto *N = newSDNode<MDNodeSDNode>(MD);
1755   CSEMap.InsertNode(N, IP);
1756   InsertNode(N);
1757   return SDValue(N, 0);
1758 }
1759 
1760 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1761   if (VT == V.getValueType())
1762     return V;
1763 
1764   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1765 }
1766 
1767 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1768                                        unsigned SrcAS, unsigned DestAS) {
1769   SDValue Ops[] = {Ptr};
1770   FoldingSetNodeID ID;
1771   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1772   ID.AddInteger(SrcAS);
1773   ID.AddInteger(DestAS);
1774 
1775   void *IP = nullptr;
1776   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1777     return SDValue(E, 0);
1778 
1779   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1780                                            VT, SrcAS, DestAS);
1781   createOperands(N, Ops);
1782 
1783   CSEMap.InsertNode(N, IP);
1784   InsertNode(N);
1785   return SDValue(N, 0);
1786 }
1787 
1788 /// getShiftAmountOperand - Return the specified value casted to
1789 /// the target's desired shift amount type.
1790 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1791   EVT OpTy = Op.getValueType();
1792   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1793   if (OpTy == ShTy || OpTy.isVector()) return Op;
1794 
1795   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1796 }
1797 
1798 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1799   SDLoc dl(Node);
1800   const TargetLowering &TLI = getTargetLoweringInfo();
1801   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1802   EVT VT = Node->getValueType(0);
1803   SDValue Tmp1 = Node->getOperand(0);
1804   SDValue Tmp2 = Node->getOperand(1);
1805   unsigned Align = Node->getConstantOperandVal(3);
1806 
1807   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1808                                Tmp2, MachinePointerInfo(V));
1809   SDValue VAList = VAListLoad;
1810 
1811   if (Align > TLI.getMinStackArgumentAlignment()) {
1812     assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1813 
1814     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1815                      getConstant(Align - 1, dl, VAList.getValueType()));
1816 
1817     VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1818                      getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1819   }
1820 
1821   // Increment the pointer, VAList, to the next vaarg
1822   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1823                  getConstant(getDataLayout().getTypeAllocSize(
1824                                                VT.getTypeForEVT(*getContext())),
1825                              dl, VAList.getValueType()));
1826   // Store the incremented VAList to the legalized pointer
1827   Tmp1 =
1828       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1829   // Load the actual argument out of the pointer VAList
1830   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1831 }
1832 
1833 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1834   SDLoc dl(Node);
1835   const TargetLowering &TLI = getTargetLoweringInfo();
1836   // This defaults to loading a pointer from the input and storing it to the
1837   // output, returning the chain.
1838   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1839   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1840   SDValue Tmp1 =
1841       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1842               Node->getOperand(2), MachinePointerInfo(VS));
1843   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1844                   MachinePointerInfo(VD));
1845 }
1846 
1847 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1848   MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1849   unsigned ByteSize = VT.getStoreSize();
1850   Type *Ty = VT.getTypeForEVT(*getContext());
1851   unsigned StackAlign =
1852       std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1853 
1854   int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1855   return getFrameIndex(FrameIdx, TLI->getPointerTy(getDataLayout()));
1856 }
1857 
1858 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1859   unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1860   Type *Ty1 = VT1.getTypeForEVT(*getContext());
1861   Type *Ty2 = VT2.getTypeForEVT(*getContext());
1862   const DataLayout &DL = getDataLayout();
1863   unsigned Align =
1864       std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1865 
1866   MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1867   int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1868   return getFrameIndex(FrameIdx, TLI->getPointerTy(getDataLayout()));
1869 }
1870 
1871 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1872                                 ISD::CondCode Cond, const SDLoc &dl) {
1873   // These setcc operations always fold.
1874   switch (Cond) {
1875   default: break;
1876   case ISD::SETFALSE:
1877   case ISD::SETFALSE2: return getConstant(0, dl, VT);
1878   case ISD::SETTRUE:
1879   case ISD::SETTRUE2: {
1880     TargetLowering::BooleanContent Cnt =
1881         TLI->getBooleanContents(N1->getValueType(0));
1882     return getConstant(
1883         Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1884         VT);
1885   }
1886 
1887   case ISD::SETOEQ:
1888   case ISD::SETOGT:
1889   case ISD::SETOGE:
1890   case ISD::SETOLT:
1891   case ISD::SETOLE:
1892   case ISD::SETONE:
1893   case ISD::SETO:
1894   case ISD::SETUO:
1895   case ISD::SETUEQ:
1896   case ISD::SETUNE:
1897     assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1898     break;
1899   }
1900 
1901   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
1902     const APInt &C2 = N2C->getAPIntValue();
1903     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
1904       const APInt &C1 = N1C->getAPIntValue();
1905 
1906       switch (Cond) {
1907       default: llvm_unreachable("Unknown integer setcc!");
1908       case ISD::SETEQ:  return getConstant(C1 == C2, dl, VT);
1909       case ISD::SETNE:  return getConstant(C1 != C2, dl, VT);
1910       case ISD::SETULT: return getConstant(C1.ult(C2), dl, VT);
1911       case ISD::SETUGT: return getConstant(C1.ugt(C2), dl, VT);
1912       case ISD::SETULE: return getConstant(C1.ule(C2), dl, VT);
1913       case ISD::SETUGE: return getConstant(C1.uge(C2), dl, VT);
1914       case ISD::SETLT:  return getConstant(C1.slt(C2), dl, VT);
1915       case ISD::SETGT:  return getConstant(C1.sgt(C2), dl, VT);
1916       case ISD::SETLE:  return getConstant(C1.sle(C2), dl, VT);
1917       case ISD::SETGE:  return getConstant(C1.sge(C2), dl, VT);
1918       }
1919     }
1920   }
1921   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) {
1922     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) {
1923       APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1924       switch (Cond) {
1925       default: break;
1926       case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
1927                           return getUNDEF(VT);
1928                         LLVM_FALLTHROUGH;
1929       case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, dl, VT);
1930       case ISD::SETNE:  if (R==APFloat::cmpUnordered)
1931                           return getUNDEF(VT);
1932                         LLVM_FALLTHROUGH;
1933       case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1934                                            R==APFloat::cmpLessThan, dl, VT);
1935       case ISD::SETLT:  if (R==APFloat::cmpUnordered)
1936                           return getUNDEF(VT);
1937                         LLVM_FALLTHROUGH;
1938       case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, dl, VT);
1939       case ISD::SETGT:  if (R==APFloat::cmpUnordered)
1940                           return getUNDEF(VT);
1941                         LLVM_FALLTHROUGH;
1942       case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, dl, VT);
1943       case ISD::SETLE:  if (R==APFloat::cmpUnordered)
1944                           return getUNDEF(VT);
1945                         LLVM_FALLTHROUGH;
1946       case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1947                                            R==APFloat::cmpEqual, dl, VT);
1948       case ISD::SETGE:  if (R==APFloat::cmpUnordered)
1949                           return getUNDEF(VT);
1950                         LLVM_FALLTHROUGH;
1951       case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1952                                            R==APFloat::cmpEqual, dl, VT);
1953       case ISD::SETO:   return getConstant(R!=APFloat::cmpUnordered, dl, VT);
1954       case ISD::SETUO:  return getConstant(R==APFloat::cmpUnordered, dl, VT);
1955       case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1956                                            R==APFloat::cmpEqual, dl, VT);
1957       case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, dl, VT);
1958       case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1959                                            R==APFloat::cmpLessThan, dl, VT);
1960       case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1961                                            R==APFloat::cmpUnordered, dl, VT);
1962       case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, dl, VT);
1963       case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, dl, VT);
1964       }
1965     } else {
1966       // Ensure that the constant occurs on the RHS.
1967       ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
1968       MVT CompVT = N1.getValueType().getSimpleVT();
1969       if (!TLI->isCondCodeLegal(SwappedCond, CompVT))
1970         return SDValue();
1971 
1972       return getSetCC(dl, VT, N2, N1, SwappedCond);
1973     }
1974   }
1975 
1976   // Could not fold it.
1977   return SDValue();
1978 }
1979 
1980 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
1981 /// use this predicate to simplify operations downstream.
1982 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1983   unsigned BitWidth = Op.getScalarValueSizeInBits();
1984   return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1985 }
1986 
1987 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1988 /// this predicate to simplify operations downstream.  Mask is known to be zero
1989 /// for bits that V cannot have.
1990 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1991                                      unsigned Depth) const {
1992   APInt KnownZero, KnownOne;
1993   computeKnownBits(Op, KnownZero, KnownOne, Depth);
1994   return (KnownZero & Mask) == Mask;
1995 }
1996 
1997 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
1998 /// is less than the element bit-width of the shift node, return it.
1999 static const APInt *getValidShiftAmountConstant(SDValue V) {
2000   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
2001     // Shifting more than the bitwidth is not valid.
2002     const APInt &ShAmt = SA->getAPIntValue();
2003     if (ShAmt.ult(V.getScalarValueSizeInBits()))
2004       return &ShAmt;
2005   }
2006   return nullptr;
2007 }
2008 
2009 /// Determine which bits of Op are known to be either zero or one and return
2010 /// them in the KnownZero/KnownOne bitsets.
2011 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero,
2012                                     APInt &KnownOne, unsigned Depth) const {
2013   unsigned BitWidth = Op.getScalarValueSizeInBits();
2014 
2015   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
2016   if (Depth == 6)
2017     return;  // Limit search depth.
2018 
2019   APInt KnownZero2, KnownOne2;
2020 
2021   switch (Op.getOpcode()) {
2022   case ISD::Constant:
2023     // We know all of the bits for a constant!
2024     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
2025     KnownZero = ~KnownOne;
2026     break;
2027   case ISD::BUILD_VECTOR:
2028     // Collect the known bits that are shared by every vector element.
2029     KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
2030     for (SDValue SrcOp : Op->ops()) {
2031       computeKnownBits(SrcOp, KnownZero2, KnownOne2, Depth + 1);
2032 
2033       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2034       if (SrcOp.getValueSizeInBits() != BitWidth) {
2035         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2036                "Expected BUILD_VECTOR implicit truncation");
2037         KnownOne2 = KnownOne2.trunc(BitWidth);
2038         KnownZero2 = KnownZero2.trunc(BitWidth);
2039       }
2040 
2041       // Known bits are the values that are shared by every element.
2042       // TODO: support per-element known bits.
2043       KnownOne &= KnownOne2;
2044       KnownZero &= KnownZero2;
2045     }
2046     break;
2047   case ISD::AND:
2048     // If either the LHS or the RHS are Zero, the result is zero.
2049     computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2050     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2051 
2052     // Output known-1 bits are only known if set in both the LHS & RHS.
2053     KnownOne &= KnownOne2;
2054     // Output known-0 are known to be clear if zero in either the LHS | RHS.
2055     KnownZero |= KnownZero2;
2056     break;
2057   case ISD::OR:
2058     computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2059     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2060 
2061     // Output known-0 bits are only known if clear in both the LHS & RHS.
2062     KnownZero &= KnownZero2;
2063     // Output known-1 are known to be set if set in either the LHS | RHS.
2064     KnownOne |= KnownOne2;
2065     break;
2066   case ISD::XOR: {
2067     computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2068     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2069 
2070     // Output known-0 bits are known if clear or set in both the LHS & RHS.
2071     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
2072     // Output known-1 are known to be set if set in only one of the LHS, RHS.
2073     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
2074     KnownZero = KnownZeroOut;
2075     break;
2076   }
2077   case ISD::MUL: {
2078     computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2079     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2080 
2081     // If low bits are zero in either operand, output low known-0 bits.
2082     // Also compute a conserative estimate for high known-0 bits.
2083     // More trickiness is possible, but this is sufficient for the
2084     // interesting case of alignment computation.
2085     KnownOne.clearAllBits();
2086     unsigned TrailZ = KnownZero.countTrailingOnes() +
2087                       KnownZero2.countTrailingOnes();
2088     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
2089                                KnownZero2.countLeadingOnes(),
2090                                BitWidth) - BitWidth;
2091 
2092     TrailZ = std::min(TrailZ, BitWidth);
2093     LeadZ = std::min(LeadZ, BitWidth);
2094     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
2095                 APInt::getHighBitsSet(BitWidth, LeadZ);
2096     break;
2097   }
2098   case ISD::UDIV: {
2099     // For the purposes of computing leading zeros we can conservatively
2100     // treat a udiv as a logical right shift by the power of 2 known to
2101     // be less than the denominator.
2102     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2103     unsigned LeadZ = KnownZero2.countLeadingOnes();
2104 
2105     KnownOne2.clearAllBits();
2106     KnownZero2.clearAllBits();
2107     computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2108     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
2109     if (RHSUnknownLeadingOnes != BitWidth)
2110       LeadZ = std::min(BitWidth,
2111                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
2112 
2113     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
2114     break;
2115   }
2116   case ISD::SELECT:
2117     computeKnownBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1);
2118     computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2119 
2120     // Only known if known in both the LHS and RHS.
2121     KnownOne &= KnownOne2;
2122     KnownZero &= KnownZero2;
2123     break;
2124   case ISD::SELECT_CC:
2125     computeKnownBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1);
2126     computeKnownBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1);
2127 
2128     // Only known if known in both the LHS and RHS.
2129     KnownOne &= KnownOne2;
2130     KnownZero &= KnownZero2;
2131     break;
2132   case ISD::SADDO:
2133   case ISD::UADDO:
2134   case ISD::SSUBO:
2135   case ISD::USUBO:
2136   case ISD::SMULO:
2137   case ISD::UMULO:
2138     if (Op.getResNo() != 1)
2139       break;
2140     // The boolean result conforms to getBooleanContents.
2141     // If we know the result of a setcc has the top bits zero, use this info.
2142     // We know that we have an integer-based boolean since these operations
2143     // are only available for integer.
2144     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2145             TargetLowering::ZeroOrOneBooleanContent &&
2146         BitWidth > 1)
2147       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
2148     break;
2149   case ISD::SETCC:
2150     // If we know the result of a setcc has the top bits zero, use this info.
2151     if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2152             TargetLowering::ZeroOrOneBooleanContent &&
2153         BitWidth > 1)
2154       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
2155     break;
2156   case ISD::SHL:
2157     if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2158       computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth + 1);
2159       KnownZero = KnownZero << *ShAmt;
2160       KnownOne = KnownOne << *ShAmt;
2161       // Low bits are known zero.
2162       KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt->getZExtValue());
2163     }
2164     break;
2165   case ISD::SRL:
2166     if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2167       computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth + 1);
2168       KnownZero = KnownZero.lshr(*ShAmt);
2169       KnownOne  = KnownOne.lshr(*ShAmt);
2170       // High bits are known zero.
2171       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt->getZExtValue());
2172       KnownZero |= HighBits;
2173     }
2174     break;
2175   case ISD::SRA:
2176     if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2177       computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth + 1);
2178       KnownZero = KnownZero.lshr(*ShAmt);
2179       KnownOne  = KnownOne.lshr(*ShAmt);
2180       // If we know the value of the sign bit, then we know it is copied across
2181       // the high bits by the shift amount.
2182       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt->getZExtValue());
2183       APInt SignBit = APInt::getSignBit(BitWidth);
2184       SignBit = SignBit.lshr(*ShAmt);  // Adjust to where it is now in the mask.
2185       if (KnownZero.intersects(SignBit)) {
2186         KnownZero |= HighBits;  // New bits are known zero.
2187       } else if (KnownOne.intersects(SignBit)) {
2188         KnownOne  |= HighBits;  // New bits are known one.
2189       }
2190     }
2191     break;
2192   case ISD::SIGN_EXTEND_INREG: {
2193     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2194     unsigned EBits = EVT.getScalarSizeInBits();
2195 
2196     // Sign extension.  Compute the demanded bits in the result that are not
2197     // present in the input.
2198     APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2199 
2200     APInt InSignBit = APInt::getSignBit(EBits);
2201     APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2202 
2203     // If the sign extended bits are demanded, we know that the sign
2204     // bit is demanded.
2205     InSignBit = InSignBit.zext(BitWidth);
2206     if (NewBits.getBoolValue())
2207       InputDemandedBits |= InSignBit;
2208 
2209     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2210     KnownOne &= InputDemandedBits;
2211     KnownZero &= InputDemandedBits;
2212 
2213     // If the sign bit of the input is known set or clear, then we know the
2214     // top bits of the result.
2215     if (KnownZero.intersects(InSignBit)) {         // Input sign bit known clear
2216       KnownZero |= NewBits;
2217       KnownOne  &= ~NewBits;
2218     } else if (KnownOne.intersects(InSignBit)) {   // Input sign bit known set
2219       KnownOne  |= NewBits;
2220       KnownZero &= ~NewBits;
2221     } else {                              // Input sign bit unknown
2222       KnownZero &= ~NewBits;
2223       KnownOne  &= ~NewBits;
2224     }
2225     break;
2226   }
2227   case ISD::CTTZ:
2228   case ISD::CTTZ_ZERO_UNDEF:
2229   case ISD::CTLZ:
2230   case ISD::CTLZ_ZERO_UNDEF:
2231   case ISD::CTPOP: {
2232     unsigned LowBits = Log2_32(BitWidth)+1;
2233     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
2234     KnownOne.clearAllBits();
2235     break;
2236   }
2237   case ISD::LOAD: {
2238     LoadSDNode *LD = cast<LoadSDNode>(Op);
2239     // If this is a ZEXTLoad and we are looking at the loaded value.
2240     if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2241       EVT VT = LD->getMemoryVT();
2242       unsigned MemBits = VT.getScalarSizeInBits();
2243       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
2244     } else if (const MDNode *Ranges = LD->getRanges()) {
2245       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2246         computeKnownBitsFromRangeMetadata(*Ranges, KnownZero, KnownOne);
2247     }
2248     break;
2249   }
2250   case ISD::ZERO_EXTEND: {
2251     EVT InVT = Op.getOperand(0).getValueType();
2252     unsigned InBits = InVT.getScalarSizeInBits();
2253     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
2254     KnownZero = KnownZero.trunc(InBits);
2255     KnownOne = KnownOne.trunc(InBits);
2256     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2257     KnownZero = KnownZero.zext(BitWidth);
2258     KnownOne = KnownOne.zext(BitWidth);
2259     KnownZero |= NewBits;
2260     break;
2261   }
2262   case ISD::SIGN_EXTEND: {
2263     EVT InVT = Op.getOperand(0).getValueType();
2264     unsigned InBits = InVT.getScalarSizeInBits();
2265     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
2266 
2267     KnownZero = KnownZero.trunc(InBits);
2268     KnownOne = KnownOne.trunc(InBits);
2269     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2270 
2271     // Note if the sign bit is known to be zero or one.
2272     bool SignBitKnownZero = KnownZero.isNegative();
2273     bool SignBitKnownOne  = KnownOne.isNegative();
2274 
2275     KnownZero = KnownZero.zext(BitWidth);
2276     KnownOne = KnownOne.zext(BitWidth);
2277 
2278     // If the sign bit is known zero or one, the top bits match.
2279     if (SignBitKnownZero)
2280       KnownZero |= NewBits;
2281     else if (SignBitKnownOne)
2282       KnownOne  |= NewBits;
2283     break;
2284   }
2285   case ISD::ANY_EXTEND: {
2286     EVT InVT = Op.getOperand(0).getValueType();
2287     unsigned InBits = InVT.getScalarSizeInBits();
2288     KnownZero = KnownZero.trunc(InBits);
2289     KnownOne = KnownOne.trunc(InBits);
2290     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2291     KnownZero = KnownZero.zext(BitWidth);
2292     KnownOne = KnownOne.zext(BitWidth);
2293     break;
2294   }
2295   case ISD::TRUNCATE: {
2296     EVT InVT = Op.getOperand(0).getValueType();
2297     unsigned InBits = InVT.getScalarSizeInBits();
2298     KnownZero = KnownZero.zext(InBits);
2299     KnownOne = KnownOne.zext(InBits);
2300     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2301     KnownZero = KnownZero.trunc(BitWidth);
2302     KnownOne = KnownOne.trunc(BitWidth);
2303     break;
2304   }
2305   case ISD::AssertZext: {
2306     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2307     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2308     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2309     KnownZero |= (~InMask);
2310     KnownOne  &= (~KnownZero);
2311     break;
2312   }
2313   case ISD::FGETSIGN:
2314     // All bits are zero except the low bit.
2315     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
2316     break;
2317 
2318   case ISD::SUB: {
2319     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
2320       // We know that the top bits of C-X are clear if X contains less bits
2321       // than C (i.e. no wrap-around can happen).  For example, 20-X is
2322       // positive if we can prove that X is >= 0 and < 16.
2323       if (CLHS->getAPIntValue().isNonNegative()) {
2324         unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2325         // NLZ can't be BitWidth with no sign bit
2326         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2327         computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2328 
2329         // If all of the MaskV bits are known to be zero, then we know the
2330         // output top bits are zero, because we now know that the output is
2331         // from [0-C].
2332         if ((KnownZero2 & MaskV) == MaskV) {
2333           unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2334           // Top bits known zero.
2335           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
2336         }
2337       }
2338     }
2339     LLVM_FALLTHROUGH;
2340   }
2341   case ISD::ADD:
2342   case ISD::ADDE: {
2343     // Output known-0 bits are known if clear or set in both the low clear bits
2344     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
2345     // low 3 bits clear.
2346     // Output known-0 bits are also known if the top bits of each input are
2347     // known to be clear. For example, if one input has the top 10 bits clear
2348     // and the other has the top 8 bits clear, we know the top 7 bits of the
2349     // output must be clear.
2350     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2351     unsigned KnownZeroHigh = KnownZero2.countLeadingOnes();
2352     unsigned KnownZeroLow = KnownZero2.countTrailingOnes();
2353 
2354     computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2355     KnownZeroHigh = std::min(KnownZeroHigh,
2356                              KnownZero2.countLeadingOnes());
2357     KnownZeroLow = std::min(KnownZeroLow,
2358                             KnownZero2.countTrailingOnes());
2359 
2360     if (Op.getOpcode() == ISD::ADD) {
2361       KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroLow);
2362       if (KnownZeroHigh > 1)
2363         KnownZero |= APInt::getHighBitsSet(BitWidth, KnownZeroHigh - 1);
2364       break;
2365     }
2366 
2367     // With ADDE, a carry bit may be added in, so we can only use this
2368     // information if we know (at least) that the low two bits are clear.  We
2369     // then return to the caller that the low bit is unknown but that other bits
2370     // are known zero.
2371     if (KnownZeroLow >= 2) // ADDE
2372       KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroLow);
2373     break;
2374   }
2375   case ISD::SREM:
2376     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2377       const APInt &RA = Rem->getAPIntValue().abs();
2378       if (RA.isPowerOf2()) {
2379         APInt LowBits = RA - 1;
2380         computeKnownBits(Op.getOperand(0), KnownZero2,KnownOne2,Depth+1);
2381 
2382         // The low bits of the first operand are unchanged by the srem.
2383         KnownZero = KnownZero2 & LowBits;
2384         KnownOne = KnownOne2 & LowBits;
2385 
2386         // If the first operand is non-negative or has all low bits zero, then
2387         // the upper bits are all zero.
2388         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
2389           KnownZero |= ~LowBits;
2390 
2391         // If the first operand is negative and not all low bits are zero, then
2392         // the upper bits are all one.
2393         if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
2394           KnownOne |= ~LowBits;
2395         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2396       }
2397     }
2398     break;
2399   case ISD::UREM: {
2400     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2401       const APInt &RA = Rem->getAPIntValue();
2402       if (RA.isPowerOf2()) {
2403         APInt LowBits = (RA - 1);
2404         computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth + 1);
2405 
2406         // The upper bits are all zero, the lower ones are unchanged.
2407         KnownZero = KnownZero2 | ~LowBits;
2408         KnownOne = KnownOne2 & LowBits;
2409         break;
2410       }
2411     }
2412 
2413     // Since the result is less than or equal to either operand, any leading
2414     // zero bits in either operand must also exist in the result.
2415     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2416     computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2417 
2418     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2419                                 KnownZero2.countLeadingOnes());
2420     KnownOne.clearAllBits();
2421     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
2422     break;
2423   }
2424   case ISD::EXTRACT_ELEMENT: {
2425     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2426     const unsigned Index = Op.getConstantOperandVal(1);
2427     const unsigned BitWidth = Op.getValueSizeInBits();
2428 
2429     // Remove low part of known bits mask
2430     KnownZero = KnownZero.getHiBits(KnownZero.getBitWidth() - Index * BitWidth);
2431     KnownOne = KnownOne.getHiBits(KnownOne.getBitWidth() - Index * BitWidth);
2432 
2433     // Remove high part of known bit mask
2434     KnownZero = KnownZero.trunc(BitWidth);
2435     KnownOne = KnownOne.trunc(BitWidth);
2436     break;
2437   }
2438   case ISD::EXTRACT_VECTOR_ELT: {
2439     // At the moment we keep this simple and skip tracking the specific
2440     // element. This way we get the lowest common denominator for all elements
2441     // of the vector.
2442     // TODO: get information for given vector element
2443     const unsigned BitWidth = Op.getValueSizeInBits();
2444     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
2445     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2446     // anything about the extended bits.
2447     if (BitWidth > EltBitWidth) {
2448       KnownZero = KnownZero.trunc(EltBitWidth);
2449       KnownOne = KnownOne.trunc(EltBitWidth);
2450     }
2451     computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2452     if (BitWidth > EltBitWidth) {
2453       KnownZero = KnownZero.zext(BitWidth);
2454       KnownOne = KnownOne.zext(BitWidth);
2455     }
2456     break;
2457   }
2458   case ISD::BSWAP: {
2459     computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2460     KnownZero = KnownZero2.byteSwap();
2461     KnownOne = KnownOne2.byteSwap();
2462     break;
2463   }
2464   case ISD::SMIN:
2465   case ISD::SMAX:
2466   case ISD::UMIN:
2467   case ISD::UMAX: {
2468     APInt Op0Zero, Op0One;
2469     APInt Op1Zero, Op1One;
2470     computeKnownBits(Op.getOperand(0), Op0Zero, Op0One, Depth);
2471     computeKnownBits(Op.getOperand(1), Op1Zero, Op1One, Depth);
2472 
2473     KnownZero = Op0Zero & Op1Zero;
2474     KnownOne = Op0One & Op1One;
2475     break;
2476   }
2477   case ISD::FrameIndex:
2478   case ISD::TargetFrameIndex:
2479     if (unsigned Align = InferPtrAlignment(Op)) {
2480       // The low bits are known zero if the pointer is aligned.
2481       KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align));
2482       break;
2483     }
2484     break;
2485 
2486   default:
2487     if (Op.getOpcode() < ISD::BUILTIN_OP_END)
2488       break;
2489     LLVM_FALLTHROUGH;
2490   case ISD::INTRINSIC_WO_CHAIN:
2491   case ISD::INTRINSIC_W_CHAIN:
2492   case ISD::INTRINSIC_VOID:
2493     // Allow the target to implement this method for its nodes.
2494     TLI->computeKnownBitsForTargetNode(Op, KnownZero, KnownOne, *this, Depth);
2495     break;
2496   }
2497 
2498   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
2499 }
2500 
2501 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
2502   // A left-shift of a constant one will have exactly one bit set because
2503   // shifting the bit off the end is undefined.
2504   if (Val.getOpcode() == ISD::SHL) {
2505     auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0));
2506     if (C && C->getAPIntValue() == 1)
2507       return true;
2508   }
2509 
2510   // Similarly, a logical right-shift of a constant sign-bit will have exactly
2511   // one bit set.
2512   if (Val.getOpcode() == ISD::SRL) {
2513     auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0));
2514     if (C && C->getAPIntValue().isSignBit())
2515       return true;
2516   }
2517 
2518   // More could be done here, though the above checks are enough
2519   // to handle some common cases.
2520 
2521   // Fall back to computeKnownBits to catch other known cases.
2522   EVT OpVT = Val.getValueType();
2523   unsigned BitWidth = OpVT.getScalarSizeInBits();
2524   APInt KnownZero, KnownOne;
2525   computeKnownBits(Val, KnownZero, KnownOne);
2526   return (KnownZero.countPopulation() == BitWidth - 1) &&
2527          (KnownOne.countPopulation() == 1);
2528 }
2529 
2530 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
2531   EVT VT = Op.getValueType();
2532   assert(VT.isInteger() && "Invalid VT!");
2533   unsigned VTBits = VT.getScalarSizeInBits();
2534   unsigned Tmp, Tmp2;
2535   unsigned FirstAnswer = 1;
2536 
2537   if (Depth == 6)
2538     return 1;  // Limit search depth.
2539 
2540   switch (Op.getOpcode()) {
2541   default: break;
2542   case ISD::AssertSext:
2543     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2544     return VTBits-Tmp+1;
2545   case ISD::AssertZext:
2546     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2547     return VTBits-Tmp;
2548 
2549   case ISD::Constant: {
2550     const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2551     return Val.getNumSignBits();
2552   }
2553 
2554   case ISD::SIGN_EXTEND:
2555     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
2556     return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2557 
2558   case ISD::SIGN_EXTEND_INREG:
2559     // Max of the input and what this extends.
2560     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
2561     Tmp = VTBits-Tmp+1;
2562 
2563     Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2564     return std::max(Tmp, Tmp2);
2565 
2566   case ISD::SRA:
2567     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2568     // SRA X, C   -> adds C sign bits.
2569     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2570       APInt ShiftVal = C->getAPIntValue();
2571       ShiftVal += Tmp;
2572       Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
2573     }
2574     return Tmp;
2575   case ISD::SHL:
2576     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2577       // shl destroys sign bits.
2578       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2579       if (C->getAPIntValue().uge(VTBits) ||      // Bad shift.
2580           C->getAPIntValue().uge(Tmp)) break;    // Shifted all sign bits out.
2581       return Tmp - C->getZExtValue();
2582     }
2583     break;
2584   case ISD::AND:
2585   case ISD::OR:
2586   case ISD::XOR:    // NOT is handled here.
2587     // Logical binary ops preserve the number of sign bits at the worst.
2588     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2589     if (Tmp != 1) {
2590       Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2591       FirstAnswer = std::min(Tmp, Tmp2);
2592       // We computed what we know about the sign bits as our first
2593       // answer. Now proceed to the generic code that uses
2594       // computeKnownBits, and pick whichever answer is better.
2595     }
2596     break;
2597 
2598   case ISD::SELECT:
2599     Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2600     if (Tmp == 1) return 1;  // Early out.
2601     Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2602     return std::min(Tmp, Tmp2);
2603   case ISD::SELECT_CC:
2604     Tmp = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2605     if (Tmp == 1) return 1;  // Early out.
2606     Tmp2 = ComputeNumSignBits(Op.getOperand(3), Depth+1);
2607     return std::min(Tmp, Tmp2);
2608   case ISD::SMIN:
2609   case ISD::SMAX:
2610   case ISD::UMIN:
2611   case ISD::UMAX:
2612     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
2613     if (Tmp == 1)
2614       return 1;  // Early out.
2615     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
2616     return std::min(Tmp, Tmp2);
2617   case ISD::SADDO:
2618   case ISD::UADDO:
2619   case ISD::SSUBO:
2620   case ISD::USUBO:
2621   case ISD::SMULO:
2622   case ISD::UMULO:
2623     if (Op.getResNo() != 1)
2624       break;
2625     // The boolean result conforms to getBooleanContents.  Fall through.
2626     // If setcc returns 0/-1, all bits are sign bits.
2627     // We know that we have an integer-based boolean since these operations
2628     // are only available for integer.
2629     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2630         TargetLowering::ZeroOrNegativeOneBooleanContent)
2631       return VTBits;
2632     break;
2633   case ISD::SETCC:
2634     // If setcc returns 0/-1, all bits are sign bits.
2635     if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2636         TargetLowering::ZeroOrNegativeOneBooleanContent)
2637       return VTBits;
2638     break;
2639   case ISD::ROTL:
2640   case ISD::ROTR:
2641     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2642       unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2643 
2644       // Handle rotate right by N like a rotate left by 32-N.
2645       if (Op.getOpcode() == ISD::ROTR)
2646         RotAmt = (VTBits-RotAmt) & (VTBits-1);
2647 
2648       // If we aren't rotating out all of the known-in sign bits, return the
2649       // number that are left.  This handles rotl(sext(x), 1) for example.
2650       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2651       if (Tmp > RotAmt+1) return Tmp-RotAmt;
2652     }
2653     break;
2654   case ISD::ADD:
2655     // Add can have at most one carry bit.  Thus we know that the output
2656     // is, at worst, one more bit than the inputs.
2657     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2658     if (Tmp == 1) return 1;  // Early out.
2659 
2660     // Special case decrementing a value (ADD X, -1):
2661     if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2662       if (CRHS->isAllOnesValue()) {
2663         APInt KnownZero, KnownOne;
2664         computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2665 
2666         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2667         // sign bits set.
2668         if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
2669           return VTBits;
2670 
2671         // If we are subtracting one from a positive number, there is no carry
2672         // out of the result.
2673         if (KnownZero.isNegative())
2674           return Tmp;
2675       }
2676 
2677     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2678     if (Tmp2 == 1) return 1;
2679     return std::min(Tmp, Tmp2)-1;
2680 
2681   case ISD::SUB:
2682     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2683     if (Tmp2 == 1) return 1;
2684 
2685     // Handle NEG.
2686     if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
2687       if (CLHS->isNullValue()) {
2688         APInt KnownZero, KnownOne;
2689         computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2690         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2691         // sign bits set.
2692         if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
2693           return VTBits;
2694 
2695         // If the input is known to be positive (the sign bit is known clear),
2696         // the output of the NEG has the same number of sign bits as the input.
2697         if (KnownZero.isNegative())
2698           return Tmp2;
2699 
2700         // Otherwise, we treat this like a SUB.
2701       }
2702 
2703     // Sub can have at most one carry bit.  Thus we know that the output
2704     // is, at worst, one more bit than the inputs.
2705     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2706     if (Tmp == 1) return 1;  // Early out.
2707     return std::min(Tmp, Tmp2)-1;
2708   case ISD::TRUNCATE:
2709     // FIXME: it's tricky to do anything useful for this, but it is an important
2710     // case for targets like X86.
2711     break;
2712   case ISD::EXTRACT_ELEMENT: {
2713     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2714     const int BitWidth = Op.getValueSizeInBits();
2715     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
2716 
2717     // Get reverse index (starting from 1), Op1 value indexes elements from
2718     // little end. Sign starts at big end.
2719     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
2720 
2721     // If the sign portion ends in our element the subtraction gives correct
2722     // result. Otherwise it gives either negative or > bitwidth result
2723     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
2724   }
2725   case ISD::EXTRACT_VECTOR_ELT: {
2726     // At the moment we keep this simple and skip tracking the specific
2727     // element. This way we get the lowest common denominator for all elements
2728     // of the vector.
2729     // TODO: get information for given vector element
2730     const unsigned BitWidth = Op.getValueSizeInBits();
2731     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
2732     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
2733     // anything about sign bits. But if the sizes match we can derive knowledge
2734     // about sign bits from the vector operand.
2735     if (BitWidth == EltBitWidth)
2736       return ComputeNumSignBits(Op.getOperand(0), Depth+1);
2737     break;
2738   }
2739   }
2740 
2741   // If we are looking at the loaded value of the SDNode.
2742   if (Op.getResNo() == 0) {
2743     // Handle LOADX separately here. EXTLOAD case will fallthrough.
2744     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
2745       unsigned ExtType = LD->getExtensionType();
2746       switch (ExtType) {
2747         default: break;
2748         case ISD::SEXTLOAD:    // '17' bits known
2749           Tmp = LD->getMemoryVT().getScalarSizeInBits();
2750           return VTBits-Tmp+1;
2751         case ISD::ZEXTLOAD:    // '16' bits known
2752           Tmp = LD->getMemoryVT().getScalarSizeInBits();
2753           return VTBits-Tmp;
2754       }
2755     }
2756   }
2757 
2758   // Allow the target to implement this method for its nodes.
2759   if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2760       Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2761       Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2762       Op.getOpcode() == ISD::INTRINSIC_VOID) {
2763     unsigned NumBits = TLI->ComputeNumSignBitsForTargetNode(Op, *this, Depth);
2764     if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2765   }
2766 
2767   // Finally, if we can prove that the top bits of the result are 0's or 1's,
2768   // use this information.
2769   APInt KnownZero, KnownOne;
2770   computeKnownBits(Op, KnownZero, KnownOne, Depth);
2771 
2772   APInt Mask;
2773   if (KnownZero.isNegative()) {        // sign bit is 0
2774     Mask = KnownZero;
2775   } else if (KnownOne.isNegative()) {  // sign bit is 1;
2776     Mask = KnownOne;
2777   } else {
2778     // Nothing known.
2779     return FirstAnswer;
2780   }
2781 
2782   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
2783   // the number of identical bits in the top of the input value.
2784   Mask = ~Mask;
2785   Mask <<= Mask.getBitWidth()-VTBits;
2786   // Return # leading zeros.  We use 'min' here in case Val was zero before
2787   // shifting.  We don't want to return '64' as for an i32 "0".
2788   return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2789 }
2790 
2791 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
2792   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
2793       !isa<ConstantSDNode>(Op.getOperand(1)))
2794     return false;
2795 
2796   if (Op.getOpcode() == ISD::OR &&
2797       !MaskedValueIsZero(Op.getOperand(0),
2798                      cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
2799     return false;
2800 
2801   return true;
2802 }
2803 
2804 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2805   // If we're told that NaNs won't happen, assume they won't.
2806   if (getTarget().Options.NoNaNsFPMath)
2807     return true;
2808 
2809   // If the value is a constant, we can obviously see if it is a NaN or not.
2810   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2811     return !C->getValueAPF().isNaN();
2812 
2813   // TODO: Recognize more cases here.
2814 
2815   return false;
2816 }
2817 
2818 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
2819   // If the value is a constant, we can obviously see if it is a zero or not.
2820   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2821     return !C->isZero();
2822 
2823   // TODO: Recognize more cases here.
2824   switch (Op.getOpcode()) {
2825   default: break;
2826   case ISD::OR:
2827     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2828       return !C->isNullValue();
2829     break;
2830   }
2831 
2832   return false;
2833 }
2834 
2835 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
2836   // Check the obvious case.
2837   if (A == B) return true;
2838 
2839   // For for negative and positive zero.
2840   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
2841     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
2842       if (CA->isZero() && CB->isZero()) return true;
2843 
2844   // Otherwise they may not be equal.
2845   return false;
2846 }
2847 
2848 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
2849   assert(A.getValueType() == B.getValueType() &&
2850          "Values must have the same type");
2851   APInt AZero, AOne;
2852   APInt BZero, BOne;
2853   computeKnownBits(A, AZero, AOne);
2854   computeKnownBits(B, BZero, BOne);
2855   return (AZero | BZero).isAllOnesValue();
2856 }
2857 
2858 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
2859                                   ArrayRef<SDValue> Ops,
2860                                   llvm::SelectionDAG &DAG) {
2861   if (Ops.size() == 1)
2862     return Ops[0];
2863 
2864   // Concat of UNDEFs is UNDEF.
2865   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
2866     return DAG.getUNDEF(VT);
2867 
2868   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
2869   // simplified to one big BUILD_VECTOR.
2870   // FIXME: Add support for SCALAR_TO_VECTOR as well.
2871   EVT SVT = VT.getScalarType();
2872   SmallVector<SDValue, 16> Elts;
2873   for (SDValue Op : Ops) {
2874     EVT OpVT = Op.getValueType();
2875     if (Op.isUndef())
2876       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
2877     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
2878       Elts.append(Op->op_begin(), Op->op_end());
2879     else
2880       return SDValue();
2881   }
2882 
2883   // BUILD_VECTOR requires all inputs to be of the same type, find the
2884   // maximum type and extend them all.
2885   for (SDValue Op : Elts)
2886     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
2887 
2888   if (SVT.bitsGT(VT.getScalarType()))
2889     for (SDValue &Op : Elts)
2890       Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
2891                ? DAG.getZExtOrTrunc(Op, DL, SVT)
2892                : DAG.getSExtOrTrunc(Op, DL, SVT);
2893 
2894   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts);
2895 }
2896 
2897 /// Gets or creates the specified node.
2898 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
2899   FoldingSetNodeID ID;
2900   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
2901   void *IP = nullptr;
2902   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
2903     return SDValue(E, 0);
2904 
2905   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
2906                               getVTList(VT));
2907   CSEMap.InsertNode(N, IP);
2908 
2909   InsertNode(N);
2910   return SDValue(N, 0);
2911 }
2912 
2913 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
2914                               SDValue Operand) {
2915   // Constant fold unary operations with an integer constant operand. Even
2916   // opaque constant will be folded, because the folding of unary operations
2917   // doesn't create new constants with different values. Nevertheless, the
2918   // opaque flag is preserved during folding to prevent future folding with
2919   // other constants.
2920   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
2921     const APInt &Val = C->getAPIntValue();
2922     switch (Opcode) {
2923     default: break;
2924     case ISD::SIGN_EXTEND:
2925       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
2926                          C->isTargetOpcode(), C->isOpaque());
2927     case ISD::ANY_EXTEND:
2928     case ISD::ZERO_EXTEND:
2929     case ISD::TRUNCATE:
2930       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
2931                          C->isTargetOpcode(), C->isOpaque());
2932     case ISD::UINT_TO_FP:
2933     case ISD::SINT_TO_FP: {
2934       APFloat apf(EVTToAPFloatSemantics(VT),
2935                   APInt::getNullValue(VT.getSizeInBits()));
2936       (void)apf.convertFromAPInt(Val,
2937                                  Opcode==ISD::SINT_TO_FP,
2938                                  APFloat::rmNearestTiesToEven);
2939       return getConstantFP(apf, DL, VT);
2940     }
2941     case ISD::BITCAST:
2942       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
2943         return getConstantFP(APFloat(APFloat::IEEEhalf, Val), DL, VT);
2944       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2945         return getConstantFP(APFloat(APFloat::IEEEsingle, Val), DL, VT);
2946       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2947         return getConstantFP(APFloat(APFloat::IEEEdouble, Val), DL, VT);
2948       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
2949         return getConstantFP(APFloat(APFloat::IEEEquad, Val), DL, VT);
2950       break;
2951     case ISD::BSWAP:
2952       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
2953                          C->isOpaque());
2954     case ISD::CTPOP:
2955       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
2956                          C->isOpaque());
2957     case ISD::CTLZ:
2958     case ISD::CTLZ_ZERO_UNDEF:
2959       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
2960                          C->isOpaque());
2961     case ISD::CTTZ:
2962     case ISD::CTTZ_ZERO_UNDEF:
2963       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
2964                          C->isOpaque());
2965     }
2966   }
2967 
2968   // Constant fold unary operations with a floating point constant operand.
2969   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
2970     APFloat V = C->getValueAPF();    // make copy
2971     switch (Opcode) {
2972     case ISD::FNEG:
2973       V.changeSign();
2974       return getConstantFP(V, DL, VT);
2975     case ISD::FABS:
2976       V.clearSign();
2977       return getConstantFP(V, DL, VT);
2978     case ISD::FCEIL: {
2979       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
2980       if (fs == APFloat::opOK || fs == APFloat::opInexact)
2981         return getConstantFP(V, DL, VT);
2982       break;
2983     }
2984     case ISD::FTRUNC: {
2985       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
2986       if (fs == APFloat::opOK || fs == APFloat::opInexact)
2987         return getConstantFP(V, DL, VT);
2988       break;
2989     }
2990     case ISD::FFLOOR: {
2991       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
2992       if (fs == APFloat::opOK || fs == APFloat::opInexact)
2993         return getConstantFP(V, DL, VT);
2994       break;
2995     }
2996     case ISD::FP_EXTEND: {
2997       bool ignored;
2998       // This can return overflow, underflow, or inexact; we don't care.
2999       // FIXME need to be more flexible about rounding mode.
3000       (void)V.convert(EVTToAPFloatSemantics(VT),
3001                       APFloat::rmNearestTiesToEven, &ignored);
3002       return getConstantFP(V, DL, VT);
3003     }
3004     case ISD::FP_TO_SINT:
3005     case ISD::FP_TO_UINT: {
3006       integerPart x[2];
3007       bool ignored;
3008       static_assert(integerPartWidth >= 64, "APFloat parts too small!");
3009       // FIXME need to be more flexible about rounding mode.
3010       APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
3011                             Opcode==ISD::FP_TO_SINT,
3012                             APFloat::rmTowardZero, &ignored);
3013       if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
3014         break;
3015       APInt api(VT.getSizeInBits(), x);
3016       return getConstant(api, DL, VT);
3017     }
3018     case ISD::BITCAST:
3019       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
3020         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3021       else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
3022         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3023       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
3024         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
3025       break;
3026     }
3027   }
3028 
3029   // Constant fold unary operations with a vector integer or float operand.
3030   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
3031     if (BV->isConstant()) {
3032       switch (Opcode) {
3033       default:
3034         // FIXME: Entirely reasonable to perform folding of other unary
3035         // operations here as the need arises.
3036         break;
3037       case ISD::FNEG:
3038       case ISD::FABS:
3039       case ISD::FCEIL:
3040       case ISD::FTRUNC:
3041       case ISD::FFLOOR:
3042       case ISD::FP_EXTEND:
3043       case ISD::FP_TO_SINT:
3044       case ISD::FP_TO_UINT:
3045       case ISD::TRUNCATE:
3046       case ISD::UINT_TO_FP:
3047       case ISD::SINT_TO_FP:
3048       case ISD::BSWAP:
3049       case ISD::CTLZ:
3050       case ISD::CTLZ_ZERO_UNDEF:
3051       case ISD::CTTZ:
3052       case ISD::CTTZ_ZERO_UNDEF:
3053       case ISD::CTPOP: {
3054         SDValue Ops = { Operand };
3055         if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
3056           return Fold;
3057       }
3058       }
3059     }
3060   }
3061 
3062   unsigned OpOpcode = Operand.getNode()->getOpcode();
3063   switch (Opcode) {
3064   case ISD::TokenFactor:
3065   case ISD::MERGE_VALUES:
3066   case ISD::CONCAT_VECTORS:
3067     return Operand;         // Factor, merge or concat of one node?  No need.
3068   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
3069   case ISD::FP_EXTEND:
3070     assert(VT.isFloatingPoint() &&
3071            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
3072     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
3073     assert((!VT.isVector() ||
3074             VT.getVectorNumElements() ==
3075             Operand.getValueType().getVectorNumElements()) &&
3076            "Vector element count mismatch!");
3077     assert(Operand.getValueType().bitsLT(VT) &&
3078            "Invalid fpext node, dst < src!");
3079     if (Operand.isUndef())
3080       return getUNDEF(VT);
3081     break;
3082   case ISD::SIGN_EXTEND:
3083     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3084            "Invalid SIGN_EXTEND!");
3085     if (Operand.getValueType() == VT) return Operand;   // noop extension
3086     assert((!VT.isVector() ||
3087             VT.getVectorNumElements() ==
3088             Operand.getValueType().getVectorNumElements()) &&
3089            "Vector element count mismatch!");
3090     assert(Operand.getValueType().bitsLT(VT) &&
3091            "Invalid sext node, dst < src!");
3092     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
3093       return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3094     else if (OpOpcode == ISD::UNDEF)
3095       // sext(undef) = 0, because the top bits will all be the same.
3096       return getConstant(0, DL, VT);
3097     break;
3098   case ISD::ZERO_EXTEND:
3099     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3100            "Invalid ZERO_EXTEND!");
3101     if (Operand.getValueType() == VT) return Operand;   // noop extension
3102     assert((!VT.isVector() ||
3103             VT.getVectorNumElements() ==
3104             Operand.getValueType().getVectorNumElements()) &&
3105            "Vector element count mismatch!");
3106     assert(Operand.getValueType().bitsLT(VT) &&
3107            "Invalid zext node, dst < src!");
3108     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
3109       return getNode(ISD::ZERO_EXTEND, DL, VT,
3110                      Operand.getNode()->getOperand(0));
3111     else if (OpOpcode == ISD::UNDEF)
3112       // zext(undef) = 0, because the top bits will be zero.
3113       return getConstant(0, DL, VT);
3114     break;
3115   case ISD::ANY_EXTEND:
3116     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3117            "Invalid ANY_EXTEND!");
3118     if (Operand.getValueType() == VT) return Operand;   // noop extension
3119     assert((!VT.isVector() ||
3120             VT.getVectorNumElements() ==
3121             Operand.getValueType().getVectorNumElements()) &&
3122            "Vector element count mismatch!");
3123     assert(Operand.getValueType().bitsLT(VT) &&
3124            "Invalid anyext node, dst < src!");
3125 
3126     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3127         OpOpcode == ISD::ANY_EXTEND)
3128       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
3129       return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3130     else if (OpOpcode == ISD::UNDEF)
3131       return getUNDEF(VT);
3132 
3133     // (ext (trunx x)) -> x
3134     if (OpOpcode == ISD::TRUNCATE) {
3135       SDValue OpOp = Operand.getNode()->getOperand(0);
3136       if (OpOp.getValueType() == VT)
3137         return OpOp;
3138     }
3139     break;
3140   case ISD::TRUNCATE:
3141     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3142            "Invalid TRUNCATE!");
3143     if (Operand.getValueType() == VT) return Operand;   // noop truncate
3144     assert((!VT.isVector() ||
3145             VT.getVectorNumElements() ==
3146             Operand.getValueType().getVectorNumElements()) &&
3147            "Vector element count mismatch!");
3148     assert(Operand.getValueType().bitsGT(VT) &&
3149            "Invalid truncate node, src < dst!");
3150     if (OpOpcode == ISD::TRUNCATE)
3151       return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
3152     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3153         OpOpcode == ISD::ANY_EXTEND) {
3154       // If the source is smaller than the dest, we still need an extend.
3155       if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
3156             .bitsLT(VT.getScalarType()))
3157         return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3158       if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
3159         return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
3160       return Operand.getNode()->getOperand(0);
3161     }
3162     if (OpOpcode == ISD::UNDEF)
3163       return getUNDEF(VT);
3164     break;
3165   case ISD::BSWAP:
3166     assert(VT.isInteger() && VT == Operand.getValueType() &&
3167            "Invalid BSWAP!");
3168     assert((VT.getScalarSizeInBits() % 16 == 0) &&
3169            "BSWAP types must be a multiple of 16 bits!");
3170     if (OpOpcode == ISD::UNDEF)
3171       return getUNDEF(VT);
3172     break;
3173   case ISD::BITREVERSE:
3174     assert(VT.isInteger() && VT == Operand.getValueType() &&
3175            "Invalid BITREVERSE!");
3176     if (OpOpcode == ISD::UNDEF)
3177       return getUNDEF(VT);
3178     break;
3179   case ISD::BITCAST:
3180     // Basic sanity checking.
3181     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
3182            "Cannot BITCAST between types of different sizes!");
3183     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
3184     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
3185       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
3186     if (OpOpcode == ISD::UNDEF)
3187       return getUNDEF(VT);
3188     break;
3189   case ISD::SCALAR_TO_VECTOR:
3190     assert(VT.isVector() && !Operand.getValueType().isVector() &&
3191            (VT.getVectorElementType() == Operand.getValueType() ||
3192             (VT.getVectorElementType().isInteger() &&
3193              Operand.getValueType().isInteger() &&
3194              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
3195            "Illegal SCALAR_TO_VECTOR node!");
3196     if (OpOpcode == ISD::UNDEF)
3197       return getUNDEF(VT);
3198     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
3199     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
3200         isa<ConstantSDNode>(Operand.getOperand(1)) &&
3201         Operand.getConstantOperandVal(1) == 0 &&
3202         Operand.getOperand(0).getValueType() == VT)
3203       return Operand.getOperand(0);
3204     break;
3205   case ISD::FNEG:
3206     // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
3207     if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
3208       // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags?
3209       return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
3210                        Operand.getNode()->getOperand(0),
3211                        &cast<BinaryWithFlagsSDNode>(Operand.getNode())->Flags);
3212     if (OpOpcode == ISD::FNEG)  // --X -> X
3213       return Operand.getNode()->getOperand(0);
3214     break;
3215   case ISD::FABS:
3216     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
3217       return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
3218     break;
3219   }
3220 
3221   SDNode *N;
3222   SDVTList VTs = getVTList(VT);
3223   SDValue Ops[] = {Operand};
3224   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
3225     FoldingSetNodeID ID;
3226     AddNodeIDNode(ID, Opcode, VTs, Ops);
3227     void *IP = nullptr;
3228     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3229       return SDValue(E, 0);
3230 
3231     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3232     createOperands(N, Ops);
3233     CSEMap.InsertNode(N, IP);
3234   } else {
3235     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3236     createOperands(N, Ops);
3237   }
3238 
3239   InsertNode(N);
3240   return SDValue(N, 0);
3241 }
3242 
3243 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
3244                                         const APInt &C2) {
3245   switch (Opcode) {
3246   case ISD::ADD:  return std::make_pair(C1 + C2, true);
3247   case ISD::SUB:  return std::make_pair(C1 - C2, true);
3248   case ISD::MUL:  return std::make_pair(C1 * C2, true);
3249   case ISD::AND:  return std::make_pair(C1 & C2, true);
3250   case ISD::OR:   return std::make_pair(C1 | C2, true);
3251   case ISD::XOR:  return std::make_pair(C1 ^ C2, true);
3252   case ISD::SHL:  return std::make_pair(C1 << C2, true);
3253   case ISD::SRL:  return std::make_pair(C1.lshr(C2), true);
3254   case ISD::SRA:  return std::make_pair(C1.ashr(C2), true);
3255   case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
3256   case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
3257   case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
3258   case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
3259   case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
3260   case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
3261   case ISD::UDIV:
3262     if (!C2.getBoolValue())
3263       break;
3264     return std::make_pair(C1.udiv(C2), true);
3265   case ISD::UREM:
3266     if (!C2.getBoolValue())
3267       break;
3268     return std::make_pair(C1.urem(C2), true);
3269   case ISD::SDIV:
3270     if (!C2.getBoolValue())
3271       break;
3272     return std::make_pair(C1.sdiv(C2), true);
3273   case ISD::SREM:
3274     if (!C2.getBoolValue())
3275       break;
3276     return std::make_pair(C1.srem(C2), true);
3277   }
3278   return std::make_pair(APInt(1, 0), false);
3279 }
3280 
3281 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3282                                              EVT VT, const ConstantSDNode *Cst1,
3283                                              const ConstantSDNode *Cst2) {
3284   if (Cst1->isOpaque() || Cst2->isOpaque())
3285     return SDValue();
3286 
3287   std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(),
3288                                             Cst2->getAPIntValue());
3289   if (!Folded.second)
3290     return SDValue();
3291   return getConstant(Folded.first, DL, VT);
3292 }
3293 
3294 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
3295                                        const GlobalAddressSDNode *GA,
3296                                        const SDNode *N2) {
3297   if (GA->getOpcode() != ISD::GlobalAddress)
3298     return SDValue();
3299   if (!TLI->isOffsetFoldingLegal(GA))
3300     return SDValue();
3301   const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2);
3302   if (!Cst2)
3303     return SDValue();
3304   int64_t Offset = Cst2->getSExtValue();
3305   switch (Opcode) {
3306   case ISD::ADD: break;
3307   case ISD::SUB: Offset = -uint64_t(Offset); break;
3308   default: return SDValue();
3309   }
3310   return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT,
3311                           GA->getOffset() + uint64_t(Offset));
3312 }
3313 
3314 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3315                                              EVT VT, SDNode *Cst1,
3316                                              SDNode *Cst2) {
3317   // If the opcode is a target-specific ISD node, there's nothing we can
3318   // do here and the operand rules may not line up with the below, so
3319   // bail early.
3320   if (Opcode >= ISD::BUILTIN_OP_END)
3321     return SDValue();
3322 
3323   // Handle the case of two scalars.
3324   if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
3325     if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
3326       SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2);
3327       assert((!Folded || !VT.isVector()) &&
3328              "Can't fold vectors ops with scalar operands");
3329       return Folded;
3330     }
3331   }
3332 
3333   // fold (add Sym, c) -> Sym+c
3334   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1))
3335     return FoldSymbolOffset(Opcode, VT, GA, Cst2);
3336   if (isCommutativeBinOp(Opcode))
3337     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2))
3338       return FoldSymbolOffset(Opcode, VT, GA, Cst1);
3339 
3340   // For vectors extract each constant element into Inputs so we can constant
3341   // fold them individually.
3342   BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
3343   BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
3344   if (!BV1 || !BV2)
3345     return SDValue();
3346 
3347   assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
3348 
3349   EVT SVT = VT.getScalarType();
3350   SmallVector<SDValue, 4> Outputs;
3351   for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
3352     ConstantSDNode *V1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I));
3353     ConstantSDNode *V2 = dyn_cast<ConstantSDNode>(BV2->getOperand(I));
3354     if (!V1 || !V2) // Not a constant, bail.
3355       return SDValue();
3356 
3357     if (V1->isOpaque() || V2->isOpaque())
3358       return SDValue();
3359 
3360     // Avoid BUILD_VECTOR nodes that perform implicit truncation.
3361     // FIXME: This is valid and could be handled by truncating the APInts.
3362     if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
3363       return SDValue();
3364 
3365     // Fold one vector element.
3366     std::pair<APInt, bool> Folded = FoldValue(Opcode, V1->getAPIntValue(),
3367                                               V2->getAPIntValue());
3368     if (!Folded.second)
3369       return SDValue();
3370     Outputs.push_back(getConstant(Folded.first, DL, SVT));
3371   }
3372 
3373   assert(VT.getVectorNumElements() == Outputs.size() &&
3374          "Vector size mismatch!");
3375 
3376   // We may have a vector type but a scalar result. Create a splat.
3377   Outputs.resize(VT.getVectorNumElements(), Outputs.back());
3378 
3379   // Build a big vector out of the scalar elements we generated.
3380   return getBuildVector(VT, SDLoc(), Outputs);
3381 }
3382 
3383 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
3384                                                    const SDLoc &DL, EVT VT,
3385                                                    ArrayRef<SDValue> Ops,
3386                                                    const SDNodeFlags *Flags) {
3387   // If the opcode is a target-specific ISD node, there's nothing we can
3388   // do here and the operand rules may not line up with the below, so
3389   // bail early.
3390   if (Opcode >= ISD::BUILTIN_OP_END)
3391     return SDValue();
3392 
3393   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
3394   if (!VT.isVector())
3395     return SDValue();
3396 
3397   unsigned NumElts = VT.getVectorNumElements();
3398 
3399   auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
3400     return !Op.getValueType().isVector() ||
3401            Op.getValueType().getVectorNumElements() == NumElts;
3402   };
3403 
3404   auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
3405     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
3406     return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
3407            (BV && BV->isConstant());
3408   };
3409 
3410   // All operands must be vector types with the same number of elements as
3411   // the result type and must be either UNDEF or a build vector of constant
3412   // or UNDEF scalars.
3413   if (!all_of(Ops, IsConstantBuildVectorOrUndef) ||
3414       !all_of(Ops, IsScalarOrSameVectorSize))
3415     return SDValue();
3416 
3417   // If we are comparing vectors, then the result needs to be a i1 boolean
3418   // that is then sign-extended back to the legal result type.
3419   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
3420 
3421   // Find legal integer scalar type for constant promotion and
3422   // ensure that its scalar size is at least as large as source.
3423   EVT LegalSVT = VT.getScalarType();
3424   if (LegalSVT.isInteger()) {
3425     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3426     if (LegalSVT.bitsLT(VT.getScalarType()))
3427       return SDValue();
3428   }
3429 
3430   // Constant fold each scalar lane separately.
3431   SmallVector<SDValue, 4> ScalarResults;
3432   for (unsigned i = 0; i != NumElts; i++) {
3433     SmallVector<SDValue, 4> ScalarOps;
3434     for (SDValue Op : Ops) {
3435       EVT InSVT = Op.getValueType().getScalarType();
3436       BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
3437       if (!InBV) {
3438         // We've checked that this is UNDEF or a constant of some kind.
3439         if (Op.isUndef())
3440           ScalarOps.push_back(getUNDEF(InSVT));
3441         else
3442           ScalarOps.push_back(Op);
3443         continue;
3444       }
3445 
3446       SDValue ScalarOp = InBV->getOperand(i);
3447       EVT ScalarVT = ScalarOp.getValueType();
3448 
3449       // Build vector (integer) scalar operands may need implicit
3450       // truncation - do this before constant folding.
3451       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
3452         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
3453 
3454       ScalarOps.push_back(ScalarOp);
3455     }
3456 
3457     // Constant fold the scalar operands.
3458     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
3459 
3460     // Legalize the (integer) scalar constant if necessary.
3461     if (LegalSVT != SVT)
3462       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
3463 
3464     // Scalar folding only succeeded if the result is a constant or UNDEF.
3465     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3466         ScalarResult.getOpcode() != ISD::ConstantFP)
3467       return SDValue();
3468     ScalarResults.push_back(ScalarResult);
3469   }
3470 
3471   return getBuildVector(VT, DL, ScalarResults);
3472 }
3473 
3474 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3475                               SDValue N1, SDValue N2,
3476                               const SDNodeFlags *Flags) {
3477   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3478   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3479   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3480   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
3481 
3482   // Canonicalize constant to RHS if commutative.
3483   if (isCommutativeBinOp(Opcode)) {
3484     if (N1C && !N2C) {
3485       std::swap(N1C, N2C);
3486       std::swap(N1, N2);
3487     } else if (N1CFP && !N2CFP) {
3488       std::swap(N1CFP, N2CFP);
3489       std::swap(N1, N2);
3490     }
3491   }
3492 
3493   switch (Opcode) {
3494   default: break;
3495   case ISD::TokenFactor:
3496     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
3497            N2.getValueType() == MVT::Other && "Invalid token factor!");
3498     // Fold trivial token factors.
3499     if (N1.getOpcode() == ISD::EntryToken) return N2;
3500     if (N2.getOpcode() == ISD::EntryToken) return N1;
3501     if (N1 == N2) return N1;
3502     break;
3503   case ISD::CONCAT_VECTORS: {
3504     // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
3505     SDValue Ops[] = {N1, N2};
3506     if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
3507       return V;
3508     break;
3509   }
3510   case ISD::AND:
3511     assert(VT.isInteger() && "This operator does not apply to FP types!");
3512     assert(N1.getValueType() == N2.getValueType() &&
3513            N1.getValueType() == VT && "Binary operator types must match!");
3514     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
3515     // worth handling here.
3516     if (N2C && N2C->isNullValue())
3517       return N2;
3518     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
3519       return N1;
3520     break;
3521   case ISD::OR:
3522   case ISD::XOR:
3523   case ISD::ADD:
3524   case ISD::SUB:
3525     assert(VT.isInteger() && "This operator does not apply to FP types!");
3526     assert(N1.getValueType() == N2.getValueType() &&
3527            N1.getValueType() == VT && "Binary operator types must match!");
3528     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
3529     // it's worth handling here.
3530     if (N2C && N2C->isNullValue())
3531       return N1;
3532     break;
3533   case ISD::UDIV:
3534   case ISD::UREM:
3535   case ISD::MULHU:
3536   case ISD::MULHS:
3537   case ISD::MUL:
3538   case ISD::SDIV:
3539   case ISD::SREM:
3540   case ISD::SMIN:
3541   case ISD::SMAX:
3542   case ISD::UMIN:
3543   case ISD::UMAX:
3544     assert(VT.isInteger() && "This operator does not apply to FP types!");
3545     assert(N1.getValueType() == N2.getValueType() &&
3546            N1.getValueType() == VT && "Binary operator types must match!");
3547     break;
3548   case ISD::FADD:
3549   case ISD::FSUB:
3550   case ISD::FMUL:
3551   case ISD::FDIV:
3552   case ISD::FREM:
3553     if (getTarget().Options.UnsafeFPMath) {
3554       if (Opcode == ISD::FADD) {
3555         // x+0 --> x
3556         if (N2CFP && N2CFP->getValueAPF().isZero())
3557           return N1;
3558       } else if (Opcode == ISD::FSUB) {
3559         // x-0 --> x
3560         if (N2CFP && N2CFP->getValueAPF().isZero())
3561           return N1;
3562       } else if (Opcode == ISD::FMUL) {
3563         // x*0 --> 0
3564         if (N2CFP && N2CFP->isZero())
3565           return N2;
3566         // x*1 --> x
3567         if (N2CFP && N2CFP->isExactlyValue(1.0))
3568           return N1;
3569       }
3570     }
3571     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
3572     assert(N1.getValueType() == N2.getValueType() &&
3573            N1.getValueType() == VT && "Binary operator types must match!");
3574     break;
3575   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
3576     assert(N1.getValueType() == VT &&
3577            N1.getValueType().isFloatingPoint() &&
3578            N2.getValueType().isFloatingPoint() &&
3579            "Invalid FCOPYSIGN!");
3580     break;
3581   case ISD::SHL:
3582   case ISD::SRA:
3583   case ISD::SRL:
3584   case ISD::ROTL:
3585   case ISD::ROTR:
3586     assert(VT == N1.getValueType() &&
3587            "Shift operators return type must be the same as their first arg");
3588     assert(VT.isInteger() && N2.getValueType().isInteger() &&
3589            "Shifts only work on integers");
3590     assert((!VT.isVector() || VT == N2.getValueType()) &&
3591            "Vector shift amounts must be in the same as their first arg");
3592     // Verify that the shift amount VT is bit enough to hold valid shift
3593     // amounts.  This catches things like trying to shift an i1024 value by an
3594     // i8, which is easy to fall into in generic code that uses
3595     // TLI.getShiftAmount().
3596     assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
3597            "Invalid use of small shift amount with oversized value!");
3598 
3599     // Always fold shifts of i1 values so the code generator doesn't need to
3600     // handle them.  Since we know the size of the shift has to be less than the
3601     // size of the value, the shift/rotate count is guaranteed to be zero.
3602     if (VT == MVT::i1)
3603       return N1;
3604     if (N2C && N2C->isNullValue())
3605       return N1;
3606     break;
3607   case ISD::FP_ROUND_INREG: {
3608     EVT EVT = cast<VTSDNode>(N2)->getVT();
3609     assert(VT == N1.getValueType() && "Not an inreg round!");
3610     assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
3611            "Cannot FP_ROUND_INREG integer types");
3612     assert(EVT.isVector() == VT.isVector() &&
3613            "FP_ROUND_INREG type should be vector iff the operand "
3614            "type is vector!");
3615     assert((!EVT.isVector() ||
3616             EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
3617            "Vector element counts must match in FP_ROUND_INREG");
3618     assert(EVT.bitsLE(VT) && "Not rounding down!");
3619     (void)EVT;
3620     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
3621     break;
3622   }
3623   case ISD::FP_ROUND:
3624     assert(VT.isFloatingPoint() &&
3625            N1.getValueType().isFloatingPoint() &&
3626            VT.bitsLE(N1.getValueType()) &&
3627            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
3628            "Invalid FP_ROUND!");
3629     if (N1.getValueType() == VT) return N1;  // noop conversion.
3630     break;
3631   case ISD::AssertSext:
3632   case ISD::AssertZext: {
3633     EVT EVT = cast<VTSDNode>(N2)->getVT();
3634     assert(VT == N1.getValueType() && "Not an inreg extend!");
3635     assert(VT.isInteger() && EVT.isInteger() &&
3636            "Cannot *_EXTEND_INREG FP types");
3637     assert(!EVT.isVector() &&
3638            "AssertSExt/AssertZExt type should be the vector element type "
3639            "rather than the vector type!");
3640     assert(EVT.bitsLE(VT) && "Not extending!");
3641     if (VT == EVT) return N1; // noop assertion.
3642     break;
3643   }
3644   case ISD::SIGN_EXTEND_INREG: {
3645     EVT EVT = cast<VTSDNode>(N2)->getVT();
3646     assert(VT == N1.getValueType() && "Not an inreg extend!");
3647     assert(VT.isInteger() && EVT.isInteger() &&
3648            "Cannot *_EXTEND_INREG FP types");
3649     assert(EVT.isVector() == VT.isVector() &&
3650            "SIGN_EXTEND_INREG type should be vector iff the operand "
3651            "type is vector!");
3652     assert((!EVT.isVector() ||
3653             EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
3654            "Vector element counts must match in SIGN_EXTEND_INREG");
3655     assert(EVT.bitsLE(VT) && "Not extending!");
3656     if (EVT == VT) return N1;  // Not actually extending
3657 
3658     auto SignExtendInReg = [&](APInt Val) {
3659       unsigned FromBits = EVT.getScalarSizeInBits();
3660       Val <<= Val.getBitWidth() - FromBits;
3661       Val = Val.ashr(Val.getBitWidth() - FromBits);
3662       return getConstant(Val, DL, VT.getScalarType());
3663     };
3664 
3665     if (N1C) {
3666       const APInt &Val = N1C->getAPIntValue();
3667       return SignExtendInReg(Val);
3668     }
3669     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
3670       SmallVector<SDValue, 8> Ops;
3671       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
3672         SDValue Op = N1.getOperand(i);
3673         if (Op.isUndef()) {
3674           Ops.push_back(getUNDEF(VT.getScalarType()));
3675           continue;
3676         }
3677         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3678           APInt Val = C->getAPIntValue();
3679           Val = Val.zextOrTrunc(VT.getScalarSizeInBits());
3680           Ops.push_back(SignExtendInReg(Val));
3681           continue;
3682         }
3683         break;
3684       }
3685       if (Ops.size() == VT.getVectorNumElements())
3686         return getBuildVector(VT, DL, Ops);
3687     }
3688     break;
3689   }
3690   case ISD::EXTRACT_VECTOR_ELT:
3691     // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
3692     if (N1.isUndef())
3693       return getUNDEF(VT);
3694 
3695     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
3696     if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements())
3697       return getUNDEF(VT);
3698 
3699     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
3700     // expanding copies of large vectors from registers.
3701     if (N2C &&
3702         N1.getOpcode() == ISD::CONCAT_VECTORS &&
3703         N1.getNumOperands() > 0) {
3704       unsigned Factor =
3705         N1.getOperand(0).getValueType().getVectorNumElements();
3706       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
3707                      N1.getOperand(N2C->getZExtValue() / Factor),
3708                      getConstant(N2C->getZExtValue() % Factor, DL,
3709                                  N2.getValueType()));
3710     }
3711 
3712     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
3713     // expanding large vector constants.
3714     if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
3715       SDValue Elt = N1.getOperand(N2C->getZExtValue());
3716 
3717       if (VT != Elt.getValueType())
3718         // If the vector element type is not legal, the BUILD_VECTOR operands
3719         // are promoted and implicitly truncated, and the result implicitly
3720         // extended. Make that explicit here.
3721         Elt = getAnyExtOrTrunc(Elt, DL, VT);
3722 
3723       return Elt;
3724     }
3725 
3726     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
3727     // operations are lowered to scalars.
3728     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
3729       // If the indices are the same, return the inserted element else
3730       // if the indices are known different, extract the element from
3731       // the original vector.
3732       SDValue N1Op2 = N1.getOperand(2);
3733       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
3734 
3735       if (N1Op2C && N2C) {
3736         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
3737           if (VT == N1.getOperand(1).getValueType())
3738             return N1.getOperand(1);
3739           else
3740             return getSExtOrTrunc(N1.getOperand(1), DL, VT);
3741         }
3742 
3743         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
3744       }
3745     }
3746     break;
3747   case ISD::EXTRACT_ELEMENT:
3748     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
3749     assert(!N1.getValueType().isVector() && !VT.isVector() &&
3750            (N1.getValueType().isInteger() == VT.isInteger()) &&
3751            N1.getValueType() != VT &&
3752            "Wrong types for EXTRACT_ELEMENT!");
3753 
3754     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
3755     // 64-bit integers into 32-bit parts.  Instead of building the extract of
3756     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
3757     if (N1.getOpcode() == ISD::BUILD_PAIR)
3758       return N1.getOperand(N2C->getZExtValue());
3759 
3760     // EXTRACT_ELEMENT of a constant int is also very common.
3761     if (N1C) {
3762       unsigned ElementSize = VT.getSizeInBits();
3763       unsigned Shift = ElementSize * N2C->getZExtValue();
3764       APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
3765       return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
3766     }
3767     break;
3768   case ISD::EXTRACT_SUBVECTOR:
3769     if (VT.isSimple() && N1.getValueType().isSimple()) {
3770       assert(VT.isVector() && N1.getValueType().isVector() &&
3771              "Extract subvector VTs must be a vectors!");
3772       assert(VT.getVectorElementType() ==
3773              N1.getValueType().getVectorElementType() &&
3774              "Extract subvector VTs must have the same element type!");
3775       assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
3776              "Extract subvector must be from larger vector to smaller vector!");
3777 
3778       if (N2C) {
3779         assert((VT.getVectorNumElements() + N2C->getZExtValue()
3780                 <= N1.getValueType().getVectorNumElements())
3781                && "Extract subvector overflow!");
3782       }
3783 
3784       // Trivial extraction.
3785       if (VT.getSimpleVT() == N1.getSimpleValueType())
3786         return N1;
3787 
3788       // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
3789       // during shuffle legalization.
3790       if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
3791           VT == N1.getOperand(1).getValueType())
3792         return N1.getOperand(1);
3793     }
3794     break;
3795   }
3796 
3797   // Perform trivial constant folding.
3798   if (SDValue SV =
3799           FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
3800     return SV;
3801 
3802   // Constant fold FP operations.
3803   bool HasFPExceptions = TLI->hasFloatingPointExceptions();
3804   if (N1CFP) {
3805     if (N2CFP) {
3806       APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
3807       APFloat::opStatus s;
3808       switch (Opcode) {
3809       case ISD::FADD:
3810         s = V1.add(V2, APFloat::rmNearestTiesToEven);
3811         if (!HasFPExceptions || s != APFloat::opInvalidOp)
3812           return getConstantFP(V1, DL, VT);
3813         break;
3814       case ISD::FSUB:
3815         s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
3816         if (!HasFPExceptions || s!=APFloat::opInvalidOp)
3817           return getConstantFP(V1, DL, VT);
3818         break;
3819       case ISD::FMUL:
3820         s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
3821         if (!HasFPExceptions || s!=APFloat::opInvalidOp)
3822           return getConstantFP(V1, DL, VT);
3823         break;
3824       case ISD::FDIV:
3825         s = V1.divide(V2, APFloat::rmNearestTiesToEven);
3826         if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
3827                                  s!=APFloat::opDivByZero)) {
3828           return getConstantFP(V1, DL, VT);
3829         }
3830         break;
3831       case ISD::FREM :
3832         s = V1.mod(V2);
3833         if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
3834                                  s!=APFloat::opDivByZero)) {
3835           return getConstantFP(V1, DL, VT);
3836         }
3837         break;
3838       case ISD::FCOPYSIGN:
3839         V1.copySign(V2);
3840         return getConstantFP(V1, DL, VT);
3841       default: break;
3842       }
3843     }
3844 
3845     if (Opcode == ISD::FP_ROUND) {
3846       APFloat V = N1CFP->getValueAPF();    // make copy
3847       bool ignored;
3848       // This can return overflow, underflow, or inexact; we don't care.
3849       // FIXME need to be more flexible about rounding mode.
3850       (void)V.convert(EVTToAPFloatSemantics(VT),
3851                       APFloat::rmNearestTiesToEven, &ignored);
3852       return getConstantFP(V, DL, VT);
3853     }
3854   }
3855 
3856   // Canonicalize an UNDEF to the RHS, even over a constant.
3857   if (N1.isUndef()) {
3858     if (isCommutativeBinOp(Opcode)) {
3859       std::swap(N1, N2);
3860     } else {
3861       switch (Opcode) {
3862       case ISD::FP_ROUND_INREG:
3863       case ISD::SIGN_EXTEND_INREG:
3864       case ISD::SUB:
3865       case ISD::FSUB:
3866       case ISD::FDIV:
3867       case ISD::FREM:
3868       case ISD::SRA:
3869         return N1;     // fold op(undef, arg2) -> undef
3870       case ISD::UDIV:
3871       case ISD::SDIV:
3872       case ISD::UREM:
3873       case ISD::SREM:
3874       case ISD::SRL:
3875       case ISD::SHL:
3876         if (!VT.isVector())
3877           return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
3878         // For vectors, we can't easily build an all zero vector, just return
3879         // the LHS.
3880         return N2;
3881       }
3882     }
3883   }
3884 
3885   // Fold a bunch of operators when the RHS is undef.
3886   if (N2.isUndef()) {
3887     switch (Opcode) {
3888     case ISD::XOR:
3889       if (N1.isUndef())
3890         // Handle undef ^ undef -> 0 special case. This is a common
3891         // idiom (misuse).
3892         return getConstant(0, DL, VT);
3893       LLVM_FALLTHROUGH;
3894     case ISD::ADD:
3895     case ISD::ADDC:
3896     case ISD::ADDE:
3897     case ISD::SUB:
3898     case ISD::UDIV:
3899     case ISD::SDIV:
3900     case ISD::UREM:
3901     case ISD::SREM:
3902       return N2;       // fold op(arg1, undef) -> undef
3903     case ISD::FADD:
3904     case ISD::FSUB:
3905     case ISD::FMUL:
3906     case ISD::FDIV:
3907     case ISD::FREM:
3908       if (getTarget().Options.UnsafeFPMath)
3909         return N2;
3910       break;
3911     case ISD::MUL:
3912     case ISD::AND:
3913     case ISD::SRL:
3914     case ISD::SHL:
3915       if (!VT.isVector())
3916         return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
3917       // For vectors, we can't easily build an all zero vector, just return
3918       // the LHS.
3919       return N1;
3920     case ISD::OR:
3921       if (!VT.isVector())
3922         return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
3923       // For vectors, we can't easily build an all one vector, just return
3924       // the LHS.
3925       return N1;
3926     case ISD::SRA:
3927       return N1;
3928     }
3929   }
3930 
3931   // Memoize this node if possible.
3932   SDNode *N;
3933   SDVTList VTs = getVTList(VT);
3934   if (VT != MVT::Glue) {
3935     SDValue Ops[] = {N1, N2};
3936     FoldingSetNodeID ID;
3937     AddNodeIDNode(ID, Opcode, VTs, Ops);
3938     void *IP = nullptr;
3939     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
3940       if (Flags)
3941         E->intersectFlagsWith(Flags);
3942       return SDValue(E, 0);
3943     }
3944 
3945     N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags);
3946     CSEMap.InsertNode(N, IP);
3947   } else {
3948     N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags);
3949   }
3950 
3951   InsertNode(N);
3952   return SDValue(N, 0);
3953 }
3954 
3955 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3956                               SDValue N1, SDValue N2, SDValue N3) {
3957   // Perform various simplifications.
3958   switch (Opcode) {
3959   case ISD::FMA: {
3960     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3961     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
3962     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
3963     if (N1CFP && N2CFP && N3CFP) {
3964       APFloat  V1 = N1CFP->getValueAPF();
3965       const APFloat &V2 = N2CFP->getValueAPF();
3966       const APFloat &V3 = N3CFP->getValueAPF();
3967       APFloat::opStatus s =
3968         V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
3969       if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
3970         return getConstantFP(V1, DL, VT);
3971     }
3972     break;
3973   }
3974   case ISD::CONCAT_VECTORS: {
3975     // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
3976     SDValue Ops[] = {N1, N2, N3};
3977     if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
3978       return V;
3979     break;
3980   }
3981   case ISD::SETCC: {
3982     // Use FoldSetCC to simplify SETCC's.
3983     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
3984       return V;
3985     // Vector constant folding.
3986     SDValue Ops[] = {N1, N2, N3};
3987     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
3988       return V;
3989     break;
3990   }
3991   case ISD::SELECT:
3992     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
3993      if (N1C->getZExtValue())
3994        return N2;             // select true, X, Y -> X
3995      return N3;             // select false, X, Y -> Y
3996     }
3997 
3998     if (N2 == N3) return N2;   // select C, X, X -> X
3999     break;
4000   case ISD::VECTOR_SHUFFLE:
4001     llvm_unreachable("should use getVectorShuffle constructor!");
4002   case ISD::INSERT_SUBVECTOR: {
4003     SDValue Index = N3;
4004     if (VT.isSimple() && N1.getValueType().isSimple()
4005         && N2.getValueType().isSimple()) {
4006       assert(VT.isVector() && N1.getValueType().isVector() &&
4007              N2.getValueType().isVector() &&
4008              "Insert subvector VTs must be a vectors");
4009       assert(VT == N1.getValueType() &&
4010              "Dest and insert subvector source types must match!");
4011       assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
4012              "Insert subvector must be from smaller vector to larger vector!");
4013       if (isa<ConstantSDNode>(Index)) {
4014         assert((N2.getValueType().getVectorNumElements() +
4015                 cast<ConstantSDNode>(Index)->getZExtValue()
4016                 <= VT.getVectorNumElements())
4017                && "Insert subvector overflow!");
4018       }
4019 
4020       // Trivial insertion.
4021       if (VT.getSimpleVT() == N2.getSimpleValueType())
4022         return N2;
4023     }
4024     break;
4025   }
4026   case ISD::BITCAST:
4027     // Fold bit_convert nodes from a type to themselves.
4028     if (N1.getValueType() == VT)
4029       return N1;
4030     break;
4031   }
4032 
4033   // Memoize node if it doesn't produce a flag.
4034   SDNode *N;
4035   SDVTList VTs = getVTList(VT);
4036   SDValue Ops[] = {N1, N2, N3};
4037   if (VT != MVT::Glue) {
4038     FoldingSetNodeID ID;
4039     AddNodeIDNode(ID, Opcode, VTs, Ops);
4040     void *IP = nullptr;
4041     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4042       return SDValue(E, 0);
4043 
4044     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4045     createOperands(N, Ops);
4046     CSEMap.InsertNode(N, IP);
4047   } else {
4048     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4049     createOperands(N, Ops);
4050   }
4051 
4052   InsertNode(N);
4053   return SDValue(N, 0);
4054 }
4055 
4056 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4057                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
4058   SDValue Ops[] = { N1, N2, N3, N4 };
4059   return getNode(Opcode, DL, VT, Ops);
4060 }
4061 
4062 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4063                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
4064                               SDValue N5) {
4065   SDValue Ops[] = { N1, N2, N3, N4, N5 };
4066   return getNode(Opcode, DL, VT, Ops);
4067 }
4068 
4069 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
4070 /// the incoming stack arguments to be loaded from the stack.
4071 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
4072   SmallVector<SDValue, 8> ArgChains;
4073 
4074   // Include the original chain at the beginning of the list. When this is
4075   // used by target LowerCall hooks, this helps legalize find the
4076   // CALLSEQ_BEGIN node.
4077   ArgChains.push_back(Chain);
4078 
4079   // Add a chain value for each stack argument.
4080   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
4081        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
4082     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4083       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4084         if (FI->getIndex() < 0)
4085           ArgChains.push_back(SDValue(L, 1));
4086 
4087   // Build a tokenfactor for all the chains.
4088   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4089 }
4090 
4091 /// getMemsetValue - Vectorized representation of the memset value
4092 /// operand.
4093 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
4094                               const SDLoc &dl) {
4095   assert(!Value.isUndef());
4096 
4097   unsigned NumBits = VT.getScalarSizeInBits();
4098   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4099     assert(C->getAPIntValue().getBitWidth() == 8);
4100     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
4101     if (VT.isInteger())
4102       return DAG.getConstant(Val, dl, VT);
4103     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
4104                              VT);
4105   }
4106 
4107   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
4108   EVT IntVT = VT.getScalarType();
4109   if (!IntVT.isInteger())
4110     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
4111 
4112   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
4113   if (NumBits > 8) {
4114     // Use a multiplication with 0x010101... to extend the input to the
4115     // required length.
4116     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
4117     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
4118                         DAG.getConstant(Magic, dl, IntVT));
4119   }
4120 
4121   if (VT != Value.getValueType() && !VT.isInteger())
4122     Value = DAG.getBitcast(VT.getScalarType(), Value);
4123   if (VT != Value.getValueType())
4124     Value = DAG.getSplatBuildVector(VT, dl, Value);
4125 
4126   return Value;
4127 }
4128 
4129 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4130 /// used when a memcpy is turned into a memset when the source is a constant
4131 /// string ptr.
4132 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
4133                                   const TargetLowering &TLI, StringRef Str) {
4134   // Handle vector with all elements zero.
4135   if (Str.empty()) {
4136     if (VT.isInteger())
4137       return DAG.getConstant(0, dl, VT);
4138     else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
4139       return DAG.getConstantFP(0.0, dl, VT);
4140     else if (VT.isVector()) {
4141       unsigned NumElts = VT.getVectorNumElements();
4142       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
4143       return DAG.getNode(ISD::BITCAST, dl, VT,
4144                          DAG.getConstant(0, dl,
4145                                          EVT::getVectorVT(*DAG.getContext(),
4146                                                           EltVT, NumElts)));
4147     } else
4148       llvm_unreachable("Expected type!");
4149   }
4150 
4151   assert(!VT.isVector() && "Can't handle vector type here!");
4152   unsigned NumVTBits = VT.getSizeInBits();
4153   unsigned NumVTBytes = NumVTBits / 8;
4154   unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size()));
4155 
4156   APInt Val(NumVTBits, 0);
4157   if (DAG.getDataLayout().isLittleEndian()) {
4158     for (unsigned i = 0; i != NumBytes; ++i)
4159       Val |= (uint64_t)(unsigned char)Str[i] << i*8;
4160   } else {
4161     for (unsigned i = 0; i != NumBytes; ++i)
4162       Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8;
4163   }
4164 
4165   // If the "cost" of materializing the integer immediate is less than the cost
4166   // of a load, then it is cost effective to turn the load into the immediate.
4167   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
4168   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
4169     return DAG.getConstant(Val, dl, VT);
4170   return SDValue(nullptr, 0);
4171 }
4172 
4173 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
4174                                            const SDLoc &DL) {
4175   EVT VT = Base.getValueType();
4176   return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
4177 }
4178 
4179 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
4180 ///
4181 static bool isMemSrcFromString(SDValue Src, StringRef &Str) {
4182   uint64_t SrcDelta = 0;
4183   GlobalAddressSDNode *G = nullptr;
4184   if (Src.getOpcode() == ISD::GlobalAddress)
4185     G = cast<GlobalAddressSDNode>(Src);
4186   else if (Src.getOpcode() == ISD::ADD &&
4187            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4188            Src.getOperand(1).getOpcode() == ISD::Constant) {
4189     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
4190     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
4191   }
4192   if (!G)
4193     return false;
4194 
4195   return getConstantStringInfo(G->getGlobal(), Str,
4196                                SrcDelta + G->getOffset(), false);
4197 }
4198 
4199 /// Determines the optimal series of memory ops to replace the memset / memcpy.
4200 /// Return true if the number of memory ops is below the threshold (Limit).
4201 /// It returns the types of the sequence of memory ops to perform
4202 /// memset / memcpy by reference.
4203 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
4204                                      unsigned Limit, uint64_t Size,
4205                                      unsigned DstAlign, unsigned SrcAlign,
4206                                      bool IsMemset,
4207                                      bool ZeroMemset,
4208                                      bool MemcpyStrSrc,
4209                                      bool AllowOverlap,
4210                                      unsigned DstAS, unsigned SrcAS,
4211                                      SelectionDAG &DAG,
4212                                      const TargetLowering &TLI) {
4213   assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
4214          "Expecting memcpy / memset source to meet alignment requirement!");
4215   // If 'SrcAlign' is zero, that means the memory operation does not need to
4216   // load the value, i.e. memset or memcpy from constant string. Otherwise,
4217   // it's the inferred alignment of the source. 'DstAlign', on the other hand,
4218   // is the specified alignment of the memory operation. If it is zero, that
4219   // means it's possible to change the alignment of the destination.
4220   // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
4221   // not need to be loaded.
4222   EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
4223                                    IsMemset, ZeroMemset, MemcpyStrSrc,
4224                                    DAG.getMachineFunction());
4225 
4226   if (VT == MVT::Other) {
4227     if (DstAlign >= DAG.getDataLayout().getPointerPrefAlignment(DstAS) ||
4228         TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign)) {
4229       VT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
4230     } else {
4231       switch (DstAlign & 7) {
4232       case 0:  VT = MVT::i64; break;
4233       case 4:  VT = MVT::i32; break;
4234       case 2:  VT = MVT::i16; break;
4235       default: VT = MVT::i8;  break;
4236       }
4237     }
4238 
4239     MVT LVT = MVT::i64;
4240     while (!TLI.isTypeLegal(LVT))
4241       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
4242     assert(LVT.isInteger());
4243 
4244     if (VT.bitsGT(LVT))
4245       VT = LVT;
4246   }
4247 
4248   unsigned NumMemOps = 0;
4249   while (Size != 0) {
4250     unsigned VTSize = VT.getSizeInBits() / 8;
4251     while (VTSize > Size) {
4252       // For now, only use non-vector load / store's for the left-over pieces.
4253       EVT NewVT = VT;
4254       unsigned NewVTSize;
4255 
4256       bool Found = false;
4257       if (VT.isVector() || VT.isFloatingPoint()) {
4258         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
4259         if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
4260             TLI.isSafeMemOpType(NewVT.getSimpleVT()))
4261           Found = true;
4262         else if (NewVT == MVT::i64 &&
4263                  TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
4264                  TLI.isSafeMemOpType(MVT::f64)) {
4265           // i64 is usually not legal on 32-bit targets, but f64 may be.
4266           NewVT = MVT::f64;
4267           Found = true;
4268         }
4269       }
4270 
4271       if (!Found) {
4272         do {
4273           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
4274           if (NewVT == MVT::i8)
4275             break;
4276         } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
4277       }
4278       NewVTSize = NewVT.getSizeInBits() / 8;
4279 
4280       // If the new VT cannot cover all of the remaining bits, then consider
4281       // issuing a (or a pair of) unaligned and overlapping load / store.
4282       // FIXME: Only does this for 64-bit or more since we don't have proper
4283       // cost model for unaligned load / store.
4284       bool Fast;
4285       if (NumMemOps && AllowOverlap &&
4286           VTSize >= 8 && NewVTSize < Size &&
4287           TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast)
4288         VTSize = Size;
4289       else {
4290         VT = NewVT;
4291         VTSize = NewVTSize;
4292       }
4293     }
4294 
4295     if (++NumMemOps > Limit)
4296       return false;
4297 
4298     MemOps.push_back(VT);
4299     Size -= VTSize;
4300   }
4301 
4302   return true;
4303 }
4304 
4305 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
4306   // On Darwin, -Os means optimize for size without hurting performance, so
4307   // only really optimize for size when -Oz (MinSize) is used.
4308   if (MF.getTarget().getTargetTriple().isOSDarwin())
4309     return MF.getFunction()->optForMinSize();
4310   return MF.getFunction()->optForSize();
4311 }
4312 
4313 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4314                                        SDValue Chain, SDValue Dst, SDValue Src,
4315                                        uint64_t Size, unsigned Align,
4316                                        bool isVol, bool AlwaysInline,
4317                                        MachinePointerInfo DstPtrInfo,
4318                                        MachinePointerInfo SrcPtrInfo) {
4319   // Turn a memcpy of undef to nop.
4320   if (Src.isUndef())
4321     return Chain;
4322 
4323   // Expand memcpy to a series of load and store ops if the size operand falls
4324   // below a certain threshold.
4325   // TODO: In the AlwaysInline case, if the size is big then generate a loop
4326   // rather than maybe a humongous number of loads and stores.
4327   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4328   std::vector<EVT> MemOps;
4329   bool DstAlignCanChange = false;
4330   MachineFunction &MF = DAG.getMachineFunction();
4331   MachineFrameInfo &MFI = MF.getFrameInfo();
4332   bool OptSize = shouldLowerMemFuncForSize(MF);
4333   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4334   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4335     DstAlignCanChange = true;
4336   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4337   if (Align > SrcAlign)
4338     SrcAlign = Align;
4339   StringRef Str;
4340   bool CopyFromStr = isMemSrcFromString(Src, Str);
4341   bool isZeroStr = CopyFromStr && Str.empty();
4342   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
4343 
4344   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4345                                 (DstAlignCanChange ? 0 : Align),
4346                                 (isZeroStr ? 0 : SrcAlign),
4347                                 false, false, CopyFromStr, true,
4348                                 DstPtrInfo.getAddrSpace(),
4349                                 SrcPtrInfo.getAddrSpace(),
4350                                 DAG, TLI))
4351     return SDValue();
4352 
4353   if (DstAlignCanChange) {
4354     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4355     unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4356 
4357     // Don't promote to an alignment that would require dynamic stack
4358     // realignment.
4359     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4360     if (!TRI->needsStackRealignment(MF))
4361       while (NewAlign > Align &&
4362              DAG.getDataLayout().exceedsNaturalStackAlignment(NewAlign))
4363           NewAlign /= 2;
4364 
4365     if (NewAlign > Align) {
4366       // Give the stack frame object a larger alignment if needed.
4367       if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4368         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4369       Align = NewAlign;
4370     }
4371   }
4372 
4373   MachineMemOperand::Flags MMOFlags =
4374       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4375   SmallVector<SDValue, 8> OutChains;
4376   unsigned NumMemOps = MemOps.size();
4377   uint64_t SrcOff = 0, DstOff = 0;
4378   for (unsigned i = 0; i != NumMemOps; ++i) {
4379     EVT VT = MemOps[i];
4380     unsigned VTSize = VT.getSizeInBits() / 8;
4381     SDValue Value, Store;
4382 
4383     if (VTSize > Size) {
4384       // Issuing an unaligned load / store pair  that overlaps with the previous
4385       // pair. Adjust the offset accordingly.
4386       assert(i == NumMemOps-1 && i != 0);
4387       SrcOff -= VTSize - Size;
4388       DstOff -= VTSize - Size;
4389     }
4390 
4391     if (CopyFromStr &&
4392         (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
4393       // It's unlikely a store of a vector immediate can be done in a single
4394       // instruction. It would require a load from a constantpool first.
4395       // We only handle zero vectors here.
4396       // FIXME: Handle other cases where store of vector immediate is done in
4397       // a single instruction.
4398       Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff));
4399       if (Value.getNode())
4400         Store = DAG.getStore(Chain, dl, Value,
4401                              DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4402                              DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
4403     }
4404 
4405     if (!Store.getNode()) {
4406       // The type might not be legal for the target.  This should only happen
4407       // if the type is smaller than a legal type, as on PPC, so the right
4408       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
4409       // to Load/Store if NVT==VT.
4410       // FIXME does the case above also need this?
4411       EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
4412       assert(NVT.bitsGE(VT));
4413       Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
4414                              DAG.getMemBasePlusOffset(Src, SrcOff, dl),
4415                              SrcPtrInfo.getWithOffset(SrcOff), VT,
4416                              MinAlign(SrcAlign, SrcOff), MMOFlags);
4417       OutChains.push_back(Value.getValue(1));
4418       Store = DAG.getTruncStore(
4419           Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4420           DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
4421     }
4422     OutChains.push_back(Store);
4423     SrcOff += VTSize;
4424     DstOff += VTSize;
4425     Size -= VTSize;
4426   }
4427 
4428   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4429 }
4430 
4431 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4432                                         SDValue Chain, SDValue Dst, SDValue Src,
4433                                         uint64_t Size, unsigned Align,
4434                                         bool isVol, bool AlwaysInline,
4435                                         MachinePointerInfo DstPtrInfo,
4436                                         MachinePointerInfo SrcPtrInfo) {
4437   // Turn a memmove of undef to nop.
4438   if (Src.isUndef())
4439     return Chain;
4440 
4441   // Expand memmove to a series of load and store ops if the size operand falls
4442   // below a certain threshold.
4443   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4444   std::vector<EVT> MemOps;
4445   bool DstAlignCanChange = false;
4446   MachineFunction &MF = DAG.getMachineFunction();
4447   MachineFrameInfo &MFI = MF.getFrameInfo();
4448   bool OptSize = shouldLowerMemFuncForSize(MF);
4449   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4450   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4451     DstAlignCanChange = true;
4452   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4453   if (Align > SrcAlign)
4454     SrcAlign = Align;
4455   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
4456 
4457   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4458                                 (DstAlignCanChange ? 0 : Align), SrcAlign,
4459                                 false, false, false, false,
4460                                 DstPtrInfo.getAddrSpace(),
4461                                 SrcPtrInfo.getAddrSpace(),
4462                                 DAG, TLI))
4463     return SDValue();
4464 
4465   if (DstAlignCanChange) {
4466     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4467     unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4468     if (NewAlign > Align) {
4469       // Give the stack frame object a larger alignment if needed.
4470       if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4471         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4472       Align = NewAlign;
4473     }
4474   }
4475 
4476   MachineMemOperand::Flags MMOFlags =
4477       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4478   uint64_t SrcOff = 0, DstOff = 0;
4479   SmallVector<SDValue, 8> LoadValues;
4480   SmallVector<SDValue, 8> LoadChains;
4481   SmallVector<SDValue, 8> OutChains;
4482   unsigned NumMemOps = MemOps.size();
4483   for (unsigned i = 0; i < NumMemOps; i++) {
4484     EVT VT = MemOps[i];
4485     unsigned VTSize = VT.getSizeInBits() / 8;
4486     SDValue Value;
4487 
4488     Value =
4489         DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
4490                     SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, MMOFlags);
4491     LoadValues.push_back(Value);
4492     LoadChains.push_back(Value.getValue(1));
4493     SrcOff += VTSize;
4494   }
4495   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
4496   OutChains.clear();
4497   for (unsigned i = 0; i < NumMemOps; i++) {
4498     EVT VT = MemOps[i];
4499     unsigned VTSize = VT.getSizeInBits() / 8;
4500     SDValue Store;
4501 
4502     Store = DAG.getStore(Chain, dl, LoadValues[i],
4503                          DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4504                          DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
4505     OutChains.push_back(Store);
4506     DstOff += VTSize;
4507   }
4508 
4509   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4510 }
4511 
4512 /// \brief Lower the call to 'memset' intrinsic function into a series of store
4513 /// operations.
4514 ///
4515 /// \param DAG Selection DAG where lowered code is placed.
4516 /// \param dl Link to corresponding IR location.
4517 /// \param Chain Control flow dependency.
4518 /// \param Dst Pointer to destination memory location.
4519 /// \param Src Value of byte to write into the memory.
4520 /// \param Size Number of bytes to write.
4521 /// \param Align Alignment of the destination in bytes.
4522 /// \param isVol True if destination is volatile.
4523 /// \param DstPtrInfo IR information on the memory pointer.
4524 /// \returns New head in the control flow, if lowering was successful, empty
4525 /// SDValue otherwise.
4526 ///
4527 /// The function tries to replace 'llvm.memset' intrinsic with several store
4528 /// operations and value calculation code. This is usually profitable for small
4529 /// memory size.
4530 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
4531                                SDValue Chain, SDValue Dst, SDValue Src,
4532                                uint64_t Size, unsigned Align, bool isVol,
4533                                MachinePointerInfo DstPtrInfo) {
4534   // Turn a memset of undef to nop.
4535   if (Src.isUndef())
4536     return Chain;
4537 
4538   // Expand memset to a series of load/store ops if the size operand
4539   // falls below a certain threshold.
4540   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4541   std::vector<EVT> MemOps;
4542   bool DstAlignCanChange = false;
4543   MachineFunction &MF = DAG.getMachineFunction();
4544   MachineFrameInfo &MFI = MF.getFrameInfo();
4545   bool OptSize = shouldLowerMemFuncForSize(MF);
4546   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4547   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4548     DstAlignCanChange = true;
4549   bool IsZeroVal =
4550     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
4551   if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
4552                                 Size, (DstAlignCanChange ? 0 : Align), 0,
4553                                 true, IsZeroVal, false, true,
4554                                 DstPtrInfo.getAddrSpace(), ~0u,
4555                                 DAG, TLI))
4556     return SDValue();
4557 
4558   if (DstAlignCanChange) {
4559     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4560     unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4561     if (NewAlign > Align) {
4562       // Give the stack frame object a larger alignment if needed.
4563       if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4564         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4565       Align = NewAlign;
4566     }
4567   }
4568 
4569   SmallVector<SDValue, 8> OutChains;
4570   uint64_t DstOff = 0;
4571   unsigned NumMemOps = MemOps.size();
4572 
4573   // Find the largest store and generate the bit pattern for it.
4574   EVT LargestVT = MemOps[0];
4575   for (unsigned i = 1; i < NumMemOps; i++)
4576     if (MemOps[i].bitsGT(LargestVT))
4577       LargestVT = MemOps[i];
4578   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
4579 
4580   for (unsigned i = 0; i < NumMemOps; i++) {
4581     EVT VT = MemOps[i];
4582     unsigned VTSize = VT.getSizeInBits() / 8;
4583     if (VTSize > Size) {
4584       // Issuing an unaligned load / store pair  that overlaps with the previous
4585       // pair. Adjust the offset accordingly.
4586       assert(i == NumMemOps-1 && i != 0);
4587       DstOff -= VTSize - Size;
4588     }
4589 
4590     // If this store is smaller than the largest store see whether we can get
4591     // the smaller value for free with a truncate.
4592     SDValue Value = MemSetValue;
4593     if (VT.bitsLT(LargestVT)) {
4594       if (!LargestVT.isVector() && !VT.isVector() &&
4595           TLI.isTruncateFree(LargestVT, VT))
4596         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
4597       else
4598         Value = getMemsetValue(Src, VT, DAG, dl);
4599     }
4600     assert(Value.getValueType() == VT && "Value with wrong type.");
4601     SDValue Store = DAG.getStore(
4602         Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4603         DstPtrInfo.getWithOffset(DstOff), Align,
4604         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
4605     OutChains.push_back(Store);
4606     DstOff += VT.getSizeInBits() / 8;
4607     Size -= VTSize;
4608   }
4609 
4610   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4611 }
4612 
4613 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
4614                                             unsigned AS) {
4615   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
4616   // pointer operands can be losslessly bitcasted to pointers of address space 0
4617   if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
4618     report_fatal_error("cannot lower memory intrinsic in address space " +
4619                        Twine(AS));
4620   }
4621 }
4622 
4623 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
4624                                 SDValue Src, SDValue Size, unsigned Align,
4625                                 bool isVol, bool AlwaysInline, bool isTailCall,
4626                                 MachinePointerInfo DstPtrInfo,
4627                                 MachinePointerInfo SrcPtrInfo) {
4628   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4629 
4630   // Check to see if we should lower the memcpy to loads and stores first.
4631   // For cases within the target-specified limits, this is the best choice.
4632   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4633   if (ConstantSize) {
4634     // Memcpy with size zero? Just return the original chain.
4635     if (ConstantSize->isNullValue())
4636       return Chain;
4637 
4638     SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
4639                                              ConstantSize->getZExtValue(),Align,
4640                                 isVol, false, DstPtrInfo, SrcPtrInfo);
4641     if (Result.getNode())
4642       return Result;
4643   }
4644 
4645   // Then check to see if we should lower the memcpy with target-specific
4646   // code. If the target chooses to do this, this is the next best.
4647   if (TSI) {
4648     SDValue Result = TSI->EmitTargetCodeForMemcpy(
4649         *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
4650         DstPtrInfo, SrcPtrInfo);
4651     if (Result.getNode())
4652       return Result;
4653   }
4654 
4655   // If we really need inline code and the target declined to provide it,
4656   // use a (potentially long) sequence of loads and stores.
4657   if (AlwaysInline) {
4658     assert(ConstantSize && "AlwaysInline requires a constant size!");
4659     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
4660                                    ConstantSize->getZExtValue(), Align, isVol,
4661                                    true, DstPtrInfo, SrcPtrInfo);
4662   }
4663 
4664   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
4665   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
4666 
4667   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
4668   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
4669   // respect volatile, so they may do things like read or write memory
4670   // beyond the given memory regions. But fixing this isn't easy, and most
4671   // people don't care.
4672 
4673   // Emit a library call.
4674   TargetLowering::ArgListTy Args;
4675   TargetLowering::ArgListEntry Entry;
4676   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
4677   Entry.Node = Dst; Args.push_back(Entry);
4678   Entry.Node = Src; Args.push_back(Entry);
4679   Entry.Node = Size; Args.push_back(Entry);
4680   // FIXME: pass in SDLoc
4681   TargetLowering::CallLoweringInfo CLI(*this);
4682   CLI.setDebugLoc(dl)
4683       .setChain(Chain)
4684       .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
4685                  Dst.getValueType().getTypeForEVT(*getContext()),
4686                  getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
4687                                    TLI->getPointerTy(getDataLayout())),
4688                  std::move(Args))
4689       .setDiscardResult()
4690       .setTailCall(isTailCall);
4691 
4692   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4693   return CallResult.second;
4694 }
4695 
4696 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
4697                                  SDValue Src, SDValue Size, unsigned Align,
4698                                  bool isVol, bool isTailCall,
4699                                  MachinePointerInfo DstPtrInfo,
4700                                  MachinePointerInfo SrcPtrInfo) {
4701   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4702 
4703   // Check to see if we should lower the memmove to loads and stores first.
4704   // For cases within the target-specified limits, this is the best choice.
4705   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4706   if (ConstantSize) {
4707     // Memmove with size zero? Just return the original chain.
4708     if (ConstantSize->isNullValue())
4709       return Chain;
4710 
4711     SDValue Result =
4712       getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
4713                                ConstantSize->getZExtValue(), Align, isVol,
4714                                false, DstPtrInfo, SrcPtrInfo);
4715     if (Result.getNode())
4716       return Result;
4717   }
4718 
4719   // Then check to see if we should lower the memmove with target-specific
4720   // code. If the target chooses to do this, this is the next best.
4721   if (TSI) {
4722     SDValue Result = TSI->EmitTargetCodeForMemmove(
4723         *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
4724     if (Result.getNode())
4725       return Result;
4726   }
4727 
4728   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
4729   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
4730 
4731   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
4732   // not be safe.  See memcpy above for more details.
4733 
4734   // Emit a library call.
4735   TargetLowering::ArgListTy Args;
4736   TargetLowering::ArgListEntry Entry;
4737   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
4738   Entry.Node = Dst; Args.push_back(Entry);
4739   Entry.Node = Src; Args.push_back(Entry);
4740   Entry.Node = Size; Args.push_back(Entry);
4741   // FIXME:  pass in SDLoc
4742   TargetLowering::CallLoweringInfo CLI(*this);
4743   CLI.setDebugLoc(dl)
4744       .setChain(Chain)
4745       .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
4746                  Dst.getValueType().getTypeForEVT(*getContext()),
4747                  getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
4748                                    TLI->getPointerTy(getDataLayout())),
4749                  std::move(Args))
4750       .setDiscardResult()
4751       .setTailCall(isTailCall);
4752 
4753   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4754   return CallResult.second;
4755 }
4756 
4757 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
4758                                 SDValue Src, SDValue Size, unsigned Align,
4759                                 bool isVol, bool isTailCall,
4760                                 MachinePointerInfo DstPtrInfo) {
4761   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4762 
4763   // Check to see if we should lower the memset to stores first.
4764   // For cases within the target-specified limits, this is the best choice.
4765   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4766   if (ConstantSize) {
4767     // Memset with size zero? Just return the original chain.
4768     if (ConstantSize->isNullValue())
4769       return Chain;
4770 
4771     SDValue Result =
4772       getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
4773                       Align, isVol, DstPtrInfo);
4774 
4775     if (Result.getNode())
4776       return Result;
4777   }
4778 
4779   // Then check to see if we should lower the memset with target-specific
4780   // code. If the target chooses to do this, this is the next best.
4781   if (TSI) {
4782     SDValue Result = TSI->EmitTargetCodeForMemset(
4783         *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
4784     if (Result.getNode())
4785       return Result;
4786   }
4787 
4788   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
4789 
4790   // Emit a library call.
4791   Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
4792   TargetLowering::ArgListTy Args;
4793   TargetLowering::ArgListEntry Entry;
4794   Entry.Node = Dst; Entry.Ty = IntPtrTy;
4795   Args.push_back(Entry);
4796   Entry.Node = Src;
4797   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
4798   Args.push_back(Entry);
4799   Entry.Node = Size;
4800   Entry.Ty = IntPtrTy;
4801   Args.push_back(Entry);
4802 
4803   // FIXME: pass in SDLoc
4804   TargetLowering::CallLoweringInfo CLI(*this);
4805   CLI.setDebugLoc(dl)
4806       .setChain(Chain)
4807       .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
4808                  Dst.getValueType().getTypeForEVT(*getContext()),
4809                  getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
4810                                    TLI->getPointerTy(getDataLayout())),
4811                  std::move(Args))
4812       .setDiscardResult()
4813       .setTailCall(isTailCall);
4814 
4815   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4816   return CallResult.second;
4817 }
4818 
4819 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
4820                                 SDVTList VTList, ArrayRef<SDValue> Ops,
4821                                 MachineMemOperand *MMO) {
4822   FoldingSetNodeID ID;
4823   ID.AddInteger(MemVT.getRawBits());
4824   AddNodeIDNode(ID, Opcode, VTList, Ops);
4825   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4826   void* IP = nullptr;
4827   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
4828     cast<AtomicSDNode>(E)->refineAlignment(MMO);
4829     return SDValue(E, 0);
4830   }
4831 
4832   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
4833                                     VTList, MemVT, MMO);
4834   createOperands(N, Ops);
4835 
4836   CSEMap.InsertNode(N, IP);
4837   InsertNode(N);
4838   return SDValue(N, 0);
4839 }
4840 
4841 SDValue SelectionDAG::getAtomicCmpSwap(
4842     unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
4843     SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
4844     unsigned Alignment, AtomicOrdering SuccessOrdering,
4845     AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) {
4846   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
4847          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
4848   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
4849 
4850   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4851     Alignment = getEVTAlignment(MemVT);
4852 
4853   MachineFunction &MF = getMachineFunction();
4854 
4855   // FIXME: Volatile isn't really correct; we should keep track of atomic
4856   // orderings in the memoperand.
4857   auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
4858                MachineMemOperand::MOStore;
4859   MachineMemOperand *MMO =
4860     MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
4861                             AAMDNodes(), nullptr, SynchScope, SuccessOrdering,
4862                             FailureOrdering);
4863 
4864   return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO);
4865 }
4866 
4867 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
4868                                        EVT MemVT, SDVTList VTs, SDValue Chain,
4869                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
4870                                        MachineMemOperand *MMO) {
4871   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
4872          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
4873   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
4874 
4875   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
4876   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
4877 }
4878 
4879 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
4880                                 SDValue Chain, SDValue Ptr, SDValue Val,
4881                                 const Value *PtrVal, unsigned Alignment,
4882                                 AtomicOrdering Ordering,
4883                                 SynchronizationScope SynchScope) {
4884   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4885     Alignment = getEVTAlignment(MemVT);
4886 
4887   MachineFunction &MF = getMachineFunction();
4888   // An atomic store does not load. An atomic load does not store.
4889   // (An atomicrmw obviously both loads and stores.)
4890   // For now, atomics are considered to be volatile always, and they are
4891   // chained as such.
4892   // FIXME: Volatile isn't really correct; we should keep track of atomic
4893   // orderings in the memoperand.
4894   auto Flags = MachineMemOperand::MOVolatile;
4895   if (Opcode != ISD::ATOMIC_STORE)
4896     Flags |= MachineMemOperand::MOLoad;
4897   if (Opcode != ISD::ATOMIC_LOAD)
4898     Flags |= MachineMemOperand::MOStore;
4899 
4900   MachineMemOperand *MMO =
4901     MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
4902                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4903                             nullptr, SynchScope, Ordering);
4904 
4905   return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
4906 }
4907 
4908 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
4909                                 SDValue Chain, SDValue Ptr, SDValue Val,
4910                                 MachineMemOperand *MMO) {
4911   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
4912           Opcode == ISD::ATOMIC_LOAD_SUB ||
4913           Opcode == ISD::ATOMIC_LOAD_AND ||
4914           Opcode == ISD::ATOMIC_LOAD_OR ||
4915           Opcode == ISD::ATOMIC_LOAD_XOR ||
4916           Opcode == ISD::ATOMIC_LOAD_NAND ||
4917           Opcode == ISD::ATOMIC_LOAD_MIN ||
4918           Opcode == ISD::ATOMIC_LOAD_MAX ||
4919           Opcode == ISD::ATOMIC_LOAD_UMIN ||
4920           Opcode == ISD::ATOMIC_LOAD_UMAX ||
4921           Opcode == ISD::ATOMIC_SWAP ||
4922           Opcode == ISD::ATOMIC_STORE) &&
4923          "Invalid Atomic Op");
4924 
4925   EVT VT = Val.getValueType();
4926 
4927   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
4928                                                getVTList(VT, MVT::Other);
4929   SDValue Ops[] = {Chain, Ptr, Val};
4930   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
4931 }
4932 
4933 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
4934                                 EVT VT, SDValue Chain, SDValue Ptr,
4935                                 MachineMemOperand *MMO) {
4936   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
4937 
4938   SDVTList VTs = getVTList(VT, MVT::Other);
4939   SDValue Ops[] = {Chain, Ptr};
4940   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
4941 }
4942 
4943 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
4944 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
4945   if (Ops.size() == 1)
4946     return Ops[0];
4947 
4948   SmallVector<EVT, 4> VTs;
4949   VTs.reserve(Ops.size());
4950   for (unsigned i = 0; i < Ops.size(); ++i)
4951     VTs.push_back(Ops[i].getValueType());
4952   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
4953 }
4954 
4955 SDValue SelectionDAG::getMemIntrinsicNode(
4956     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
4957     EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol,
4958     bool ReadMem, bool WriteMem, unsigned Size) {
4959   if (Align == 0)  // Ensure that codegen never sees alignment 0
4960     Align = getEVTAlignment(MemVT);
4961 
4962   MachineFunction &MF = getMachineFunction();
4963   auto Flags = MachineMemOperand::MONone;
4964   if (WriteMem)
4965     Flags |= MachineMemOperand::MOStore;
4966   if (ReadMem)
4967     Flags |= MachineMemOperand::MOLoad;
4968   if (Vol)
4969     Flags |= MachineMemOperand::MOVolatile;
4970   if (!Size)
4971     Size = MemVT.getStoreSize();
4972   MachineMemOperand *MMO =
4973     MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
4974 
4975   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
4976 }
4977 
4978 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
4979                                           SDVTList VTList,
4980                                           ArrayRef<SDValue> Ops, EVT MemVT,
4981                                           MachineMemOperand *MMO) {
4982   assert((Opcode == ISD::INTRINSIC_VOID ||
4983           Opcode == ISD::INTRINSIC_W_CHAIN ||
4984           Opcode == ISD::PREFETCH ||
4985           Opcode == ISD::LIFETIME_START ||
4986           Opcode == ISD::LIFETIME_END ||
4987           (Opcode <= INT_MAX &&
4988            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
4989          "Opcode is not a memory-accessing opcode!");
4990 
4991   // Memoize the node unless it returns a flag.
4992   MemIntrinsicSDNode *N;
4993   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4994     FoldingSetNodeID ID;
4995     AddNodeIDNode(ID, Opcode, VTList, Ops);
4996     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4997     void *IP = nullptr;
4998     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
4999       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
5000       return SDValue(E, 0);
5001     }
5002 
5003     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5004                                       VTList, MemVT, MMO);
5005     createOperands(N, Ops);
5006 
5007   CSEMap.InsertNode(N, IP);
5008   } else {
5009     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5010                                       VTList, MemVT, MMO);
5011     createOperands(N, Ops);
5012   }
5013   InsertNode(N);
5014   return SDValue(N, 0);
5015 }
5016 
5017 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5018 /// MachinePointerInfo record from it.  This is particularly useful because the
5019 /// code generator has many cases where it doesn't bother passing in a
5020 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5021 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5022                                            int64_t Offset = 0) {
5023   // If this is FI+Offset, we can model it.
5024   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
5025     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
5026                                              FI->getIndex(), Offset);
5027 
5028   // If this is (FI+Offset1)+Offset2, we can model it.
5029   if (Ptr.getOpcode() != ISD::ADD ||
5030       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
5031       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
5032     return MachinePointerInfo();
5033 
5034   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5035   return MachinePointerInfo::getFixedStack(
5036       DAG.getMachineFunction(), FI,
5037       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
5038 }
5039 
5040 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5041 /// MachinePointerInfo record from it.  This is particularly useful because the
5042 /// code generator has many cases where it doesn't bother passing in a
5043 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5044 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5045                                            SDValue OffsetOp) {
5046   // If the 'Offset' value isn't a constant, we can't handle this.
5047   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
5048     return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue());
5049   if (OffsetOp.isUndef())
5050     return InferPointerInfo(DAG, Ptr);
5051   return MachinePointerInfo();
5052 }
5053 
5054 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5055                               EVT VT, const SDLoc &dl, SDValue Chain,
5056                               SDValue Ptr, SDValue Offset,
5057                               MachinePointerInfo PtrInfo, EVT MemVT,
5058                               unsigned Alignment,
5059                               MachineMemOperand::Flags MMOFlags,
5060                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
5061   assert(Chain.getValueType() == MVT::Other &&
5062         "Invalid chain type");
5063   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
5064     Alignment = getEVTAlignment(MemVT);
5065 
5066   MMOFlags |= MachineMemOperand::MOLoad;
5067   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
5068   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
5069   // clients.
5070   if (PtrInfo.V.isNull())
5071     PtrInfo = InferPointerInfo(*this, Ptr, Offset);
5072 
5073   MachineFunction &MF = getMachineFunction();
5074   MachineMemOperand *MMO = MF.getMachineMemOperand(
5075       PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
5076   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
5077 }
5078 
5079 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5080                               EVT VT, const SDLoc &dl, SDValue Chain,
5081                               SDValue Ptr, SDValue Offset, EVT MemVT,
5082                               MachineMemOperand *MMO) {
5083   if (VT == MemVT) {
5084     ExtType = ISD::NON_EXTLOAD;
5085   } else if (ExtType == ISD::NON_EXTLOAD) {
5086     assert(VT == MemVT && "Non-extending load from different memory type!");
5087   } else {
5088     // Extending load.
5089     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
5090            "Should only be an extending load, not truncating!");
5091     assert(VT.isInteger() == MemVT.isInteger() &&
5092            "Cannot convert from FP to Int or Int -> FP!");
5093     assert(VT.isVector() == MemVT.isVector() &&
5094            "Cannot use an ext load to convert to or from a vector!");
5095     assert((!VT.isVector() ||
5096             VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
5097            "Cannot use an ext load to change the number of vector elements!");
5098   }
5099 
5100   bool Indexed = AM != ISD::UNINDEXED;
5101   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
5102 
5103   SDVTList VTs = Indexed ?
5104     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
5105   SDValue Ops[] = { Chain, Ptr, Offset };
5106   FoldingSetNodeID ID;
5107   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
5108   ID.AddInteger(MemVT.getRawBits());
5109   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
5110       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
5111   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5112   void *IP = nullptr;
5113   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5114     cast<LoadSDNode>(E)->refineAlignment(MMO);
5115     return SDValue(E, 0);
5116   }
5117   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5118                                   ExtType, MemVT, MMO);
5119   createOperands(N, Ops);
5120 
5121   CSEMap.InsertNode(N, IP);
5122   InsertNode(N);
5123   return SDValue(N, 0);
5124 }
5125 
5126 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5127                               SDValue Ptr, MachinePointerInfo PtrInfo,
5128                               unsigned Alignment,
5129                               MachineMemOperand::Flags MMOFlags,
5130                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
5131   SDValue Undef = getUNDEF(Ptr.getValueType());
5132   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5133                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
5134 }
5135 
5136 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5137                               SDValue Ptr, MachineMemOperand *MMO) {
5138   SDValue Undef = getUNDEF(Ptr.getValueType());
5139   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5140                  VT, MMO);
5141 }
5142 
5143 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5144                                  EVT VT, SDValue Chain, SDValue Ptr,
5145                                  MachinePointerInfo PtrInfo, EVT MemVT,
5146                                  unsigned Alignment,
5147                                  MachineMemOperand::Flags MMOFlags,
5148                                  const AAMDNodes &AAInfo) {
5149   SDValue Undef = getUNDEF(Ptr.getValueType());
5150   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
5151                  MemVT, Alignment, MMOFlags, AAInfo);
5152 }
5153 
5154 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5155                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
5156                                  MachineMemOperand *MMO) {
5157   SDValue Undef = getUNDEF(Ptr.getValueType());
5158   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
5159                  MemVT, MMO);
5160 }
5161 
5162 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
5163                                      SDValue Base, SDValue Offset,
5164                                      ISD::MemIndexedMode AM) {
5165   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
5166   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
5167   // Don't propagate the invariant or dereferenceable flags.
5168   auto MMOFlags =
5169       LD->getMemOperand()->getFlags() &
5170       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5171   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
5172                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
5173                  LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
5174                  LD->getAAInfo());
5175 }
5176 
5177 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5178                                SDValue Ptr, MachinePointerInfo PtrInfo,
5179                                unsigned Alignment,
5180                                MachineMemOperand::Flags MMOFlags,
5181                                const AAMDNodes &AAInfo) {
5182   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
5183   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
5184     Alignment = getEVTAlignment(Val.getValueType());
5185 
5186   MMOFlags |= MachineMemOperand::MOStore;
5187   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5188 
5189   if (PtrInfo.V.isNull())
5190     PtrInfo = InferPointerInfo(*this, Ptr);
5191 
5192   MachineFunction &MF = getMachineFunction();
5193   MachineMemOperand *MMO = MF.getMachineMemOperand(
5194       PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
5195   return getStore(Chain, dl, Val, Ptr, MMO);
5196 }
5197 
5198 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5199                                SDValue Ptr, MachineMemOperand *MMO) {
5200   assert(Chain.getValueType() == MVT::Other &&
5201         "Invalid chain type");
5202   EVT VT = Val.getValueType();
5203   SDVTList VTs = getVTList(MVT::Other);
5204   SDValue Undef = getUNDEF(Ptr.getValueType());
5205   SDValue Ops[] = { Chain, Val, Ptr, Undef };
5206   FoldingSetNodeID ID;
5207   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5208   ID.AddInteger(VT.getRawBits());
5209   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5210       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
5211   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5212   void *IP = nullptr;
5213   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5214     cast<StoreSDNode>(E)->refineAlignment(MMO);
5215     return SDValue(E, 0);
5216   }
5217   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5218                                    ISD::UNINDEXED, false, VT, MMO);
5219   createOperands(N, Ops);
5220 
5221   CSEMap.InsertNode(N, IP);
5222   InsertNode(N);
5223   return SDValue(N, 0);
5224 }
5225 
5226 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5227                                     SDValue Ptr, MachinePointerInfo PtrInfo,
5228                                     EVT SVT, unsigned Alignment,
5229                                     MachineMemOperand::Flags MMOFlags,
5230                                     const AAMDNodes &AAInfo) {
5231   assert(Chain.getValueType() == MVT::Other &&
5232         "Invalid chain type");
5233   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
5234     Alignment = getEVTAlignment(SVT);
5235 
5236   MMOFlags |= MachineMemOperand::MOStore;
5237   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5238 
5239   if (PtrInfo.V.isNull())
5240     PtrInfo = InferPointerInfo(*this, Ptr);
5241 
5242   MachineFunction &MF = getMachineFunction();
5243   MachineMemOperand *MMO = MF.getMachineMemOperand(
5244       PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
5245   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
5246 }
5247 
5248 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5249                                     SDValue Ptr, EVT SVT,
5250                                     MachineMemOperand *MMO) {
5251   EVT VT = Val.getValueType();
5252 
5253   assert(Chain.getValueType() == MVT::Other &&
5254         "Invalid chain type");
5255   if (VT == SVT)
5256     return getStore(Chain, dl, Val, Ptr, MMO);
5257 
5258   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
5259          "Should only be a truncating store, not extending!");
5260   assert(VT.isInteger() == SVT.isInteger() &&
5261          "Can't do FP-INT conversion!");
5262   assert(VT.isVector() == SVT.isVector() &&
5263          "Cannot use trunc store to convert to or from a vector!");
5264   assert((!VT.isVector() ||
5265           VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
5266          "Cannot use trunc store to change the number of vector elements!");
5267 
5268   SDVTList VTs = getVTList(MVT::Other);
5269   SDValue Undef = getUNDEF(Ptr.getValueType());
5270   SDValue Ops[] = { Chain, Val, Ptr, Undef };
5271   FoldingSetNodeID ID;
5272   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5273   ID.AddInteger(SVT.getRawBits());
5274   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5275       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
5276   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5277   void *IP = nullptr;
5278   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5279     cast<StoreSDNode>(E)->refineAlignment(MMO);
5280     return SDValue(E, 0);
5281   }
5282   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5283                                    ISD::UNINDEXED, true, SVT, MMO);
5284   createOperands(N, Ops);
5285 
5286   CSEMap.InsertNode(N, IP);
5287   InsertNode(N);
5288   return SDValue(N, 0);
5289 }
5290 
5291 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
5292                                       SDValue Base, SDValue Offset,
5293                                       ISD::MemIndexedMode AM) {
5294   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
5295   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
5296   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
5297   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
5298   FoldingSetNodeID ID;
5299   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5300   ID.AddInteger(ST->getMemoryVT().getRawBits());
5301   ID.AddInteger(ST->getRawSubclassData());
5302   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
5303   void *IP = nullptr;
5304   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
5305     return SDValue(E, 0);
5306 
5307   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5308                                    ST->isTruncatingStore(), ST->getMemoryVT(),
5309                                    ST->getMemOperand());
5310   createOperands(N, Ops);
5311 
5312   CSEMap.InsertNode(N, IP);
5313   InsertNode(N);
5314   return SDValue(N, 0);
5315 }
5316 
5317 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5318                                     SDValue Ptr, SDValue Mask, SDValue Src0,
5319                                     EVT MemVT, MachineMemOperand *MMO,
5320                                     ISD::LoadExtType ExtTy, bool isExpanding) {
5321 
5322   SDVTList VTs = getVTList(VT, MVT::Other);
5323   SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
5324   FoldingSetNodeID ID;
5325   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
5326   ID.AddInteger(VT.getRawBits());
5327   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
5328       dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
5329   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5330   void *IP = nullptr;
5331   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5332     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
5333     return SDValue(E, 0);
5334   }
5335   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5336                                         ExtTy, isExpanding, MemVT, MMO);
5337   createOperands(N, Ops);
5338 
5339   CSEMap.InsertNode(N, IP);
5340   InsertNode(N);
5341   return SDValue(N, 0);
5342 }
5343 
5344 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
5345                                      SDValue Val, SDValue Ptr, SDValue Mask,
5346                                      EVT MemVT, MachineMemOperand *MMO,
5347                                      bool IsTruncating, bool IsCompressing) {
5348   assert(Chain.getValueType() == MVT::Other &&
5349         "Invalid chain type");
5350   EVT VT = Val.getValueType();
5351   SDVTList VTs = getVTList(MVT::Other);
5352   SDValue Ops[] = { Chain, Ptr, Mask, Val };
5353   FoldingSetNodeID ID;
5354   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
5355   ID.AddInteger(VT.getRawBits());
5356   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
5357       dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
5358   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5359   void *IP = nullptr;
5360   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5361     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
5362     return SDValue(E, 0);
5363   }
5364   auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5365                                          IsTruncating, IsCompressing, MemVT, MMO);
5366   createOperands(N, Ops);
5367 
5368   CSEMap.InsertNode(N, IP);
5369   InsertNode(N);
5370   return SDValue(N, 0);
5371 }
5372 
5373 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
5374                                       ArrayRef<SDValue> Ops,
5375                                       MachineMemOperand *MMO) {
5376   assert(Ops.size() == 5 && "Incompatible number of operands");
5377 
5378   FoldingSetNodeID ID;
5379   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
5380   ID.AddInteger(VT.getRawBits());
5381   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
5382       dl.getIROrder(), VTs, VT, MMO));
5383   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5384   void *IP = nullptr;
5385   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5386     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
5387     return SDValue(E, 0);
5388   }
5389 
5390   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5391                                           VTs, VT, MMO);
5392   createOperands(N, Ops);
5393 
5394   assert(N->getValue().getValueType() == N->getValueType(0) &&
5395          "Incompatible type of the PassThru value in MaskedGatherSDNode");
5396   assert(N->getMask().getValueType().getVectorNumElements() ==
5397              N->getValueType(0).getVectorNumElements() &&
5398          "Vector width mismatch between mask and data");
5399   assert(N->getIndex().getValueType().getVectorNumElements() ==
5400              N->getValueType(0).getVectorNumElements() &&
5401          "Vector width mismatch between index and data");
5402 
5403   CSEMap.InsertNode(N, IP);
5404   InsertNode(N);
5405   return SDValue(N, 0);
5406 }
5407 
5408 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
5409                                        ArrayRef<SDValue> Ops,
5410                                        MachineMemOperand *MMO) {
5411   assert(Ops.size() == 5 && "Incompatible number of operands");
5412 
5413   FoldingSetNodeID ID;
5414   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
5415   ID.AddInteger(VT.getRawBits());
5416   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
5417       dl.getIROrder(), VTs, VT, MMO));
5418   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5419   void *IP = nullptr;
5420   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5421     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
5422     return SDValue(E, 0);
5423   }
5424   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5425                                            VTs, VT, MMO);
5426   createOperands(N, Ops);
5427 
5428   assert(N->getMask().getValueType().getVectorNumElements() ==
5429              N->getValue().getValueType().getVectorNumElements() &&
5430          "Vector width mismatch between mask and data");
5431   assert(N->getIndex().getValueType().getVectorNumElements() ==
5432              N->getValue().getValueType().getVectorNumElements() &&
5433          "Vector width mismatch between index and data");
5434 
5435   CSEMap.InsertNode(N, IP);
5436   InsertNode(N);
5437   return SDValue(N, 0);
5438 }
5439 
5440 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
5441                                SDValue Ptr, SDValue SV, unsigned Align) {
5442   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
5443   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
5444 }
5445 
5446 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5447                               ArrayRef<SDUse> Ops) {
5448   switch (Ops.size()) {
5449   case 0: return getNode(Opcode, DL, VT);
5450   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
5451   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
5452   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5453   default: break;
5454   }
5455 
5456   // Copy from an SDUse array into an SDValue array for use with
5457   // the regular getNode logic.
5458   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
5459   return getNode(Opcode, DL, VT, NewOps);
5460 }
5461 
5462 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5463                               ArrayRef<SDValue> Ops, const SDNodeFlags *Flags) {
5464   unsigned NumOps = Ops.size();
5465   switch (NumOps) {
5466   case 0: return getNode(Opcode, DL, VT);
5467   case 1: return getNode(Opcode, DL, VT, Ops[0]);
5468   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
5469   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5470   default: break;
5471   }
5472 
5473   switch (Opcode) {
5474   default: break;
5475   case ISD::CONCAT_VECTORS: {
5476     // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
5477     if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
5478       return V;
5479     break;
5480   }
5481   case ISD::SELECT_CC: {
5482     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
5483     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
5484            "LHS and RHS of condition must have same type!");
5485     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
5486            "True and False arms of SelectCC must have same type!");
5487     assert(Ops[2].getValueType() == VT &&
5488            "select_cc node must be of same type as true and false value!");
5489     break;
5490   }
5491   case ISD::BR_CC: {
5492     assert(NumOps == 5 && "BR_CC takes 5 operands!");
5493     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
5494            "LHS/RHS of comparison should match types!");
5495     break;
5496   }
5497   }
5498 
5499   // Memoize nodes.
5500   SDNode *N;
5501   SDVTList VTs = getVTList(VT);
5502 
5503   if (VT != MVT::Glue) {
5504     FoldingSetNodeID ID;
5505     AddNodeIDNode(ID, Opcode, VTs, Ops);
5506     void *IP = nullptr;
5507 
5508     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5509       return SDValue(E, 0);
5510 
5511     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5512     createOperands(N, Ops);
5513 
5514     CSEMap.InsertNode(N, IP);
5515   } else {
5516     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5517     createOperands(N, Ops);
5518   }
5519 
5520   InsertNode(N);
5521   return SDValue(N, 0);
5522 }
5523 
5524 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
5525                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
5526   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
5527 }
5528 
5529 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
5530                               ArrayRef<SDValue> Ops) {
5531   if (VTList.NumVTs == 1)
5532     return getNode(Opcode, DL, VTList.VTs[0], Ops);
5533 
5534 #if 0
5535   switch (Opcode) {
5536   // FIXME: figure out how to safely handle things like
5537   // int foo(int x) { return 1 << (x & 255); }
5538   // int bar() { return foo(256); }
5539   case ISD::SRA_PARTS:
5540   case ISD::SRL_PARTS:
5541   case ISD::SHL_PARTS:
5542     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5543         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
5544       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
5545     else if (N3.getOpcode() == ISD::AND)
5546       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
5547         // If the and is only masking out bits that cannot effect the shift,
5548         // eliminate the and.
5549         unsigned NumBits = VT.getScalarSizeInBits()*2;
5550         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
5551           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
5552       }
5553     break;
5554   }
5555 #endif
5556 
5557   // Memoize the node unless it returns a flag.
5558   SDNode *N;
5559   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5560     FoldingSetNodeID ID;
5561     AddNodeIDNode(ID, Opcode, VTList, Ops);
5562     void *IP = nullptr;
5563     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5564       return SDValue(E, 0);
5565 
5566     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
5567     createOperands(N, Ops);
5568     CSEMap.InsertNode(N, IP);
5569   } else {
5570     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
5571     createOperands(N, Ops);
5572   }
5573   InsertNode(N);
5574   return SDValue(N, 0);
5575 }
5576 
5577 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
5578                               SDVTList VTList) {
5579   return getNode(Opcode, DL, VTList, None);
5580 }
5581 
5582 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
5583                               SDValue N1) {
5584   SDValue Ops[] = { N1 };
5585   return getNode(Opcode, DL, VTList, Ops);
5586 }
5587 
5588 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
5589                               SDValue N1, SDValue N2) {
5590   SDValue Ops[] = { N1, N2 };
5591   return getNode(Opcode, DL, VTList, Ops);
5592 }
5593 
5594 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
5595                               SDValue N1, SDValue N2, SDValue N3) {
5596   SDValue Ops[] = { N1, N2, N3 };
5597   return getNode(Opcode, DL, VTList, Ops);
5598 }
5599 
5600 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
5601                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
5602   SDValue Ops[] = { N1, N2, N3, N4 };
5603   return getNode(Opcode, DL, VTList, Ops);
5604 }
5605 
5606 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
5607                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
5608                               SDValue N5) {
5609   SDValue Ops[] = { N1, N2, N3, N4, N5 };
5610   return getNode(Opcode, DL, VTList, Ops);
5611 }
5612 
5613 SDVTList SelectionDAG::getVTList(EVT VT) {
5614   return makeVTList(SDNode::getValueTypeList(VT), 1);
5615 }
5616 
5617 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
5618   FoldingSetNodeID ID;
5619   ID.AddInteger(2U);
5620   ID.AddInteger(VT1.getRawBits());
5621   ID.AddInteger(VT2.getRawBits());
5622 
5623   void *IP = nullptr;
5624   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5625   if (!Result) {
5626     EVT *Array = Allocator.Allocate<EVT>(2);
5627     Array[0] = VT1;
5628     Array[1] = VT2;
5629     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
5630     VTListMap.InsertNode(Result, IP);
5631   }
5632   return Result->getSDVTList();
5633 }
5634 
5635 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
5636   FoldingSetNodeID ID;
5637   ID.AddInteger(3U);
5638   ID.AddInteger(VT1.getRawBits());
5639   ID.AddInteger(VT2.getRawBits());
5640   ID.AddInteger(VT3.getRawBits());
5641 
5642   void *IP = nullptr;
5643   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5644   if (!Result) {
5645     EVT *Array = Allocator.Allocate<EVT>(3);
5646     Array[0] = VT1;
5647     Array[1] = VT2;
5648     Array[2] = VT3;
5649     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
5650     VTListMap.InsertNode(Result, IP);
5651   }
5652   return Result->getSDVTList();
5653 }
5654 
5655 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
5656   FoldingSetNodeID ID;
5657   ID.AddInteger(4U);
5658   ID.AddInteger(VT1.getRawBits());
5659   ID.AddInteger(VT2.getRawBits());
5660   ID.AddInteger(VT3.getRawBits());
5661   ID.AddInteger(VT4.getRawBits());
5662 
5663   void *IP = nullptr;
5664   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5665   if (!Result) {
5666     EVT *Array = Allocator.Allocate<EVT>(4);
5667     Array[0] = VT1;
5668     Array[1] = VT2;
5669     Array[2] = VT3;
5670     Array[3] = VT4;
5671     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
5672     VTListMap.InsertNode(Result, IP);
5673   }
5674   return Result->getSDVTList();
5675 }
5676 
5677 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
5678   unsigned NumVTs = VTs.size();
5679   FoldingSetNodeID ID;
5680   ID.AddInteger(NumVTs);
5681   for (unsigned index = 0; index < NumVTs; index++) {
5682     ID.AddInteger(VTs[index].getRawBits());
5683   }
5684 
5685   void *IP = nullptr;
5686   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5687   if (!Result) {
5688     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
5689     std::copy(VTs.begin(), VTs.end(), Array);
5690     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
5691     VTListMap.InsertNode(Result, IP);
5692   }
5693   return Result->getSDVTList();
5694 }
5695 
5696 
5697 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
5698 /// specified operands.  If the resultant node already exists in the DAG,
5699 /// this does not modify the specified node, instead it returns the node that
5700 /// already exists.  If the resultant node does not exist in the DAG, the
5701 /// input node is returned.  As a degenerate case, if you specify the same
5702 /// input operands as the node already has, the input node is returned.
5703 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
5704   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
5705 
5706   // Check to see if there is no change.
5707   if (Op == N->getOperand(0)) return N;
5708 
5709   // See if the modified node already exists.
5710   void *InsertPos = nullptr;
5711   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
5712     return Existing;
5713 
5714   // Nope it doesn't.  Remove the node from its current place in the maps.
5715   if (InsertPos)
5716     if (!RemoveNodeFromCSEMaps(N))
5717       InsertPos = nullptr;
5718 
5719   // Now we update the operands.
5720   N->OperandList[0].set(Op);
5721 
5722   // If this gets put into a CSE map, add it.
5723   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5724   return N;
5725 }
5726 
5727 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
5728   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
5729 
5730   // Check to see if there is no change.
5731   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
5732     return N;   // No operands changed, just return the input node.
5733 
5734   // See if the modified node already exists.
5735   void *InsertPos = nullptr;
5736   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
5737     return Existing;
5738 
5739   // Nope it doesn't.  Remove the node from its current place in the maps.
5740   if (InsertPos)
5741     if (!RemoveNodeFromCSEMaps(N))
5742       InsertPos = nullptr;
5743 
5744   // Now we update the operands.
5745   if (N->OperandList[0] != Op1)
5746     N->OperandList[0].set(Op1);
5747   if (N->OperandList[1] != Op2)
5748     N->OperandList[1].set(Op2);
5749 
5750   // If this gets put into a CSE map, add it.
5751   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5752   return N;
5753 }
5754 
5755 SDNode *SelectionDAG::
5756 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
5757   SDValue Ops[] = { Op1, Op2, Op3 };
5758   return UpdateNodeOperands(N, Ops);
5759 }
5760 
5761 SDNode *SelectionDAG::
5762 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
5763                    SDValue Op3, SDValue Op4) {
5764   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
5765   return UpdateNodeOperands(N, Ops);
5766 }
5767 
5768 SDNode *SelectionDAG::
5769 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
5770                    SDValue Op3, SDValue Op4, SDValue Op5) {
5771   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
5772   return UpdateNodeOperands(N, Ops);
5773 }
5774 
5775 SDNode *SelectionDAG::
5776 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
5777   unsigned NumOps = Ops.size();
5778   assert(N->getNumOperands() == NumOps &&
5779          "Update with wrong number of operands");
5780 
5781   // If no operands changed just return the input node.
5782   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
5783     return N;
5784 
5785   // See if the modified node already exists.
5786   void *InsertPos = nullptr;
5787   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
5788     return Existing;
5789 
5790   // Nope it doesn't.  Remove the node from its current place in the maps.
5791   if (InsertPos)
5792     if (!RemoveNodeFromCSEMaps(N))
5793       InsertPos = nullptr;
5794 
5795   // Now we update the operands.
5796   for (unsigned i = 0; i != NumOps; ++i)
5797     if (N->OperandList[i] != Ops[i])
5798       N->OperandList[i].set(Ops[i]);
5799 
5800   // If this gets put into a CSE map, add it.
5801   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5802   return N;
5803 }
5804 
5805 /// DropOperands - Release the operands and set this node to have
5806 /// zero operands.
5807 void SDNode::DropOperands() {
5808   // Unlike the code in MorphNodeTo that does this, we don't need to
5809   // watch for dead nodes here.
5810   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
5811     SDUse &Use = *I++;
5812     Use.set(SDValue());
5813   }
5814 }
5815 
5816 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
5817 /// machine opcode.
5818 ///
5819 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5820                                    EVT VT) {
5821   SDVTList VTs = getVTList(VT);
5822   return SelectNodeTo(N, MachineOpc, VTs, None);
5823 }
5824 
5825 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5826                                    EVT VT, SDValue Op1) {
5827   SDVTList VTs = getVTList(VT);
5828   SDValue Ops[] = { Op1 };
5829   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5830 }
5831 
5832 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5833                                    EVT VT, SDValue Op1,
5834                                    SDValue Op2) {
5835   SDVTList VTs = getVTList(VT);
5836   SDValue Ops[] = { Op1, Op2 };
5837   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5838 }
5839 
5840 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5841                                    EVT VT, SDValue Op1,
5842                                    SDValue Op2, SDValue Op3) {
5843   SDVTList VTs = getVTList(VT);
5844   SDValue Ops[] = { Op1, Op2, Op3 };
5845   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5846 }
5847 
5848 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5849                                    EVT VT, ArrayRef<SDValue> Ops) {
5850   SDVTList VTs = getVTList(VT);
5851   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5852 }
5853 
5854 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5855                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
5856   SDVTList VTs = getVTList(VT1, VT2);
5857   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5858 }
5859 
5860 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5861                                    EVT VT1, EVT VT2) {
5862   SDVTList VTs = getVTList(VT1, VT2);
5863   return SelectNodeTo(N, MachineOpc, VTs, None);
5864 }
5865 
5866 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5867                                    EVT VT1, EVT VT2, EVT VT3,
5868                                    ArrayRef<SDValue> Ops) {
5869   SDVTList VTs = getVTList(VT1, VT2, VT3);
5870   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5871 }
5872 
5873 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5874                                    EVT VT1, EVT VT2,
5875                                    SDValue Op1, SDValue Op2) {
5876   SDVTList VTs = getVTList(VT1, VT2);
5877   SDValue Ops[] = { Op1, Op2 };
5878   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5879 }
5880 
5881 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5882                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
5883   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
5884   // Reset the NodeID to -1.
5885   New->setNodeId(-1);
5886   if (New != N) {
5887     ReplaceAllUsesWith(N, New);
5888     RemoveDeadNode(N);
5889   }
5890   return New;
5891 }
5892 
5893 /// UpdadeSDLocOnMergedSDNode - If the opt level is -O0 then it throws away
5894 /// the line number information on the merged node since it is not possible to
5895 /// preserve the information that operation is associated with multiple lines.
5896 /// This will make the debugger working better at -O0, were there is a higher
5897 /// probability having other instructions associated with that line.
5898 ///
5899 /// For IROrder, we keep the smaller of the two
5900 SDNode *SelectionDAG::UpdadeSDLocOnMergedSDNode(SDNode *N, const SDLoc &OLoc) {
5901   DebugLoc NLoc = N->getDebugLoc();
5902   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
5903     N->setDebugLoc(DebugLoc());
5904   }
5905   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
5906   N->setIROrder(Order);
5907   return N;
5908 }
5909 
5910 /// MorphNodeTo - This *mutates* the specified node to have the specified
5911 /// return type, opcode, and operands.
5912 ///
5913 /// Note that MorphNodeTo returns the resultant node.  If there is already a
5914 /// node of the specified opcode and operands, it returns that node instead of
5915 /// the current one.  Note that the SDLoc need not be the same.
5916 ///
5917 /// Using MorphNodeTo is faster than creating a new node and swapping it in
5918 /// with ReplaceAllUsesWith both because it often avoids allocating a new
5919 /// node, and because it doesn't require CSE recalculation for any of
5920 /// the node's users.
5921 ///
5922 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
5923 /// As a consequence it isn't appropriate to use from within the DAG combiner or
5924 /// the legalizer which maintain worklists that would need to be updated when
5925 /// deleting things.
5926 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
5927                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
5928   // If an identical node already exists, use it.
5929   void *IP = nullptr;
5930   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
5931     FoldingSetNodeID ID;
5932     AddNodeIDNode(ID, Opc, VTs, Ops);
5933     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
5934       return UpdadeSDLocOnMergedSDNode(ON, SDLoc(N));
5935   }
5936 
5937   if (!RemoveNodeFromCSEMaps(N))
5938     IP = nullptr;
5939 
5940   // Start the morphing.
5941   N->NodeType = Opc;
5942   N->ValueList = VTs.VTs;
5943   N->NumValues = VTs.NumVTs;
5944 
5945   // Clear the operands list, updating used nodes to remove this from their
5946   // use list.  Keep track of any operands that become dead as a result.
5947   SmallPtrSet<SDNode*, 16> DeadNodeSet;
5948   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
5949     SDUse &Use = *I++;
5950     SDNode *Used = Use.getNode();
5951     Use.set(SDValue());
5952     if (Used->use_empty())
5953       DeadNodeSet.insert(Used);
5954   }
5955 
5956   // For MachineNode, initialize the memory references information.
5957   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
5958     MN->setMemRefs(nullptr, nullptr);
5959 
5960   // Swap for an appropriately sized array from the recycler.
5961   removeOperands(N);
5962   createOperands(N, Ops);
5963 
5964   // Delete any nodes that are still dead after adding the uses for the
5965   // new operands.
5966   if (!DeadNodeSet.empty()) {
5967     SmallVector<SDNode *, 16> DeadNodes;
5968     for (SDNode *N : DeadNodeSet)
5969       if (N->use_empty())
5970         DeadNodes.push_back(N);
5971     RemoveDeadNodes(DeadNodes);
5972   }
5973 
5974   if (IP)
5975     CSEMap.InsertNode(N, IP);   // Memoize the new node.
5976   return N;
5977 }
5978 
5979 
5980 /// getMachineNode - These are used for target selectors to create a new node
5981 /// with specified return type(s), MachineInstr opcode, and operands.
5982 ///
5983 /// Note that getMachineNode returns the resultant node.  If there is already a
5984 /// node of the specified opcode and operands, it returns that node instead of
5985 /// the current one.
5986 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
5987                                             EVT VT) {
5988   SDVTList VTs = getVTList(VT);
5989   return getMachineNode(Opcode, dl, VTs, None);
5990 }
5991 
5992 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
5993                                             EVT VT, SDValue Op1) {
5994   SDVTList VTs = getVTList(VT);
5995   SDValue Ops[] = { Op1 };
5996   return getMachineNode(Opcode, dl, VTs, Ops);
5997 }
5998 
5999 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6000                                             EVT VT, SDValue Op1, SDValue Op2) {
6001   SDVTList VTs = getVTList(VT);
6002   SDValue Ops[] = { Op1, Op2 };
6003   return getMachineNode(Opcode, dl, VTs, Ops);
6004 }
6005 
6006 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6007                                             EVT VT, SDValue Op1, SDValue Op2,
6008                                             SDValue Op3) {
6009   SDVTList VTs = getVTList(VT);
6010   SDValue Ops[] = { Op1, Op2, Op3 };
6011   return getMachineNode(Opcode, dl, VTs, Ops);
6012 }
6013 
6014 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6015                                             EVT VT, ArrayRef<SDValue> Ops) {
6016   SDVTList VTs = getVTList(VT);
6017   return getMachineNode(Opcode, dl, VTs, Ops);
6018 }
6019 
6020 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6021                                             EVT VT1, EVT VT2, SDValue Op1,
6022                                             SDValue Op2) {
6023   SDVTList VTs = getVTList(VT1, VT2);
6024   SDValue Ops[] = { Op1, Op2 };
6025   return getMachineNode(Opcode, dl, VTs, Ops);
6026 }
6027 
6028 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6029                                             EVT VT1, EVT VT2, SDValue Op1,
6030                                             SDValue Op2, SDValue Op3) {
6031   SDVTList VTs = getVTList(VT1, VT2);
6032   SDValue Ops[] = { Op1, Op2, Op3 };
6033   return getMachineNode(Opcode, dl, VTs, Ops);
6034 }
6035 
6036 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6037                                             EVT VT1, EVT VT2,
6038                                             ArrayRef<SDValue> Ops) {
6039   SDVTList VTs = getVTList(VT1, VT2);
6040   return getMachineNode(Opcode, dl, VTs, Ops);
6041 }
6042 
6043 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6044                                             EVT VT1, EVT VT2, EVT VT3,
6045                                             SDValue Op1, SDValue Op2) {
6046   SDVTList VTs = getVTList(VT1, VT2, VT3);
6047   SDValue Ops[] = { Op1, Op2 };
6048   return getMachineNode(Opcode, dl, VTs, Ops);
6049 }
6050 
6051 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6052                                             EVT VT1, EVT VT2, EVT VT3,
6053                                             SDValue Op1, SDValue Op2,
6054                                             SDValue Op3) {
6055   SDVTList VTs = getVTList(VT1, VT2, VT3);
6056   SDValue Ops[] = { Op1, Op2, Op3 };
6057   return getMachineNode(Opcode, dl, VTs, Ops);
6058 }
6059 
6060 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6061                                             EVT VT1, EVT VT2, EVT VT3,
6062                                             ArrayRef<SDValue> Ops) {
6063   SDVTList VTs = getVTList(VT1, VT2, VT3);
6064   return getMachineNode(Opcode, dl, VTs, Ops);
6065 }
6066 
6067 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6068                                             ArrayRef<EVT> ResultTys,
6069                                             ArrayRef<SDValue> Ops) {
6070   SDVTList VTs = getVTList(ResultTys);
6071   return getMachineNode(Opcode, dl, VTs, Ops);
6072 }
6073 
6074 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
6075                                             SDVTList VTs,
6076                                             ArrayRef<SDValue> Ops) {
6077   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
6078   MachineSDNode *N;
6079   void *IP = nullptr;
6080 
6081   if (DoCSE) {
6082     FoldingSetNodeID ID;
6083     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
6084     IP = nullptr;
6085     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6086       return cast<MachineSDNode>(UpdadeSDLocOnMergedSDNode(E, DL));
6087     }
6088   }
6089 
6090   // Allocate a new MachineSDNode.
6091   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6092   createOperands(N, Ops);
6093 
6094   if (DoCSE)
6095     CSEMap.InsertNode(N, IP);
6096 
6097   InsertNode(N);
6098   return N;
6099 }
6100 
6101 /// getTargetExtractSubreg - A convenience function for creating
6102 /// TargetOpcode::EXTRACT_SUBREG nodes.
6103 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6104                                              SDValue Operand) {
6105   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6106   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
6107                                   VT, Operand, SRIdxVal);
6108   return SDValue(Subreg, 0);
6109 }
6110 
6111 /// getTargetInsertSubreg - A convenience function for creating
6112 /// TargetOpcode::INSERT_SUBREG nodes.
6113 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6114                                             SDValue Operand, SDValue Subreg) {
6115   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6116   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
6117                                   VT, Operand, Subreg, SRIdxVal);
6118   return SDValue(Result, 0);
6119 }
6120 
6121 /// getNodeIfExists - Get the specified node if it's already available, or
6122 /// else return NULL.
6123 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
6124                                       ArrayRef<SDValue> Ops,
6125                                       const SDNodeFlags *Flags) {
6126   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
6127     FoldingSetNodeID ID;
6128     AddNodeIDNode(ID, Opcode, VTList, Ops);
6129     void *IP = nullptr;
6130     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
6131       if (Flags)
6132         E->intersectFlagsWith(Flags);
6133       return E;
6134     }
6135   }
6136   return nullptr;
6137 }
6138 
6139 /// getDbgValue - Creates a SDDbgValue node.
6140 ///
6141 /// SDNode
6142 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N,
6143                                       unsigned R, bool IsIndirect, uint64_t Off,
6144                                       const DebugLoc &DL, unsigned O) {
6145   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6146          "Expected inlined-at fields to agree");
6147   return new (DbgInfo->getAlloc())
6148       SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O);
6149 }
6150 
6151 /// Constant
6152 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr,
6153                                               const Value *C, uint64_t Off,
6154                                               const DebugLoc &DL, unsigned O) {
6155   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6156          "Expected inlined-at fields to agree");
6157   return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O);
6158 }
6159 
6160 /// FrameIndex
6161 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr,
6162                                                 unsigned FI, uint64_t Off,
6163                                                 const DebugLoc &DL,
6164                                                 unsigned O) {
6165   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6166          "Expected inlined-at fields to agree");
6167   return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O);
6168 }
6169 
6170 namespace {
6171 
6172 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
6173 /// pointed to by a use iterator is deleted, increment the use iterator
6174 /// so that it doesn't dangle.
6175 ///
6176 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
6177   SDNode::use_iterator &UI;
6178   SDNode::use_iterator &UE;
6179 
6180   void NodeDeleted(SDNode *N, SDNode *E) override {
6181     // Increment the iterator as needed.
6182     while (UI != UE && N == *UI)
6183       ++UI;
6184   }
6185 
6186 public:
6187   RAUWUpdateListener(SelectionDAG &d,
6188                      SDNode::use_iterator &ui,
6189                      SDNode::use_iterator &ue)
6190     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
6191 };
6192 
6193 }
6194 
6195 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6196 /// This can cause recursive merging of nodes in the DAG.
6197 ///
6198 /// This version assumes From has a single result value.
6199 ///
6200 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
6201   SDNode *From = FromN.getNode();
6202   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
6203          "Cannot replace with this method!");
6204   assert(From != To.getNode() && "Cannot replace uses of with self");
6205 
6206   // Preserve Debug Values
6207   TransferDbgValues(FromN, To);
6208 
6209   // Iterate over all the existing uses of From. New uses will be added
6210   // to the beginning of the use list, which we avoid visiting.
6211   // This specifically avoids visiting uses of From that arise while the
6212   // replacement is happening, because any such uses would be the result
6213   // of CSE: If an existing node looks like From after one of its operands
6214   // is replaced by To, we don't want to replace of all its users with To
6215   // too. See PR3018 for more info.
6216   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6217   RAUWUpdateListener Listener(*this, UI, UE);
6218   while (UI != UE) {
6219     SDNode *User = *UI;
6220 
6221     // This node is about to morph, remove its old self from the CSE maps.
6222     RemoveNodeFromCSEMaps(User);
6223 
6224     // A user can appear in a use list multiple times, and when this
6225     // happens the uses are usually next to each other in the list.
6226     // To help reduce the number of CSE recomputations, process all
6227     // the uses of this user that we can find this way.
6228     do {
6229       SDUse &Use = UI.getUse();
6230       ++UI;
6231       Use.set(To);
6232     } while (UI != UE && *UI == User);
6233 
6234     // Now that we have modified User, add it back to the CSE maps.  If it
6235     // already exists there, recursively merge the results together.
6236     AddModifiedNodeToCSEMaps(User);
6237   }
6238 
6239 
6240   // If we just RAUW'd the root, take note.
6241   if (FromN == getRoot())
6242     setRoot(To);
6243 }
6244 
6245 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6246 /// This can cause recursive merging of nodes in the DAG.
6247 ///
6248 /// This version assumes that for each value of From, there is a
6249 /// corresponding value in To in the same position with the same type.
6250 ///
6251 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
6252 #ifndef NDEBUG
6253   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6254     assert((!From->hasAnyUseOfValue(i) ||
6255             From->getValueType(i) == To->getValueType(i)) &&
6256            "Cannot use this version of ReplaceAllUsesWith!");
6257 #endif
6258 
6259   // Handle the trivial case.
6260   if (From == To)
6261     return;
6262 
6263   // Preserve Debug Info. Only do this if there's a use.
6264   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6265     if (From->hasAnyUseOfValue(i)) {
6266       assert((i < To->getNumValues()) && "Invalid To location");
6267       TransferDbgValues(SDValue(From, i), SDValue(To, i));
6268     }
6269 
6270   // Iterate over just the existing users of From. See the comments in
6271   // the ReplaceAllUsesWith above.
6272   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6273   RAUWUpdateListener Listener(*this, UI, UE);
6274   while (UI != UE) {
6275     SDNode *User = *UI;
6276 
6277     // This node is about to morph, remove its old self from the CSE maps.
6278     RemoveNodeFromCSEMaps(User);
6279 
6280     // A user can appear in a use list multiple times, and when this
6281     // happens the uses are usually next to each other in the list.
6282     // To help reduce the number of CSE recomputations, process all
6283     // the uses of this user that we can find this way.
6284     do {
6285       SDUse &Use = UI.getUse();
6286       ++UI;
6287       Use.setNode(To);
6288     } while (UI != UE && *UI == User);
6289 
6290     // Now that we have modified User, add it back to the CSE maps.  If it
6291     // already exists there, recursively merge the results together.
6292     AddModifiedNodeToCSEMaps(User);
6293   }
6294 
6295   // If we just RAUW'd the root, take note.
6296   if (From == getRoot().getNode())
6297     setRoot(SDValue(To, getRoot().getResNo()));
6298 }
6299 
6300 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6301 /// This can cause recursive merging of nodes in the DAG.
6302 ///
6303 /// This version can replace From with any result values.  To must match the
6304 /// number and types of values returned by From.
6305 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
6306   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
6307     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
6308 
6309   // Preserve Debug Info.
6310   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6311     TransferDbgValues(SDValue(From, i), *To);
6312 
6313   // Iterate over just the existing users of From. See the comments in
6314   // the ReplaceAllUsesWith above.
6315   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6316   RAUWUpdateListener Listener(*this, UI, UE);
6317   while (UI != UE) {
6318     SDNode *User = *UI;
6319 
6320     // This node is about to morph, remove its old self from the CSE maps.
6321     RemoveNodeFromCSEMaps(User);
6322 
6323     // A user can appear in a use list multiple times, and when this
6324     // happens the uses are usually next to each other in the list.
6325     // To help reduce the number of CSE recomputations, process all
6326     // the uses of this user that we can find this way.
6327     do {
6328       SDUse &Use = UI.getUse();
6329       const SDValue &ToOp = To[Use.getResNo()];
6330       ++UI;
6331       Use.set(ToOp);
6332     } while (UI != UE && *UI == User);
6333 
6334     // Now that we have modified User, add it back to the CSE maps.  If it
6335     // already exists there, recursively merge the results together.
6336     AddModifiedNodeToCSEMaps(User);
6337   }
6338 
6339   // If we just RAUW'd the root, take note.
6340   if (From == getRoot().getNode())
6341     setRoot(SDValue(To[getRoot().getResNo()]));
6342 }
6343 
6344 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
6345 /// uses of other values produced by From.getNode() alone.  The Deleted
6346 /// vector is handled the same way as for ReplaceAllUsesWith.
6347 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
6348   // Handle the really simple, really trivial case efficiently.
6349   if (From == To) return;
6350 
6351   // Handle the simple, trivial, case efficiently.
6352   if (From.getNode()->getNumValues() == 1) {
6353     ReplaceAllUsesWith(From, To);
6354     return;
6355   }
6356 
6357   // Preserve Debug Info.
6358   TransferDbgValues(From, To);
6359 
6360   // Iterate over just the existing users of From. See the comments in
6361   // the ReplaceAllUsesWith above.
6362   SDNode::use_iterator UI = From.getNode()->use_begin(),
6363                        UE = From.getNode()->use_end();
6364   RAUWUpdateListener Listener(*this, UI, UE);
6365   while (UI != UE) {
6366     SDNode *User = *UI;
6367     bool UserRemovedFromCSEMaps = false;
6368 
6369     // A user can appear in a use list multiple times, and when this
6370     // happens the uses are usually next to each other in the list.
6371     // To help reduce the number of CSE recomputations, process all
6372     // the uses of this user that we can find this way.
6373     do {
6374       SDUse &Use = UI.getUse();
6375 
6376       // Skip uses of different values from the same node.
6377       if (Use.getResNo() != From.getResNo()) {
6378         ++UI;
6379         continue;
6380       }
6381 
6382       // If this node hasn't been modified yet, it's still in the CSE maps,
6383       // so remove its old self from the CSE maps.
6384       if (!UserRemovedFromCSEMaps) {
6385         RemoveNodeFromCSEMaps(User);
6386         UserRemovedFromCSEMaps = true;
6387       }
6388 
6389       ++UI;
6390       Use.set(To);
6391     } while (UI != UE && *UI == User);
6392 
6393     // We are iterating over all uses of the From node, so if a use
6394     // doesn't use the specific value, no changes are made.
6395     if (!UserRemovedFromCSEMaps)
6396       continue;
6397 
6398     // Now that we have modified User, add it back to the CSE maps.  If it
6399     // already exists there, recursively merge the results together.
6400     AddModifiedNodeToCSEMaps(User);
6401   }
6402 
6403   // If we just RAUW'd the root, take note.
6404   if (From == getRoot())
6405     setRoot(To);
6406 }
6407 
6408 namespace {
6409   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
6410   /// to record information about a use.
6411   struct UseMemo {
6412     SDNode *User;
6413     unsigned Index;
6414     SDUse *Use;
6415   };
6416 
6417   /// operator< - Sort Memos by User.
6418   bool operator<(const UseMemo &L, const UseMemo &R) {
6419     return (intptr_t)L.User < (intptr_t)R.User;
6420   }
6421 }
6422 
6423 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
6424 /// uses of other values produced by From.getNode() alone.  The same value
6425 /// may appear in both the From and To list.  The Deleted vector is
6426 /// handled the same way as for ReplaceAllUsesWith.
6427 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
6428                                               const SDValue *To,
6429                                               unsigned Num){
6430   // Handle the simple, trivial case efficiently.
6431   if (Num == 1)
6432     return ReplaceAllUsesOfValueWith(*From, *To);
6433 
6434   TransferDbgValues(*From, *To);
6435 
6436   // Read up all the uses and make records of them. This helps
6437   // processing new uses that are introduced during the
6438   // replacement process.
6439   SmallVector<UseMemo, 4> Uses;
6440   for (unsigned i = 0; i != Num; ++i) {
6441     unsigned FromResNo = From[i].getResNo();
6442     SDNode *FromNode = From[i].getNode();
6443     for (SDNode::use_iterator UI = FromNode->use_begin(),
6444          E = FromNode->use_end(); UI != E; ++UI) {
6445       SDUse &Use = UI.getUse();
6446       if (Use.getResNo() == FromResNo) {
6447         UseMemo Memo = { *UI, i, &Use };
6448         Uses.push_back(Memo);
6449       }
6450     }
6451   }
6452 
6453   // Sort the uses, so that all the uses from a given User are together.
6454   std::sort(Uses.begin(), Uses.end());
6455 
6456   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
6457        UseIndex != UseIndexEnd; ) {
6458     // We know that this user uses some value of From.  If it is the right
6459     // value, update it.
6460     SDNode *User = Uses[UseIndex].User;
6461 
6462     // This node is about to morph, remove its old self from the CSE maps.
6463     RemoveNodeFromCSEMaps(User);
6464 
6465     // The Uses array is sorted, so all the uses for a given User
6466     // are next to each other in the list.
6467     // To help reduce the number of CSE recomputations, process all
6468     // the uses of this user that we can find this way.
6469     do {
6470       unsigned i = Uses[UseIndex].Index;
6471       SDUse &Use = *Uses[UseIndex].Use;
6472       ++UseIndex;
6473 
6474       Use.set(To[i]);
6475     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
6476 
6477     // Now that we have modified User, add it back to the CSE maps.  If it
6478     // already exists there, recursively merge the results together.
6479     AddModifiedNodeToCSEMaps(User);
6480   }
6481 }
6482 
6483 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
6484 /// based on their topological order. It returns the maximum id and a vector
6485 /// of the SDNodes* in assigned order by reference.
6486 unsigned SelectionDAG::AssignTopologicalOrder() {
6487 
6488   unsigned DAGSize = 0;
6489 
6490   // SortedPos tracks the progress of the algorithm. Nodes before it are
6491   // sorted, nodes after it are unsorted. When the algorithm completes
6492   // it is at the end of the list.
6493   allnodes_iterator SortedPos = allnodes_begin();
6494 
6495   // Visit all the nodes. Move nodes with no operands to the front of
6496   // the list immediately. Annotate nodes that do have operands with their
6497   // operand count. Before we do this, the Node Id fields of the nodes
6498   // may contain arbitrary values. After, the Node Id fields for nodes
6499   // before SortedPos will contain the topological sort index, and the
6500   // Node Id fields for nodes At SortedPos and after will contain the
6501   // count of outstanding operands.
6502   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
6503     SDNode *N = &*I++;
6504     checkForCycles(N, this);
6505     unsigned Degree = N->getNumOperands();
6506     if (Degree == 0) {
6507       // A node with no uses, add it to the result array immediately.
6508       N->setNodeId(DAGSize++);
6509       allnodes_iterator Q(N);
6510       if (Q != SortedPos)
6511         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
6512       assert(SortedPos != AllNodes.end() && "Overran node list");
6513       ++SortedPos;
6514     } else {
6515       // Temporarily use the Node Id as scratch space for the degree count.
6516       N->setNodeId(Degree);
6517     }
6518   }
6519 
6520   // Visit all the nodes. As we iterate, move nodes into sorted order,
6521   // such that by the time the end is reached all nodes will be sorted.
6522   for (SDNode &Node : allnodes()) {
6523     SDNode *N = &Node;
6524     checkForCycles(N, this);
6525     // N is in sorted position, so all its uses have one less operand
6526     // that needs to be sorted.
6527     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6528          UI != UE; ++UI) {
6529       SDNode *P = *UI;
6530       unsigned Degree = P->getNodeId();
6531       assert(Degree != 0 && "Invalid node degree");
6532       --Degree;
6533       if (Degree == 0) {
6534         // All of P's operands are sorted, so P may sorted now.
6535         P->setNodeId(DAGSize++);
6536         if (P->getIterator() != SortedPos)
6537           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
6538         assert(SortedPos != AllNodes.end() && "Overran node list");
6539         ++SortedPos;
6540       } else {
6541         // Update P's outstanding operand count.
6542         P->setNodeId(Degree);
6543       }
6544     }
6545     if (Node.getIterator() == SortedPos) {
6546 #ifndef NDEBUG
6547       allnodes_iterator I(N);
6548       SDNode *S = &*++I;
6549       dbgs() << "Overran sorted position:\n";
6550       S->dumprFull(this); dbgs() << "\n";
6551       dbgs() << "Checking if this is due to cycles\n";
6552       checkForCycles(this, true);
6553 #endif
6554       llvm_unreachable(nullptr);
6555     }
6556   }
6557 
6558   assert(SortedPos == AllNodes.end() &&
6559          "Topological sort incomplete!");
6560   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
6561          "First node in topological sort is not the entry token!");
6562   assert(AllNodes.front().getNodeId() == 0 &&
6563          "First node in topological sort has non-zero id!");
6564   assert(AllNodes.front().getNumOperands() == 0 &&
6565          "First node in topological sort has operands!");
6566   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
6567          "Last node in topologic sort has unexpected id!");
6568   assert(AllNodes.back().use_empty() &&
6569          "Last node in topologic sort has users!");
6570   assert(DAGSize == allnodes_size() && "Node count mismatch!");
6571   return DAGSize;
6572 }
6573 
6574 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
6575 /// value is produced by SD.
6576 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
6577   if (SD) {
6578     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
6579     SD->setHasDebugValue(true);
6580   }
6581   DbgInfo->add(DB, SD, isParameter);
6582 }
6583 
6584 /// TransferDbgValues - Transfer SDDbgValues. Called in replace nodes.
6585 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
6586   if (From == To || !From.getNode()->getHasDebugValue())
6587     return;
6588   SDNode *FromNode = From.getNode();
6589   SDNode *ToNode = To.getNode();
6590   ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
6591   SmallVector<SDDbgValue *, 2> ClonedDVs;
6592   for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
6593        I != E; ++I) {
6594     SDDbgValue *Dbg = *I;
6595     // Only add Dbgvalues attached to same ResNo.
6596     if (Dbg->getKind() == SDDbgValue::SDNODE &&
6597         Dbg->getSDNode() == From.getNode() &&
6598         Dbg->getResNo() == From.getResNo() && !Dbg->isInvalidated()) {
6599       assert(FromNode != ToNode &&
6600              "Should not transfer Debug Values intranode");
6601       SDDbgValue *Clone =
6602           getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode,
6603                       To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(),
6604                       Dbg->getDebugLoc(), Dbg->getOrder());
6605       ClonedDVs.push_back(Clone);
6606       Dbg->setIsInvalidated();
6607     }
6608   }
6609   for (SDDbgValue *I : ClonedDVs)
6610     AddDbgValue(I, ToNode, false);
6611 }
6612 
6613 //===----------------------------------------------------------------------===//
6614 //                              SDNode Class
6615 //===----------------------------------------------------------------------===//
6616 
6617 bool llvm::isNullConstant(SDValue V) {
6618   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
6619   return Const != nullptr && Const->isNullValue();
6620 }
6621 
6622 bool llvm::isNullFPConstant(SDValue V) {
6623   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
6624   return Const != nullptr && Const->isZero() && !Const->isNegative();
6625 }
6626 
6627 bool llvm::isAllOnesConstant(SDValue V) {
6628   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
6629   return Const != nullptr && Const->isAllOnesValue();
6630 }
6631 
6632 bool llvm::isOneConstant(SDValue V) {
6633   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
6634   return Const != nullptr && Const->isOne();
6635 }
6636 
6637 bool llvm::isBitwiseNot(SDValue V) {
6638   return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1));
6639 }
6640 
6641 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N) {
6642   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
6643     return CN;
6644 
6645   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
6646     BitVector UndefElements;
6647     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
6648 
6649     // BuildVectors can truncate their operands. Ignore that case here.
6650     // FIXME: We blindly ignore splats which include undef which is overly
6651     // pessimistic.
6652     if (CN && UndefElements.none() &&
6653         CN->getValueType(0) == N.getValueType().getScalarType())
6654       return CN;
6655   }
6656 
6657   return nullptr;
6658 }
6659 
6660 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N) {
6661   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
6662     return CN;
6663 
6664   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
6665     BitVector UndefElements;
6666     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
6667 
6668     if (CN && UndefElements.none())
6669       return CN;
6670   }
6671 
6672   return nullptr;
6673 }
6674 
6675 HandleSDNode::~HandleSDNode() {
6676   DropOperands();
6677 }
6678 
6679 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
6680                                          const DebugLoc &DL,
6681                                          const GlobalValue *GA, EVT VT,
6682                                          int64_t o, unsigned char TF)
6683     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
6684   TheGlobal = GA;
6685 }
6686 
6687 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
6688                                          EVT VT, unsigned SrcAS,
6689                                          unsigned DestAS)
6690     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
6691       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
6692 
6693 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
6694                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
6695     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
6696   MemSDNodeBits.IsVolatile = MMO->isVolatile();
6697   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
6698   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
6699   MemSDNodeBits.IsInvariant = MMO->isInvariant();
6700 
6701   // We check here that the size of the memory operand fits within the size of
6702   // the MMO. This is because the MMO might indicate only a possible address
6703   // range instead of specifying the affected memory addresses precisely.
6704   assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
6705 }
6706 
6707 /// Profile - Gather unique data for the node.
6708 ///
6709 void SDNode::Profile(FoldingSetNodeID &ID) const {
6710   AddNodeIDNode(ID, this);
6711 }
6712 
6713 namespace {
6714   struct EVTArray {
6715     std::vector<EVT> VTs;
6716 
6717     EVTArray() {
6718       VTs.reserve(MVT::LAST_VALUETYPE);
6719       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
6720         VTs.push_back(MVT((MVT::SimpleValueType)i));
6721     }
6722   };
6723 }
6724 
6725 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
6726 static ManagedStatic<EVTArray> SimpleVTArray;
6727 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
6728 
6729 /// getValueTypeList - Return a pointer to the specified value type.
6730 ///
6731 const EVT *SDNode::getValueTypeList(EVT VT) {
6732   if (VT.isExtended()) {
6733     sys::SmartScopedLock<true> Lock(*VTMutex);
6734     return &(*EVTs->insert(VT).first);
6735   } else {
6736     assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
6737            "Value type out of range!");
6738     return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
6739   }
6740 }
6741 
6742 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
6743 /// indicated value.  This method ignores uses of other values defined by this
6744 /// operation.
6745 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
6746   assert(Value < getNumValues() && "Bad value!");
6747 
6748   // TODO: Only iterate over uses of a given value of the node
6749   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
6750     if (UI.getUse().getResNo() == Value) {
6751       if (NUses == 0)
6752         return false;
6753       --NUses;
6754     }
6755   }
6756 
6757   // Found exactly the right number of uses?
6758   return NUses == 0;
6759 }
6760 
6761 
6762 /// hasAnyUseOfValue - Return true if there are any use of the indicated
6763 /// value. This method ignores uses of other values defined by this operation.
6764 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
6765   assert(Value < getNumValues() && "Bad value!");
6766 
6767   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
6768     if (UI.getUse().getResNo() == Value)
6769       return true;
6770 
6771   return false;
6772 }
6773 
6774 
6775 /// isOnlyUserOf - Return true if this node is the only use of N.
6776 ///
6777 bool SDNode::isOnlyUserOf(const SDNode *N) const {
6778   bool Seen = false;
6779   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
6780     SDNode *User = *I;
6781     if (User == this)
6782       Seen = true;
6783     else
6784       return false;
6785   }
6786 
6787   return Seen;
6788 }
6789 
6790 /// isOperand - Return true if this node is an operand of N.
6791 ///
6792 bool SDValue::isOperandOf(const SDNode *N) const {
6793   for (const SDValue &Op : N->op_values())
6794     if (*this == Op)
6795       return true;
6796   return false;
6797 }
6798 
6799 bool SDNode::isOperandOf(const SDNode *N) const {
6800   for (const SDValue &Op : N->op_values())
6801     if (this == Op.getNode())
6802       return true;
6803   return false;
6804 }
6805 
6806 /// reachesChainWithoutSideEffects - Return true if this operand (which must
6807 /// be a chain) reaches the specified operand without crossing any
6808 /// side-effecting instructions on any chain path.  In practice, this looks
6809 /// through token factors and non-volatile loads.  In order to remain efficient,
6810 /// this only looks a couple of nodes in, it does not do an exhaustive search.
6811 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
6812                                                unsigned Depth) const {
6813   if (*this == Dest) return true;
6814 
6815   // Don't search too deeply, we just want to be able to see through
6816   // TokenFactor's etc.
6817   if (Depth == 0) return false;
6818 
6819   // If this is a token factor, all inputs to the TF happen in parallel.  If any
6820   // of the operands of the TF does not reach dest, then we cannot do the xform.
6821   if (getOpcode() == ISD::TokenFactor) {
6822     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6823       if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
6824         return false;
6825     return true;
6826   }
6827 
6828   // Loads don't have side effects, look through them.
6829   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
6830     if (!Ld->isVolatile())
6831       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
6832   }
6833   return false;
6834 }
6835 
6836 bool SDNode::hasPredecessor(const SDNode *N) const {
6837   SmallPtrSet<const SDNode *, 32> Visited;
6838   SmallVector<const SDNode *, 16> Worklist;
6839   Worklist.push_back(this);
6840   return hasPredecessorHelper(N, Visited, Worklist);
6841 }
6842 
6843 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
6844   assert(Num < NumOperands && "Invalid child # of SDNode!");
6845   return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
6846 }
6847 
6848 const SDNodeFlags *SDNode::getFlags() const {
6849   if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this))
6850     return &FlagsNode->Flags;
6851   return nullptr;
6852 }
6853 
6854 void SDNode::intersectFlagsWith(const SDNodeFlags *Flags) {
6855   if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this))
6856     FlagsNode->Flags.intersectWith(Flags);
6857 }
6858 
6859 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
6860   assert(N->getNumValues() == 1 &&
6861          "Can't unroll a vector with multiple results!");
6862 
6863   EVT VT = N->getValueType(0);
6864   unsigned NE = VT.getVectorNumElements();
6865   EVT EltVT = VT.getVectorElementType();
6866   SDLoc dl(N);
6867 
6868   SmallVector<SDValue, 8> Scalars;
6869   SmallVector<SDValue, 4> Operands(N->getNumOperands());
6870 
6871   // If ResNE is 0, fully unroll the vector op.
6872   if (ResNE == 0)
6873     ResNE = NE;
6874   else if (NE > ResNE)
6875     NE = ResNE;
6876 
6877   unsigned i;
6878   for (i= 0; i != NE; ++i) {
6879     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
6880       SDValue Operand = N->getOperand(j);
6881       EVT OperandVT = Operand.getValueType();
6882       if (OperandVT.isVector()) {
6883         // A vector operand; extract a single element.
6884         EVT OperandEltVT = OperandVT.getVectorElementType();
6885         Operands[j] =
6886             getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
6887                     getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
6888       } else {
6889         // A scalar operand; just use it as is.
6890         Operands[j] = Operand;
6891       }
6892     }
6893 
6894     switch (N->getOpcode()) {
6895     default: {
6896       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
6897                                 N->getFlags()));
6898       break;
6899     }
6900     case ISD::VSELECT:
6901       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
6902       break;
6903     case ISD::SHL:
6904     case ISD::SRA:
6905     case ISD::SRL:
6906     case ISD::ROTL:
6907     case ISD::ROTR:
6908       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6909                                getShiftAmountOperand(Operands[0].getValueType(),
6910                                                      Operands[1])));
6911       break;
6912     case ISD::SIGN_EXTEND_INREG:
6913     case ISD::FP_ROUND_INREG: {
6914       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6915       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6916                                 Operands[0],
6917                                 getValueType(ExtVT)));
6918     }
6919     }
6920   }
6921 
6922   for (; i < ResNE; ++i)
6923     Scalars.push_back(getUNDEF(EltVT));
6924 
6925   return getNode(ISD::BUILD_VECTOR, dl,
6926                  EVT::getVectorVT(*getContext(), EltVT, ResNE), Scalars);
6927 }
6928 
6929 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
6930                                                   LoadSDNode *Base,
6931                                                   unsigned Bytes,
6932                                                   int Dist) const {
6933   if (LD->isVolatile() || Base->isVolatile())
6934     return false;
6935   if (LD->isIndexed() || Base->isIndexed())
6936     return false;
6937   if (LD->getChain() != Base->getChain())
6938     return false;
6939   EVT VT = LD->getValueType(0);
6940   if (VT.getSizeInBits() / 8 != Bytes)
6941     return false;
6942 
6943   SDValue Loc = LD->getOperand(1);
6944   SDValue BaseLoc = Base->getOperand(1);
6945   if (Loc.getOpcode() == ISD::FrameIndex) {
6946     if (BaseLoc.getOpcode() != ISD::FrameIndex)
6947       return false;
6948     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
6949     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
6950     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6951     int FS  = MFI.getObjectSize(FI);
6952     int BFS = MFI.getObjectSize(BFI);
6953     if (FS != BFS || FS != (int)Bytes) return false;
6954     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
6955   }
6956 
6957   // Handle X + C.
6958   if (isBaseWithConstantOffset(Loc)) {
6959     int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
6960     if (Loc.getOperand(0) == BaseLoc) {
6961       // If the base location is a simple address with no offset itself, then
6962       // the second load's first add operand should be the base address.
6963       if (LocOffset == Dist * (int)Bytes)
6964         return true;
6965     } else if (isBaseWithConstantOffset(BaseLoc)) {
6966       // The base location itself has an offset, so subtract that value from the
6967       // second load's offset before comparing to distance * size.
6968       int64_t BOffset =
6969         cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue();
6970       if (Loc.getOperand(0) == BaseLoc.getOperand(0)) {
6971         if ((LocOffset - BOffset) == Dist * (int)Bytes)
6972           return true;
6973       }
6974     }
6975   }
6976   const GlobalValue *GV1 = nullptr;
6977   const GlobalValue *GV2 = nullptr;
6978   int64_t Offset1 = 0;
6979   int64_t Offset2 = 0;
6980   bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6981   bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6982   if (isGA1 && isGA2 && GV1 == GV2)
6983     return Offset1 == (Offset2 + Dist*Bytes);
6984   return false;
6985 }
6986 
6987 
6988 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6989 /// it cannot be inferred.
6990 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6991   // If this is a GlobalAddress + cst, return the alignment.
6992   const GlobalValue *GV;
6993   int64_t GVOffset = 0;
6994   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
6995     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
6996     APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0);
6997     llvm::computeKnownBits(const_cast<GlobalValue *>(GV), KnownZero, KnownOne,
6998                            getDataLayout());
6999     unsigned AlignBits = KnownZero.countTrailingOnes();
7000     unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
7001     if (Align)
7002       return MinAlign(Align, GVOffset);
7003   }
7004 
7005   // If this is a direct reference to a stack slot, use information about the
7006   // stack slot's alignment.
7007   int FrameIdx = 1 << 31;
7008   int64_t FrameOffset = 0;
7009   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
7010     FrameIdx = FI->getIndex();
7011   } else if (isBaseWithConstantOffset(Ptr) &&
7012              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7013     // Handle FI+Cst
7014     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7015     FrameOffset = Ptr.getConstantOperandVal(1);
7016   }
7017 
7018   if (FrameIdx != (1 << 31)) {
7019     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7020     unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
7021                                     FrameOffset);
7022     return FIInfoAlign;
7023   }
7024 
7025   return 0;
7026 }
7027 
7028 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
7029 /// which is split (or expanded) into two not necessarily identical pieces.
7030 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
7031   // Currently all types are split in half.
7032   EVT LoVT, HiVT;
7033   if (!VT.isVector()) {
7034     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
7035   } else {
7036     unsigned NumElements = VT.getVectorNumElements();
7037     assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7038     LoVT = HiVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
7039                                    NumElements/2);
7040   }
7041   return std::make_pair(LoVT, HiVT);
7042 }
7043 
7044 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
7045 /// low/high part.
7046 std::pair<SDValue, SDValue>
7047 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
7048                           const EVT &HiVT) {
7049   assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
7050          N.getValueType().getVectorNumElements() &&
7051          "More vector elements requested than available!");
7052   SDValue Lo, Hi;
7053   Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
7054                getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
7055   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
7056                getConstant(LoVT.getVectorNumElements(), DL,
7057                            TLI->getVectorIdxTy(getDataLayout())));
7058   return std::make_pair(Lo, Hi);
7059 }
7060 
7061 void SelectionDAG::ExtractVectorElements(SDValue Op,
7062                                          SmallVectorImpl<SDValue> &Args,
7063                                          unsigned Start, unsigned Count) {
7064   EVT VT = Op.getValueType();
7065   if (Count == 0)
7066     Count = VT.getVectorNumElements();
7067 
7068   EVT EltVT = VT.getVectorElementType();
7069   EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
7070   SDLoc SL(Op);
7071   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
7072     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7073                            Op, getConstant(i, SL, IdxTy)));
7074   }
7075 }
7076 
7077 // getAddressSpace - Return the address space this GlobalAddress belongs to.
7078 unsigned GlobalAddressSDNode::getAddressSpace() const {
7079   return getGlobal()->getType()->getAddressSpace();
7080 }
7081 
7082 
7083 Type *ConstantPoolSDNode::getType() const {
7084   if (isMachineConstantPoolEntry())
7085     return Val.MachineCPVal->getType();
7086   return Val.ConstVal->getType();
7087 }
7088 
7089 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
7090                                         APInt &SplatUndef,
7091                                         unsigned &SplatBitSize,
7092                                         bool &HasAnyUndefs,
7093                                         unsigned MinSplatBits,
7094                                         bool isBigEndian) const {
7095   EVT VT = getValueType(0);
7096   assert(VT.isVector() && "Expected a vector type");
7097   unsigned sz = VT.getSizeInBits();
7098   if (MinSplatBits > sz)
7099     return false;
7100 
7101   SplatValue = APInt(sz, 0);
7102   SplatUndef = APInt(sz, 0);
7103 
7104   // Get the bits.  Bits with undefined values (when the corresponding element
7105   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
7106   // in SplatValue.  If any of the values are not constant, give up and return
7107   // false.
7108   unsigned int nOps = getNumOperands();
7109   assert(nOps > 0 && "isConstantSplat has 0-size build vector");
7110   unsigned EltBitSize = VT.getScalarSizeInBits();
7111 
7112   for (unsigned j = 0; j < nOps; ++j) {
7113     unsigned i = isBigEndian ? nOps-1-j : j;
7114     SDValue OpVal = getOperand(i);
7115     unsigned BitPos = j * EltBitSize;
7116 
7117     if (OpVal.isUndef())
7118       SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
7119     else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
7120       SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize).
7121                     zextOrTrunc(sz) << BitPos;
7122     else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
7123       SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
7124      else
7125       return false;
7126   }
7127 
7128   // The build_vector is all constants or undefs.  Find the smallest element
7129   // size that splats the vector.
7130 
7131   HasAnyUndefs = (SplatUndef != 0);
7132   while (sz > 8) {
7133 
7134     unsigned HalfSize = sz / 2;
7135     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
7136     APInt LowValue = SplatValue.trunc(HalfSize);
7137     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
7138     APInt LowUndef = SplatUndef.trunc(HalfSize);
7139 
7140     // If the two halves do not match (ignoring undef bits), stop here.
7141     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
7142         MinSplatBits > HalfSize)
7143       break;
7144 
7145     SplatValue = HighValue | LowValue;
7146     SplatUndef = HighUndef & LowUndef;
7147 
7148     sz = HalfSize;
7149   }
7150 
7151   SplatBitSize = sz;
7152   return true;
7153 }
7154 
7155 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
7156   if (UndefElements) {
7157     UndefElements->clear();
7158     UndefElements->resize(getNumOperands());
7159   }
7160   SDValue Splatted;
7161   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
7162     SDValue Op = getOperand(i);
7163     if (Op.isUndef()) {
7164       if (UndefElements)
7165         (*UndefElements)[i] = true;
7166     } else if (!Splatted) {
7167       Splatted = Op;
7168     } else if (Splatted != Op) {
7169       return SDValue();
7170     }
7171   }
7172 
7173   if (!Splatted) {
7174     assert(getOperand(0).isUndef() &&
7175            "Can only have a splat without a constant for all undefs.");
7176     return getOperand(0);
7177   }
7178 
7179   return Splatted;
7180 }
7181 
7182 ConstantSDNode *
7183 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
7184   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
7185 }
7186 
7187 ConstantFPSDNode *
7188 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
7189   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
7190 }
7191 
7192 int32_t
7193 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
7194                                                    uint32_t BitWidth) const {
7195   if (ConstantFPSDNode *CN =
7196           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
7197     bool IsExact;
7198     APSInt IntVal(BitWidth);
7199     const APFloat &APF = CN->getValueAPF();
7200     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
7201             APFloat::opOK ||
7202         !IsExact)
7203       return -1;
7204 
7205     return IntVal.exactLogBase2();
7206   }
7207   return -1;
7208 }
7209 
7210 bool BuildVectorSDNode::isConstant() const {
7211   for (const SDValue &Op : op_values()) {
7212     unsigned Opc = Op.getOpcode();
7213     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
7214       return false;
7215   }
7216   return true;
7217 }
7218 
7219 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
7220   // Find the first non-undef value in the shuffle mask.
7221   unsigned i, e;
7222   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
7223     /* search */;
7224 
7225   assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
7226 
7227   // Make sure all remaining elements are either undef or the same as the first
7228   // non-undef value.
7229   for (int Idx = Mask[i]; i != e; ++i)
7230     if (Mask[i] >= 0 && Mask[i] != Idx)
7231       return false;
7232   return true;
7233 }
7234 
7235 // \brief Returns the SDNode if it is a constant integer BuildVector
7236 // or constant integer.
7237 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
7238   if (isa<ConstantSDNode>(N))
7239     return N.getNode();
7240   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
7241     return N.getNode();
7242   // Treat a GlobalAddress supporting constant offset folding as a
7243   // constant integer.
7244   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
7245     if (GA->getOpcode() == ISD::GlobalAddress &&
7246         TLI->isOffsetFoldingLegal(GA))
7247       return GA;
7248   return nullptr;
7249 }
7250 
7251 #ifndef NDEBUG
7252 static void checkForCyclesHelper(const SDNode *N,
7253                                  SmallPtrSetImpl<const SDNode*> &Visited,
7254                                  SmallPtrSetImpl<const SDNode*> &Checked,
7255                                  const llvm::SelectionDAG *DAG) {
7256   // If this node has already been checked, don't check it again.
7257   if (Checked.count(N))
7258     return;
7259 
7260   // If a node has already been visited on this depth-first walk, reject it as
7261   // a cycle.
7262   if (!Visited.insert(N).second) {
7263     errs() << "Detected cycle in SelectionDAG\n";
7264     dbgs() << "Offending node:\n";
7265     N->dumprFull(DAG); dbgs() << "\n";
7266     abort();
7267   }
7268 
7269   for (const SDValue &Op : N->op_values())
7270     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
7271 
7272   Checked.insert(N);
7273   Visited.erase(N);
7274 }
7275 #endif
7276 
7277 void llvm::checkForCycles(const llvm::SDNode *N,
7278                           const llvm::SelectionDAG *DAG,
7279                           bool force) {
7280 #ifndef NDEBUG
7281   bool check = force;
7282 #ifdef EXPENSIVE_CHECKS
7283   check = true;
7284 #endif  // EXPENSIVE_CHECKS
7285   if (check) {
7286     assert(N && "Checking nonexistent SDNode");
7287     SmallPtrSet<const SDNode*, 32> visited;
7288     SmallPtrSet<const SDNode*, 32> checked;
7289     checkForCyclesHelper(N, visited, checked, DAG);
7290   }
7291 #endif  // !NDEBUG
7292 }
7293 
7294 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
7295   checkForCycles(DAG->getRoot().getNode(), DAG, force);
7296 }
7297