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