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