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