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