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