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