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