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