SelectionDAG: Handle out-of-bounds index in extract vector element
[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 out-of-bounds element is an UNDEF
3412     if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements())
3413       return getUNDEF(VT);
3414
3415     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
3416     // expanding copies of large vectors from registers.
3417     if (N2C &&
3418         N1.getOpcode() == ISD::CONCAT_VECTORS &&
3419         N1.getNumOperands() > 0) {
3420       unsigned Factor =
3421         N1.getOperand(0).getValueType().getVectorNumElements();
3422       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
3423                      N1.getOperand(N2C->getZExtValue() / Factor),
3424                      getConstant(N2C->getZExtValue() % Factor, DL,
3425                                  N2.getValueType()));
3426     }
3427
3428     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
3429     // expanding large vector constants.
3430     if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
3431       SDValue Elt = N1.getOperand(N2C->getZExtValue());
3432
3433       if (VT != Elt.getValueType())
3434         // If the vector element type is not legal, the BUILD_VECTOR operands
3435         // are promoted and implicitly truncated, and the result implicitly
3436         // extended. Make that explicit here.
3437         Elt = getAnyExtOrTrunc(Elt, DL, VT);
3438
3439       return Elt;
3440     }
3441
3442     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
3443     // operations are lowered to scalars.
3444     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
3445       // If the indices are the same, return the inserted element else
3446       // if the indices are known different, extract the element from
3447       // the original vector.
3448       SDValue N1Op2 = N1.getOperand(2);
3449       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2.getNode());
3450
3451       if (N1Op2C && N2C) {
3452         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
3453           if (VT == N1.getOperand(1).getValueType())
3454             return N1.getOperand(1);
3455           else
3456             return getSExtOrTrunc(N1.getOperand(1), DL, VT);
3457         }
3458
3459         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
3460       }
3461     }
3462     break;
3463   case ISD::EXTRACT_ELEMENT:
3464     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
3465     assert(!N1.getValueType().isVector() && !VT.isVector() &&
3466            (N1.getValueType().isInteger() == VT.isInteger()) &&
3467            N1.getValueType() != VT &&
3468            "Wrong types for EXTRACT_ELEMENT!");
3469
3470     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
3471     // 64-bit integers into 32-bit parts.  Instead of building the extract of
3472     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
3473     if (N1.getOpcode() == ISD::BUILD_PAIR)
3474       return N1.getOperand(N2C->getZExtValue());
3475
3476     // EXTRACT_ELEMENT of a constant int is also very common.
3477     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3478       unsigned ElementSize = VT.getSizeInBits();
3479       unsigned Shift = ElementSize * N2C->getZExtValue();
3480       APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
3481       return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
3482     }
3483     break;
3484   case ISD::EXTRACT_SUBVECTOR: {
3485     SDValue Index = N2;
3486     if (VT.isSimple() && N1.getValueType().isSimple()) {
3487       assert(VT.isVector() && N1.getValueType().isVector() &&
3488              "Extract subvector VTs must be a vectors!");
3489       assert(VT.getVectorElementType() ==
3490              N1.getValueType().getVectorElementType() &&
3491              "Extract subvector VTs must have the same element type!");
3492       assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
3493              "Extract subvector must be from larger vector to smaller vector!");
3494
3495       if (isa<ConstantSDNode>(Index.getNode())) {
3496         assert((VT.getVectorNumElements() +
3497                 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
3498                 <= N1.getValueType().getVectorNumElements())
3499                && "Extract subvector overflow!");
3500       }
3501
3502       // Trivial extraction.
3503       if (VT.getSimpleVT() == N1.getSimpleValueType())
3504         return N1;
3505     }
3506     break;
3507   }
3508   }
3509
3510   // Perform trivial constant folding.
3511   if (SDValue SV =
3512           FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
3513     return SV;
3514
3515   // Canonicalize constant to RHS if commutative.
3516   if (N1C && !N2C && isCommutativeBinOp(Opcode)) {
3517     std::swap(N1C, N2C);
3518     std::swap(N1, N2);
3519   }
3520
3521   // Constant fold FP operations.
3522   bool HasFPExceptions = TLI->hasFloatingPointExceptions();
3523   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
3524   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
3525   if (N1CFP) {
3526     if (!N2CFP && isCommutativeBinOp(Opcode)) {
3527       // Canonicalize constant to RHS if commutative.
3528       std::swap(N1CFP, N2CFP);
3529       std::swap(N1, N2);
3530     } else if (N2CFP) {
3531       APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
3532       APFloat::opStatus s;
3533       switch (Opcode) {
3534       case ISD::FADD:
3535         s = V1.add(V2, APFloat::rmNearestTiesToEven);
3536         if (!HasFPExceptions || s != APFloat::opInvalidOp)
3537           return getConstantFP(V1, DL, VT);
3538         break;
3539       case ISD::FSUB:
3540         s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
3541         if (!HasFPExceptions || s!=APFloat::opInvalidOp)
3542           return getConstantFP(V1, DL, VT);
3543         break;
3544       case ISD::FMUL:
3545         s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
3546         if (!HasFPExceptions || s!=APFloat::opInvalidOp)
3547           return getConstantFP(V1, DL, VT);
3548         break;
3549       case ISD::FDIV:
3550         s = V1.divide(V2, APFloat::rmNearestTiesToEven);
3551         if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
3552                                  s!=APFloat::opDivByZero)) {
3553           return getConstantFP(V1, DL, VT);
3554         }
3555         break;
3556       case ISD::FREM :
3557         s = V1.mod(V2, APFloat::rmNearestTiesToEven);
3558         if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
3559                                  s!=APFloat::opDivByZero)) {
3560           return getConstantFP(V1, DL, VT);
3561         }
3562         break;
3563       case ISD::FCOPYSIGN:
3564         V1.copySign(V2);
3565         return getConstantFP(V1, DL, VT);
3566       default: break;
3567       }
3568     }
3569
3570     if (Opcode == ISD::FP_ROUND) {
3571       APFloat V = N1CFP->getValueAPF();    // make copy
3572       bool ignored;
3573       // This can return overflow, underflow, or inexact; we don't care.
3574       // FIXME need to be more flexible about rounding mode.
3575       (void)V.convert(EVTToAPFloatSemantics(VT),
3576                       APFloat::rmNearestTiesToEven, &ignored);
3577       return getConstantFP(V, DL, VT);
3578     }
3579   }
3580
3581   // Canonicalize an UNDEF to the RHS, even over a constant.
3582   if (N1.getOpcode() == ISD::UNDEF) {
3583     if (isCommutativeBinOp(Opcode)) {
3584       std::swap(N1, N2);
3585     } else {
3586       switch (Opcode) {
3587       case ISD::FP_ROUND_INREG:
3588       case ISD::SIGN_EXTEND_INREG:
3589       case ISD::SUB:
3590       case ISD::FSUB:
3591       case ISD::FDIV:
3592       case ISD::FREM:
3593       case ISD::SRA:
3594         return N1;     // fold op(undef, arg2) -> undef
3595       case ISD::UDIV:
3596       case ISD::SDIV:
3597       case ISD::UREM:
3598       case ISD::SREM:
3599       case ISD::SRL:
3600       case ISD::SHL:
3601         if (!VT.isVector())
3602           return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
3603         // For vectors, we can't easily build an all zero vector, just return
3604         // the LHS.
3605         return N2;
3606       }
3607     }
3608   }
3609
3610   // Fold a bunch of operators when the RHS is undef.
3611   if (N2.getOpcode() == ISD::UNDEF) {
3612     switch (Opcode) {
3613     case ISD::XOR:
3614       if (N1.getOpcode() == ISD::UNDEF)
3615         // Handle undef ^ undef -> 0 special case. This is a common
3616         // idiom (misuse).
3617         return getConstant(0, DL, VT);
3618       // fallthrough
3619     case ISD::ADD:
3620     case ISD::ADDC:
3621     case ISD::ADDE:
3622     case ISD::SUB:
3623     case ISD::UDIV:
3624     case ISD::SDIV:
3625     case ISD::UREM:
3626     case ISD::SREM:
3627       return N2;       // fold op(arg1, undef) -> undef
3628     case ISD::FADD:
3629     case ISD::FSUB:
3630     case ISD::FMUL:
3631     case ISD::FDIV:
3632     case ISD::FREM:
3633       if (getTarget().Options.UnsafeFPMath)
3634         return N2;
3635       break;
3636     case ISD::MUL:
3637     case ISD::AND:
3638     case ISD::SRL:
3639     case ISD::SHL:
3640       if (!VT.isVector())
3641         return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
3642       // For vectors, we can't easily build an all zero vector, just return
3643       // the LHS.
3644       return N1;
3645     case ISD::OR:
3646       if (!VT.isVector())
3647         return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
3648       // For vectors, we can't easily build an all one vector, just return
3649       // the LHS.
3650       return N1;
3651     case ISD::SRA:
3652       return N1;
3653     }
3654   }
3655
3656   // Memoize this node if possible.
3657   SDNode *N;
3658   SDVTList VTs = getVTList(VT);
3659   SDValue Ops[] = { N1, N2 };
3660   if (VT != MVT::Glue) {
3661     SDValue Ops[] = {N1, N2};
3662     FoldingSetNodeID ID;
3663     AddNodeIDNode(ID, Opcode, VTs, Ops);
3664     AddNodeIDFlags(ID, Opcode, Flags);
3665     void *IP = nullptr;
3666     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3667       return SDValue(E, 0);
3668
3669     N = GetSDNodeWithFlags(Opcode, DL, VTs, Ops, Flags);
3670     
3671     CSEMap.InsertNode(N, IP);
3672   } else {
3673     N = GetSDNodeWithFlags(Opcode, DL, VTs, Ops, Flags);
3674   }
3675
3676   InsertNode(N);
3677   return SDValue(N, 0);
3678 }
3679
3680 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3681                               SDValue N1, SDValue N2, SDValue N3) {
3682   // Perform various simplifications.
3683   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
3684   switch (Opcode) {
3685   case ISD::FMA: {
3686     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3687     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
3688     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
3689     if (N1CFP && N2CFP && N3CFP) {
3690       APFloat  V1 = N1CFP->getValueAPF();
3691       const APFloat &V2 = N2CFP->getValueAPF();
3692       const APFloat &V3 = N3CFP->getValueAPF();
3693       APFloat::opStatus s =
3694         V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
3695       if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
3696         return getConstantFP(V1, DL, VT);
3697     }
3698     break;
3699   }
3700   case ISD::CONCAT_VECTORS:
3701     // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3702     // one big BUILD_VECTOR.
3703     if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3704         N2.getOpcode() == ISD::BUILD_VECTOR &&
3705         N3.getOpcode() == ISD::BUILD_VECTOR) {
3706       SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
3707                                     N1.getNode()->op_end());
3708       Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
3709       Elts.append(N3.getNode()->op_begin(), N3.getNode()->op_end());
3710       return getNode(ISD::BUILD_VECTOR, DL, VT, Elts);
3711     }
3712     break;
3713   case ISD::SETCC: {
3714     // Use FoldSetCC to simplify SETCC's.
3715     SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
3716     if (Simp.getNode()) return Simp;
3717     break;
3718   }
3719   case ISD::SELECT:
3720     if (N1C) {
3721      if (N1C->getZExtValue())
3722        return N2;             // select true, X, Y -> X
3723      return N3;             // select false, X, Y -> Y
3724     }
3725
3726     if (N2 == N3) return N2;   // select C, X, X -> X
3727     break;
3728   case ISD::VECTOR_SHUFFLE:
3729     llvm_unreachable("should use getVectorShuffle constructor!");
3730   case ISD::INSERT_SUBVECTOR: {
3731     SDValue Index = N3;
3732     if (VT.isSimple() && N1.getValueType().isSimple()
3733         && N2.getValueType().isSimple()) {
3734       assert(VT.isVector() && N1.getValueType().isVector() &&
3735              N2.getValueType().isVector() &&
3736              "Insert subvector VTs must be a vectors");
3737       assert(VT == N1.getValueType() &&
3738              "Dest and insert subvector source types must match!");
3739       assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
3740              "Insert subvector must be from smaller vector to larger vector!");
3741       if (isa<ConstantSDNode>(Index.getNode())) {
3742         assert((N2.getValueType().getVectorNumElements() +
3743                 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
3744                 <= VT.getVectorNumElements())
3745                && "Insert subvector overflow!");
3746       }
3747
3748       // Trivial insertion.
3749       if (VT.getSimpleVT() == N2.getSimpleValueType())
3750         return N2;
3751     }
3752     break;
3753   }
3754   case ISD::BITCAST:
3755     // Fold bit_convert nodes from a type to themselves.
3756     if (N1.getValueType() == VT)
3757       return N1;
3758     break;
3759   }
3760
3761   // Memoize node if it doesn't produce a flag.
3762   SDNode *N;
3763   SDVTList VTs = getVTList(VT);
3764   if (VT != MVT::Glue) {
3765     SDValue Ops[] = { N1, N2, N3 };
3766     FoldingSetNodeID ID;
3767     AddNodeIDNode(ID, Opcode, VTs, Ops);
3768     void *IP = nullptr;
3769     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3770       return SDValue(E, 0);
3771
3772     N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(),
3773                                           DL.getDebugLoc(), VTs, N1, N2, N3);
3774     CSEMap.InsertNode(N, IP);
3775   } else {
3776     N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(),
3777                                           DL.getDebugLoc(), VTs, N1, N2, N3);
3778   }
3779
3780   InsertNode(N);
3781   return SDValue(N, 0);
3782 }
3783
3784 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3785                               SDValue N1, SDValue N2, SDValue N3,
3786                               SDValue N4) {
3787   SDValue Ops[] = { N1, N2, N3, N4 };
3788   return getNode(Opcode, DL, VT, Ops);
3789 }
3790
3791 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3792                               SDValue N1, SDValue N2, SDValue N3,
3793                               SDValue N4, SDValue N5) {
3794   SDValue Ops[] = { N1, N2, N3, N4, N5 };
3795   return getNode(Opcode, DL, VT, Ops);
3796 }
3797
3798 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
3799 /// the incoming stack arguments to be loaded from the stack.
3800 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3801   SmallVector<SDValue, 8> ArgChains;
3802
3803   // Include the original chain at the beginning of the list. When this is
3804   // used by target LowerCall hooks, this helps legalize find the
3805   // CALLSEQ_BEGIN node.
3806   ArgChains.push_back(Chain);
3807
3808   // Add a chain value for each stack argument.
3809   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3810        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3811     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3812       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3813         if (FI->getIndex() < 0)
3814           ArgChains.push_back(SDValue(L, 1));
3815
3816   // Build a tokenfactor for all the chains.
3817   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3818 }
3819
3820 /// getMemsetValue - Vectorized representation of the memset value
3821 /// operand.
3822 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3823                               SDLoc dl) {
3824   assert(Value.getOpcode() != ISD::UNDEF);
3825
3826   unsigned NumBits = VT.getScalarType().getSizeInBits();
3827   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3828     assert(C->getAPIntValue().getBitWidth() == 8);
3829     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
3830     if (VT.isInteger())
3831       return DAG.getConstant(Val, dl, VT);
3832     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
3833                              VT);
3834   }
3835
3836   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
3837   EVT IntVT = VT.getScalarType();
3838   if (!IntVT.isInteger())
3839     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
3840
3841   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
3842   if (NumBits > 8) {
3843     // Use a multiplication with 0x010101... to extend the input to the
3844     // required length.
3845     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
3846     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
3847                         DAG.getConstant(Magic, dl, IntVT));
3848   }
3849
3850   if (VT != Value.getValueType() && !VT.isInteger())
3851     Value = DAG.getNode(ISD::BITCAST, dl, VT.getScalarType(), Value);
3852   if (VT != Value.getValueType()) {
3853     assert(VT.getVectorElementType() == Value.getValueType() &&
3854            "value type should be one vector element here");
3855     SmallVector<SDValue, 8> BVOps(VT.getVectorNumElements(), Value);
3856     Value = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, BVOps);
3857   }
3858
3859   return Value;
3860 }
3861
3862 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3863 /// used when a memcpy is turned into a memset when the source is a constant
3864 /// string ptr.
3865 static SDValue getMemsetStringVal(EVT VT, SDLoc dl, SelectionDAG &DAG,
3866                                   const TargetLowering &TLI, StringRef Str) {
3867   // Handle vector with all elements zero.
3868   if (Str.empty()) {
3869     if (VT.isInteger())
3870       return DAG.getConstant(0, dl, VT);
3871     else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
3872       return DAG.getConstantFP(0.0, dl, VT);
3873     else if (VT.isVector()) {
3874       unsigned NumElts = VT.getVectorNumElements();
3875       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3876       return DAG.getNode(ISD::BITCAST, dl, VT,
3877                          DAG.getConstant(0, dl,
3878                                          EVT::getVectorVT(*DAG.getContext(),
3879                                                           EltVT, NumElts)));
3880     } else
3881       llvm_unreachable("Expected type!");
3882   }
3883
3884   assert(!VT.isVector() && "Can't handle vector type here!");
3885   unsigned NumVTBits = VT.getSizeInBits();
3886   unsigned NumVTBytes = NumVTBits / 8;
3887   unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size()));
3888
3889   APInt Val(NumVTBits, 0);
3890   if (TLI.isLittleEndian()) {
3891     for (unsigned i = 0; i != NumBytes; ++i)
3892       Val |= (uint64_t)(unsigned char)Str[i] << i*8;
3893   } else {
3894     for (unsigned i = 0; i != NumBytes; ++i)
3895       Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8;
3896   }
3897
3898   // If the "cost" of materializing the integer immediate is less than the cost
3899   // of a load, then it is cost effective to turn the load into the immediate.
3900   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
3901   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
3902     return DAG.getConstant(Val, dl, VT);
3903   return SDValue(nullptr, 0);
3904 }
3905
3906 /// getMemBasePlusOffset - Returns base and offset node for the
3907 ///
3908 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset, SDLoc dl,
3909                                       SelectionDAG &DAG) {
3910   EVT VT = Base.getValueType();
3911   return DAG.getNode(ISD::ADD, dl,
3912                      VT, Base, DAG.getConstant(Offset, dl, VT));
3913 }
3914
3915 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3916 ///
3917 static bool isMemSrcFromString(SDValue Src, StringRef &Str) {
3918   unsigned SrcDelta = 0;
3919   GlobalAddressSDNode *G = nullptr;
3920   if (Src.getOpcode() == ISD::GlobalAddress)
3921     G = cast<GlobalAddressSDNode>(Src);
3922   else if (Src.getOpcode() == ISD::ADD &&
3923            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3924            Src.getOperand(1).getOpcode() == ISD::Constant) {
3925     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3926     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3927   }
3928   if (!G)
3929     return false;
3930
3931   return getConstantStringInfo(G->getGlobal(), Str, SrcDelta, false);
3932 }
3933
3934 /// FindOptimalMemOpLowering - Determines the optimial series memory ops
3935 /// to replace the memset / memcpy. Return true if the number of memory ops
3936 /// is below the threshold. It returns the types of the sequence of
3937 /// memory ops to perform memset / memcpy by reference.
3938 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
3939                                      unsigned Limit, uint64_t Size,
3940                                      unsigned DstAlign, unsigned SrcAlign,
3941                                      bool IsMemset,
3942                                      bool ZeroMemset,
3943                                      bool MemcpyStrSrc,
3944                                      bool AllowOverlap,
3945                                      SelectionDAG &DAG,
3946                                      const TargetLowering &TLI) {
3947   assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
3948          "Expecting memcpy / memset source to meet alignment requirement!");
3949   // If 'SrcAlign' is zero, that means the memory operation does not need to
3950   // load the value, i.e. memset or memcpy from constant string. Otherwise,
3951   // it's the inferred alignment of the source. 'DstAlign', on the other hand,
3952   // is the specified alignment of the memory operation. If it is zero, that
3953   // means it's possible to change the alignment of the destination.
3954   // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
3955   // not need to be loaded.
3956   EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
3957                                    IsMemset, ZeroMemset, MemcpyStrSrc,
3958                                    DAG.getMachineFunction());
3959
3960   if (VT == MVT::Other) {
3961     unsigned AS = 0;
3962     if (DstAlign >= TLI.getDataLayout()->getPointerPrefAlignment(AS) ||
3963         TLI.allowsMisalignedMemoryAccesses(VT, AS, DstAlign)) {
3964       VT = TLI.getPointerTy();
3965     } else {
3966       switch (DstAlign & 7) {
3967       case 0:  VT = MVT::i64; break;
3968       case 4:  VT = MVT::i32; break;
3969       case 2:  VT = MVT::i16; break;
3970       default: VT = MVT::i8;  break;
3971       }
3972     }
3973
3974     MVT LVT = MVT::i64;
3975     while (!TLI.isTypeLegal(LVT))
3976       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3977     assert(LVT.isInteger());
3978
3979     if (VT.bitsGT(LVT))
3980       VT = LVT;
3981   }
3982
3983   unsigned NumMemOps = 0;
3984   while (Size != 0) {
3985     unsigned VTSize = VT.getSizeInBits() / 8;
3986     while (VTSize > Size) {
3987       // For now, only use non-vector load / store's for the left-over pieces.
3988       EVT NewVT = VT;
3989       unsigned NewVTSize;
3990
3991       bool Found = false;
3992       if (VT.isVector() || VT.isFloatingPoint()) {
3993         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
3994         if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
3995             TLI.isSafeMemOpType(NewVT.getSimpleVT()))
3996           Found = true;
3997         else if (NewVT == MVT::i64 &&
3998                  TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
3999                  TLI.isSafeMemOpType(MVT::f64)) {
4000           // i64 is usually not legal on 32-bit targets, but f64 may be.
4001           NewVT = MVT::f64;
4002           Found = true;
4003         }
4004       }
4005
4006       if (!Found) {
4007         do {
4008           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
4009           if (NewVT == MVT::i8)
4010             break;
4011         } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
4012       }
4013       NewVTSize = NewVT.getSizeInBits() / 8;
4014
4015       // If the new VT cannot cover all of the remaining bits, then consider
4016       // issuing a (or a pair of) unaligned and overlapping load / store.
4017       // FIXME: Only does this for 64-bit or more since we don't have proper
4018       // cost model for unaligned load / store.
4019       bool Fast;
4020       unsigned AS = 0;
4021       if (NumMemOps && AllowOverlap &&
4022           VTSize >= 8 && NewVTSize < Size &&
4023           TLI.allowsMisalignedMemoryAccesses(VT, AS, DstAlign, &Fast) && Fast)
4024         VTSize = Size;
4025       else {
4026         VT = NewVT;
4027         VTSize = NewVTSize;
4028       }
4029     }
4030
4031     if (++NumMemOps > Limit)
4032       return false;
4033
4034     MemOps.push_back(VT);
4035     Size -= VTSize;
4036   }
4037
4038   return true;
4039 }
4040
4041 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, SDLoc dl,
4042                                        SDValue Chain, SDValue Dst,
4043                                        SDValue Src, uint64_t Size,
4044                                        unsigned Align, bool isVol,
4045                                        bool AlwaysInline,
4046                                        MachinePointerInfo DstPtrInfo,
4047                                        MachinePointerInfo SrcPtrInfo) {
4048   // Turn a memcpy of undef to nop.
4049   if (Src.getOpcode() == ISD::UNDEF)
4050     return Chain;
4051
4052   // Expand memcpy to a series of load and store ops if the size operand falls
4053   // below a certain threshold.
4054   // TODO: In the AlwaysInline case, if the size is big then generate a loop
4055   // rather than maybe a humongous number of loads and stores.
4056   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4057   std::vector<EVT> MemOps;
4058   bool DstAlignCanChange = false;
4059   MachineFunction &MF = DAG.getMachineFunction();
4060   MachineFrameInfo *MFI = MF.getFrameInfo();
4061   bool OptSize = MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
4062   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4063   if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
4064     DstAlignCanChange = true;
4065   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4066   if (Align > SrcAlign)
4067     SrcAlign = Align;
4068   StringRef Str;
4069   bool CopyFromStr = isMemSrcFromString(Src, Str);
4070   bool isZeroStr = CopyFromStr && Str.empty();
4071   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
4072
4073   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4074                                 (DstAlignCanChange ? 0 : Align),
4075                                 (isZeroStr ? 0 : SrcAlign),
4076                                 false, false, CopyFromStr, true, DAG, TLI))
4077     return SDValue();
4078
4079   if (DstAlignCanChange) {
4080     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4081     unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
4082
4083     // Don't promote to an alignment that would require dynamic stack
4084     // realignment.
4085     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4086     if (!TRI->needsStackRealignment(MF))
4087        while (NewAlign > Align &&
4088              TLI.getDataLayout()->exceedsNaturalStackAlignment(NewAlign))
4089           NewAlign /= 2;
4090
4091     if (NewAlign > Align) {
4092       // Give the stack frame object a larger alignment if needed.
4093       if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
4094         MFI->setObjectAlignment(FI->getIndex(), NewAlign);
4095       Align = NewAlign;
4096     }
4097   }
4098
4099   SmallVector<SDValue, 8> OutChains;
4100   unsigned NumMemOps = MemOps.size();
4101   uint64_t SrcOff = 0, DstOff = 0;
4102   for (unsigned i = 0; i != NumMemOps; ++i) {
4103     EVT VT = MemOps[i];
4104     unsigned VTSize = VT.getSizeInBits() / 8;
4105     SDValue Value, Store;
4106
4107     if (VTSize > Size) {
4108       // Issuing an unaligned load / store pair  that overlaps with the previous
4109       // pair. Adjust the offset accordingly.
4110       assert(i == NumMemOps-1 && i != 0);
4111       SrcOff -= VTSize - Size;
4112       DstOff -= VTSize - Size;
4113     }
4114
4115     if (CopyFromStr &&
4116         (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
4117       // It's unlikely a store of a vector immediate can be done in a single
4118       // instruction. It would require a load from a constantpool first.
4119       // We only handle zero vectors here.
4120       // FIXME: Handle other cases where store of vector immediate is done in
4121       // a single instruction.
4122       Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff));
4123       if (Value.getNode())
4124         Store = DAG.getStore(Chain, dl, Value,
4125                              getMemBasePlusOffset(Dst, DstOff, dl, DAG),
4126                              DstPtrInfo.getWithOffset(DstOff), isVol,
4127                              false, Align);
4128     }
4129
4130     if (!Store.getNode()) {
4131       // The type might not be legal for the target.  This should only happen
4132       // if the type is smaller than a legal type, as on PPC, so the right
4133       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
4134       // to Load/Store if NVT==VT.
4135       // FIXME does the case above also need this?
4136       EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
4137       assert(NVT.bitsGE(VT));
4138       Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
4139                              getMemBasePlusOffset(Src, SrcOff, dl, DAG),
4140                              SrcPtrInfo.getWithOffset(SrcOff), VT, isVol, false,
4141                              false, MinAlign(SrcAlign, SrcOff));
4142       Store = DAG.getTruncStore(Chain, dl, Value,
4143                                 getMemBasePlusOffset(Dst, DstOff, dl, DAG),
4144                                 DstPtrInfo.getWithOffset(DstOff), VT, isVol,
4145                                 false, Align);
4146     }
4147     OutChains.push_back(Store);
4148     SrcOff += VTSize;
4149     DstOff += VTSize;
4150     Size -= VTSize;
4151   }
4152
4153   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4154 }
4155
4156 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, SDLoc dl,
4157                                         SDValue Chain, SDValue Dst,
4158                                         SDValue Src, uint64_t Size,
4159                                         unsigned Align,  bool isVol,
4160                                         bool AlwaysInline,
4161                                         MachinePointerInfo DstPtrInfo,
4162                                         MachinePointerInfo SrcPtrInfo) {
4163   // Turn a memmove of undef to nop.
4164   if (Src.getOpcode() == ISD::UNDEF)
4165     return Chain;
4166
4167   // Expand memmove to a series of load and store ops if the size operand falls
4168   // below a certain threshold.
4169   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4170   std::vector<EVT> MemOps;
4171   bool DstAlignCanChange = false;
4172   MachineFunction &MF = DAG.getMachineFunction();
4173   MachineFrameInfo *MFI = MF.getFrameInfo();
4174   bool OptSize = MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
4175   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4176   if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
4177     DstAlignCanChange = true;
4178   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4179   if (Align > SrcAlign)
4180     SrcAlign = Align;
4181   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
4182
4183   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4184                                 (DstAlignCanChange ? 0 : Align), SrcAlign,
4185                                 false, false, false, false, DAG, TLI))
4186     return SDValue();
4187
4188   if (DstAlignCanChange) {
4189     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4190     unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
4191     if (NewAlign > Align) {
4192       // Give the stack frame object a larger alignment if needed.
4193       if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
4194         MFI->setObjectAlignment(FI->getIndex(), NewAlign);
4195       Align = NewAlign;
4196     }
4197   }
4198
4199   uint64_t SrcOff = 0, DstOff = 0;
4200   SmallVector<SDValue, 8> LoadValues;
4201   SmallVector<SDValue, 8> LoadChains;
4202   SmallVector<SDValue, 8> OutChains;
4203   unsigned NumMemOps = MemOps.size();
4204   for (unsigned i = 0; i < NumMemOps; i++) {
4205     EVT VT = MemOps[i];
4206     unsigned VTSize = VT.getSizeInBits() / 8;
4207     SDValue Value;
4208
4209     Value = DAG.getLoad(VT, dl, Chain,
4210                         getMemBasePlusOffset(Src, SrcOff, dl, DAG),
4211                         SrcPtrInfo.getWithOffset(SrcOff), isVol,
4212                         false, false, SrcAlign);
4213     LoadValues.push_back(Value);
4214     LoadChains.push_back(Value.getValue(1));
4215     SrcOff += VTSize;
4216   }
4217   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
4218   OutChains.clear();
4219   for (unsigned i = 0; i < NumMemOps; i++) {
4220     EVT VT = MemOps[i];
4221     unsigned VTSize = VT.getSizeInBits() / 8;
4222     SDValue Store;
4223
4224     Store = DAG.getStore(Chain, dl, LoadValues[i],
4225                          getMemBasePlusOffset(Dst, DstOff, dl, DAG),
4226                          DstPtrInfo.getWithOffset(DstOff), isVol, false, Align);
4227     OutChains.push_back(Store);
4228     DstOff += VTSize;
4229   }
4230
4231   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4232 }
4233
4234 /// \brief Lower the call to 'memset' intrinsic function into a series of store
4235 /// operations.
4236 ///
4237 /// \param DAG Selection DAG where lowered code is placed.
4238 /// \param dl Link to corresponding IR location.
4239 /// \param Chain Control flow dependency.
4240 /// \param Dst Pointer to destination memory location.
4241 /// \param Src Value of byte to write into the memory.
4242 /// \param Size Number of bytes to write.
4243 /// \param Align Alignment of the destination in bytes.
4244 /// \param isVol True if destination is volatile.
4245 /// \param DstPtrInfo IR information on the memory pointer.
4246 /// \returns New head in the control flow, if lowering was successful, empty
4247 /// SDValue otherwise.
4248 ///
4249 /// The function tries to replace 'llvm.memset' intrinsic with several store
4250 /// operations and value calculation code. This is usually profitable for small
4251 /// memory size.
4252 static SDValue getMemsetStores(SelectionDAG &DAG, SDLoc dl,
4253                                SDValue Chain, SDValue Dst,
4254                                SDValue Src, uint64_t Size,
4255                                unsigned Align, bool isVol,
4256                                MachinePointerInfo DstPtrInfo) {
4257   // Turn a memset of undef to nop.
4258   if (Src.getOpcode() == ISD::UNDEF)
4259     return Chain;
4260
4261   // Expand memset to a series of load/store ops if the size operand
4262   // falls below a certain threshold.
4263   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4264   std::vector<EVT> MemOps;
4265   bool DstAlignCanChange = false;
4266   MachineFunction &MF = DAG.getMachineFunction();
4267   MachineFrameInfo *MFI = MF.getFrameInfo();
4268   bool OptSize = MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
4269   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4270   if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
4271     DstAlignCanChange = true;
4272   bool IsZeroVal =
4273     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
4274   if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
4275                                 Size, (DstAlignCanChange ? 0 : Align), 0,
4276                                 true, IsZeroVal, false, true, DAG, TLI))
4277     return SDValue();
4278
4279   if (DstAlignCanChange) {
4280     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4281     unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
4282     if (NewAlign > Align) {
4283       // Give the stack frame object a larger alignment if needed.
4284       if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
4285         MFI->setObjectAlignment(FI->getIndex(), NewAlign);
4286       Align = NewAlign;
4287     }
4288   }
4289
4290   SmallVector<SDValue, 8> OutChains;
4291   uint64_t DstOff = 0;
4292   unsigned NumMemOps = MemOps.size();
4293
4294   // Find the largest store and generate the bit pattern for it.
4295   EVT LargestVT = MemOps[0];
4296   for (unsigned i = 1; i < NumMemOps; i++)
4297     if (MemOps[i].bitsGT(LargestVT))
4298       LargestVT = MemOps[i];
4299   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
4300
4301   for (unsigned i = 0; i < NumMemOps; i++) {
4302     EVT VT = MemOps[i];
4303     unsigned VTSize = VT.getSizeInBits() / 8;
4304     if (VTSize > Size) {
4305       // Issuing an unaligned load / store pair  that overlaps with the previous
4306       // pair. Adjust the offset accordingly.
4307       assert(i == NumMemOps-1 && i != 0);
4308       DstOff -= VTSize - Size;
4309     }
4310
4311     // If this store is smaller than the largest store see whether we can get
4312     // the smaller value for free with a truncate.
4313     SDValue Value = MemSetValue;
4314     if (VT.bitsLT(LargestVT)) {
4315       if (!LargestVT.isVector() && !VT.isVector() &&
4316           TLI.isTruncateFree(LargestVT, VT))
4317         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
4318       else
4319         Value = getMemsetValue(Src, VT, DAG, dl);
4320     }
4321     assert(Value.getValueType() == VT && "Value with wrong type.");
4322     SDValue Store = DAG.getStore(Chain, dl, Value,
4323                                  getMemBasePlusOffset(Dst, DstOff, dl, DAG),
4324                                  DstPtrInfo.getWithOffset(DstOff),
4325                                  isVol, false, Align);
4326     OutChains.push_back(Store);
4327     DstOff += VT.getSizeInBits() / 8;
4328     Size -= VTSize;
4329   }
4330
4331   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4332 }
4333
4334 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDLoc dl, SDValue Dst,
4335                                 SDValue Src, SDValue Size,
4336                                 unsigned Align, bool isVol, bool AlwaysInline,
4337                                 bool isTailCall, MachinePointerInfo DstPtrInfo,
4338                                 MachinePointerInfo SrcPtrInfo) {
4339   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4340
4341   // Check to see if we should lower the memcpy to loads and stores first.
4342   // For cases within the target-specified limits, this is the best choice.
4343   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4344   if (ConstantSize) {
4345     // Memcpy with size zero? Just return the original chain.
4346     if (ConstantSize->isNullValue())
4347       return Chain;
4348
4349     SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
4350                                              ConstantSize->getZExtValue(),Align,
4351                                 isVol, false, DstPtrInfo, SrcPtrInfo);
4352     if (Result.getNode())
4353       return Result;
4354   }
4355
4356   // Then check to see if we should lower the memcpy with target-specific
4357   // code. If the target chooses to do this, this is the next best.
4358   if (TSI) {
4359     SDValue Result = TSI->EmitTargetCodeForMemcpy(
4360         *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
4361         DstPtrInfo, SrcPtrInfo);
4362     if (Result.getNode())
4363       return Result;
4364   }
4365
4366   // If we really need inline code and the target declined to provide it,
4367   // use a (potentially long) sequence of loads and stores.
4368   if (AlwaysInline) {
4369     assert(ConstantSize && "AlwaysInline requires a constant size!");
4370     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
4371                                    ConstantSize->getZExtValue(), Align, isVol,
4372                                    true, DstPtrInfo, SrcPtrInfo);
4373   }
4374
4375   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
4376   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
4377   // respect volatile, so they may do things like read or write memory
4378   // beyond the given memory regions. But fixing this isn't easy, and most
4379   // people don't care.
4380
4381   // Emit a library call.
4382   TargetLowering::ArgListTy Args;
4383   TargetLowering::ArgListEntry Entry;
4384   Entry.Ty = TLI->getDataLayout()->getIntPtrType(*getContext());
4385   Entry.Node = Dst; Args.push_back(Entry);
4386   Entry.Node = Src; Args.push_back(Entry);
4387   Entry.Node = Size; Args.push_back(Entry);
4388   // FIXME: pass in SDLoc
4389   TargetLowering::CallLoweringInfo CLI(*this);
4390   CLI.setDebugLoc(dl).setChain(Chain)
4391     .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
4392                Type::getVoidTy(*getContext()),
4393                getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
4394                                  TLI->getPointerTy()), std::move(Args), 0)
4395     .setDiscardResult()
4396     .setTailCall(isTailCall);
4397
4398   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4399   return CallResult.second;
4400 }
4401
4402 SDValue SelectionDAG::getMemmove(SDValue Chain, SDLoc dl, SDValue Dst,
4403                                  SDValue Src, SDValue Size,
4404                                  unsigned Align, bool isVol, bool isTailCall,
4405                                  MachinePointerInfo DstPtrInfo,
4406                                  MachinePointerInfo SrcPtrInfo) {
4407   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4408
4409   // Check to see if we should lower the memmove to loads and stores first.
4410   // For cases within the target-specified limits, this is the best choice.
4411   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4412   if (ConstantSize) {
4413     // Memmove with size zero? Just return the original chain.
4414     if (ConstantSize->isNullValue())
4415       return Chain;
4416
4417     SDValue Result =
4418       getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
4419                                ConstantSize->getZExtValue(), Align, isVol,
4420                                false, DstPtrInfo, SrcPtrInfo);
4421     if (Result.getNode())
4422       return Result;
4423   }
4424
4425   // Then check to see if we should lower the memmove with target-specific
4426   // code. If the target chooses to do this, this is the next best.
4427   if (TSI) {
4428     SDValue Result = TSI->EmitTargetCodeForMemmove(
4429         *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
4430     if (Result.getNode())
4431       return Result;
4432   }
4433
4434   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
4435   // not be safe.  See memcpy above for more details.
4436
4437   // Emit a library call.
4438   TargetLowering::ArgListTy Args;
4439   TargetLowering::ArgListEntry Entry;
4440   Entry.Ty = TLI->getDataLayout()->getIntPtrType(*getContext());
4441   Entry.Node = Dst; Args.push_back(Entry);
4442   Entry.Node = Src; Args.push_back(Entry);
4443   Entry.Node = Size; Args.push_back(Entry);
4444   // FIXME:  pass in SDLoc
4445   TargetLowering::CallLoweringInfo CLI(*this);
4446   CLI.setDebugLoc(dl).setChain(Chain)
4447     .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
4448                Type::getVoidTy(*getContext()),
4449                getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
4450                                  TLI->getPointerTy()), std::move(Args), 0)
4451     .setDiscardResult()
4452     .setTailCall(isTailCall);
4453
4454   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4455   return CallResult.second;
4456 }
4457
4458 SDValue SelectionDAG::getMemset(SDValue Chain, SDLoc dl, SDValue Dst,
4459                                 SDValue Src, SDValue Size,
4460                                 unsigned Align, bool isVol, bool isTailCall,
4461                                 MachinePointerInfo DstPtrInfo) {
4462   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4463
4464   // Check to see if we should lower the memset to stores first.
4465   // For cases within the target-specified limits, this is the best choice.
4466   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4467   if (ConstantSize) {
4468     // Memset with size zero? Just return the original chain.
4469     if (ConstantSize->isNullValue())
4470       return Chain;
4471
4472     SDValue Result =
4473       getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
4474                       Align, isVol, DstPtrInfo);
4475
4476     if (Result.getNode())
4477       return Result;
4478   }
4479
4480   // Then check to see if we should lower the memset with target-specific
4481   // code. If the target chooses to do this, this is the next best.
4482   if (TSI) {
4483     SDValue Result = TSI->EmitTargetCodeForMemset(
4484         *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
4485     if (Result.getNode())
4486       return Result;
4487   }
4488
4489   // Emit a library call.
4490   Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(*getContext());
4491   TargetLowering::ArgListTy Args;
4492   TargetLowering::ArgListEntry Entry;
4493   Entry.Node = Dst; Entry.Ty = IntPtrTy;
4494   Args.push_back(Entry);
4495   Entry.Node = Src;
4496   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
4497   Args.push_back(Entry);
4498   Entry.Node = Size;
4499   Entry.Ty = IntPtrTy;
4500   Args.push_back(Entry);
4501
4502   // FIXME: pass in SDLoc
4503   TargetLowering::CallLoweringInfo CLI(*this);
4504   CLI.setDebugLoc(dl).setChain(Chain)
4505     .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
4506                Type::getVoidTy(*getContext()),
4507                getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
4508                                  TLI->getPointerTy()), std::move(Args), 0)
4509     .setDiscardResult()
4510     .setTailCall(isTailCall);
4511
4512   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4513   return CallResult.second;
4514 }
4515
4516 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4517                                 SDVTList VTList, ArrayRef<SDValue> Ops,
4518                                 MachineMemOperand *MMO,
4519                                 AtomicOrdering SuccessOrdering,
4520                                 AtomicOrdering FailureOrdering,
4521                                 SynchronizationScope SynchScope) {
4522   FoldingSetNodeID ID;
4523   ID.AddInteger(MemVT.getRawBits());
4524   AddNodeIDNode(ID, Opcode, VTList, Ops);
4525   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4526   void* IP = nullptr;
4527   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4528     cast<AtomicSDNode>(E)->refineAlignment(MMO);
4529     return SDValue(E, 0);
4530   }
4531
4532   // Allocate the operands array for the node out of the BumpPtrAllocator, since
4533   // SDNode doesn't have access to it.  This memory will be "leaked" when
4534   // the node is deallocated, but recovered when the allocator is released.
4535   // If the number of operands is less than 5 we use AtomicSDNode's internal
4536   // storage.
4537   unsigned NumOps = Ops.size();
4538   SDUse *DynOps = NumOps > 4 ? OperandAllocator.Allocate<SDUse>(NumOps)
4539                              : nullptr;
4540
4541   SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl.getIROrder(),
4542                                                dl.getDebugLoc(), VTList, MemVT,
4543                                                Ops.data(), DynOps, NumOps, MMO,
4544                                                SuccessOrdering, FailureOrdering,
4545                                                SynchScope);
4546   CSEMap.InsertNode(N, IP);
4547   InsertNode(N);
4548   return SDValue(N, 0);
4549 }
4550
4551 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4552                                 SDVTList VTList, ArrayRef<SDValue> Ops,
4553                                 MachineMemOperand *MMO,
4554                                 AtomicOrdering Ordering,
4555                                 SynchronizationScope SynchScope) {
4556   return getAtomic(Opcode, dl, MemVT, VTList, Ops, MMO, Ordering,
4557                    Ordering, SynchScope);
4558 }
4559
4560 SDValue SelectionDAG::getAtomicCmpSwap(
4561     unsigned Opcode, SDLoc dl, EVT MemVT, SDVTList VTs, SDValue Chain,
4562     SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
4563     unsigned Alignment, AtomicOrdering SuccessOrdering,
4564     AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) {
4565   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
4566          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
4567   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
4568
4569   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4570     Alignment = getEVTAlignment(MemVT);
4571
4572   MachineFunction &MF = getMachineFunction();
4573
4574   // FIXME: Volatile isn't really correct; we should keep track of atomic
4575   // orderings in the memoperand.
4576   unsigned Flags = MachineMemOperand::MOVolatile;
4577   Flags |= MachineMemOperand::MOLoad;
4578   Flags |= MachineMemOperand::MOStore;
4579
4580   MachineMemOperand *MMO =
4581     MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment);
4582
4583   return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO,
4584                           SuccessOrdering, FailureOrdering, SynchScope);
4585 }
4586
4587 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, SDLoc dl, EVT MemVT,
4588                                        SDVTList VTs, SDValue Chain, SDValue Ptr,
4589                                        SDValue Cmp, SDValue Swp,
4590                                        MachineMemOperand *MMO,
4591                                        AtomicOrdering SuccessOrdering,
4592                                        AtomicOrdering FailureOrdering,
4593                                        SynchronizationScope SynchScope) {
4594   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
4595          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
4596   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
4597
4598   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
4599   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO,
4600                    SuccessOrdering, FailureOrdering, SynchScope);
4601 }
4602
4603 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4604                                 SDValue Chain,
4605                                 SDValue Ptr, SDValue Val,
4606                                 const Value* PtrVal,
4607                                 unsigned Alignment,
4608                                 AtomicOrdering Ordering,
4609                                 SynchronizationScope SynchScope) {
4610   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4611     Alignment = getEVTAlignment(MemVT);
4612
4613   MachineFunction &MF = getMachineFunction();
4614   // An atomic store does not load. An atomic load does not store.
4615   // (An atomicrmw obviously both loads and stores.)
4616   // For now, atomics are considered to be volatile always, and they are
4617   // chained as such.
4618   // FIXME: Volatile isn't really correct; we should keep track of atomic
4619   // orderings in the memoperand.
4620   unsigned Flags = MachineMemOperand::MOVolatile;
4621   if (Opcode != ISD::ATOMIC_STORE)
4622     Flags |= MachineMemOperand::MOLoad;
4623   if (Opcode != ISD::ATOMIC_LOAD)
4624     Flags |= MachineMemOperand::MOStore;
4625
4626   MachineMemOperand *MMO =
4627     MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
4628                             MemVT.getStoreSize(), Alignment);
4629
4630   return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO,
4631                    Ordering, SynchScope);
4632 }
4633
4634 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4635                                 SDValue Chain,
4636                                 SDValue Ptr, SDValue Val,
4637                                 MachineMemOperand *MMO,
4638                                 AtomicOrdering Ordering,
4639                                 SynchronizationScope SynchScope) {
4640   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
4641           Opcode == ISD::ATOMIC_LOAD_SUB ||
4642           Opcode == ISD::ATOMIC_LOAD_AND ||
4643           Opcode == ISD::ATOMIC_LOAD_OR ||
4644           Opcode == ISD::ATOMIC_LOAD_XOR ||
4645           Opcode == ISD::ATOMIC_LOAD_NAND ||
4646           Opcode == ISD::ATOMIC_LOAD_MIN ||
4647           Opcode == ISD::ATOMIC_LOAD_MAX ||
4648           Opcode == ISD::ATOMIC_LOAD_UMIN ||
4649           Opcode == ISD::ATOMIC_LOAD_UMAX ||
4650           Opcode == ISD::ATOMIC_SWAP ||
4651           Opcode == ISD::ATOMIC_STORE) &&
4652          "Invalid Atomic Op");
4653
4654   EVT VT = Val.getValueType();
4655
4656   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
4657                                                getVTList(VT, MVT::Other);
4658   SDValue Ops[] = {Chain, Ptr, Val};
4659   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope);
4660 }
4661
4662 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4663                                 EVT VT, SDValue Chain,
4664                                 SDValue Ptr,
4665                                 MachineMemOperand *MMO,
4666                                 AtomicOrdering Ordering,
4667                                 SynchronizationScope SynchScope) {
4668   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
4669
4670   SDVTList VTs = getVTList(VT, MVT::Other);
4671   SDValue Ops[] = {Chain, Ptr};
4672   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope);
4673 }
4674
4675 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
4676 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, SDLoc dl) {
4677   if (Ops.size() == 1)
4678     return Ops[0];
4679
4680   SmallVector<EVT, 4> VTs;
4681   VTs.reserve(Ops.size());
4682   for (unsigned i = 0; i < Ops.size(); ++i)
4683     VTs.push_back(Ops[i].getValueType());
4684   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
4685 }
4686
4687 SDValue
4688 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList,
4689                                   ArrayRef<SDValue> Ops,
4690                                   EVT MemVT, MachinePointerInfo PtrInfo,
4691                                   unsigned Align, bool Vol,
4692                                   bool ReadMem, bool WriteMem, unsigned Size) {
4693   if (Align == 0)  // Ensure that codegen never sees alignment 0
4694     Align = getEVTAlignment(MemVT);
4695
4696   MachineFunction &MF = getMachineFunction();
4697   unsigned Flags = 0;
4698   if (WriteMem)
4699     Flags |= MachineMemOperand::MOStore;
4700   if (ReadMem)
4701     Flags |= MachineMemOperand::MOLoad;
4702   if (Vol)
4703     Flags |= MachineMemOperand::MOVolatile;
4704   if (!Size)
4705     Size = MemVT.getStoreSize();
4706   MachineMemOperand *MMO =
4707     MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
4708
4709   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
4710 }
4711
4712 SDValue
4713 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList,
4714                                   ArrayRef<SDValue> Ops, EVT MemVT,
4715                                   MachineMemOperand *MMO) {
4716   assert((Opcode == ISD::INTRINSIC_VOID ||
4717           Opcode == ISD::INTRINSIC_W_CHAIN ||
4718           Opcode == ISD::PREFETCH ||
4719           Opcode == ISD::LIFETIME_START ||
4720           Opcode == ISD::LIFETIME_END ||
4721           (Opcode <= INT_MAX &&
4722            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
4723          "Opcode is not a memory-accessing opcode!");
4724
4725   // Memoize the node unless it returns a flag.
4726   MemIntrinsicSDNode *N;
4727   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4728     FoldingSetNodeID ID;
4729     AddNodeIDNode(ID, Opcode, VTList, Ops);
4730     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4731     void *IP = nullptr;
4732     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4733       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
4734       return SDValue(E, 0);
4735     }
4736
4737     N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(),
4738                                                dl.getDebugLoc(), VTList, Ops,
4739                                                MemVT, MMO);
4740     CSEMap.InsertNode(N, IP);
4741   } else {
4742     N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(),
4743                                                dl.getDebugLoc(), VTList, Ops,
4744                                                MemVT, MMO);
4745   }
4746   InsertNode(N);
4747   return SDValue(N, 0);
4748 }
4749
4750 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4751 /// MachinePointerInfo record from it.  This is particularly useful because the
4752 /// code generator has many cases where it doesn't bother passing in a
4753 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4754 static MachinePointerInfo InferPointerInfo(SDValue Ptr, int64_t Offset = 0) {
4755   // If this is FI+Offset, we can model it.
4756   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
4757     return MachinePointerInfo::getFixedStack(FI->getIndex(), Offset);
4758
4759   // If this is (FI+Offset1)+Offset2, we can model it.
4760   if (Ptr.getOpcode() != ISD::ADD ||
4761       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
4762       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
4763     return MachinePointerInfo();
4764
4765   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4766   return MachinePointerInfo::getFixedStack(FI, Offset+
4767                        cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
4768 }
4769
4770 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4771 /// MachinePointerInfo record from it.  This is particularly useful because the
4772 /// code generator has many cases where it doesn't bother passing in a
4773 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4774 static MachinePointerInfo InferPointerInfo(SDValue Ptr, SDValue OffsetOp) {
4775   // If the 'Offset' value isn't a constant, we can't handle this.
4776   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
4777     return InferPointerInfo(Ptr, OffsetNode->getSExtValue());
4778   if (OffsetOp.getOpcode() == ISD::UNDEF)
4779     return InferPointerInfo(Ptr);
4780   return MachinePointerInfo();
4781 }
4782
4783
4784 SDValue
4785 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4786                       EVT VT, SDLoc dl, SDValue Chain,
4787                       SDValue Ptr, SDValue Offset,
4788                       MachinePointerInfo PtrInfo, EVT MemVT,
4789                       bool isVolatile, bool isNonTemporal, bool isInvariant,
4790                       unsigned Alignment, const AAMDNodes &AAInfo,
4791                       const MDNode *Ranges) {
4792   assert(Chain.getValueType() == MVT::Other &&
4793         "Invalid chain type");
4794   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4795     Alignment = getEVTAlignment(VT);
4796
4797   unsigned Flags = MachineMemOperand::MOLoad;
4798   if (isVolatile)
4799     Flags |= MachineMemOperand::MOVolatile;
4800   if (isNonTemporal)
4801     Flags |= MachineMemOperand::MONonTemporal;
4802   if (isInvariant)
4803     Flags |= MachineMemOperand::MOInvariant;
4804
4805   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
4806   // clients.
4807   if (PtrInfo.V.isNull())
4808     PtrInfo = InferPointerInfo(Ptr, Offset);
4809
4810   MachineFunction &MF = getMachineFunction();
4811   MachineMemOperand *MMO =
4812     MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
4813                             AAInfo, Ranges);
4814   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
4815 }
4816
4817 SDValue
4818 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4819                       EVT VT, SDLoc dl, SDValue Chain,
4820                       SDValue Ptr, SDValue Offset, EVT MemVT,
4821                       MachineMemOperand *MMO) {
4822   if (VT == MemVT) {
4823     ExtType = ISD::NON_EXTLOAD;
4824   } else if (ExtType == ISD::NON_EXTLOAD) {
4825     assert(VT == MemVT && "Non-extending load from different memory type!");
4826   } else {
4827     // Extending load.
4828     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
4829            "Should only be an extending load, not truncating!");
4830     assert(VT.isInteger() == MemVT.isInteger() &&
4831            "Cannot convert from FP to Int or Int -> FP!");
4832     assert(VT.isVector() == MemVT.isVector() &&
4833            "Cannot use an ext load to convert to or from a vector!");
4834     assert((!VT.isVector() ||
4835             VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
4836            "Cannot use an ext load to change the number of vector elements!");
4837   }
4838
4839   bool Indexed = AM != ISD::UNINDEXED;
4840   assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
4841          "Unindexed load with an offset!");
4842
4843   SDVTList VTs = Indexed ?
4844     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
4845   SDValue Ops[] = { Chain, Ptr, Offset };
4846   FoldingSetNodeID ID;
4847   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
4848   ID.AddInteger(MemVT.getRawBits());
4849   ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
4850                                      MMO->isNonTemporal(),
4851                                      MMO->isInvariant()));
4852   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4853   void *IP = nullptr;
4854   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4855     cast<LoadSDNode>(E)->refineAlignment(MMO);
4856     return SDValue(E, 0);
4857   }
4858   SDNode *N = new (NodeAllocator) LoadSDNode(Ops, dl.getIROrder(),
4859                                              dl.getDebugLoc(), VTs, AM, ExtType,
4860                                              MemVT, MMO);
4861   CSEMap.InsertNode(N, IP);
4862   InsertNode(N);
4863   return SDValue(N, 0);
4864 }
4865
4866 SDValue SelectionDAG::getLoad(EVT VT, SDLoc dl,
4867                               SDValue Chain, SDValue Ptr,
4868                               MachinePointerInfo PtrInfo,
4869                               bool isVolatile, bool isNonTemporal,
4870                               bool isInvariant, unsigned Alignment,
4871                               const AAMDNodes &AAInfo,
4872                               const MDNode *Ranges) {
4873   SDValue Undef = getUNDEF(Ptr.getValueType());
4874   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
4875                  PtrInfo, VT, isVolatile, isNonTemporal, isInvariant, Alignment,
4876                  AAInfo, Ranges);
4877 }
4878
4879 SDValue SelectionDAG::getLoad(EVT VT, SDLoc dl,
4880                               SDValue Chain, SDValue Ptr,
4881                               MachineMemOperand *MMO) {
4882   SDValue Undef = getUNDEF(Ptr.getValueType());
4883   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
4884                  VT, MMO);
4885 }
4886
4887 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT,
4888                                  SDValue Chain, SDValue Ptr,
4889                                  MachinePointerInfo PtrInfo, EVT MemVT,
4890                                  bool isVolatile, bool isNonTemporal,
4891                                  bool isInvariant, unsigned Alignment,
4892                                  const AAMDNodes &AAInfo) {
4893   SDValue Undef = getUNDEF(Ptr.getValueType());
4894   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
4895                  PtrInfo, MemVT, isVolatile, isNonTemporal, isInvariant,
4896                  Alignment, AAInfo);
4897 }
4898
4899
4900 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT,
4901                                  SDValue Chain, SDValue Ptr, EVT MemVT,
4902                                  MachineMemOperand *MMO) {
4903   SDValue Undef = getUNDEF(Ptr.getValueType());
4904   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
4905                  MemVT, MMO);
4906 }
4907
4908 SDValue
4909 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDLoc dl, SDValue Base,
4910                              SDValue Offset, ISD::MemIndexedMode AM) {
4911   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
4912   assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
4913          "Load is already a indexed load!");
4914   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
4915                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
4916                  LD->getMemoryVT(), LD->isVolatile(), LD->isNonTemporal(),
4917                  false, LD->getAlignment());
4918 }
4919
4920 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val,
4921                                SDValue Ptr, MachinePointerInfo PtrInfo,
4922                                bool isVolatile, bool isNonTemporal,
4923                                unsigned Alignment, const AAMDNodes &AAInfo) {
4924   assert(Chain.getValueType() == MVT::Other &&
4925         "Invalid chain type");
4926   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4927     Alignment = getEVTAlignment(Val.getValueType());
4928
4929   unsigned Flags = MachineMemOperand::MOStore;
4930   if (isVolatile)
4931     Flags |= MachineMemOperand::MOVolatile;
4932   if (isNonTemporal)
4933     Flags |= MachineMemOperand::MONonTemporal;
4934
4935   if (PtrInfo.V.isNull())
4936     PtrInfo = InferPointerInfo(Ptr);
4937
4938   MachineFunction &MF = getMachineFunction();
4939   MachineMemOperand *MMO =
4940     MF.getMachineMemOperand(PtrInfo, Flags,
4941                             Val.getValueType().getStoreSize(), Alignment,
4942                             AAInfo);
4943
4944   return getStore(Chain, dl, Val, Ptr, MMO);
4945 }
4946
4947 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val,
4948                                SDValue Ptr, MachineMemOperand *MMO) {
4949   assert(Chain.getValueType() == MVT::Other &&
4950         "Invalid chain type");
4951   EVT VT = Val.getValueType();
4952   SDVTList VTs = getVTList(MVT::Other);
4953   SDValue Undef = getUNDEF(Ptr.getValueType());
4954   SDValue Ops[] = { Chain, Val, Ptr, Undef };
4955   FoldingSetNodeID ID;
4956   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
4957   ID.AddInteger(VT.getRawBits());
4958   ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
4959                                      MMO->isNonTemporal(), MMO->isInvariant()));
4960   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4961   void *IP = nullptr;
4962   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4963     cast<StoreSDNode>(E)->refineAlignment(MMO);
4964     return SDValue(E, 0);
4965   }
4966   SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(),
4967                                               dl.getDebugLoc(), VTs,
4968                                               ISD::UNINDEXED, false, VT, MMO);
4969   CSEMap.InsertNode(N, IP);
4970   InsertNode(N);
4971   return SDValue(N, 0);
4972 }
4973
4974 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val,
4975                                     SDValue Ptr, MachinePointerInfo PtrInfo,
4976                                     EVT SVT,bool isVolatile, bool isNonTemporal,
4977                                     unsigned Alignment,
4978                                     const AAMDNodes &AAInfo) {
4979   assert(Chain.getValueType() == MVT::Other &&
4980         "Invalid chain type");
4981   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4982     Alignment = getEVTAlignment(SVT);
4983
4984   unsigned Flags = MachineMemOperand::MOStore;
4985   if (isVolatile)
4986     Flags |= MachineMemOperand::MOVolatile;
4987   if (isNonTemporal)
4988     Flags |= MachineMemOperand::MONonTemporal;
4989
4990   if (PtrInfo.V.isNull())
4991     PtrInfo = InferPointerInfo(Ptr);
4992
4993   MachineFunction &MF = getMachineFunction();
4994   MachineMemOperand *MMO =
4995     MF.getMachineMemOperand(PtrInfo, Flags, SVT.getStoreSize(), Alignment,
4996                             AAInfo);
4997
4998   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
4999 }
5000
5001 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val,
5002                                     SDValue Ptr, EVT SVT,
5003                                     MachineMemOperand *MMO) {
5004   EVT VT = Val.getValueType();
5005
5006   assert(Chain.getValueType() == MVT::Other &&
5007         "Invalid chain type");
5008   if (VT == SVT)
5009     return getStore(Chain, dl, Val, Ptr, MMO);
5010
5011   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
5012          "Should only be a truncating store, not extending!");
5013   assert(VT.isInteger() == SVT.isInteger() &&
5014          "Can't do FP-INT conversion!");
5015   assert(VT.isVector() == SVT.isVector() &&
5016          "Cannot use trunc store to convert to or from a vector!");
5017   assert((!VT.isVector() ||
5018           VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
5019          "Cannot use trunc store to change the number of vector elements!");
5020
5021   SDVTList VTs = getVTList(MVT::Other);
5022   SDValue Undef = getUNDEF(Ptr.getValueType());
5023   SDValue Ops[] = { Chain, Val, Ptr, Undef };
5024   FoldingSetNodeID ID;
5025   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5026   ID.AddInteger(SVT.getRawBits());
5027   ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
5028                                      MMO->isNonTemporal(), MMO->isInvariant()));
5029   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5030   void *IP = nullptr;
5031   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
5032     cast<StoreSDNode>(E)->refineAlignment(MMO);
5033     return SDValue(E, 0);
5034   }
5035   SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(),
5036                                               dl.getDebugLoc(), VTs,
5037                                               ISD::UNINDEXED, true, SVT, MMO);
5038   CSEMap.InsertNode(N, IP);
5039   InsertNode(N);
5040   return SDValue(N, 0);
5041 }
5042
5043 SDValue
5044 SelectionDAG::getIndexedStore(SDValue OrigStore, SDLoc dl, SDValue Base,
5045                               SDValue Offset, ISD::MemIndexedMode AM) {
5046   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
5047   assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
5048          "Store is already a indexed store!");
5049   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
5050   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
5051   FoldingSetNodeID ID;
5052   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5053   ID.AddInteger(ST->getMemoryVT().getRawBits());
5054   ID.AddInteger(ST->getRawSubclassData());
5055   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
5056   void *IP = nullptr;
5057   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5058     return SDValue(E, 0);
5059
5060   SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(),
5061                                               dl.getDebugLoc(), VTs, AM,
5062                                               ST->isTruncatingStore(),
5063                                               ST->getMemoryVT(),
5064                                               ST->getMemOperand());
5065   CSEMap.InsertNode(N, IP);
5066   InsertNode(N);
5067   return SDValue(N, 0);
5068 }
5069
5070 SDValue
5071 SelectionDAG::getMaskedLoad(EVT VT, SDLoc dl, SDValue Chain,
5072                             SDValue Ptr, SDValue Mask, SDValue Src0, EVT MemVT,
5073                             MachineMemOperand *MMO, ISD::LoadExtType ExtTy) {
5074
5075   SDVTList VTs = getVTList(VT, MVT::Other);
5076   SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
5077   FoldingSetNodeID ID;
5078   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
5079   ID.AddInteger(VT.getRawBits());
5080   ID.AddInteger(encodeMemSDNodeFlags(ExtTy, ISD::UNINDEXED,
5081                                      MMO->isVolatile(),
5082                                      MMO->isNonTemporal(),
5083                                      MMO->isInvariant()));
5084   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5085   void *IP = nullptr;
5086   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
5087     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
5088     return SDValue(E, 0);
5089   }
5090   SDNode *N = new (NodeAllocator) MaskedLoadSDNode(dl.getIROrder(),
5091                                              dl.getDebugLoc(), Ops, 4, VTs,
5092                                              ExtTy, MemVT, MMO);
5093   CSEMap.InsertNode(N, IP);
5094   InsertNode(N);
5095   return SDValue(N, 0);
5096 }
5097
5098 SDValue SelectionDAG::getMaskedStore(SDValue Chain, SDLoc dl, SDValue Val,
5099                                      SDValue Ptr, SDValue Mask, EVT MemVT,
5100                                      MachineMemOperand *MMO, bool isTrunc) {
5101   assert(Chain.getValueType() == MVT::Other &&
5102         "Invalid chain type");
5103   EVT VT = Val.getValueType();
5104   SDVTList VTs = getVTList(MVT::Other);
5105   SDValue Ops[] = { Chain, Ptr, Mask, Val };
5106   FoldingSetNodeID ID;
5107   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
5108   ID.AddInteger(VT.getRawBits());
5109   ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
5110                                      MMO->isNonTemporal(), MMO->isInvariant()));
5111   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5112   void *IP = nullptr;
5113   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
5114     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
5115     return SDValue(E, 0);
5116   }
5117   SDNode *N = new (NodeAllocator) MaskedStoreSDNode(dl.getIROrder(),
5118                                                     dl.getDebugLoc(), Ops, 4,
5119                                                     VTs, isTrunc, MemVT, MMO);
5120   CSEMap.InsertNode(N, IP);
5121   InsertNode(N);
5122   return SDValue(N, 0);
5123 }
5124
5125 SDValue
5126 SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, SDLoc dl,
5127                               ArrayRef<SDValue> Ops,
5128                               MachineMemOperand *MMO) {
5129
5130   FoldingSetNodeID ID;
5131   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
5132   ID.AddInteger(VT.getRawBits());
5133   ID.AddInteger(encodeMemSDNodeFlags(ISD::NON_EXTLOAD, ISD::UNINDEXED,
5134                                      MMO->isVolatile(),
5135                                      MMO->isNonTemporal(),
5136                                      MMO->isInvariant()));
5137   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5138   void *IP = nullptr;
5139   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
5140     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
5141     return SDValue(E, 0);
5142   }
5143   MaskedGatherSDNode *N = 
5144     new (NodeAllocator) MaskedGatherSDNode(dl.getIROrder(), dl.getDebugLoc(),
5145                                            Ops, VTs, VT, MMO);
5146   CSEMap.InsertNode(N, IP);
5147   InsertNode(N);
5148   return SDValue(N, 0);
5149 }
5150
5151 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, SDLoc dl,
5152                                        ArrayRef<SDValue> Ops,
5153                                        MachineMemOperand *MMO) {
5154   FoldingSetNodeID ID;
5155   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
5156   ID.AddInteger(VT.getRawBits());
5157   ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
5158                                      MMO->isNonTemporal(),
5159                                      MMO->isInvariant()));
5160   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5161   void *IP = nullptr;
5162   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
5163     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
5164     return SDValue(E, 0);
5165   }
5166   SDNode *N =
5167     new (NodeAllocator) MaskedScatterSDNode(dl.getIROrder(), dl.getDebugLoc(),
5168                                             Ops, VTs, VT, MMO);
5169   CSEMap.InsertNode(N, IP);
5170   InsertNode(N);
5171   return SDValue(N, 0);
5172 }
5173
5174 SDValue SelectionDAG::getVAArg(EVT VT, SDLoc dl,
5175                                SDValue Chain, SDValue Ptr,
5176                                SDValue SV,
5177                                unsigned Align) {
5178   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
5179   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
5180 }
5181
5182 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
5183                               ArrayRef<SDUse> Ops) {
5184   switch (Ops.size()) {
5185   case 0: return getNode(Opcode, DL, VT);
5186   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
5187   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
5188   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5189   default: break;
5190   }
5191
5192   // Copy from an SDUse array into an SDValue array for use with
5193   // the regular getNode logic.
5194   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
5195   return getNode(Opcode, DL, VT, NewOps);
5196 }
5197
5198 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
5199                               ArrayRef<SDValue> Ops) {
5200   unsigned NumOps = Ops.size();
5201   switch (NumOps) {
5202   case 0: return getNode(Opcode, DL, VT);
5203   case 1: return getNode(Opcode, DL, VT, Ops[0]);
5204   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
5205   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5206   default: break;
5207   }
5208
5209   switch (Opcode) {
5210   default: break;
5211   case ISD::SELECT_CC: {
5212     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
5213     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
5214            "LHS and RHS of condition must have same type!");
5215     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
5216            "True and False arms of SelectCC must have same type!");
5217     assert(Ops[2].getValueType() == VT &&
5218            "select_cc node must be of same type as true and false value!");
5219     break;
5220   }
5221   case ISD::BR_CC: {
5222     assert(NumOps == 5 && "BR_CC takes 5 operands!");
5223     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
5224            "LHS/RHS of comparison should match types!");
5225     break;
5226   }
5227   }
5228
5229   // Memoize nodes.
5230   SDNode *N;
5231   SDVTList VTs = getVTList(VT);
5232
5233   if (VT != MVT::Glue) {
5234     FoldingSetNodeID ID;
5235     AddNodeIDNode(ID, Opcode, VTs, Ops);
5236     void *IP = nullptr;
5237
5238     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5239       return SDValue(E, 0);
5240
5241     N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(),
5242                                    VTs, Ops);
5243     CSEMap.InsertNode(N, IP);
5244   } else {
5245     N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(),
5246                                    VTs, Ops);
5247   }
5248
5249   InsertNode(N);
5250   return SDValue(N, 0);
5251 }
5252
5253 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL,
5254                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
5255   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
5256 }
5257
5258 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5259                               ArrayRef<SDValue> Ops) {
5260   if (VTList.NumVTs == 1)
5261     return getNode(Opcode, DL, VTList.VTs[0], Ops);
5262
5263 #if 0
5264   switch (Opcode) {
5265   // FIXME: figure out how to safely handle things like
5266   // int foo(int x) { return 1 << (x & 255); }
5267   // int bar() { return foo(256); }
5268   case ISD::SRA_PARTS:
5269   case ISD::SRL_PARTS:
5270   case ISD::SHL_PARTS:
5271     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5272         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
5273       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
5274     else if (N3.getOpcode() == ISD::AND)
5275       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
5276         // If the and is only masking out bits that cannot effect the shift,
5277         // eliminate the and.
5278         unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
5279         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
5280           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
5281       }
5282     break;
5283   }
5284 #endif
5285
5286   // Memoize the node unless it returns a flag.
5287   SDNode *N;
5288   unsigned NumOps = Ops.size();
5289   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5290     FoldingSetNodeID ID;
5291     AddNodeIDNode(ID, Opcode, VTList, Ops);
5292     void *IP = nullptr;
5293     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5294       return SDValue(E, 0);
5295
5296     if (NumOps == 1) {
5297       N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(),
5298                                           DL.getDebugLoc(), VTList, Ops[0]);
5299     } else if (NumOps == 2) {
5300       N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(),
5301                                            DL.getDebugLoc(), VTList, Ops[0],
5302                                            Ops[1]);
5303     } else if (NumOps == 3) {
5304       N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(),
5305                                             DL.getDebugLoc(), VTList, Ops[0],
5306                                             Ops[1], Ops[2]);
5307     } else {
5308       N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(),
5309                                      VTList, Ops);
5310     }
5311     CSEMap.InsertNode(N, IP);
5312   } else {
5313     if (NumOps == 1) {
5314       N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(),
5315                                           DL.getDebugLoc(), VTList, Ops[0]);
5316     } else if (NumOps == 2) {
5317       N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(),
5318                                            DL.getDebugLoc(), VTList, Ops[0],
5319                                            Ops[1]);
5320     } else if (NumOps == 3) {
5321       N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(),
5322                                             DL.getDebugLoc(), VTList, Ops[0],
5323                                             Ops[1], Ops[2]);
5324     } else {
5325       N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(),
5326                                      VTList, Ops);
5327     }
5328   }
5329   InsertNode(N);
5330   return SDValue(N, 0);
5331 }
5332
5333 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList) {
5334   return getNode(Opcode, DL, VTList, None);
5335 }
5336
5337 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5338                               SDValue N1) {
5339   SDValue Ops[] = { N1 };
5340   return getNode(Opcode, DL, VTList, Ops);
5341 }
5342
5343 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5344                               SDValue N1, SDValue N2) {
5345   SDValue Ops[] = { N1, N2 };
5346   return getNode(Opcode, DL, VTList, Ops);
5347 }
5348
5349 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5350                               SDValue N1, SDValue N2, SDValue N3) {
5351   SDValue Ops[] = { N1, N2, N3 };
5352   return getNode(Opcode, DL, VTList, Ops);
5353 }
5354
5355 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5356                               SDValue N1, SDValue N2, SDValue N3,
5357                               SDValue N4) {
5358   SDValue Ops[] = { N1, N2, N3, N4 };
5359   return getNode(Opcode, DL, VTList, Ops);
5360 }
5361
5362 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5363                               SDValue N1, SDValue N2, SDValue N3,
5364                               SDValue N4, SDValue N5) {
5365   SDValue Ops[] = { N1, N2, N3, N4, N5 };
5366   return getNode(Opcode, DL, VTList, Ops);
5367 }
5368
5369 SDVTList SelectionDAG::getVTList(EVT VT) {
5370   return makeVTList(SDNode::getValueTypeList(VT), 1);
5371 }
5372
5373 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
5374   FoldingSetNodeID ID;
5375   ID.AddInteger(2U);
5376   ID.AddInteger(VT1.getRawBits());
5377   ID.AddInteger(VT2.getRawBits());
5378
5379   void *IP = nullptr;
5380   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5381   if (!Result) {
5382     EVT *Array = Allocator.Allocate<EVT>(2);
5383     Array[0] = VT1;
5384     Array[1] = VT2;
5385     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
5386     VTListMap.InsertNode(Result, IP);
5387   }
5388   return Result->getSDVTList();
5389 }
5390
5391 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
5392   FoldingSetNodeID ID;
5393   ID.AddInteger(3U);
5394   ID.AddInteger(VT1.getRawBits());
5395   ID.AddInteger(VT2.getRawBits());
5396   ID.AddInteger(VT3.getRawBits());
5397
5398   void *IP = nullptr;
5399   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5400   if (!Result) {
5401     EVT *Array = Allocator.Allocate<EVT>(3);
5402     Array[0] = VT1;
5403     Array[1] = VT2;
5404     Array[2] = VT3;
5405     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
5406     VTListMap.InsertNode(Result, IP);
5407   }
5408   return Result->getSDVTList();
5409 }
5410
5411 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
5412   FoldingSetNodeID ID;
5413   ID.AddInteger(4U);
5414   ID.AddInteger(VT1.getRawBits());
5415   ID.AddInteger(VT2.getRawBits());
5416   ID.AddInteger(VT3.getRawBits());
5417   ID.AddInteger(VT4.getRawBits());
5418
5419   void *IP = nullptr;
5420   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5421   if (!Result) {
5422     EVT *Array = Allocator.Allocate<EVT>(4);
5423     Array[0] = VT1;
5424     Array[1] = VT2;
5425     Array[2] = VT3;
5426     Array[3] = VT4;
5427     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
5428     VTListMap.InsertNode(Result, IP);
5429   }
5430   return Result->getSDVTList();
5431 }
5432
5433 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
5434   unsigned NumVTs = VTs.size();
5435   FoldingSetNodeID ID;
5436   ID.AddInteger(NumVTs);
5437   for (unsigned index = 0; index < NumVTs; index++) {
5438     ID.AddInteger(VTs[index].getRawBits());
5439   }
5440
5441   void *IP = nullptr;
5442   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5443   if (!Result) {
5444     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
5445     std::copy(VTs.begin(), VTs.end(), Array);
5446     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
5447     VTListMap.InsertNode(Result, IP);
5448   }
5449   return Result->getSDVTList();
5450 }
5451
5452
5453 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
5454 /// specified operands.  If the resultant node already exists in the DAG,
5455 /// this does not modify the specified node, instead it returns the node that
5456 /// already exists.  If the resultant node does not exist in the DAG, the
5457 /// input node is returned.  As a degenerate case, if you specify the same
5458 /// input operands as the node already has, the input node is returned.
5459 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
5460   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
5461
5462   // Check to see if there is no change.
5463   if (Op == N->getOperand(0)) return N;
5464
5465   // See if the modified node already exists.
5466   void *InsertPos = nullptr;
5467   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
5468     return Existing;
5469
5470   // Nope it doesn't.  Remove the node from its current place in the maps.
5471   if (InsertPos)
5472     if (!RemoveNodeFromCSEMaps(N))
5473       InsertPos = nullptr;
5474
5475   // Now we update the operands.
5476   N->OperandList[0].set(Op);
5477
5478   // If this gets put into a CSE map, add it.
5479   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5480   return N;
5481 }
5482
5483 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
5484   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
5485
5486   // Check to see if there is no change.
5487   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
5488     return N;   // No operands changed, just return the input node.
5489
5490   // See if the modified node already exists.
5491   void *InsertPos = nullptr;
5492   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
5493     return Existing;
5494
5495   // Nope it doesn't.  Remove the node from its current place in the maps.
5496   if (InsertPos)
5497     if (!RemoveNodeFromCSEMaps(N))
5498       InsertPos = nullptr;
5499
5500   // Now we update the operands.
5501   if (N->OperandList[0] != Op1)
5502     N->OperandList[0].set(Op1);
5503   if (N->OperandList[1] != Op2)
5504     N->OperandList[1].set(Op2);
5505
5506   // If this gets put into a CSE map, add it.
5507   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5508   return N;
5509 }
5510
5511 SDNode *SelectionDAG::
5512 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
5513   SDValue Ops[] = { Op1, Op2, Op3 };
5514   return UpdateNodeOperands(N, Ops);
5515 }
5516
5517 SDNode *SelectionDAG::
5518 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
5519                    SDValue Op3, SDValue Op4) {
5520   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
5521   return UpdateNodeOperands(N, Ops);
5522 }
5523
5524 SDNode *SelectionDAG::
5525 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
5526                    SDValue Op3, SDValue Op4, SDValue Op5) {
5527   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
5528   return UpdateNodeOperands(N, Ops);
5529 }
5530
5531 SDNode *SelectionDAG::
5532 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
5533   unsigned NumOps = Ops.size();
5534   assert(N->getNumOperands() == NumOps &&
5535          "Update with wrong number of operands");
5536
5537   // If no operands changed just return the input node.
5538   if (Ops.empty() || std::equal(Ops.begin(), Ops.end(), N->op_begin()))
5539     return N;
5540
5541   // See if the modified node already exists.
5542   void *InsertPos = nullptr;
5543   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
5544     return Existing;
5545
5546   // Nope it doesn't.  Remove the node from its current place in the maps.
5547   if (InsertPos)
5548     if (!RemoveNodeFromCSEMaps(N))
5549       InsertPos = nullptr;
5550
5551   // Now we update the operands.
5552   for (unsigned i = 0; i != NumOps; ++i)
5553     if (N->OperandList[i] != Ops[i])
5554       N->OperandList[i].set(Ops[i]);
5555
5556   // If this gets put into a CSE map, add it.
5557   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5558   return N;
5559 }
5560
5561 /// DropOperands - Release the operands and set this node to have
5562 /// zero operands.
5563 void SDNode::DropOperands() {
5564   // Unlike the code in MorphNodeTo that does this, we don't need to
5565   // watch for dead nodes here.
5566   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
5567     SDUse &Use = *I++;
5568     Use.set(SDValue());
5569   }
5570 }
5571
5572 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
5573 /// machine opcode.
5574 ///
5575 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5576                                    EVT VT) {
5577   SDVTList VTs = getVTList(VT);
5578   return SelectNodeTo(N, MachineOpc, VTs, None);
5579 }
5580
5581 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5582                                    EVT VT, SDValue Op1) {
5583   SDVTList VTs = getVTList(VT);
5584   SDValue Ops[] = { Op1 };
5585   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5586 }
5587
5588 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5589                                    EVT VT, SDValue Op1,
5590                                    SDValue Op2) {
5591   SDVTList VTs = getVTList(VT);
5592   SDValue Ops[] = { Op1, Op2 };
5593   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5594 }
5595
5596 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5597                                    EVT VT, SDValue Op1,
5598                                    SDValue Op2, SDValue Op3) {
5599   SDVTList VTs = getVTList(VT);
5600   SDValue Ops[] = { Op1, Op2, Op3 };
5601   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5602 }
5603
5604 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5605                                    EVT VT, ArrayRef<SDValue> Ops) {
5606   SDVTList VTs = getVTList(VT);
5607   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5608 }
5609
5610 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5611                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
5612   SDVTList VTs = getVTList(VT1, VT2);
5613   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5614 }
5615
5616 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5617                                    EVT VT1, EVT VT2) {
5618   SDVTList VTs = getVTList(VT1, VT2);
5619   return SelectNodeTo(N, MachineOpc, VTs, None);
5620 }
5621
5622 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5623                                    EVT VT1, EVT VT2, EVT VT3,
5624                                    ArrayRef<SDValue> Ops) {
5625   SDVTList VTs = getVTList(VT1, VT2, VT3);
5626   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5627 }
5628
5629 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5630                                    EVT VT1, EVT VT2, EVT VT3, EVT VT4,
5631                                    ArrayRef<SDValue> Ops) {
5632   SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5633   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5634 }
5635
5636 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5637                                    EVT VT1, EVT VT2,
5638                                    SDValue Op1) {
5639   SDVTList VTs = getVTList(VT1, VT2);
5640   SDValue Ops[] = { Op1 };
5641   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5642 }
5643
5644 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5645                                    EVT VT1, EVT VT2,
5646                                    SDValue Op1, SDValue Op2) {
5647   SDVTList VTs = getVTList(VT1, VT2);
5648   SDValue Ops[] = { Op1, Op2 };
5649   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5650 }
5651
5652 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5653                                    EVT VT1, EVT VT2,
5654                                    SDValue Op1, SDValue Op2,
5655                                    SDValue Op3) {
5656   SDVTList VTs = getVTList(VT1, VT2);
5657   SDValue Ops[] = { Op1, Op2, Op3 };
5658   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5659 }
5660
5661 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5662                                    EVT VT1, EVT VT2, EVT VT3,
5663                                    SDValue Op1, SDValue Op2,
5664                                    SDValue Op3) {
5665   SDVTList VTs = getVTList(VT1, VT2, VT3);
5666   SDValue Ops[] = { Op1, Op2, Op3 };
5667   return SelectNodeTo(N, MachineOpc, VTs, Ops);
5668 }
5669
5670 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5671                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
5672   N = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
5673   // Reset the NodeID to -1.
5674   N->setNodeId(-1);
5675   return N;
5676 }
5677
5678 /// UpdadeSDLocOnMergedSDNode - If the opt level is -O0 then it throws away
5679 /// the line number information on the merged node since it is not possible to
5680 /// preserve the information that operation is associated with multiple lines.
5681 /// This will make the debugger working better at -O0, were there is a higher
5682 /// probability having other instructions associated with that line.
5683 ///
5684 /// For IROrder, we keep the smaller of the two
5685 SDNode *SelectionDAG::UpdadeSDLocOnMergedSDNode(SDNode *N, SDLoc OLoc) {
5686   DebugLoc NLoc = N->getDebugLoc();
5687   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
5688     N->setDebugLoc(DebugLoc());
5689   }
5690   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
5691   N->setIROrder(Order);
5692   return N;
5693 }
5694
5695 /// MorphNodeTo - This *mutates* the specified node to have the specified
5696 /// return type, opcode, and operands.
5697 ///
5698 /// Note that MorphNodeTo returns the resultant node.  If there is already a
5699 /// node of the specified opcode and operands, it returns that node instead of
5700 /// the current one.  Note that the SDLoc need not be the same.
5701 ///
5702 /// Using MorphNodeTo is faster than creating a new node and swapping it in
5703 /// with ReplaceAllUsesWith both because it often avoids allocating a new
5704 /// node, and because it doesn't require CSE recalculation for any of
5705 /// the node's users.
5706 ///
5707 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
5708 /// As a consequence it isn't appropriate to use from within the DAG combiner or
5709 /// the legalizer which maintain worklists that would need to be updated when
5710 /// deleting things.
5711 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
5712                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
5713   unsigned NumOps = Ops.size();
5714   // If an identical node already exists, use it.
5715   void *IP = nullptr;
5716   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
5717     FoldingSetNodeID ID;
5718     AddNodeIDNode(ID, Opc, VTs, Ops);
5719     if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
5720       return UpdadeSDLocOnMergedSDNode(ON, SDLoc(N));
5721   }
5722
5723   if (!RemoveNodeFromCSEMaps(N))
5724     IP = nullptr;
5725
5726   // Start the morphing.
5727   N->NodeType = Opc;
5728   N->ValueList = VTs.VTs;
5729   N->NumValues = VTs.NumVTs;
5730
5731   // Clear the operands list, updating used nodes to remove this from their
5732   // use list.  Keep track of any operands that become dead as a result.
5733   SmallPtrSet<SDNode*, 16> DeadNodeSet;
5734   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
5735     SDUse &Use = *I++;
5736     SDNode *Used = Use.getNode();
5737     Use.set(SDValue());
5738     if (Used->use_empty())
5739       DeadNodeSet.insert(Used);
5740   }
5741
5742   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
5743     // Initialize the memory references information.
5744     MN->setMemRefs(nullptr, nullptr);
5745     // If NumOps is larger than the # of operands we can have in a
5746     // MachineSDNode, reallocate the operand list.
5747     if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
5748       if (MN->OperandsNeedDelete)
5749         delete[] MN->OperandList;
5750       if (NumOps > array_lengthof(MN->LocalOperands))
5751         // We're creating a final node that will live unmorphed for the
5752         // remainder of the current SelectionDAG iteration, so we can allocate
5753         // the operands directly out of a pool with no recycling metadata.
5754         MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5755                          Ops.data(), NumOps);
5756       else
5757         MN->InitOperands(MN->LocalOperands, Ops.data(), NumOps);
5758       MN->OperandsNeedDelete = false;
5759     } else
5760       MN->InitOperands(MN->OperandList, Ops.data(), NumOps);
5761   } else {
5762     // If NumOps is larger than the # of operands we currently have, reallocate
5763     // the operand list.
5764     if (NumOps > N->NumOperands) {
5765       if (N->OperandsNeedDelete)
5766         delete[] N->OperandList;
5767       N->InitOperands(new SDUse[NumOps], Ops.data(), NumOps);
5768       N->OperandsNeedDelete = true;
5769     } else
5770       N->InitOperands(N->OperandList, Ops.data(), NumOps);
5771   }
5772
5773   // Delete any nodes that are still dead after adding the uses for the
5774   // new operands.
5775   if (!DeadNodeSet.empty()) {
5776     SmallVector<SDNode *, 16> DeadNodes;
5777     for (SDNode *N : DeadNodeSet)
5778       if (N->use_empty())
5779         DeadNodes.push_back(N);
5780     RemoveDeadNodes(DeadNodes);
5781   }
5782
5783   if (IP)
5784     CSEMap.InsertNode(N, IP);   // Memoize the new node.
5785   return N;
5786 }
5787
5788
5789 /// getMachineNode - These are used for target selectors to create a new node
5790 /// with specified return type(s), MachineInstr opcode, and operands.
5791 ///
5792 /// Note that getMachineNode returns the resultant node.  If there is already a
5793 /// node of the specified opcode and operands, it returns that node instead of
5794 /// the current one.
5795 MachineSDNode *
5796 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT) {
5797   SDVTList VTs = getVTList(VT);
5798   return getMachineNode(Opcode, dl, VTs, None);
5799 }
5800
5801 MachineSDNode *
5802 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, SDValue Op1) {
5803   SDVTList VTs = getVTList(VT);
5804   SDValue Ops[] = { Op1 };
5805   return getMachineNode(Opcode, dl, VTs, Ops);
5806 }
5807
5808 MachineSDNode *
5809 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5810                              SDValue Op1, SDValue Op2) {
5811   SDVTList VTs = getVTList(VT);
5812   SDValue Ops[] = { Op1, Op2 };
5813   return getMachineNode(Opcode, dl, VTs, Ops);
5814 }
5815
5816 MachineSDNode *
5817 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5818                              SDValue Op1, SDValue Op2, SDValue Op3) {
5819   SDVTList VTs = getVTList(VT);
5820   SDValue Ops[] = { Op1, Op2, Op3 };
5821   return getMachineNode(Opcode, dl, VTs, Ops);
5822 }
5823
5824 MachineSDNode *
5825 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5826                              ArrayRef<SDValue> Ops) {
5827   SDVTList VTs = getVTList(VT);
5828   return getMachineNode(Opcode, dl, VTs, Ops);
5829 }
5830
5831 MachineSDNode *
5832 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2) {
5833   SDVTList VTs = getVTList(VT1, VT2);
5834   return getMachineNode(Opcode, dl, VTs, None);
5835 }
5836
5837 MachineSDNode *
5838 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5839                              EVT VT1, EVT VT2, SDValue Op1) {
5840   SDVTList VTs = getVTList(VT1, VT2);
5841   SDValue Ops[] = { Op1 };
5842   return getMachineNode(Opcode, dl, VTs, Ops);
5843 }
5844
5845 MachineSDNode *
5846 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5847                              EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
5848   SDVTList VTs = getVTList(VT1, VT2);
5849   SDValue Ops[] = { Op1, Op2 };
5850   return getMachineNode(Opcode, dl, VTs, Ops);
5851 }
5852
5853 MachineSDNode *
5854 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5855                              EVT VT1, EVT VT2, SDValue Op1,
5856                              SDValue Op2, SDValue Op3) {
5857   SDVTList VTs = getVTList(VT1, VT2);
5858   SDValue Ops[] = { Op1, Op2, Op3 };
5859   return getMachineNode(Opcode, dl, VTs, Ops);
5860 }
5861
5862 MachineSDNode *
5863 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5864                              EVT VT1, EVT VT2,
5865                              ArrayRef<SDValue> Ops) {
5866   SDVTList VTs = getVTList(VT1, VT2);
5867   return getMachineNode(Opcode, dl, VTs, Ops);
5868 }
5869
5870 MachineSDNode *
5871 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5872                              EVT VT1, EVT VT2, EVT VT3,
5873                              SDValue Op1, SDValue Op2) {
5874   SDVTList VTs = getVTList(VT1, VT2, VT3);
5875   SDValue Ops[] = { Op1, Op2 };
5876   return getMachineNode(Opcode, dl, VTs, Ops);
5877 }
5878
5879 MachineSDNode *
5880 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5881                              EVT VT1, EVT VT2, EVT VT3,
5882                              SDValue Op1, SDValue Op2, SDValue Op3) {
5883   SDVTList VTs = getVTList(VT1, VT2, VT3);
5884   SDValue Ops[] = { Op1, Op2, Op3 };
5885   return getMachineNode(Opcode, dl, VTs, Ops);
5886 }
5887
5888 MachineSDNode *
5889 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5890                              EVT VT1, EVT VT2, EVT VT3,
5891                              ArrayRef<SDValue> Ops) {
5892   SDVTList VTs = getVTList(VT1, VT2, VT3);
5893   return getMachineNode(Opcode, dl, VTs, Ops);
5894 }
5895
5896 MachineSDNode *
5897 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1,
5898                              EVT VT2, EVT VT3, EVT VT4,
5899                              ArrayRef<SDValue> Ops) {
5900   SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5901   return getMachineNode(Opcode, dl, VTs, Ops);
5902 }
5903
5904 MachineSDNode *
5905 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5906                              ArrayRef<EVT> ResultTys,
5907                              ArrayRef<SDValue> Ops) {
5908   SDVTList VTs = getVTList(ResultTys);
5909   return getMachineNode(Opcode, dl, VTs, Ops);
5910 }
5911
5912 MachineSDNode *
5913 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc DL, SDVTList VTs,
5914                              ArrayRef<SDValue> OpsArray) {
5915   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
5916   MachineSDNode *N;
5917   void *IP = nullptr;
5918   const SDValue *Ops = OpsArray.data();
5919   unsigned NumOps = OpsArray.size();
5920
5921   if (DoCSE) {
5922     FoldingSetNodeID ID;
5923     AddNodeIDNode(ID, ~Opcode, VTs, OpsArray);
5924     IP = nullptr;
5925     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
5926       return cast<MachineSDNode>(UpdadeSDLocOnMergedSDNode(E, DL));
5927     }
5928   }
5929
5930   // Allocate a new MachineSDNode.
5931   N = new (NodeAllocator) MachineSDNode(~Opcode, DL.getIROrder(),
5932                                         DL.getDebugLoc(), VTs);
5933
5934   // Initialize the operands list.
5935   if (NumOps > array_lengthof(N->LocalOperands))
5936     // We're creating a final node that will live unmorphed for the
5937     // remainder of the current SelectionDAG iteration, so we can allocate
5938     // the operands directly out of a pool with no recycling metadata.
5939     N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5940                     Ops, NumOps);
5941   else
5942     N->InitOperands(N->LocalOperands, Ops, NumOps);
5943   N->OperandsNeedDelete = false;
5944
5945   if (DoCSE)
5946     CSEMap.InsertNode(N, IP);
5947
5948   InsertNode(N);
5949   return N;
5950 }
5951
5952 /// getTargetExtractSubreg - A convenience function for creating
5953 /// TargetOpcode::EXTRACT_SUBREG nodes.
5954 SDValue
5955 SelectionDAG::getTargetExtractSubreg(int SRIdx, SDLoc DL, EVT VT,
5956                                      SDValue Operand) {
5957   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
5958   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
5959                                   VT, Operand, SRIdxVal);
5960   return SDValue(Subreg, 0);
5961 }
5962
5963 /// getTargetInsertSubreg - A convenience function for creating
5964 /// TargetOpcode::INSERT_SUBREG nodes.
5965 SDValue
5966 SelectionDAG::getTargetInsertSubreg(int SRIdx, SDLoc DL, EVT VT,
5967                                     SDValue Operand, SDValue Subreg) {
5968   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
5969   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
5970                                   VT, Operand, Subreg, SRIdxVal);
5971   return SDValue(Result, 0);
5972 }
5973
5974 /// getNodeIfExists - Get the specified node if it's already available, or
5975 /// else return NULL.
5976 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
5977                                       ArrayRef<SDValue> Ops,
5978                                       const SDNodeFlags *Flags) {
5979   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
5980     FoldingSetNodeID ID;
5981     AddNodeIDNode(ID, Opcode, VTList, Ops);
5982     AddNodeIDFlags(ID, Opcode, Flags);
5983     void *IP = nullptr;
5984     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5985       return E;
5986   }
5987   return nullptr;
5988 }
5989
5990 /// getDbgValue - Creates a SDDbgValue node.
5991 ///
5992 /// SDNode
5993 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N,
5994                                       unsigned R, bool IsIndirect, uint64_t Off,
5995                                       DebugLoc DL, unsigned O) {
5996   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
5997          "Expected inlined-at fields to agree");
5998   return new (Allocator) SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O);
5999 }
6000
6001 /// Constant
6002 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr,
6003                                               const Value *C, uint64_t Off,
6004                                               DebugLoc DL, unsigned O) {
6005   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6006          "Expected inlined-at fields to agree");
6007   return new (Allocator) SDDbgValue(Var, Expr, C, Off, DL, O);
6008 }
6009
6010 /// FrameIndex
6011 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr,
6012                                                 unsigned FI, uint64_t Off,
6013                                                 DebugLoc DL, unsigned O) {
6014   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6015          "Expected inlined-at fields to agree");
6016   return new (Allocator) SDDbgValue(Var, Expr, FI, Off, DL, O);
6017 }
6018
6019 namespace {
6020
6021 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
6022 /// pointed to by a use iterator is deleted, increment the use iterator
6023 /// so that it doesn't dangle.
6024 ///
6025 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
6026   SDNode::use_iterator &UI;
6027   SDNode::use_iterator &UE;
6028
6029   void NodeDeleted(SDNode *N, SDNode *E) override {
6030     // Increment the iterator as needed.
6031     while (UI != UE && N == *UI)
6032       ++UI;
6033   }
6034
6035 public:
6036   RAUWUpdateListener(SelectionDAG &d,
6037                      SDNode::use_iterator &ui,
6038                      SDNode::use_iterator &ue)
6039     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
6040 };
6041
6042 }
6043
6044 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6045 /// This can cause recursive merging of nodes in the DAG.
6046 ///
6047 /// This version assumes From has a single result value.
6048 ///
6049 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
6050   SDNode *From = FromN.getNode();
6051   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
6052          "Cannot replace with this method!");
6053   assert(From != To.getNode() && "Cannot replace uses of with self");
6054
6055   // Iterate over all the existing uses of From. New uses will be added
6056   // to the beginning of the use list, which we avoid visiting.
6057   // This specifically avoids visiting uses of From that arise while the
6058   // replacement is happening, because any such uses would be the result
6059   // of CSE: If an existing node looks like From after one of its operands
6060   // is replaced by To, we don't want to replace of all its users with To
6061   // too. See PR3018 for more info.
6062   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6063   RAUWUpdateListener Listener(*this, UI, UE);
6064   while (UI != UE) {
6065     SDNode *User = *UI;
6066
6067     // This node is about to morph, remove its old self from the CSE maps.
6068     RemoveNodeFromCSEMaps(User);
6069
6070     // A user can appear in a use list multiple times, and when this
6071     // happens the uses are usually next to each other in the list.
6072     // To help reduce the number of CSE recomputations, process all
6073     // the uses of this user that we can find this way.
6074     do {
6075       SDUse &Use = UI.getUse();
6076       ++UI;
6077       Use.set(To);
6078     } while (UI != UE && *UI == User);
6079
6080     // Now that we have modified User, add it back to the CSE maps.  If it
6081     // already exists there, recursively merge the results together.
6082     AddModifiedNodeToCSEMaps(User);
6083   }
6084
6085   // If we just RAUW'd the root, take note.
6086   if (FromN == getRoot())
6087     setRoot(To);
6088 }
6089
6090 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6091 /// This can cause recursive merging of nodes in the DAG.
6092 ///
6093 /// This version assumes that for each value of From, there is a
6094 /// corresponding value in To in the same position with the same type.
6095 ///
6096 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
6097 #ifndef NDEBUG
6098   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6099     assert((!From->hasAnyUseOfValue(i) ||
6100             From->getValueType(i) == To->getValueType(i)) &&
6101            "Cannot use this version of ReplaceAllUsesWith!");
6102 #endif
6103
6104   // Handle the trivial case.
6105   if (From == To)
6106     return;
6107
6108   // Iterate over just the existing users of From. See the comments in
6109   // the ReplaceAllUsesWith above.
6110   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6111   RAUWUpdateListener Listener(*this, UI, UE);
6112   while (UI != UE) {
6113     SDNode *User = *UI;
6114
6115     // This node is about to morph, remove its old self from the CSE maps.
6116     RemoveNodeFromCSEMaps(User);
6117
6118     // A user can appear in a use list multiple times, and when this
6119     // happens the uses are usually next to each other in the list.
6120     // To help reduce the number of CSE recomputations, process all
6121     // the uses of this user that we can find this way.
6122     do {
6123       SDUse &Use = UI.getUse();
6124       ++UI;
6125       Use.setNode(To);
6126     } while (UI != UE && *UI == User);
6127
6128     // Now that we have modified User, add it back to the CSE maps.  If it
6129     // already exists there, recursively merge the results together.
6130     AddModifiedNodeToCSEMaps(User);
6131   }
6132
6133   // If we just RAUW'd the root, take note.
6134   if (From == getRoot().getNode())
6135     setRoot(SDValue(To, getRoot().getResNo()));
6136 }
6137
6138 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6139 /// This can cause recursive merging of nodes in the DAG.
6140 ///
6141 /// This version can replace From with any result values.  To must match the
6142 /// number and types of values returned by From.
6143 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
6144   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
6145     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
6146
6147   // Iterate over just the existing users of From. See the comments in
6148   // the ReplaceAllUsesWith above.
6149   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6150   RAUWUpdateListener Listener(*this, UI, UE);
6151   while (UI != UE) {
6152     SDNode *User = *UI;
6153
6154     // This node is about to morph, remove its old self from the CSE maps.
6155     RemoveNodeFromCSEMaps(User);
6156
6157     // A user can appear in a use list multiple times, and when this
6158     // happens the uses are usually next to each other in the list.
6159     // To help reduce the number of CSE recomputations, process all
6160     // the uses of this user that we can find this way.
6161     do {
6162       SDUse &Use = UI.getUse();
6163       const SDValue &ToOp = To[Use.getResNo()];
6164       ++UI;
6165       Use.set(ToOp);
6166     } while (UI != UE && *UI == User);
6167
6168     // Now that we have modified User, add it back to the CSE maps.  If it
6169     // already exists there, recursively merge the results together.
6170     AddModifiedNodeToCSEMaps(User);
6171   }
6172
6173   // If we just RAUW'd the root, take note.
6174   if (From == getRoot().getNode())
6175     setRoot(SDValue(To[getRoot().getResNo()]));
6176 }
6177
6178 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
6179 /// uses of other values produced by From.getNode() alone.  The Deleted
6180 /// vector is handled the same way as for ReplaceAllUsesWith.
6181 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
6182   // Handle the really simple, really trivial case efficiently.
6183   if (From == To) return;
6184
6185   // Handle the simple, trivial, case efficiently.
6186   if (From.getNode()->getNumValues() == 1) {
6187     ReplaceAllUsesWith(From, To);
6188     return;
6189   }
6190
6191   // Iterate over just the existing users of From. See the comments in
6192   // the ReplaceAllUsesWith above.
6193   SDNode::use_iterator UI = From.getNode()->use_begin(),
6194                        UE = From.getNode()->use_end();
6195   RAUWUpdateListener Listener(*this, UI, UE);
6196   while (UI != UE) {
6197     SDNode *User = *UI;
6198     bool UserRemovedFromCSEMaps = false;
6199
6200     // A user can appear in a use list multiple times, and when this
6201     // happens the uses are usually next to each other in the list.
6202     // To help reduce the number of CSE recomputations, process all
6203     // the uses of this user that we can find this way.
6204     do {
6205       SDUse &Use = UI.getUse();
6206
6207       // Skip uses of different values from the same node.
6208       if (Use.getResNo() != From.getResNo()) {
6209         ++UI;
6210         continue;
6211       }
6212
6213       // If this node hasn't been modified yet, it's still in the CSE maps,
6214       // so remove its old self from the CSE maps.
6215       if (!UserRemovedFromCSEMaps) {
6216         RemoveNodeFromCSEMaps(User);
6217         UserRemovedFromCSEMaps = true;
6218       }
6219
6220       ++UI;
6221       Use.set(To);
6222     } while (UI != UE && *UI == User);
6223
6224     // We are iterating over all uses of the From node, so if a use
6225     // doesn't use the specific value, no changes are made.
6226     if (!UserRemovedFromCSEMaps)
6227       continue;
6228
6229     // Now that we have modified User, add it back to the CSE maps.  If it
6230     // already exists there, recursively merge the results together.
6231     AddModifiedNodeToCSEMaps(User);
6232   }
6233
6234   // If we just RAUW'd the root, take note.
6235   if (From == getRoot())
6236     setRoot(To);
6237 }
6238
6239 namespace {
6240   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
6241   /// to record information about a use.
6242   struct UseMemo {
6243     SDNode *User;
6244     unsigned Index;
6245     SDUse *Use;
6246   };
6247
6248   /// operator< - Sort Memos by User.
6249   bool operator<(const UseMemo &L, const UseMemo &R) {
6250     return (intptr_t)L.User < (intptr_t)R.User;
6251   }
6252 }
6253
6254 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
6255 /// uses of other values produced by From.getNode() alone.  The same value
6256 /// may appear in both the From and To list.  The Deleted vector is
6257 /// handled the same way as for ReplaceAllUsesWith.
6258 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
6259                                               const SDValue *To,
6260                                               unsigned Num){
6261   // Handle the simple, trivial case efficiently.
6262   if (Num == 1)
6263     return ReplaceAllUsesOfValueWith(*From, *To);
6264
6265   // Read up all the uses and make records of them. This helps
6266   // processing new uses that are introduced during the
6267   // replacement process.
6268   SmallVector<UseMemo, 4> Uses;
6269   for (unsigned i = 0; i != Num; ++i) {
6270     unsigned FromResNo = From[i].getResNo();
6271     SDNode *FromNode = From[i].getNode();
6272     for (SDNode::use_iterator UI = FromNode->use_begin(),
6273          E = FromNode->use_end(); UI != E; ++UI) {
6274       SDUse &Use = UI.getUse();
6275       if (Use.getResNo() == FromResNo) {
6276         UseMemo Memo = { *UI, i, &Use };
6277         Uses.push_back(Memo);
6278       }
6279     }
6280   }
6281
6282   // Sort the uses, so that all the uses from a given User are together.
6283   std::sort(Uses.begin(), Uses.end());
6284
6285   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
6286        UseIndex != UseIndexEnd; ) {
6287     // We know that this user uses some value of From.  If it is the right
6288     // value, update it.
6289     SDNode *User = Uses[UseIndex].User;
6290
6291     // This node is about to morph, remove its old self from the CSE maps.
6292     RemoveNodeFromCSEMaps(User);
6293
6294     // The Uses array is sorted, so all the uses for a given User
6295     // are next to each other in the list.
6296     // To help reduce the number of CSE recomputations, process all
6297     // the uses of this user that we can find this way.
6298     do {
6299       unsigned i = Uses[UseIndex].Index;
6300       SDUse &Use = *Uses[UseIndex].Use;
6301       ++UseIndex;
6302
6303       Use.set(To[i]);
6304     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
6305
6306     // Now that we have modified User, add it back to the CSE maps.  If it
6307     // already exists there, recursively merge the results together.
6308     AddModifiedNodeToCSEMaps(User);
6309   }
6310 }
6311
6312 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
6313 /// based on their topological order. It returns the maximum id and a vector
6314 /// of the SDNodes* in assigned order by reference.
6315 unsigned SelectionDAG::AssignTopologicalOrder() {
6316
6317   unsigned DAGSize = 0;
6318
6319   // SortedPos tracks the progress of the algorithm. Nodes before it are
6320   // sorted, nodes after it are unsorted. When the algorithm completes
6321   // it is at the end of the list.
6322   allnodes_iterator SortedPos = allnodes_begin();
6323
6324   // Visit all the nodes. Move nodes with no operands to the front of
6325   // the list immediately. Annotate nodes that do have operands with their
6326   // operand count. Before we do this, the Node Id fields of the nodes
6327   // may contain arbitrary values. After, the Node Id fields for nodes
6328   // before SortedPos will contain the topological sort index, and the
6329   // Node Id fields for nodes At SortedPos and after will contain the
6330   // count of outstanding operands.
6331   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
6332     SDNode *N = I++;
6333     checkForCycles(N, this);
6334     unsigned Degree = N->getNumOperands();
6335     if (Degree == 0) {
6336       // A node with no uses, add it to the result array immediately.
6337       N->setNodeId(DAGSize++);
6338       allnodes_iterator Q = N;
6339       if (Q != SortedPos)
6340         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
6341       assert(SortedPos != AllNodes.end() && "Overran node list");
6342       ++SortedPos;
6343     } else {
6344       // Temporarily use the Node Id as scratch space for the degree count.
6345       N->setNodeId(Degree);
6346     }
6347   }
6348
6349   // Visit all the nodes. As we iterate, move nodes into sorted order,
6350   // such that by the time the end is reached all nodes will be sorted.
6351   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
6352     SDNode *N = I;
6353     checkForCycles(N, this);
6354     // N is in sorted position, so all its uses have one less operand
6355     // that needs to be sorted.
6356     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6357          UI != UE; ++UI) {
6358       SDNode *P = *UI;
6359       unsigned Degree = P->getNodeId();
6360       assert(Degree != 0 && "Invalid node degree");
6361       --Degree;
6362       if (Degree == 0) {
6363         // All of P's operands are sorted, so P may sorted now.
6364         P->setNodeId(DAGSize++);
6365         if (P != SortedPos)
6366           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
6367         assert(SortedPos != AllNodes.end() && "Overran node list");
6368         ++SortedPos;
6369       } else {
6370         // Update P's outstanding operand count.
6371         P->setNodeId(Degree);
6372       }
6373     }
6374     if (I == SortedPos) {
6375 #ifndef NDEBUG
6376       SDNode *S = ++I;
6377       dbgs() << "Overran sorted position:\n";
6378       S->dumprFull(this); dbgs() << "\n";
6379       dbgs() << "Checking if this is due to cycles\n";
6380       checkForCycles(this, true);
6381 #endif
6382       llvm_unreachable(nullptr);
6383     }
6384   }
6385
6386   assert(SortedPos == AllNodes.end() &&
6387          "Topological sort incomplete!");
6388   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
6389          "First node in topological sort is not the entry token!");
6390   assert(AllNodes.front().getNodeId() == 0 &&
6391          "First node in topological sort has non-zero id!");
6392   assert(AllNodes.front().getNumOperands() == 0 &&
6393          "First node in topological sort has operands!");
6394   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
6395          "Last node in topologic sort has unexpected id!");
6396   assert(AllNodes.back().use_empty() &&
6397          "Last node in topologic sort has users!");
6398   assert(DAGSize == allnodes_size() && "Node count mismatch!");
6399   return DAGSize;
6400 }
6401
6402 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
6403 /// value is produced by SD.
6404 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
6405   if (SD) {
6406     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
6407     SD->setHasDebugValue(true);
6408   }
6409   DbgInfo->add(DB, SD, isParameter);
6410 }
6411
6412 /// TransferDbgValues - Transfer SDDbgValues.
6413 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
6414   if (From == To || !From.getNode()->getHasDebugValue())
6415     return;
6416   SDNode *FromNode = From.getNode();
6417   SDNode *ToNode = To.getNode();
6418   ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
6419   SmallVector<SDDbgValue *, 2> ClonedDVs;
6420   for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
6421        I != E; ++I) {
6422     SDDbgValue *Dbg = *I;
6423     if (Dbg->getKind() == SDDbgValue::SDNODE) {
6424       SDDbgValue *Clone =
6425           getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode,
6426                       To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(),
6427                       Dbg->getDebugLoc(), Dbg->getOrder());
6428       ClonedDVs.push_back(Clone);
6429     }
6430   }
6431   for (SmallVectorImpl<SDDbgValue *>::iterator I = ClonedDVs.begin(),
6432          E = ClonedDVs.end(); I != E; ++I)
6433     AddDbgValue(*I, ToNode, false);
6434 }
6435
6436 //===----------------------------------------------------------------------===//
6437 //                              SDNode Class
6438 //===----------------------------------------------------------------------===//
6439
6440 HandleSDNode::~HandleSDNode() {
6441   DropOperands();
6442 }
6443
6444 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
6445                                          DebugLoc DL, const GlobalValue *GA,
6446                                          EVT VT, int64_t o, unsigned char TF)
6447   : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
6448   TheGlobal = GA;
6449 }
6450
6451 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, DebugLoc dl, EVT VT,
6452                                          SDValue X, unsigned SrcAS,
6453                                          unsigned DestAS)
6454  : UnarySDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT), X),
6455    SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
6456
6457 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
6458                      EVT memvt, MachineMemOperand *mmo)
6459  : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
6460   SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
6461                                       MMO->isNonTemporal(), MMO->isInvariant());
6462   assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
6463   assert(isNonTemporal() == MMO->isNonTemporal() &&
6464          "Non-temporal encoding error!");
6465   // We check here that the size of the memory operand fits within the size of
6466   // the MMO. This is because the MMO might indicate only a possible address
6467   // range instead of specifying the affected memory addresses precisely.
6468   assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
6469 }
6470
6471 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
6472                      ArrayRef<SDValue> Ops, EVT memvt, MachineMemOperand *mmo)
6473    : SDNode(Opc, Order, dl, VTs, Ops),
6474      MemoryVT(memvt), MMO(mmo) {
6475   SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
6476                                       MMO->isNonTemporal(), MMO->isInvariant());
6477   assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
6478   assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
6479 }
6480
6481 /// Profile - Gather unique data for the node.
6482 ///
6483 void SDNode::Profile(FoldingSetNodeID &ID) const {
6484   AddNodeIDNode(ID, this);
6485 }
6486
6487 namespace {
6488   struct EVTArray {
6489     std::vector<EVT> VTs;
6490
6491     EVTArray() {
6492       VTs.reserve(MVT::LAST_VALUETYPE);
6493       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
6494         VTs.push_back(MVT((MVT::SimpleValueType)i));
6495     }
6496   };
6497 }
6498
6499 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
6500 static ManagedStatic<EVTArray> SimpleVTArray;
6501 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
6502
6503 /// getValueTypeList - Return a pointer to the specified value type.
6504 ///
6505 const EVT *SDNode::getValueTypeList(EVT VT) {
6506   if (VT.isExtended()) {
6507     sys::SmartScopedLock<true> Lock(*VTMutex);
6508     return &(*EVTs->insert(VT).first);
6509   } else {
6510     assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
6511            "Value type out of range!");
6512     return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
6513   }
6514 }
6515
6516 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
6517 /// indicated value.  This method ignores uses of other values defined by this
6518 /// operation.
6519 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
6520   assert(Value < getNumValues() && "Bad value!");
6521
6522   // TODO: Only iterate over uses of a given value of the node
6523   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
6524     if (UI.getUse().getResNo() == Value) {
6525       if (NUses == 0)
6526         return false;
6527       --NUses;
6528     }
6529   }
6530
6531   // Found exactly the right number of uses?
6532   return NUses == 0;
6533 }
6534
6535
6536 /// hasAnyUseOfValue - Return true if there are any use of the indicated
6537 /// value. This method ignores uses of other values defined by this operation.
6538 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
6539   assert(Value < getNumValues() && "Bad value!");
6540
6541   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
6542     if (UI.getUse().getResNo() == Value)
6543       return true;
6544
6545   return false;
6546 }
6547
6548
6549 /// isOnlyUserOf - Return true if this node is the only use of N.
6550 ///
6551 bool SDNode::isOnlyUserOf(SDNode *N) const {
6552   bool Seen = false;
6553   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
6554     SDNode *User = *I;
6555     if (User == this)
6556       Seen = true;
6557     else
6558       return false;
6559   }
6560
6561   return Seen;
6562 }
6563
6564 /// isOperand - Return true if this node is an operand of N.
6565 ///
6566 bool SDValue::isOperandOf(SDNode *N) const {
6567   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6568     if (*this == N->getOperand(i))
6569       return true;
6570   return false;
6571 }
6572
6573 bool SDNode::isOperandOf(SDNode *N) const {
6574   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
6575     if (this == N->OperandList[i].getNode())
6576       return true;
6577   return false;
6578 }
6579
6580 /// reachesChainWithoutSideEffects - Return true if this operand (which must
6581 /// be a chain) reaches the specified operand without crossing any
6582 /// side-effecting instructions on any chain path.  In practice, this looks
6583 /// through token factors and non-volatile loads.  In order to remain efficient,
6584 /// this only looks a couple of nodes in, it does not do an exhaustive search.
6585 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
6586                                                unsigned Depth) const {
6587   if (*this == Dest) return true;
6588
6589   // Don't search too deeply, we just want to be able to see through
6590   // TokenFactor's etc.
6591   if (Depth == 0) return false;
6592
6593   // If this is a token factor, all inputs to the TF happen in parallel.  If any
6594   // of the operands of the TF does not reach dest, then we cannot do the xform.
6595   if (getOpcode() == ISD::TokenFactor) {
6596     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6597       if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
6598         return false;
6599     return true;
6600   }
6601
6602   // Loads don't have side effects, look through them.
6603   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
6604     if (!Ld->isVolatile())
6605       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
6606   }
6607   return false;
6608 }
6609
6610 /// hasPredecessor - Return true if N is a predecessor of this node.
6611 /// N is either an operand of this node, or can be reached by recursively
6612 /// traversing up the operands.
6613 /// NOTE: This is an expensive method. Use it carefully.
6614 bool SDNode::hasPredecessor(const SDNode *N) const {
6615   SmallPtrSet<const SDNode *, 32> Visited;
6616   SmallVector<const SDNode *, 16> Worklist;
6617   return hasPredecessorHelper(N, Visited, Worklist);
6618 }
6619
6620 bool
6621 SDNode::hasPredecessorHelper(const SDNode *N,
6622                              SmallPtrSetImpl<const SDNode *> &Visited,
6623                              SmallVectorImpl<const SDNode *> &Worklist) const {
6624   if (Visited.empty()) {
6625     Worklist.push_back(this);
6626   } else {
6627     // Take a look in the visited set. If we've already encountered this node
6628     // we needn't search further.
6629     if (Visited.count(N))
6630       return true;
6631   }
6632
6633   // Haven't visited N yet. Continue the search.
6634   while (!Worklist.empty()) {
6635     const SDNode *M = Worklist.pop_back_val();
6636     for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
6637       SDNode *Op = M->getOperand(i).getNode();
6638       if (Visited.insert(Op).second)
6639         Worklist.push_back(Op);
6640       if (Op == N)
6641         return true;
6642     }
6643   }
6644
6645   return false;
6646 }
6647
6648 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
6649   assert(Num < NumOperands && "Invalid child # of SDNode!");
6650   return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
6651 }
6652
6653 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
6654   assert(N->getNumValues() == 1 &&
6655          "Can't unroll a vector with multiple results!");
6656
6657   EVT VT = N->getValueType(0);
6658   unsigned NE = VT.getVectorNumElements();
6659   EVT EltVT = VT.getVectorElementType();
6660   SDLoc dl(N);
6661
6662   SmallVector<SDValue, 8> Scalars;
6663   SmallVector<SDValue, 4> Operands(N->getNumOperands());
6664
6665   // If ResNE is 0, fully unroll the vector op.
6666   if (ResNE == 0)
6667     ResNE = NE;
6668   else if (NE > ResNE)
6669     NE = ResNE;
6670
6671   unsigned i;
6672   for (i= 0; i != NE; ++i) {
6673     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
6674       SDValue Operand = N->getOperand(j);
6675       EVT OperandVT = Operand.getValueType();
6676       if (OperandVT.isVector()) {
6677         // A vector operand; extract a single element.
6678         EVT OperandEltVT = OperandVT.getVectorElementType();
6679         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
6680                               OperandEltVT,
6681                               Operand,
6682                               getConstant(i, dl, TLI->getVectorIdxTy()));
6683       } else {
6684         // A scalar operand; just use it as is.
6685         Operands[j] = Operand;
6686       }
6687     }
6688
6689     switch (N->getOpcode()) {
6690     default:
6691       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands));
6692       break;
6693     case ISD::VSELECT:
6694       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
6695       break;
6696     case ISD::SHL:
6697     case ISD::SRA:
6698     case ISD::SRL:
6699     case ISD::ROTL:
6700     case ISD::ROTR:
6701       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6702                                getShiftAmountOperand(Operands[0].getValueType(),
6703                                                      Operands[1])));
6704       break;
6705     case ISD::SIGN_EXTEND_INREG:
6706     case ISD::FP_ROUND_INREG: {
6707       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6708       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6709                                 Operands[0],
6710                                 getValueType(ExtVT)));
6711     }
6712     }
6713   }
6714
6715   for (; i < ResNE; ++i)
6716     Scalars.push_back(getUNDEF(EltVT));
6717
6718   return getNode(ISD::BUILD_VECTOR, dl,
6719                  EVT::getVectorVT(*getContext(), EltVT, ResNE), Scalars);
6720 }
6721
6722
6723 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
6724 /// location that is 'Dist' units away from the location that the 'Base' load
6725 /// is loading from.
6726 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
6727                                      unsigned Bytes, int Dist) const {
6728   if (LD->getChain() != Base->getChain())
6729     return false;
6730   EVT VT = LD->getValueType(0);
6731   if (VT.getSizeInBits() / 8 != Bytes)
6732     return false;
6733
6734   SDValue Loc = LD->getOperand(1);
6735   SDValue BaseLoc = Base->getOperand(1);
6736   if (Loc.getOpcode() == ISD::FrameIndex) {
6737     if (BaseLoc.getOpcode() != ISD::FrameIndex)
6738       return false;
6739     const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6740     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
6741     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6742     int FS  = MFI->getObjectSize(FI);
6743     int BFS = MFI->getObjectSize(BFI);
6744     if (FS != BFS || FS != (int)Bytes) return false;
6745     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6746   }
6747
6748   // Handle X + C.
6749   if (isBaseWithConstantOffset(Loc)) {
6750     int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
6751     if (Loc.getOperand(0) == BaseLoc) {
6752       // If the base location is a simple address with no offset itself, then
6753       // the second load's first add operand should be the base address.
6754       if (LocOffset == Dist * (int)Bytes)
6755         return true;
6756     } else if (isBaseWithConstantOffset(BaseLoc)) {
6757       // The base location itself has an offset, so subtract that value from the
6758       // second load's offset before comparing to distance * size.
6759       int64_t BOffset =
6760         cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue();
6761       if (Loc.getOperand(0) == BaseLoc.getOperand(0)) {
6762         if ((LocOffset - BOffset) == Dist * (int)Bytes)
6763           return true;
6764       }
6765     }
6766   }
6767   const GlobalValue *GV1 = nullptr;
6768   const GlobalValue *GV2 = nullptr;
6769   int64_t Offset1 = 0;
6770   int64_t Offset2 = 0;
6771   bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6772   bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6773   if (isGA1 && isGA2 && GV1 == GV2)
6774     return Offset1 == (Offset2 + Dist*Bytes);
6775   return false;
6776 }
6777
6778
6779 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6780 /// it cannot be inferred.
6781 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6782   // If this is a GlobalAddress + cst, return the alignment.
6783   const GlobalValue *GV;
6784   int64_t GVOffset = 0;
6785   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
6786     unsigned PtrWidth = TLI->getPointerTypeSizeInBits(GV->getType());
6787     APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0);
6788     llvm::computeKnownBits(const_cast<GlobalValue *>(GV), KnownZero, KnownOne,
6789                            *TLI->getDataLayout());
6790     unsigned AlignBits = KnownZero.countTrailingOnes();
6791     unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
6792     if (Align)
6793       return MinAlign(Align, GVOffset);
6794   }
6795
6796   // If this is a direct reference to a stack slot, use information about the
6797   // stack slot's alignment.
6798   int FrameIdx = 1 << 31;
6799   int64_t FrameOffset = 0;
6800   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
6801     FrameIdx = FI->getIndex();
6802   } else if (isBaseWithConstantOffset(Ptr) &&
6803              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6804     // Handle FI+Cst
6805     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6806     FrameOffset = Ptr.getConstantOperandVal(1);
6807   }
6808
6809   if (FrameIdx != (1 << 31)) {
6810     const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
6811     unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
6812                                     FrameOffset);
6813     return FIInfoAlign;
6814   }
6815
6816   return 0;
6817 }
6818
6819 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
6820 /// which is split (or expanded) into two not necessarily identical pieces.
6821 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
6822   // Currently all types are split in half.
6823   EVT LoVT, HiVT;
6824   if (!VT.isVector()) {
6825     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
6826   } else {
6827     unsigned NumElements = VT.getVectorNumElements();
6828     assert(!(NumElements & 1) && "Splitting vector, but not in half!");
6829     LoVT = HiVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
6830                                    NumElements/2);
6831   }
6832   return std::make_pair(LoVT, HiVT);
6833 }
6834
6835 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
6836 /// low/high part.
6837 std::pair<SDValue, SDValue>
6838 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
6839                           const EVT &HiVT) {
6840   assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
6841          N.getValueType().getVectorNumElements() &&
6842          "More vector elements requested than available!");
6843   SDValue Lo, Hi;
6844   Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
6845                getConstant(0, DL, TLI->getVectorIdxTy()));
6846   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
6847                getConstant(LoVT.getVectorNumElements(), DL,
6848                            TLI->getVectorIdxTy()));
6849   return std::make_pair(Lo, Hi);
6850 }
6851
6852 void SelectionDAG::ExtractVectorElements(SDValue Op,
6853                                          SmallVectorImpl<SDValue> &Args,
6854                                          unsigned Start, unsigned Count) {
6855   EVT VT = Op.getValueType();
6856   if (Count == 0)
6857     Count = VT.getVectorNumElements();
6858
6859   EVT EltVT = VT.getVectorElementType();
6860   EVT IdxTy = TLI->getVectorIdxTy();
6861   SDLoc SL(Op);
6862   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
6863     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
6864                            Op, getConstant(i, SL, IdxTy)));
6865   }
6866 }
6867
6868 // getAddressSpace - Return the address space this GlobalAddress belongs to.
6869 unsigned GlobalAddressSDNode::getAddressSpace() const {
6870   return getGlobal()->getType()->getAddressSpace();
6871 }
6872
6873
6874 Type *ConstantPoolSDNode::getType() const {
6875   if (isMachineConstantPoolEntry())
6876     return Val.MachineCPVal->getType();
6877   return Val.ConstVal->getType();
6878 }
6879
6880 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
6881                                         APInt &SplatUndef,
6882                                         unsigned &SplatBitSize,
6883                                         bool &HasAnyUndefs,
6884                                         unsigned MinSplatBits,
6885                                         bool isBigEndian) const {
6886   EVT VT = getValueType(0);
6887   assert(VT.isVector() && "Expected a vector type");
6888   unsigned sz = VT.getSizeInBits();
6889   if (MinSplatBits > sz)
6890     return false;
6891
6892   SplatValue = APInt(sz, 0);
6893   SplatUndef = APInt(sz, 0);
6894
6895   // Get the bits.  Bits with undefined values (when the corresponding element
6896   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
6897   // in SplatValue.  If any of the values are not constant, give up and return
6898   // false.
6899   unsigned int nOps = getNumOperands();
6900   assert(nOps > 0 && "isConstantSplat has 0-size build vector");
6901   unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
6902
6903   for (unsigned j = 0; j < nOps; ++j) {
6904     unsigned i = isBigEndian ? nOps-1-j : j;
6905     SDValue OpVal = getOperand(i);
6906     unsigned BitPos = j * EltBitSize;
6907
6908     if (OpVal.getOpcode() == ISD::UNDEF)
6909       SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
6910     else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
6911       SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize).
6912                     zextOrTrunc(sz) << BitPos;
6913     else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
6914       SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
6915      else
6916       return false;
6917   }
6918
6919   // The build_vector is all constants or undefs.  Find the smallest element
6920   // size that splats the vector.
6921
6922   HasAnyUndefs = (SplatUndef != 0);
6923   while (sz > 8) {
6924
6925     unsigned HalfSize = sz / 2;
6926     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
6927     APInt LowValue = SplatValue.trunc(HalfSize);
6928     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
6929     APInt LowUndef = SplatUndef.trunc(HalfSize);
6930
6931     // If the two halves do not match (ignoring undef bits), stop here.
6932     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
6933         MinSplatBits > HalfSize)
6934       break;
6935
6936     SplatValue = HighValue | LowValue;
6937     SplatUndef = HighUndef & LowUndef;
6938
6939     sz = HalfSize;
6940   }
6941
6942   SplatBitSize = sz;
6943   return true;
6944 }
6945
6946 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
6947   if (UndefElements) {
6948     UndefElements->clear();
6949     UndefElements->resize(getNumOperands());
6950   }
6951   SDValue Splatted;
6952   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
6953     SDValue Op = getOperand(i);
6954     if (Op.getOpcode() == ISD::UNDEF) {
6955       if (UndefElements)
6956         (*UndefElements)[i] = true;
6957     } else if (!Splatted) {
6958       Splatted = Op;
6959     } else if (Splatted != Op) {
6960       return SDValue();
6961     }
6962   }
6963
6964   if (!Splatted) {
6965     assert(getOperand(0).getOpcode() == ISD::UNDEF &&
6966            "Can only have a splat without a constant for all undefs.");
6967     return getOperand(0);
6968   }
6969
6970   return Splatted;
6971 }
6972
6973 ConstantSDNode *
6974 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
6975   return dyn_cast_or_null<ConstantSDNode>(
6976       getSplatValue(UndefElements).getNode());
6977 }
6978
6979 ConstantFPSDNode *
6980 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
6981   return dyn_cast_or_null<ConstantFPSDNode>(
6982       getSplatValue(UndefElements).getNode());
6983 }
6984
6985 bool BuildVectorSDNode::isConstant() const {
6986   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
6987     unsigned Opc = getOperand(i).getOpcode();
6988     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
6989       return false;
6990   }
6991   return true;
6992 }
6993
6994 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
6995   // Find the first non-undef value in the shuffle mask.
6996   unsigned i, e;
6997   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
6998     /* search */;
6999
7000   assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
7001
7002   // Make sure all remaining elements are either undef or the same as the first
7003   // non-undef value.
7004   for (int Idx = Mask[i]; i != e; ++i)
7005     if (Mask[i] >= 0 && Mask[i] != Idx)
7006       return false;
7007   return true;
7008 }
7009
7010 #ifndef NDEBUG
7011 static void checkForCyclesHelper(const SDNode *N,
7012                                  SmallPtrSetImpl<const SDNode*> &Visited,
7013                                  SmallPtrSetImpl<const SDNode*> &Checked,
7014                                  const llvm::SelectionDAG *DAG) {
7015   // If this node has already been checked, don't check it again.
7016   if (Checked.count(N))
7017     return;
7018
7019   // If a node has already been visited on this depth-first walk, reject it as
7020   // a cycle.
7021   if (!Visited.insert(N).second) {
7022     errs() << "Detected cycle in SelectionDAG\n";
7023     dbgs() << "Offending node:\n";
7024     N->dumprFull(DAG); dbgs() << "\n";
7025     abort();
7026   }
7027
7028   for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
7029     checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked, DAG);
7030
7031   Checked.insert(N);
7032   Visited.erase(N);
7033 }
7034 #endif
7035
7036 void llvm::checkForCycles(const llvm::SDNode *N,
7037                           const llvm::SelectionDAG *DAG,
7038                           bool force) {
7039 #ifndef NDEBUG
7040   bool check = force;
7041 #ifdef XDEBUG
7042   check = true;
7043 #endif  // XDEBUG
7044   if (check) {
7045     assert(N && "Checking nonexistent SDNode");
7046     SmallPtrSet<const SDNode*, 32> visited;
7047     SmallPtrSet<const SDNode*, 32> checked;
7048     checkForCyclesHelper(N, visited, checked, DAG);
7049   }
7050 #endif  // !NDEBUG
7051 }
7052
7053 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
7054   checkForCycles(DAG->getRoot().getNode(), DAG, force);
7055 }