SelectionDAG.cpp revision c0e18d6638548720f2b3c0c77b8b3d3c7ff8d9a8
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#include "llvm/CodeGen/SelectionDAG.h"
14#include "llvm/Constants.h"
15#include "llvm/Analysis/ValueTracking.h"
16#include "llvm/GlobalAlias.h"
17#include "llvm/GlobalVariable.h"
18#include "llvm/Intrinsics.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Assembly/Writer.h"
21#include "llvm/CallingConv.h"
22#include "llvm/CodeGen/MachineBasicBlock.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineModuleInfo.h"
26#include "llvm/CodeGen/PseudoSourceValue.h"
27#include "llvm/Target/TargetRegisterInfo.h"
28#include "llvm/Target/TargetData.h"
29#include "llvm/Target/TargetLowering.h"
30#include "llvm/Target/TargetInstrInfo.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/MathExtras.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/ADT/SetVector.h"
36#include "llvm/ADT/SmallPtrSet.h"
37#include "llvm/ADT/SmallSet.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/ADT/StringExtras.h"
40#include <algorithm>
41#include <cmath>
42using namespace llvm;
43
44/// makeVTList - Return an instance of the SDVTList struct initialized with the
45/// specified members.
46static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
47  SDVTList Res = {VTs, NumVTs};
48  return Res;
49}
50
51static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
52  switch (VT.getSimpleVT()) {
53  default: assert(0 && "Unknown FP format");
54  case MVT::f32:     return &APFloat::IEEEsingle;
55  case MVT::f64:     return &APFloat::IEEEdouble;
56  case MVT::f80:     return &APFloat::x87DoubleExtended;
57  case MVT::f128:    return &APFloat::IEEEquad;
58  case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
59  }
60}
61
62SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
63
64//===----------------------------------------------------------------------===//
65//                              ConstantFPSDNode Class
66//===----------------------------------------------------------------------===//
67
68/// isExactlyValue - We don't rely on operator== working on double values, as
69/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
70/// As such, this method can be used to do an exact bit-for-bit comparison of
71/// two floating point values.
72bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
73  return getValueAPF().bitwiseIsEqual(V);
74}
75
76bool ConstantFPSDNode::isValueValidForType(MVT VT,
77                                           const APFloat& Val) {
78  assert(VT.isFloatingPoint() && "Can only convert between FP types");
79
80  // PPC long double cannot be converted to any other type.
81  if (VT == MVT::ppcf128 ||
82      &Val.getSemantics() == &APFloat::PPCDoubleDouble)
83    return false;
84
85  // convert modifies in place, so make a copy.
86  APFloat Val2 = APFloat(Val);
87  return Val2.convert(*MVTToAPFloatSemantics(VT),
88                      APFloat::rmNearestTiesToEven) == APFloat::opOK;
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::BIT_CONVERT)
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.
115  SDValue NotZero = N->getOperand(i);
116  if (isa<ConstantSDNode>(NotZero)) {
117    if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
118      return false;
119  } else if (isa<ConstantFPSDNode>(NotZero)) {
120    if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
121                convertToAPInt().isAllOnesValue())
122      return false;
123  } else
124    return false;
125
126  // Okay, we have at least one ~0 value, check to see if the rest match or are
127  // undefs.
128  for (++i; i != e; ++i)
129    if (N->getOperand(i) != NotZero &&
130        N->getOperand(i).getOpcode() != ISD::UNDEF)
131      return false;
132  return true;
133}
134
135
136/// isBuildVectorAllZeros - Return true if the specified node is a
137/// BUILD_VECTOR where all of the elements are 0 or undef.
138bool ISD::isBuildVectorAllZeros(const SDNode *N) {
139  // Look through a bit convert.
140  if (N->getOpcode() == ISD::BIT_CONVERT)
141    N = N->getOperand(0).getNode();
142
143  if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
144
145  unsigned i = 0, e = N->getNumOperands();
146
147  // Skip over all of the undef values.
148  while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
149    ++i;
150
151  // Do not accept an all-undef vector.
152  if (i == e) return false;
153
154  // Do not accept build_vectors that aren't all constants or which have non-~0
155  // elements.
156  SDValue Zero = N->getOperand(i);
157  if (isa<ConstantSDNode>(Zero)) {
158    if (!cast<ConstantSDNode>(Zero)->isNullValue())
159      return false;
160  } else if (isa<ConstantFPSDNode>(Zero)) {
161    if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
162      return false;
163  } else
164    return false;
165
166  // Okay, we have at least one ~0 value, check to see if the rest match or are
167  // undefs.
168  for (++i; i != e; ++i)
169    if (N->getOperand(i) != Zero &&
170        N->getOperand(i).getOpcode() != ISD::UNDEF)
171      return false;
172  return true;
173}
174
175/// isScalarToVector - Return true if the specified node is a
176/// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
177/// element is not an undef.
178bool ISD::isScalarToVector(const SDNode *N) {
179  if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
180    return true;
181
182  if (N->getOpcode() != ISD::BUILD_VECTOR)
183    return false;
184  if (N->getOperand(0).getOpcode() == ISD::UNDEF)
185    return false;
186  unsigned NumElems = N->getNumOperands();
187  for (unsigned i = 1; i < NumElems; ++i) {
188    SDValue V = N->getOperand(i);
189    if (V.getOpcode() != ISD::UNDEF)
190      return false;
191  }
192  return true;
193}
194
195
196/// isDebugLabel - Return true if the specified node represents a debug
197/// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
198bool ISD::isDebugLabel(const SDNode *N) {
199  SDValue Zero;
200  if (N->getOpcode() == ISD::DBG_LABEL)
201    return true;
202  if (N->isMachineOpcode() &&
203      N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
204    return true;
205  return false;
206}
207
208/// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
209/// when given the operation for (X op Y).
210ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
211  // To perform this operation, we just need to swap the L and G bits of the
212  // operation.
213  unsigned OldL = (Operation >> 2) & 1;
214  unsigned OldG = (Operation >> 1) & 1;
215  return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
216                       (OldL << 1) |       // New G bit
217                       (OldG << 2));        // New L bit.
218}
219
220/// getSetCCInverse - Return the operation corresponding to !(X op Y), where
221/// 'op' is a valid SetCC operation.
222ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
223  unsigned Operation = Op;
224  if (isInteger)
225    Operation ^= 7;   // Flip L, G, E bits, but not U.
226  else
227    Operation ^= 15;  // Flip all of the condition bits.
228  if (Operation > ISD::SETTRUE2)
229    Operation &= ~8;     // Don't let N and U bits get set.
230  return ISD::CondCode(Operation);
231}
232
233
234/// isSignedOp - For an integer comparison, return 1 if the comparison is a
235/// signed operation and 2 if the result is an unsigned comparison.  Return zero
236/// if the operation does not depend on the sign of the input (setne and seteq).
237static int isSignedOp(ISD::CondCode Opcode) {
238  switch (Opcode) {
239  default: assert(0 && "Illegal integer setcc operation!");
240  case ISD::SETEQ:
241  case ISD::SETNE: return 0;
242  case ISD::SETLT:
243  case ISD::SETLE:
244  case ISD::SETGT:
245  case ISD::SETGE: return 1;
246  case ISD::SETULT:
247  case ISD::SETULE:
248  case ISD::SETUGT:
249  case ISD::SETUGE: return 2;
250  }
251}
252
253/// getSetCCOrOperation - Return the result of a logical OR between different
254/// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
255/// returns SETCC_INVALID if it is not possible to represent the resultant
256/// comparison.
257ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
258                                       bool isInteger) {
259  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
260    // Cannot fold a signed integer setcc with an unsigned integer setcc.
261    return ISD::SETCC_INVALID;
262
263  unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
264
265  // If the N and U bits get set then the resultant comparison DOES suddenly
266  // care about orderedness, and is true when ordered.
267  if (Op > ISD::SETTRUE2)
268    Op &= ~16;     // Clear the U bit if the N bit is set.
269
270  // Canonicalize illegal integer setcc's.
271  if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
272    Op = ISD::SETNE;
273
274  return ISD::CondCode(Op);
275}
276
277/// getSetCCAndOperation - Return the result of a logical AND between different
278/// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
279/// function returns zero if it is not possible to represent the resultant
280/// comparison.
281ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
282                                        bool isInteger) {
283  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
284    // Cannot fold a signed setcc with an unsigned setcc.
285    return ISD::SETCC_INVALID;
286
287  // Combine all of the condition bits.
288  ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
289
290  // Canonicalize illegal integer setcc's.
291  if (isInteger) {
292    switch (Result) {
293    default: break;
294    case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
295    case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
296    case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
297    case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
298    case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
299    }
300  }
301
302  return Result;
303}
304
305const TargetMachine &SelectionDAG::getTarget() const {
306  return MF->getTarget();
307}
308
309//===----------------------------------------------------------------------===//
310//                           SDNode Profile Support
311//===----------------------------------------------------------------------===//
312
313/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
314///
315static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
316  ID.AddInteger(OpC);
317}
318
319/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
320/// solely with their pointer.
321static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
322  ID.AddPointer(VTList.VTs);
323}
324
325/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
326///
327static void AddNodeIDOperands(FoldingSetNodeID &ID,
328                              const SDValue *Ops, unsigned NumOps) {
329  for (; NumOps; --NumOps, ++Ops) {
330    ID.AddPointer(Ops->getNode());
331    ID.AddInteger(Ops->getResNo());
332  }
333}
334
335/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
336///
337static void AddNodeIDOperands(FoldingSetNodeID &ID,
338                              const SDUse *Ops, unsigned NumOps) {
339  for (; NumOps; --NumOps, ++Ops) {
340    ID.AddPointer(Ops->getVal());
341    ID.AddInteger(Ops->getSDValue().getResNo());
342  }
343}
344
345static void AddNodeIDNode(FoldingSetNodeID &ID,
346                          unsigned short OpC, SDVTList VTList,
347                          const SDValue *OpList, unsigned N) {
348  AddNodeIDOpcode(ID, OpC);
349  AddNodeIDValueTypes(ID, VTList);
350  AddNodeIDOperands(ID, OpList, N);
351}
352
353
354/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
355/// data.
356static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
357  AddNodeIDOpcode(ID, N->getOpcode());
358  // Add the return value info.
359  AddNodeIDValueTypes(ID, N->getVTList());
360  // Add the operand info.
361  AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
362
363  // Handle SDNode leafs with special info.
364  switch (N->getOpcode()) {
365  default: break;  // Normal nodes don't need extra info.
366  case ISD::ARG_FLAGS:
367    ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
368    break;
369  case ISD::TargetConstant:
370  case ISD::Constant:
371    ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
372    break;
373  case ISD::TargetConstantFP:
374  case ISD::ConstantFP: {
375    ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
376    break;
377  }
378  case ISD::TargetGlobalAddress:
379  case ISD::GlobalAddress:
380  case ISD::TargetGlobalTLSAddress:
381  case ISD::GlobalTLSAddress: {
382    const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
383    ID.AddPointer(GA->getGlobal());
384    ID.AddInteger(GA->getOffset());
385    break;
386  }
387  case ISD::BasicBlock:
388    ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
389    break;
390  case ISD::Register:
391    ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
392    break;
393  case ISD::DBG_STOPPOINT: {
394    const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
395    ID.AddInteger(DSP->getLine());
396    ID.AddInteger(DSP->getColumn());
397    ID.AddPointer(DSP->getCompileUnit());
398    break;
399  }
400  case ISD::SRCVALUE:
401    ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
402    break;
403  case ISD::MEMOPERAND: {
404    const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
405    MO.Profile(ID);
406    break;
407  }
408  case ISD::FrameIndex:
409  case ISD::TargetFrameIndex:
410    ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
411    break;
412  case ISD::JumpTable:
413  case ISD::TargetJumpTable:
414    ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
415    break;
416  case ISD::ConstantPool:
417  case ISD::TargetConstantPool: {
418    const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
419    ID.AddInteger(CP->getAlignment());
420    ID.AddInteger(CP->getOffset());
421    if (CP->isMachineConstantPoolEntry())
422      CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
423    else
424      ID.AddPointer(CP->getConstVal());
425    break;
426  }
427  case ISD::CALL: {
428    const CallSDNode *Call = cast<CallSDNode>(N);
429    ID.AddInteger(Call->getCallingConv());
430    ID.AddInteger(Call->isVarArg());
431    break;
432  }
433  case ISD::LOAD: {
434    const LoadSDNode *LD = cast<LoadSDNode>(N);
435    ID.AddInteger(LD->getAddressingMode());
436    ID.AddInteger(LD->getExtensionType());
437    ID.AddInteger(LD->getMemoryVT().getRawBits());
438    ID.AddInteger(LD->getRawFlags());
439    break;
440  }
441  case ISD::STORE: {
442    const StoreSDNode *ST = cast<StoreSDNode>(N);
443    ID.AddInteger(ST->getAddressingMode());
444    ID.AddInteger(ST->isTruncatingStore());
445    ID.AddInteger(ST->getMemoryVT().getRawBits());
446    ID.AddInteger(ST->getRawFlags());
447    break;
448  }
449  case ISD::ATOMIC_CMP_SWAP_8:
450  case ISD::ATOMIC_SWAP_8:
451  case ISD::ATOMIC_LOAD_ADD_8:
452  case ISD::ATOMIC_LOAD_SUB_8:
453  case ISD::ATOMIC_LOAD_AND_8:
454  case ISD::ATOMIC_LOAD_OR_8:
455  case ISD::ATOMIC_LOAD_XOR_8:
456  case ISD::ATOMIC_LOAD_NAND_8:
457  case ISD::ATOMIC_LOAD_MIN_8:
458  case ISD::ATOMIC_LOAD_MAX_8:
459  case ISD::ATOMIC_LOAD_UMIN_8:
460  case ISD::ATOMIC_LOAD_UMAX_8:
461  case ISD::ATOMIC_CMP_SWAP_16:
462  case ISD::ATOMIC_SWAP_16:
463  case ISD::ATOMIC_LOAD_ADD_16:
464  case ISD::ATOMIC_LOAD_SUB_16:
465  case ISD::ATOMIC_LOAD_AND_16:
466  case ISD::ATOMIC_LOAD_OR_16:
467  case ISD::ATOMIC_LOAD_XOR_16:
468  case ISD::ATOMIC_LOAD_NAND_16:
469  case ISD::ATOMIC_LOAD_MIN_16:
470  case ISD::ATOMIC_LOAD_MAX_16:
471  case ISD::ATOMIC_LOAD_UMIN_16:
472  case ISD::ATOMIC_LOAD_UMAX_16:
473  case ISD::ATOMIC_CMP_SWAP_32:
474  case ISD::ATOMIC_SWAP_32:
475  case ISD::ATOMIC_LOAD_ADD_32:
476  case ISD::ATOMIC_LOAD_SUB_32:
477  case ISD::ATOMIC_LOAD_AND_32:
478  case ISD::ATOMIC_LOAD_OR_32:
479  case ISD::ATOMIC_LOAD_XOR_32:
480  case ISD::ATOMIC_LOAD_NAND_32:
481  case ISD::ATOMIC_LOAD_MIN_32:
482  case ISD::ATOMIC_LOAD_MAX_32:
483  case ISD::ATOMIC_LOAD_UMIN_32:
484  case ISD::ATOMIC_LOAD_UMAX_32:
485  case ISD::ATOMIC_CMP_SWAP_64:
486  case ISD::ATOMIC_SWAP_64:
487  case ISD::ATOMIC_LOAD_ADD_64:
488  case ISD::ATOMIC_LOAD_SUB_64:
489  case ISD::ATOMIC_LOAD_AND_64:
490  case ISD::ATOMIC_LOAD_OR_64:
491  case ISD::ATOMIC_LOAD_XOR_64:
492  case ISD::ATOMIC_LOAD_NAND_64:
493  case ISD::ATOMIC_LOAD_MIN_64:
494  case ISD::ATOMIC_LOAD_MAX_64:
495  case ISD::ATOMIC_LOAD_UMIN_64:
496  case ISD::ATOMIC_LOAD_UMAX_64: {
497    const AtomicSDNode *AT = cast<AtomicSDNode>(N);
498    ID.AddInteger(AT->getRawFlags());
499    break;
500  }
501  } // end switch (N->getOpcode())
502}
503
504/// encodeMemSDNodeFlags - Generic routine for computing a value for use in
505/// the CSE map that carries both alignment and volatility information.
506///
507static unsigned encodeMemSDNodeFlags(bool isVolatile, unsigned Alignment) {
508  return isVolatile | ((Log2_32(Alignment) + 1) << 1);
509}
510
511//===----------------------------------------------------------------------===//
512//                              SelectionDAG Class
513//===----------------------------------------------------------------------===//
514
515/// RemoveDeadNodes - This method deletes all unreachable nodes in the
516/// SelectionDAG.
517void SelectionDAG::RemoveDeadNodes() {
518  // Create a dummy node (which is not added to allnodes), that adds a reference
519  // to the root node, preventing it from being deleted.
520  HandleSDNode Dummy(getRoot());
521
522  SmallVector<SDNode*, 128> DeadNodes;
523
524  // Add all obviously-dead nodes to the DeadNodes worklist.
525  for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
526    if (I->use_empty())
527      DeadNodes.push_back(I);
528
529  RemoveDeadNodes(DeadNodes);
530
531  // If the root changed (e.g. it was a dead load, update the root).
532  setRoot(Dummy.getValue());
533}
534
535/// RemoveDeadNodes - This method deletes the unreachable nodes in the
536/// given list, and any nodes that become unreachable as a result.
537void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
538                                   DAGUpdateListener *UpdateListener) {
539
540  // Process the worklist, deleting the nodes and adding their uses to the
541  // worklist.
542  while (!DeadNodes.empty()) {
543    SDNode *N = DeadNodes.back();
544    DeadNodes.pop_back();
545
546    if (UpdateListener)
547      UpdateListener->NodeDeleted(N, 0);
548
549    // Take the node out of the appropriate CSE map.
550    RemoveNodeFromCSEMaps(N);
551
552    // Next, brutally remove the operand list.  This is safe to do, as there are
553    // no cycles in the graph.
554    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
555      SDNode *Operand = I->getVal();
556      Operand->removeUser(std::distance(N->op_begin(), I), N);
557
558      // Now that we removed this operand, see if there are no uses of it left.
559      if (Operand->use_empty())
560        DeadNodes.push_back(Operand);
561    }
562    if (N->OperandsNeedDelete) {
563      delete[] N->OperandList;
564    }
565    N->OperandList = 0;
566    N->NumOperands = 0;
567
568    // Finally, remove N itself.
569    NodeAllocator.Deallocate(AllNodes.remove(N));
570  }
571}
572
573void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
574  SmallVector<SDNode*, 16> DeadNodes(1, N);
575  RemoveDeadNodes(DeadNodes, UpdateListener);
576}
577
578void SelectionDAG::DeleteNode(SDNode *N) {
579  assert(N->use_empty() && "Cannot delete a node that is not dead!");
580
581  // First take this out of the appropriate CSE map.
582  RemoveNodeFromCSEMaps(N);
583
584  // Finally, remove uses due to operands of this node, remove from the
585  // AllNodes list, and delete the node.
586  DeleteNodeNotInCSEMaps(N);
587}
588
589void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
590
591  // Drop all of the operands and decrement used node's use counts.
592  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
593    I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
594  if (N->OperandsNeedDelete)
595    delete[] N->OperandList;
596
597  assert(N != AllNodes.begin());
598  NodeAllocator.Deallocate(AllNodes.remove(N));
599}
600
601/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
602/// correspond to it.  This is useful when we're about to delete or repurpose
603/// the node.  We don't want future request for structurally identical nodes
604/// to return N anymore.
605bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
606  bool Erased = false;
607  switch (N->getOpcode()) {
608  case ISD::EntryToken:
609    assert(0 && "EntryToken should not be in CSEMaps!");
610    return false;
611  case ISD::HANDLENODE: return false;  // noop.
612  case ISD::CONDCODE:
613    assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
614           "Cond code doesn't exist!");
615    Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
616    CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
617    break;
618  case ISD::ExternalSymbol:
619    Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
620    break;
621  case ISD::TargetExternalSymbol:
622    Erased =
623      TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
624    break;
625  case ISD::VALUETYPE: {
626    MVT VT = cast<VTSDNode>(N)->getVT();
627    if (VT.isExtended()) {
628      Erased = ExtendedValueTypeNodes.erase(VT);
629    } else {
630      Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
631      ValueTypeNodes[VT.getSimpleVT()] = 0;
632    }
633    break;
634  }
635  default:
636    // Remove it from the CSE Map.
637    Erased = CSEMap.RemoveNode(N);
638    break;
639  }
640#ifndef NDEBUG
641  // Verify that the node was actually in one of the CSE maps, unless it has a
642  // flag result (which cannot be CSE'd) or is one of the special cases that are
643  // not subject to CSE.
644  if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
645      !N->isMachineOpcode() &&
646      N->getOpcode() != ISD::DBG_LABEL &&
647      N->getOpcode() != ISD::DBG_STOPPOINT &&
648      N->getOpcode() != ISD::EH_LABEL &&
649      N->getOpcode() != ISD::DECLARE) {
650    N->dump(this);
651    cerr << "\n";
652    assert(0 && "Node is not in map!");
653  }
654#endif
655  return Erased;
656}
657
658/// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
659/// has been taken out and modified in some way.  If the specified node already
660/// exists in the CSE maps, do not modify the maps, but return the existing node
661/// instead.  If it doesn't exist, add it and return null.
662///
663SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
664  assert(N->getNumOperands() && "This is a leaf node!");
665
666  if (N->getValueType(0) == MVT::Flag)
667    return 0;   // Never CSE anything that produces a flag.
668
669  switch (N->getOpcode()) {
670  default: break;
671  case ISD::HANDLENODE:
672  case ISD::DBG_LABEL:
673  case ISD::DBG_STOPPOINT:
674  case ISD::EH_LABEL:
675  case ISD::DECLARE:
676    return 0;    // Never add these nodes.
677  }
678
679  // Check that remaining values produced are not flags.
680  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
681    if (N->getValueType(i) == MVT::Flag)
682      return 0;   // Never CSE anything that produces a flag.
683
684  SDNode *New = CSEMap.GetOrInsertNode(N);
685  if (New != N) return New;  // Node already existed.
686  return 0;
687}
688
689/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
690/// were replaced with those specified.  If this node is never memoized,
691/// return null, otherwise return a pointer to the slot it would take.  If a
692/// node already exists with these operands, the slot will be non-null.
693SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
694                                           void *&InsertPos) {
695  if (N->getValueType(0) == MVT::Flag)
696    return 0;   // Never CSE anything that produces a flag.
697
698  switch (N->getOpcode()) {
699  default: break;
700  case ISD::HANDLENODE:
701  case ISD::DBG_LABEL:
702  case ISD::DBG_STOPPOINT:
703  case ISD::EH_LABEL:
704    return 0;    // Never add these nodes.
705  }
706
707  // Check that remaining values produced are not flags.
708  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
709    if (N->getValueType(i) == MVT::Flag)
710      return 0;   // Never CSE anything that produces a flag.
711
712  SDValue Ops[] = { Op };
713  FoldingSetNodeID ID;
714  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
715  return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
716}
717
718/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
719/// were replaced with those specified.  If this node is never memoized,
720/// return null, otherwise return a pointer to the slot it would take.  If a
721/// node already exists with these operands, the slot will be non-null.
722SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
723                                           SDValue Op1, SDValue Op2,
724                                           void *&InsertPos) {
725  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
726
727  // Check that remaining values produced are not flags.
728  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
729    if (N->getValueType(i) == MVT::Flag)
730      return 0;   // Never CSE anything that produces a flag.
731
732  SDValue Ops[] = { Op1, Op2 };
733  FoldingSetNodeID ID;
734  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
735  return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
736}
737
738
739/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
740/// were replaced with those specified.  If this node is never memoized,
741/// return null, otherwise return a pointer to the slot it would take.  If a
742/// node already exists with these operands, the slot will be non-null.
743SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
744                                           const SDValue *Ops,unsigned NumOps,
745                                           void *&InsertPos) {
746  if (N->getValueType(0) == MVT::Flag)
747    return 0;   // Never CSE anything that produces a flag.
748
749  switch (N->getOpcode()) {
750  default: break;
751  case ISD::HANDLENODE:
752  case ISD::DBG_LABEL:
753  case ISD::DBG_STOPPOINT:
754  case ISD::EH_LABEL:
755  case ISD::DECLARE:
756    return 0;    // Never add these nodes.
757  }
758
759  // Check that remaining values produced are not flags.
760  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
761    if (N->getValueType(i) == MVT::Flag)
762      return 0;   // Never CSE anything that produces a flag.
763
764  FoldingSetNodeID ID;
765  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
766
767  if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
768    ID.AddInteger(LD->getAddressingMode());
769    ID.AddInteger(LD->getExtensionType());
770    ID.AddInteger(LD->getMemoryVT().getRawBits());
771    ID.AddInteger(LD->getRawFlags());
772  } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
773    ID.AddInteger(ST->getAddressingMode());
774    ID.AddInteger(ST->isTruncatingStore());
775    ID.AddInteger(ST->getMemoryVT().getRawBits());
776    ID.AddInteger(ST->getRawFlags());
777  }
778
779  return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
780}
781
782/// VerifyNode - Sanity check the given node.  Aborts if it is invalid.
783void SelectionDAG::VerifyNode(SDNode *N) {
784  switch (N->getOpcode()) {
785  default:
786    break;
787  case ISD::BUILD_VECTOR: {
788    assert(N->getNumValues() == 1 && "Too many results for BUILD_VECTOR!");
789    assert(N->getValueType(0).isVector() && "Wrong BUILD_VECTOR return type!");
790    assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
791           "Wrong number of BUILD_VECTOR operands!");
792    MVT EltVT = N->getValueType(0).getVectorElementType();
793    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
794      assert(I->getSDValue().getValueType() == EltVT &&
795             "Wrong BUILD_VECTOR operand type!");
796    break;
797  }
798  }
799}
800
801/// getMVTAlignment - Compute the default alignment value for the
802/// given type.
803///
804unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
805  const Type *Ty = VT == MVT::iPTR ?
806                   PointerType::get(Type::Int8Ty, 0) :
807                   VT.getTypeForMVT();
808
809  return TLI.getTargetData()->getABITypeAlignment(Ty);
810}
811
812SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
813  : TLI(tli), FLI(fli),
814    EntryNode(ISD::EntryToken, getVTList(MVT::Other)),
815    Root(getEntryNode()) {
816  AllNodes.push_back(&EntryNode);
817}
818
819void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi) {
820  MF = &mf;
821  MMI = mmi;
822}
823
824SelectionDAG::~SelectionDAG() {
825  allnodes_clear();
826}
827
828void SelectionDAG::allnodes_clear() {
829  assert(&*AllNodes.begin() == &EntryNode);
830  AllNodes.remove(AllNodes.begin());
831  while (!AllNodes.empty()) {
832    SDNode *N = AllNodes.remove(AllNodes.begin());
833    N->SetNextInBucket(0);
834    if (N->OperandsNeedDelete)
835      delete [] N->OperandList;
836    NodeAllocator.Deallocate(N);
837  }
838}
839
840void SelectionDAG::clear() {
841  allnodes_clear();
842  OperandAllocator.Reset();
843  CSEMap.clear();
844
845  ExtendedValueTypeNodes.clear();
846  ExternalSymbols.clear();
847  TargetExternalSymbols.clear();
848  std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
849            static_cast<CondCodeSDNode*>(0));
850  std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
851            static_cast<SDNode*>(0));
852
853  EntryNode.Uses = 0;
854  AllNodes.push_back(&EntryNode);
855  Root = getEntryNode();
856}
857
858SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, MVT VT) {
859  if (Op.getValueType() == VT) return Op;
860  APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
861                                   VT.getSizeInBits());
862  return getNode(ISD::AND, Op.getValueType(), Op,
863                 getConstant(Imm, Op.getValueType()));
864}
865
866SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
867  MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
868  return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
869}
870
871SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
872  return getConstant(*ConstantInt::get(Val), VT, isT);
873}
874
875SDValue SelectionDAG::getConstant(const ConstantInt &Val, MVT VT, bool isT) {
876  assert(VT.isInteger() && "Cannot create FP integer constant!");
877
878  MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
879  assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
880         "APInt size does not match type size!");
881
882  unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
883  FoldingSetNodeID ID;
884  AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
885  ID.AddPointer(&Val);
886  void *IP = 0;
887  SDNode *N = NULL;
888  if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
889    if (!VT.isVector())
890      return SDValue(N, 0);
891  if (!N) {
892    N = NodeAllocator.Allocate<ConstantSDNode>();
893    new (N) ConstantSDNode(isT, &Val, EltVT);
894    CSEMap.InsertNode(N, IP);
895    AllNodes.push_back(N);
896  }
897
898  SDValue Result(N, 0);
899  if (VT.isVector()) {
900    SmallVector<SDValue, 8> Ops;
901    Ops.assign(VT.getVectorNumElements(), Result);
902    Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
903  }
904  return Result;
905}
906
907SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
908  return getConstant(Val, TLI.getPointerTy(), isTarget);
909}
910
911
912SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
913  return getConstantFP(*ConstantFP::get(V), VT, isTarget);
914}
915
916SDValue SelectionDAG::getConstantFP(const ConstantFP& V, MVT VT, bool isTarget){
917  assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
918
919  MVT EltVT =
920    VT.isVector() ? VT.getVectorElementType() : VT;
921
922  // Do the map lookup using the actual bit pattern for the floating point
923  // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
924  // we don't have issues with SNANs.
925  unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
926  FoldingSetNodeID ID;
927  AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
928  ID.AddPointer(&V);
929  void *IP = 0;
930  SDNode *N = NULL;
931  if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
932    if (!VT.isVector())
933      return SDValue(N, 0);
934  if (!N) {
935    N = NodeAllocator.Allocate<ConstantFPSDNode>();
936    new (N) ConstantFPSDNode(isTarget, &V, EltVT);
937    CSEMap.InsertNode(N, IP);
938    AllNodes.push_back(N);
939  }
940
941  SDValue Result(N, 0);
942  if (VT.isVector()) {
943    SmallVector<SDValue, 8> Ops;
944    Ops.assign(VT.getVectorNumElements(), Result);
945    Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
946  }
947  return Result;
948}
949
950SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
951  MVT EltVT =
952    VT.isVector() ? VT.getVectorElementType() : VT;
953  if (EltVT==MVT::f32)
954    return getConstantFP(APFloat((float)Val), VT, isTarget);
955  else
956    return getConstantFP(APFloat(Val), VT, isTarget);
957}
958
959SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
960                                       MVT VT, int Offset,
961                                       bool isTargetGA) {
962  unsigned Opc;
963
964  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
965  if (!GVar) {
966    // If GV is an alias then use the aliasee for determining thread-localness.
967    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
968      GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
969  }
970
971  if (GVar && GVar->isThreadLocal())
972    Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
973  else
974    Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
975
976  FoldingSetNodeID ID;
977  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
978  ID.AddPointer(GV);
979  ID.AddInteger(Offset);
980  void *IP = 0;
981  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
982   return SDValue(E, 0);
983  SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
984  new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
985  CSEMap.InsertNode(N, IP);
986  AllNodes.push_back(N);
987  return SDValue(N, 0);
988}
989
990SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
991  unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
992  FoldingSetNodeID ID;
993  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
994  ID.AddInteger(FI);
995  void *IP = 0;
996  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
997    return SDValue(E, 0);
998  SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
999  new (N) FrameIndexSDNode(FI, VT, isTarget);
1000  CSEMap.InsertNode(N, IP);
1001  AllNodes.push_back(N);
1002  return SDValue(N, 0);
1003}
1004
1005SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
1006  unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1007  FoldingSetNodeID ID;
1008  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1009  ID.AddInteger(JTI);
1010  void *IP = 0;
1011  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1012    return SDValue(E, 0);
1013  SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
1014  new (N) JumpTableSDNode(JTI, VT, isTarget);
1015  CSEMap.InsertNode(N, IP);
1016  AllNodes.push_back(N);
1017  return SDValue(N, 0);
1018}
1019
1020SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT,
1021                                      unsigned Alignment, int Offset,
1022                                      bool isTarget) {
1023  if (Alignment == 0)
1024    Alignment =
1025      TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
1026  unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1027  FoldingSetNodeID ID;
1028  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1029  ID.AddInteger(Alignment);
1030  ID.AddInteger(Offset);
1031  ID.AddPointer(C);
1032  void *IP = 0;
1033  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1034    return SDValue(E, 0);
1035  SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1036  new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
1037  CSEMap.InsertNode(N, IP);
1038  AllNodes.push_back(N);
1039  return SDValue(N, 0);
1040}
1041
1042
1043SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
1044                                      unsigned Alignment, int Offset,
1045                                      bool isTarget) {
1046  if (Alignment == 0)
1047    Alignment =
1048      TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
1049  unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1050  FoldingSetNodeID ID;
1051  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1052  ID.AddInteger(Alignment);
1053  ID.AddInteger(Offset);
1054  C->AddSelectionDAGCSEId(ID);
1055  void *IP = 0;
1056  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1057    return SDValue(E, 0);
1058  SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1059  new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
1060  CSEMap.InsertNode(N, IP);
1061  AllNodes.push_back(N);
1062  return SDValue(N, 0);
1063}
1064
1065
1066SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1067  FoldingSetNodeID ID;
1068  AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1069  ID.AddPointer(MBB);
1070  void *IP = 0;
1071  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1072    return SDValue(E, 0);
1073  SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1074  new (N) BasicBlockSDNode(MBB);
1075  CSEMap.InsertNode(N, IP);
1076  AllNodes.push_back(N);
1077  return SDValue(N, 0);
1078}
1079
1080SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
1081  FoldingSetNodeID ID;
1082  AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
1083  ID.AddInteger(Flags.getRawBits());
1084  void *IP = 0;
1085  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1086    return SDValue(E, 0);
1087  SDNode *N = NodeAllocator.Allocate<ARG_FLAGSSDNode>();
1088  new (N) ARG_FLAGSSDNode(Flags);
1089  CSEMap.InsertNode(N, IP);
1090  AllNodes.push_back(N);
1091  return SDValue(N, 0);
1092}
1093
1094SDValue SelectionDAG::getValueType(MVT VT) {
1095  if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
1096    ValueTypeNodes.resize(VT.getSimpleVT()+1);
1097
1098  SDNode *&N = VT.isExtended() ?
1099    ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
1100
1101  if (N) return SDValue(N, 0);
1102  N = NodeAllocator.Allocate<VTSDNode>();
1103  new (N) VTSDNode(VT);
1104  AllNodes.push_back(N);
1105  return SDValue(N, 0);
1106}
1107
1108SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
1109  SDNode *&N = ExternalSymbols[Sym];
1110  if (N) return SDValue(N, 0);
1111  N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1112  new (N) ExternalSymbolSDNode(false, Sym, VT);
1113  AllNodes.push_back(N);
1114  return SDValue(N, 0);
1115}
1116
1117SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1118  SDNode *&N = TargetExternalSymbols[Sym];
1119  if (N) return SDValue(N, 0);
1120  N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1121  new (N) ExternalSymbolSDNode(true, Sym, VT);
1122  AllNodes.push_back(N);
1123  return SDValue(N, 0);
1124}
1125
1126SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1127  if ((unsigned)Cond >= CondCodeNodes.size())
1128    CondCodeNodes.resize(Cond+1);
1129
1130  if (CondCodeNodes[Cond] == 0) {
1131    CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1132    new (N) CondCodeSDNode(Cond);
1133    CondCodeNodes[Cond] = N;
1134    AllNodes.push_back(N);
1135  }
1136  return SDValue(CondCodeNodes[Cond], 0);
1137}
1138
1139SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1140  FoldingSetNodeID ID;
1141  AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1142  ID.AddInteger(RegNo);
1143  void *IP = 0;
1144  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1145    return SDValue(E, 0);
1146  SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1147  new (N) RegisterSDNode(RegNo, VT);
1148  CSEMap.InsertNode(N, IP);
1149  AllNodes.push_back(N);
1150  return SDValue(N, 0);
1151}
1152
1153SDValue SelectionDAG::getDbgStopPoint(SDValue Root,
1154                                        unsigned Line, unsigned Col,
1155                                        const CompileUnitDesc *CU) {
1156  SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
1157  new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1158  AllNodes.push_back(N);
1159  return SDValue(N, 0);
1160}
1161
1162SDValue SelectionDAG::getLabel(unsigned Opcode,
1163                               SDValue Root,
1164                               unsigned LabelID) {
1165  FoldingSetNodeID ID;
1166  SDValue Ops[] = { Root };
1167  AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1168  ID.AddInteger(LabelID);
1169  void *IP = 0;
1170  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1171    return SDValue(E, 0);
1172  SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1173  new (N) LabelSDNode(Opcode, Root, LabelID);
1174  CSEMap.InsertNode(N, IP);
1175  AllNodes.push_back(N);
1176  return SDValue(N, 0);
1177}
1178
1179SDValue SelectionDAG::getSrcValue(const Value *V) {
1180  assert((!V || isa<PointerType>(V->getType())) &&
1181         "SrcValue is not a pointer?");
1182
1183  FoldingSetNodeID ID;
1184  AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1185  ID.AddPointer(V);
1186
1187  void *IP = 0;
1188  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1189    return SDValue(E, 0);
1190
1191  SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1192  new (N) SrcValueSDNode(V);
1193  CSEMap.InsertNode(N, IP);
1194  AllNodes.push_back(N);
1195  return SDValue(N, 0);
1196}
1197
1198SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1199  const Value *v = MO.getValue();
1200  assert((!v || isa<PointerType>(v->getType())) &&
1201         "SrcValue is not a pointer?");
1202
1203  FoldingSetNodeID ID;
1204  AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1205  MO.Profile(ID);
1206
1207  void *IP = 0;
1208  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1209    return SDValue(E, 0);
1210
1211  SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
1212  new (N) MemOperandSDNode(MO);
1213  CSEMap.InsertNode(N, IP);
1214  AllNodes.push_back(N);
1215  return SDValue(N, 0);
1216}
1217
1218/// CreateStackTemporary - Create a stack temporary, suitable for holding the
1219/// specified value type.
1220SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1221  MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1222  unsigned ByteSize = VT.getSizeInBits()/8;
1223  const Type *Ty = VT.getTypeForMVT();
1224  unsigned StackAlign =
1225  std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1226
1227  int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1228  return getFrameIndex(FrameIdx, TLI.getPointerTy());
1229}
1230
1231SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
1232                                SDValue N2, ISD::CondCode Cond) {
1233  // These setcc operations always fold.
1234  switch (Cond) {
1235  default: break;
1236  case ISD::SETFALSE:
1237  case ISD::SETFALSE2: return getConstant(0, VT);
1238  case ISD::SETTRUE:
1239  case ISD::SETTRUE2:  return getConstant(1, VT);
1240
1241  case ISD::SETOEQ:
1242  case ISD::SETOGT:
1243  case ISD::SETOGE:
1244  case ISD::SETOLT:
1245  case ISD::SETOLE:
1246  case ISD::SETONE:
1247  case ISD::SETO:
1248  case ISD::SETUO:
1249  case ISD::SETUEQ:
1250  case ISD::SETUNE:
1251    assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1252    break;
1253  }
1254
1255  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1256    const APInt &C2 = N2C->getAPIntValue();
1257    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1258      const APInt &C1 = N1C->getAPIntValue();
1259
1260      switch (Cond) {
1261      default: assert(0 && "Unknown integer setcc!");
1262      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
1263      case ISD::SETNE:  return getConstant(C1 != C2, VT);
1264      case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1265      case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1266      case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1267      case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1268      case ISD::SETLT:  return getConstant(C1.slt(C2), VT);
1269      case ISD::SETGT:  return getConstant(C1.sgt(C2), VT);
1270      case ISD::SETLE:  return getConstant(C1.sle(C2), VT);
1271      case ISD::SETGE:  return getConstant(C1.sge(C2), VT);
1272      }
1273    }
1274  }
1275  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1276    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1277      // No compile time operations on this type yet.
1278      if (N1C->getValueType(0) == MVT::ppcf128)
1279        return SDValue();
1280
1281      APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1282      switch (Cond) {
1283      default: break;
1284      case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
1285                          return getNode(ISD::UNDEF, VT);
1286                        // fall through
1287      case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1288      case ISD::SETNE:  if (R==APFloat::cmpUnordered)
1289                          return getNode(ISD::UNDEF, VT);
1290                        // fall through
1291      case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1292                                           R==APFloat::cmpLessThan, VT);
1293      case ISD::SETLT:  if (R==APFloat::cmpUnordered)
1294                          return getNode(ISD::UNDEF, VT);
1295                        // fall through
1296      case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1297      case ISD::SETGT:  if (R==APFloat::cmpUnordered)
1298                          return getNode(ISD::UNDEF, VT);
1299                        // fall through
1300      case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1301      case ISD::SETLE:  if (R==APFloat::cmpUnordered)
1302                          return getNode(ISD::UNDEF, VT);
1303                        // fall through
1304      case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1305                                           R==APFloat::cmpEqual, VT);
1306      case ISD::SETGE:  if (R==APFloat::cmpUnordered)
1307                          return getNode(ISD::UNDEF, VT);
1308                        // fall through
1309      case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1310                                           R==APFloat::cmpEqual, VT);
1311      case ISD::SETO:   return getConstant(R!=APFloat::cmpUnordered, VT);
1312      case ISD::SETUO:  return getConstant(R==APFloat::cmpUnordered, VT);
1313      case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1314                                           R==APFloat::cmpEqual, VT);
1315      case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1316      case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1317                                           R==APFloat::cmpLessThan, VT);
1318      case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1319                                           R==APFloat::cmpUnordered, VT);
1320      case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1321      case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1322      }
1323    } else {
1324      // Ensure that the constant occurs on the RHS.
1325      return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1326    }
1327  }
1328
1329  // Could not fold it.
1330  return SDValue();
1331}
1332
1333/// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
1334/// use this predicate to simplify operations downstream.
1335bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1336  unsigned BitWidth = Op.getValueSizeInBits();
1337  return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1338}
1339
1340/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1341/// this predicate to simplify operations downstream.  Mask is known to be zero
1342/// for bits that V cannot have.
1343bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1344                                     unsigned Depth) const {
1345  APInt KnownZero, KnownOne;
1346  ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1347  assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1348  return (KnownZero & Mask) == Mask;
1349}
1350
1351/// ComputeMaskedBits - Determine which of the bits specified in Mask are
1352/// known to be either zero or one and return them in the KnownZero/KnownOne
1353/// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
1354/// processing.
1355void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1356                                     APInt &KnownZero, APInt &KnownOne,
1357                                     unsigned Depth) const {
1358  unsigned BitWidth = Mask.getBitWidth();
1359  assert(BitWidth == Op.getValueType().getSizeInBits() &&
1360         "Mask size mismatches value type size!");
1361
1362  KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
1363  if (Depth == 6 || Mask == 0)
1364    return;  // Limit search depth.
1365
1366  APInt KnownZero2, KnownOne2;
1367
1368  switch (Op.getOpcode()) {
1369  case ISD::Constant:
1370    // We know all of the bits for a constant!
1371    KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1372    KnownZero = ~KnownOne & Mask;
1373    return;
1374  case ISD::AND:
1375    // If either the LHS or the RHS are Zero, the result is zero.
1376    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1377    ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1378                      KnownZero2, KnownOne2, Depth+1);
1379    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1380    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1381
1382    // Output known-1 bits are only known if set in both the LHS & RHS.
1383    KnownOne &= KnownOne2;
1384    // Output known-0 are known to be clear if zero in either the LHS | RHS.
1385    KnownZero |= KnownZero2;
1386    return;
1387  case ISD::OR:
1388    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1389    ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1390                      KnownZero2, KnownOne2, Depth+1);
1391    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1392    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1393
1394    // Output known-0 bits are only known if clear in both the LHS & RHS.
1395    KnownZero &= KnownZero2;
1396    // Output known-1 are known to be set if set in either the LHS | RHS.
1397    KnownOne |= KnownOne2;
1398    return;
1399  case ISD::XOR: {
1400    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1401    ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1402    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1403    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1404
1405    // Output known-0 bits are known if clear or set in both the LHS & RHS.
1406    APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1407    // Output known-1 are known to be set if set in only one of the LHS, RHS.
1408    KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1409    KnownZero = KnownZeroOut;
1410    return;
1411  }
1412  case ISD::MUL: {
1413    APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1414    ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1415    ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1416    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1417    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1418
1419    // If low bits are zero in either operand, output low known-0 bits.
1420    // Also compute a conserative estimate for high known-0 bits.
1421    // More trickiness is possible, but this is sufficient for the
1422    // interesting case of alignment computation.
1423    KnownOne.clear();
1424    unsigned TrailZ = KnownZero.countTrailingOnes() +
1425                      KnownZero2.countTrailingOnes();
1426    unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
1427                               KnownZero2.countLeadingOnes(),
1428                               BitWidth) - BitWidth;
1429
1430    TrailZ = std::min(TrailZ, BitWidth);
1431    LeadZ = std::min(LeadZ, BitWidth);
1432    KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1433                APInt::getHighBitsSet(BitWidth, LeadZ);
1434    KnownZero &= Mask;
1435    return;
1436  }
1437  case ISD::UDIV: {
1438    // For the purposes of computing leading zeros we can conservatively
1439    // treat a udiv as a logical right shift by the power of 2 known to
1440    // be less than the denominator.
1441    APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1442    ComputeMaskedBits(Op.getOperand(0),
1443                      AllOnes, KnownZero2, KnownOne2, Depth+1);
1444    unsigned LeadZ = KnownZero2.countLeadingOnes();
1445
1446    KnownOne2.clear();
1447    KnownZero2.clear();
1448    ComputeMaskedBits(Op.getOperand(1),
1449                      AllOnes, KnownZero2, KnownOne2, Depth+1);
1450    unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1451    if (RHSUnknownLeadingOnes != BitWidth)
1452      LeadZ = std::min(BitWidth,
1453                       LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1454
1455    KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1456    return;
1457  }
1458  case ISD::SELECT:
1459    ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1460    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1461    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1462    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1463
1464    // Only known if known in both the LHS and RHS.
1465    KnownOne &= KnownOne2;
1466    KnownZero &= KnownZero2;
1467    return;
1468  case ISD::SELECT_CC:
1469    ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1470    ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1471    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1472    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1473
1474    // Only known if known in both the LHS and RHS.
1475    KnownOne &= KnownOne2;
1476    KnownZero &= KnownZero2;
1477    return;
1478  case ISD::SETCC:
1479    // If we know the result of a setcc has the top bits zero, use this info.
1480    if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1481        BitWidth > 1)
1482      KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1483    return;
1484  case ISD::SHL:
1485    // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1486    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1487      unsigned ShAmt = SA->getZExtValue();
1488
1489      // If the shift count is an invalid immediate, don't do anything.
1490      if (ShAmt >= BitWidth)
1491        return;
1492
1493      ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1494                        KnownZero, KnownOne, Depth+1);
1495      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1496      KnownZero <<= ShAmt;
1497      KnownOne  <<= ShAmt;
1498      // low bits known zero.
1499      KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1500    }
1501    return;
1502  case ISD::SRL:
1503    // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1504    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1505      unsigned ShAmt = SA->getZExtValue();
1506
1507      // If the shift count is an invalid immediate, don't do anything.
1508      if (ShAmt >= BitWidth)
1509        return;
1510
1511      ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1512                        KnownZero, KnownOne, Depth+1);
1513      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1514      KnownZero = KnownZero.lshr(ShAmt);
1515      KnownOne  = KnownOne.lshr(ShAmt);
1516
1517      APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1518      KnownZero |= HighBits;  // High bits known zero.
1519    }
1520    return;
1521  case ISD::SRA:
1522    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1523      unsigned ShAmt = SA->getZExtValue();
1524
1525      // If the shift count is an invalid immediate, don't do anything.
1526      if (ShAmt >= BitWidth)
1527        return;
1528
1529      APInt InDemandedMask = (Mask << ShAmt);
1530      // If any of the demanded bits are produced by the sign extension, we also
1531      // demand the input sign bit.
1532      APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1533      if (HighBits.getBoolValue())
1534        InDemandedMask |= APInt::getSignBit(BitWidth);
1535
1536      ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1537                        Depth+1);
1538      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1539      KnownZero = KnownZero.lshr(ShAmt);
1540      KnownOne  = KnownOne.lshr(ShAmt);
1541
1542      // Handle the sign bits.
1543      APInt SignBit = APInt::getSignBit(BitWidth);
1544      SignBit = SignBit.lshr(ShAmt);  // Adjust to where it is now in the mask.
1545
1546      if (KnownZero.intersects(SignBit)) {
1547        KnownZero |= HighBits;  // New bits are known zero.
1548      } else if (KnownOne.intersects(SignBit)) {
1549        KnownOne  |= HighBits;  // New bits are known one.
1550      }
1551    }
1552    return;
1553  case ISD::SIGN_EXTEND_INREG: {
1554    MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1555    unsigned EBits = EVT.getSizeInBits();
1556
1557    // Sign extension.  Compute the demanded bits in the result that are not
1558    // present in the input.
1559    APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1560
1561    APInt InSignBit = APInt::getSignBit(EBits);
1562    APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1563
1564    // If the sign extended bits are demanded, we know that the sign
1565    // bit is demanded.
1566    InSignBit.zext(BitWidth);
1567    if (NewBits.getBoolValue())
1568      InputDemandedBits |= InSignBit;
1569
1570    ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1571                      KnownZero, KnownOne, Depth+1);
1572    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1573
1574    // If the sign bit of the input is known set or clear, then we know the
1575    // top bits of the result.
1576    if (KnownZero.intersects(InSignBit)) {         // Input sign bit known clear
1577      KnownZero |= NewBits;
1578      KnownOne  &= ~NewBits;
1579    } else if (KnownOne.intersects(InSignBit)) {   // Input sign bit known set
1580      KnownOne  |= NewBits;
1581      KnownZero &= ~NewBits;
1582    } else {                              // Input sign bit unknown
1583      KnownZero &= ~NewBits;
1584      KnownOne  &= ~NewBits;
1585    }
1586    return;
1587  }
1588  case ISD::CTTZ:
1589  case ISD::CTLZ:
1590  case ISD::CTPOP: {
1591    unsigned LowBits = Log2_32(BitWidth)+1;
1592    KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1593    KnownOne.clear();
1594    return;
1595  }
1596  case ISD::LOAD: {
1597    if (ISD::isZEXTLoad(Op.getNode())) {
1598      LoadSDNode *LD = cast<LoadSDNode>(Op);
1599      MVT VT = LD->getMemoryVT();
1600      unsigned MemBits = VT.getSizeInBits();
1601      KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1602    }
1603    return;
1604  }
1605  case ISD::ZERO_EXTEND: {
1606    MVT InVT = Op.getOperand(0).getValueType();
1607    unsigned InBits = InVT.getSizeInBits();
1608    APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1609    APInt InMask    = Mask;
1610    InMask.trunc(InBits);
1611    KnownZero.trunc(InBits);
1612    KnownOne.trunc(InBits);
1613    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1614    KnownZero.zext(BitWidth);
1615    KnownOne.zext(BitWidth);
1616    KnownZero |= NewBits;
1617    return;
1618  }
1619  case ISD::SIGN_EXTEND: {
1620    MVT InVT = Op.getOperand(0).getValueType();
1621    unsigned InBits = InVT.getSizeInBits();
1622    APInt InSignBit = APInt::getSignBit(InBits);
1623    APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1624    APInt InMask = Mask;
1625    InMask.trunc(InBits);
1626
1627    // If any of the sign extended bits are demanded, we know that the sign
1628    // bit is demanded. Temporarily set this bit in the mask for our callee.
1629    if (NewBits.getBoolValue())
1630      InMask |= InSignBit;
1631
1632    KnownZero.trunc(InBits);
1633    KnownOne.trunc(InBits);
1634    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1635
1636    // Note if the sign bit is known to be zero or one.
1637    bool SignBitKnownZero = KnownZero.isNegative();
1638    bool SignBitKnownOne  = KnownOne.isNegative();
1639    assert(!(SignBitKnownZero && SignBitKnownOne) &&
1640           "Sign bit can't be known to be both zero and one!");
1641
1642    // If the sign bit wasn't actually demanded by our caller, we don't
1643    // want it set in the KnownZero and KnownOne result values. Reset the
1644    // mask and reapply it to the result values.
1645    InMask = Mask;
1646    InMask.trunc(InBits);
1647    KnownZero &= InMask;
1648    KnownOne  &= InMask;
1649
1650    KnownZero.zext(BitWidth);
1651    KnownOne.zext(BitWidth);
1652
1653    // If the sign bit is known zero or one, the top bits match.
1654    if (SignBitKnownZero)
1655      KnownZero |= NewBits;
1656    else if (SignBitKnownOne)
1657      KnownOne  |= NewBits;
1658    return;
1659  }
1660  case ISD::ANY_EXTEND: {
1661    MVT InVT = Op.getOperand(0).getValueType();
1662    unsigned InBits = InVT.getSizeInBits();
1663    APInt InMask = Mask;
1664    InMask.trunc(InBits);
1665    KnownZero.trunc(InBits);
1666    KnownOne.trunc(InBits);
1667    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1668    KnownZero.zext(BitWidth);
1669    KnownOne.zext(BitWidth);
1670    return;
1671  }
1672  case ISD::TRUNCATE: {
1673    MVT InVT = Op.getOperand(0).getValueType();
1674    unsigned InBits = InVT.getSizeInBits();
1675    APInt InMask = Mask;
1676    InMask.zext(InBits);
1677    KnownZero.zext(InBits);
1678    KnownOne.zext(InBits);
1679    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1680    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1681    KnownZero.trunc(BitWidth);
1682    KnownOne.trunc(BitWidth);
1683    break;
1684  }
1685  case ISD::AssertZext: {
1686    MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1687    APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1688    ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1689                      KnownOne, Depth+1);
1690    KnownZero |= (~InMask) & Mask;
1691    return;
1692  }
1693  case ISD::FGETSIGN:
1694    // All bits are zero except the low bit.
1695    KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1696    return;
1697
1698  case ISD::SUB: {
1699    if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1700      // We know that the top bits of C-X are clear if X contains less bits
1701      // than C (i.e. no wrap-around can happen).  For example, 20-X is
1702      // positive if we can prove that X is >= 0 and < 16.
1703      if (CLHS->getAPIntValue().isNonNegative()) {
1704        unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1705        // NLZ can't be BitWidth with no sign bit
1706        APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1707        ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1708                          Depth+1);
1709
1710        // If all of the MaskV bits are known to be zero, then we know the
1711        // output top bits are zero, because we now know that the output is
1712        // from [0-C].
1713        if ((KnownZero2 & MaskV) == MaskV) {
1714          unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1715          // Top bits known zero.
1716          KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1717        }
1718      }
1719    }
1720  }
1721  // fall through
1722  case ISD::ADD: {
1723    // Output known-0 bits are known if clear or set in both the low clear bits
1724    // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
1725    // low 3 bits clear.
1726    APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1727    ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1728    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1729    unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1730
1731    ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1732    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1733    KnownZeroOut = std::min(KnownZeroOut,
1734                            KnownZero2.countTrailingOnes());
1735
1736    KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1737    return;
1738  }
1739  case ISD::SREM:
1740    if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1741      const APInt &RA = Rem->getAPIntValue();
1742      if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1743        APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1744        APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1745        ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1746
1747        // If the sign bit of the first operand is zero, the sign bit of
1748        // the result is zero. If the first operand has no one bits below
1749        // the second operand's single 1 bit, its sign will be zero.
1750        if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1751          KnownZero2 |= ~LowBits;
1752
1753        KnownZero |= KnownZero2 & Mask;
1754
1755        assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1756      }
1757    }
1758    return;
1759  case ISD::UREM: {
1760    if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1761      const APInt &RA = Rem->getAPIntValue();
1762      if (RA.isPowerOf2()) {
1763        APInt LowBits = (RA - 1);
1764        APInt Mask2 = LowBits & Mask;
1765        KnownZero |= ~LowBits & Mask;
1766        ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1767        assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1768        break;
1769      }
1770    }
1771
1772    // Since the result is less than or equal to either operand, any leading
1773    // zero bits in either operand must also exist in the result.
1774    APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1775    ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1776                      Depth+1);
1777    ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1778                      Depth+1);
1779
1780    uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1781                                KnownZero2.countLeadingOnes());
1782    KnownOne.clear();
1783    KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1784    return;
1785  }
1786  default:
1787    // Allow the target to implement this method for its nodes.
1788    if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1789  case ISD::INTRINSIC_WO_CHAIN:
1790  case ISD::INTRINSIC_W_CHAIN:
1791  case ISD::INTRINSIC_VOID:
1792      TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1793    }
1794    return;
1795  }
1796}
1797
1798/// ComputeNumSignBits - Return the number of times the sign bit of the
1799/// register is replicated into the other bits.  We know that at least 1 bit
1800/// is always equal to the sign bit (itself), but other cases can give us
1801/// information.  For example, immediately after an "SRA X, 2", we know that
1802/// the top 3 bits are all equal to each other, so we return 3.
1803unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1804  MVT VT = Op.getValueType();
1805  assert(VT.isInteger() && "Invalid VT!");
1806  unsigned VTBits = VT.getSizeInBits();
1807  unsigned Tmp, Tmp2;
1808  unsigned FirstAnswer = 1;
1809
1810  if (Depth == 6)
1811    return 1;  // Limit search depth.
1812
1813  switch (Op.getOpcode()) {
1814  default: break;
1815  case ISD::AssertSext:
1816    Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1817    return VTBits-Tmp+1;
1818  case ISD::AssertZext:
1819    Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1820    return VTBits-Tmp;
1821
1822  case ISD::Constant: {
1823    const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1824    // If negative, return # leading ones.
1825    if (Val.isNegative())
1826      return Val.countLeadingOnes();
1827
1828    // Return # leading zeros.
1829    return Val.countLeadingZeros();
1830  }
1831
1832  case ISD::SIGN_EXTEND:
1833    Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1834    return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1835
1836  case ISD::SIGN_EXTEND_INREG:
1837    // Max of the input and what this extends.
1838    Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1839    Tmp = VTBits-Tmp+1;
1840
1841    Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1842    return std::max(Tmp, Tmp2);
1843
1844  case ISD::SRA:
1845    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1846    // SRA X, C   -> adds C sign bits.
1847    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1848      Tmp += C->getZExtValue();
1849      if (Tmp > VTBits) Tmp = VTBits;
1850    }
1851    return Tmp;
1852  case ISD::SHL:
1853    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1854      // shl destroys sign bits.
1855      Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1856      if (C->getZExtValue() >= VTBits ||      // Bad shift.
1857          C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
1858      return Tmp - C->getZExtValue();
1859    }
1860    break;
1861  case ISD::AND:
1862  case ISD::OR:
1863  case ISD::XOR:    // NOT is handled here.
1864    // Logical binary ops preserve the number of sign bits at the worst.
1865    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1866    if (Tmp != 1) {
1867      Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1868      FirstAnswer = std::min(Tmp, Tmp2);
1869      // We computed what we know about the sign bits as our first
1870      // answer. Now proceed to the generic code that uses
1871      // ComputeMaskedBits, and pick whichever answer is better.
1872    }
1873    break;
1874
1875  case ISD::SELECT:
1876    Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1877    if (Tmp == 1) return 1;  // Early out.
1878    Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1879    return std::min(Tmp, Tmp2);
1880
1881  case ISD::SETCC:
1882    // If setcc returns 0/-1, all bits are sign bits.
1883    if (TLI.getSetCCResultContents() ==
1884        TargetLowering::ZeroOrNegativeOneSetCCResult)
1885      return VTBits;
1886    break;
1887  case ISD::ROTL:
1888  case ISD::ROTR:
1889    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1890      unsigned RotAmt = C->getZExtValue() & (VTBits-1);
1891
1892      // Handle rotate right by N like a rotate left by 32-N.
1893      if (Op.getOpcode() == ISD::ROTR)
1894        RotAmt = (VTBits-RotAmt) & (VTBits-1);
1895
1896      // If we aren't rotating out all of the known-in sign bits, return the
1897      // number that are left.  This handles rotl(sext(x), 1) for example.
1898      Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1899      if (Tmp > RotAmt+1) return Tmp-RotAmt;
1900    }
1901    break;
1902  case ISD::ADD:
1903    // Add can have at most one carry bit.  Thus we know that the output
1904    // is, at worst, one more bit than the inputs.
1905    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1906    if (Tmp == 1) return 1;  // Early out.
1907
1908    // Special case decrementing a value (ADD X, -1):
1909    if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1910      if (CRHS->isAllOnesValue()) {
1911        APInt KnownZero, KnownOne;
1912        APInt Mask = APInt::getAllOnesValue(VTBits);
1913        ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1914
1915        // If the input is known to be 0 or 1, the output is 0/-1, which is all
1916        // sign bits set.
1917        if ((KnownZero | APInt(VTBits, 1)) == Mask)
1918          return VTBits;
1919
1920        // If we are subtracting one from a positive number, there is no carry
1921        // out of the result.
1922        if (KnownZero.isNegative())
1923          return Tmp;
1924      }
1925
1926    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1927    if (Tmp2 == 1) return 1;
1928      return std::min(Tmp, Tmp2)-1;
1929    break;
1930
1931  case ISD::SUB:
1932    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1933    if (Tmp2 == 1) return 1;
1934
1935    // Handle NEG.
1936    if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1937      if (CLHS->isNullValue()) {
1938        APInt KnownZero, KnownOne;
1939        APInt Mask = APInt::getAllOnesValue(VTBits);
1940        ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1941        // If the input is known to be 0 or 1, the output is 0/-1, which is all
1942        // sign bits set.
1943        if ((KnownZero | APInt(VTBits, 1)) == Mask)
1944          return VTBits;
1945
1946        // If the input is known to be positive (the sign bit is known clear),
1947        // the output of the NEG has the same number of sign bits as the input.
1948        if (KnownZero.isNegative())
1949          return Tmp2;
1950
1951        // Otherwise, we treat this like a SUB.
1952      }
1953
1954    // Sub can have at most one carry bit.  Thus we know that the output
1955    // is, at worst, one more bit than the inputs.
1956    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1957    if (Tmp == 1) return 1;  // Early out.
1958      return std::min(Tmp, Tmp2)-1;
1959    break;
1960  case ISD::TRUNCATE:
1961    // FIXME: it's tricky to do anything useful for this, but it is an important
1962    // case for targets like X86.
1963    break;
1964  }
1965
1966  // Handle LOADX separately here. EXTLOAD case will fallthrough.
1967  if (Op.getOpcode() == ISD::LOAD) {
1968    LoadSDNode *LD = cast<LoadSDNode>(Op);
1969    unsigned ExtType = LD->getExtensionType();
1970    switch (ExtType) {
1971    default: break;
1972    case ISD::SEXTLOAD:    // '17' bits known
1973      Tmp = LD->getMemoryVT().getSizeInBits();
1974      return VTBits-Tmp+1;
1975    case ISD::ZEXTLOAD:    // '16' bits known
1976      Tmp = LD->getMemoryVT().getSizeInBits();
1977      return VTBits-Tmp;
1978    }
1979  }
1980
1981  // Allow the target to implement this method for its nodes.
1982  if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1983      Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1984      Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1985      Op.getOpcode() == ISD::INTRINSIC_VOID) {
1986    unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1987    if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1988  }
1989
1990  // Finally, if we can prove that the top bits of the result are 0's or 1's,
1991  // use this information.
1992  APInt KnownZero, KnownOne;
1993  APInt Mask = APInt::getAllOnesValue(VTBits);
1994  ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1995
1996  if (KnownZero.isNegative()) {        // sign bit is 0
1997    Mask = KnownZero;
1998  } else if (KnownOne.isNegative()) {  // sign bit is 1;
1999    Mask = KnownOne;
2000  } else {
2001    // Nothing known.
2002    return FirstAnswer;
2003  }
2004
2005  // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
2006  // the number of identical bits in the top of the input value.
2007  Mask = ~Mask;
2008  Mask <<= Mask.getBitWidth()-VTBits;
2009  // Return # leading zeros.  We use 'min' here in case Val was zero before
2010  // shifting.  We don't want to return '64' as for an i32 "0".
2011  return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2012}
2013
2014
2015bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2016  GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2017  if (!GA) return false;
2018  GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2019  if (!GV) return false;
2020  MachineModuleInfo *MMI = getMachineModuleInfo();
2021  return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
2022}
2023
2024
2025/// getShuffleScalarElt - Returns the scalar element that will make up the ith
2026/// element of the result of the vector shuffle.
2027SDValue SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
2028  MVT VT = N->getValueType(0);
2029  SDValue PermMask = N->getOperand(2);
2030  SDValue Idx = PermMask.getOperand(i);
2031  if (Idx.getOpcode() == ISD::UNDEF)
2032    return getNode(ISD::UNDEF, VT.getVectorElementType());
2033  unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
2034  unsigned NumElems = PermMask.getNumOperands();
2035  SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2036  Index %= NumElems;
2037
2038  if (V.getOpcode() == ISD::BIT_CONVERT) {
2039    V = V.getOperand(0);
2040    if (V.getValueType().getVectorNumElements() != NumElems)
2041      return SDValue();
2042  }
2043  if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2044    return (Index == 0) ? V.getOperand(0)
2045                      : getNode(ISD::UNDEF, VT.getVectorElementType());
2046  if (V.getOpcode() == ISD::BUILD_VECTOR)
2047    return V.getOperand(Index);
2048  if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
2049    return getShuffleScalarElt(V.getNode(), Index);
2050  return SDValue();
2051}
2052
2053
2054/// getNode - Gets or creates the specified node.
2055///
2056SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT) {
2057  FoldingSetNodeID ID;
2058  AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2059  void *IP = 0;
2060  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2061    return SDValue(E, 0);
2062  SDNode *N = NodeAllocator.Allocate<SDNode>();
2063  new (N) SDNode(Opcode, SDNode::getSDVTList(VT));
2064  CSEMap.InsertNode(N, IP);
2065
2066  AllNodes.push_back(N);
2067#ifndef NDEBUG
2068  VerifyNode(N);
2069#endif
2070  return SDValue(N, 0);
2071}
2072
2073SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT, SDValue Operand) {
2074  // Constant fold unary operations with an integer constant operand.
2075  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2076    const APInt &Val = C->getAPIntValue();
2077    unsigned BitWidth = VT.getSizeInBits();
2078    switch (Opcode) {
2079    default: break;
2080    case ISD::SIGN_EXTEND:
2081      return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2082    case ISD::ANY_EXTEND:
2083    case ISD::ZERO_EXTEND:
2084    case ISD::TRUNCATE:
2085      return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2086    case ISD::UINT_TO_FP:
2087    case ISD::SINT_TO_FP: {
2088      const uint64_t zero[] = {0, 0};
2089      // No compile time operations on this type.
2090      if (VT==MVT::ppcf128)
2091        break;
2092      APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2093      (void)apf.convertFromAPInt(Val,
2094                                 Opcode==ISD::SINT_TO_FP,
2095                                 APFloat::rmNearestTiesToEven);
2096      return getConstantFP(apf, VT);
2097    }
2098    case ISD::BIT_CONVERT:
2099      if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2100        return getConstantFP(Val.bitsToFloat(), VT);
2101      else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2102        return getConstantFP(Val.bitsToDouble(), VT);
2103      break;
2104    case ISD::BSWAP:
2105      return getConstant(Val.byteSwap(), VT);
2106    case ISD::CTPOP:
2107      return getConstant(Val.countPopulation(), VT);
2108    case ISD::CTLZ:
2109      return getConstant(Val.countLeadingZeros(), VT);
2110    case ISD::CTTZ:
2111      return getConstant(Val.countTrailingZeros(), VT);
2112    }
2113  }
2114
2115  // Constant fold unary operations with a floating point constant operand.
2116  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2117    APFloat V = C->getValueAPF();    // make copy
2118    if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2119      switch (Opcode) {
2120      case ISD::FNEG:
2121        V.changeSign();
2122        return getConstantFP(V, VT);
2123      case ISD::FABS:
2124        V.clearSign();
2125        return getConstantFP(V, VT);
2126      case ISD::FP_ROUND:
2127      case ISD::FP_EXTEND:
2128        // This can return overflow, underflow, or inexact; we don't care.
2129        // FIXME need to be more flexible about rounding mode.
2130        (void)V.convert(*MVTToAPFloatSemantics(VT),
2131                        APFloat::rmNearestTiesToEven);
2132        return getConstantFP(V, VT);
2133      case ISD::FP_TO_SINT:
2134      case ISD::FP_TO_UINT: {
2135        integerPart x;
2136        assert(integerPartWidth >= 64);
2137        // FIXME need to be more flexible about rounding mode.
2138        APFloat::opStatus s = V.convertToInteger(&x, 64U,
2139                              Opcode==ISD::FP_TO_SINT,
2140                              APFloat::rmTowardZero);
2141        if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
2142          break;
2143        return getConstant(x, VT);
2144      }
2145      case ISD::BIT_CONVERT:
2146        if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2147          return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2148        else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2149          return getConstant(V.convertToAPInt().getZExtValue(), VT);
2150        break;
2151      }
2152    }
2153  }
2154
2155  unsigned OpOpcode = Operand.getNode()->getOpcode();
2156  switch (Opcode) {
2157  case ISD::TokenFactor:
2158  case ISD::CONCAT_VECTORS:
2159    return Operand;         // Factor or concat of one node?  No need.
2160  case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2161  case ISD::FP_EXTEND:
2162    assert(VT.isFloatingPoint() &&
2163           Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2164    if (Operand.getValueType() == VT) return Operand;  // noop conversion.
2165    if (Operand.getOpcode() == ISD::UNDEF)
2166      return getNode(ISD::UNDEF, VT);
2167    break;
2168  case ISD::SIGN_EXTEND:
2169    assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2170           "Invalid SIGN_EXTEND!");
2171    if (Operand.getValueType() == VT) return Operand;   // noop extension
2172    assert(Operand.getValueType().bitsLT(VT)
2173           && "Invalid sext node, dst < src!");
2174    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2175      return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
2176    break;
2177  case ISD::ZERO_EXTEND:
2178    assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2179           "Invalid ZERO_EXTEND!");
2180    if (Operand.getValueType() == VT) return Operand;   // noop extension
2181    assert(Operand.getValueType().bitsLT(VT)
2182           && "Invalid zext node, dst < src!");
2183    if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
2184      return getNode(ISD::ZERO_EXTEND, VT, Operand.getNode()->getOperand(0));
2185    break;
2186  case ISD::ANY_EXTEND:
2187    assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2188           "Invalid ANY_EXTEND!");
2189    if (Operand.getValueType() == VT) return Operand;   // noop extension
2190    assert(Operand.getValueType().bitsLT(VT)
2191           && "Invalid anyext node, dst < src!");
2192    if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2193      // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
2194      return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
2195    break;
2196  case ISD::TRUNCATE:
2197    assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2198           "Invalid TRUNCATE!");
2199    if (Operand.getValueType() == VT) return Operand;   // noop truncate
2200    assert(Operand.getValueType().bitsGT(VT)
2201           && "Invalid truncate node, src < dst!");
2202    if (OpOpcode == ISD::TRUNCATE)
2203      return getNode(ISD::TRUNCATE, VT, Operand.getNode()->getOperand(0));
2204    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2205             OpOpcode == ISD::ANY_EXTEND) {
2206      // If the source is smaller than the dest, we still need an extend.
2207      if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
2208        return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
2209      else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2210        return getNode(ISD::TRUNCATE, VT, Operand.getNode()->getOperand(0));
2211      else
2212        return Operand.getNode()->getOperand(0);
2213    }
2214    break;
2215  case ISD::BIT_CONVERT:
2216    // Basic sanity checking.
2217    assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2218           && "Cannot BIT_CONVERT between types of different sizes!");
2219    if (VT == Operand.getValueType()) return Operand;  // noop conversion.
2220    if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
2221      return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2222    if (OpOpcode == ISD::UNDEF)
2223      return getNode(ISD::UNDEF, VT);
2224    break;
2225  case ISD::SCALAR_TO_VECTOR:
2226    assert(VT.isVector() && !Operand.getValueType().isVector() &&
2227           VT.getVectorElementType() == Operand.getValueType() &&
2228           "Illegal SCALAR_TO_VECTOR node!");
2229    if (OpOpcode == ISD::UNDEF)
2230      return getNode(ISD::UNDEF, VT);
2231    // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2232    if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2233        isa<ConstantSDNode>(Operand.getOperand(1)) &&
2234        Operand.getConstantOperandVal(1) == 0 &&
2235        Operand.getOperand(0).getValueType() == VT)
2236      return Operand.getOperand(0);
2237    break;
2238  case ISD::FNEG:
2239    if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
2240      return getNode(ISD::FSUB, VT, Operand.getNode()->getOperand(1),
2241                     Operand.getNode()->getOperand(0));
2242    if (OpOpcode == ISD::FNEG)  // --X -> X
2243      return Operand.getNode()->getOperand(0);
2244    break;
2245  case ISD::FABS:
2246    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
2247      return getNode(ISD::FABS, VT, Operand.getNode()->getOperand(0));
2248    break;
2249  }
2250
2251  SDNode *N;
2252  SDVTList VTs = getVTList(VT);
2253  if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2254    FoldingSetNodeID ID;
2255    SDValue Ops[1] = { Operand };
2256    AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2257    void *IP = 0;
2258    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2259      return SDValue(E, 0);
2260    N = NodeAllocator.Allocate<UnarySDNode>();
2261    new (N) UnarySDNode(Opcode, VTs, Operand);
2262    CSEMap.InsertNode(N, IP);
2263  } else {
2264    N = NodeAllocator.Allocate<UnarySDNode>();
2265    new (N) UnarySDNode(Opcode, VTs, Operand);
2266  }
2267
2268  AllNodes.push_back(N);
2269#ifndef NDEBUG
2270  VerifyNode(N);
2271#endif
2272  return SDValue(N, 0);
2273}
2274
2275SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2276                                             MVT VT,
2277                                             ConstantSDNode *Cst1,
2278                                             ConstantSDNode *Cst2) {
2279  const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2280
2281  switch (Opcode) {
2282  case ISD::ADD:  return getConstant(C1 + C2, VT);
2283  case ISD::SUB:  return getConstant(C1 - C2, VT);
2284  case ISD::MUL:  return getConstant(C1 * C2, VT);
2285  case ISD::UDIV:
2286    if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2287    break;
2288  case ISD::UREM:
2289    if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2290    break;
2291  case ISD::SDIV:
2292    if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2293    break;
2294  case ISD::SREM:
2295    if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2296    break;
2297  case ISD::AND:  return getConstant(C1 & C2, VT);
2298  case ISD::OR:   return getConstant(C1 | C2, VT);
2299  case ISD::XOR:  return getConstant(C1 ^ C2, VT);
2300  case ISD::SHL:  return getConstant(C1 << C2, VT);
2301  case ISD::SRL:  return getConstant(C1.lshr(C2), VT);
2302  case ISD::SRA:  return getConstant(C1.ashr(C2), VT);
2303  case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2304  case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2305  default: break;
2306  }
2307
2308  return SDValue();
2309}
2310
2311SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2312                              SDValue N1, SDValue N2) {
2313  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2314  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2315  switch (Opcode) {
2316  default: break;
2317  case ISD::TokenFactor:
2318    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2319           N2.getValueType() == MVT::Other && "Invalid token factor!");
2320    // Fold trivial token factors.
2321    if (N1.getOpcode() == ISD::EntryToken) return N2;
2322    if (N2.getOpcode() == ISD::EntryToken) return N1;
2323    if (N1 == N2) return N1;
2324    break;
2325  case ISD::CONCAT_VECTORS:
2326    // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2327    // one big BUILD_VECTOR.
2328    if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2329        N2.getOpcode() == ISD::BUILD_VECTOR) {
2330      SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2331      Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2332      return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
2333    }
2334    break;
2335  case ISD::AND:
2336    assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2337           N1.getValueType() == VT && "Binary operator types must match!");
2338    // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
2339    // worth handling here.
2340    if (N2C && N2C->isNullValue())
2341      return N2;
2342    if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
2343      return N1;
2344    break;
2345  case ISD::OR:
2346  case ISD::XOR:
2347  case ISD::ADD:
2348  case ISD::SUB:
2349    assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2350           N1.getValueType() == VT && "Binary operator types must match!");
2351    // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
2352    // it's worth handling here.
2353    if (N2C && N2C->isNullValue())
2354      return N1;
2355    break;
2356  case ISD::UDIV:
2357  case ISD::UREM:
2358  case ISD::MULHU:
2359  case ISD::MULHS:
2360    assert(VT.isInteger() && "This operator does not apply to FP types!");
2361    // fall through
2362  case ISD::MUL:
2363  case ISD::SDIV:
2364  case ISD::SREM:
2365  case ISD::FADD:
2366  case ISD::FSUB:
2367  case ISD::FMUL:
2368  case ISD::FDIV:
2369  case ISD::FREM:
2370    assert(N1.getValueType() == N2.getValueType() &&
2371           N1.getValueType() == VT && "Binary operator types must match!");
2372    break;
2373  case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
2374    assert(N1.getValueType() == VT &&
2375           N1.getValueType().isFloatingPoint() &&
2376           N2.getValueType().isFloatingPoint() &&
2377           "Invalid FCOPYSIGN!");
2378    break;
2379  case ISD::SHL:
2380  case ISD::SRA:
2381  case ISD::SRL:
2382  case ISD::ROTL:
2383  case ISD::ROTR:
2384    assert(VT == N1.getValueType() &&
2385           "Shift operators return type must be the same as their first arg");
2386    assert(VT.isInteger() && N2.getValueType().isInteger() &&
2387           "Shifts only work on integers");
2388
2389    // Always fold shifts of i1 values so the code generator doesn't need to
2390    // handle them.  Since we know the size of the shift has to be less than the
2391    // size of the value, the shift/rotate count is guaranteed to be zero.
2392    if (VT == MVT::i1)
2393      return N1;
2394    break;
2395  case ISD::FP_ROUND_INREG: {
2396    MVT EVT = cast<VTSDNode>(N2)->getVT();
2397    assert(VT == N1.getValueType() && "Not an inreg round!");
2398    assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2399           "Cannot FP_ROUND_INREG integer types");
2400    assert(EVT.bitsLE(VT) && "Not rounding down!");
2401    if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
2402    break;
2403  }
2404  case ISD::FP_ROUND:
2405    assert(VT.isFloatingPoint() &&
2406           N1.getValueType().isFloatingPoint() &&
2407           VT.bitsLE(N1.getValueType()) &&
2408           isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2409    if (N1.getValueType() == VT) return N1;  // noop conversion.
2410    break;
2411  case ISD::AssertSext:
2412  case ISD::AssertZext: {
2413    MVT EVT = cast<VTSDNode>(N2)->getVT();
2414    assert(VT == N1.getValueType() && "Not an inreg extend!");
2415    assert(VT.isInteger() && EVT.isInteger() &&
2416           "Cannot *_EXTEND_INREG FP types");
2417    assert(EVT.bitsLE(VT) && "Not extending!");
2418    if (VT == EVT) return N1; // noop assertion.
2419    break;
2420  }
2421  case ISD::SIGN_EXTEND_INREG: {
2422    MVT EVT = cast<VTSDNode>(N2)->getVT();
2423    assert(VT == N1.getValueType() && "Not an inreg extend!");
2424    assert(VT.isInteger() && EVT.isInteger() &&
2425           "Cannot *_EXTEND_INREG FP types");
2426    assert(EVT.bitsLE(VT) && "Not extending!");
2427    if (EVT == VT) return N1;  // Not actually extending
2428
2429    if (N1C) {
2430      APInt Val = N1C->getAPIntValue();
2431      unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2432      Val <<= Val.getBitWidth()-FromBits;
2433      Val = Val.ashr(Val.getBitWidth()-FromBits);
2434      return getConstant(Val, VT);
2435    }
2436    break;
2437  }
2438  case ISD::EXTRACT_VECTOR_ELT:
2439    // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2440    if (N1.getOpcode() == ISD::UNDEF)
2441      return getNode(ISD::UNDEF, VT);
2442
2443    // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2444    // expanding copies of large vectors from registers.
2445    if (N2C &&
2446        N1.getOpcode() == ISD::CONCAT_VECTORS &&
2447        N1.getNumOperands() > 0) {
2448      unsigned Factor =
2449        N1.getOperand(0).getValueType().getVectorNumElements();
2450      return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2451                     N1.getOperand(N2C->getZExtValue() / Factor),
2452                     getConstant(N2C->getZExtValue() % Factor,
2453                                 N2.getValueType()));
2454    }
2455
2456    // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2457    // expanding large vector constants.
2458    if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR)
2459      return N1.getOperand(N2C->getZExtValue());
2460
2461    // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2462    // operations are lowered to scalars.
2463    if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2464      if (N1.getOperand(2) == N2)
2465        return N1.getOperand(1);
2466      else
2467        return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2468    }
2469    break;
2470  case ISD::EXTRACT_ELEMENT:
2471    assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2472    assert(!N1.getValueType().isVector() && !VT.isVector() &&
2473           (N1.getValueType().isInteger() == VT.isInteger()) &&
2474           "Wrong types for EXTRACT_ELEMENT!");
2475
2476    // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2477    // 64-bit integers into 32-bit parts.  Instead of building the extract of
2478    // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2479    if (N1.getOpcode() == ISD::BUILD_PAIR)
2480      return N1.getOperand(N2C->getZExtValue());
2481
2482    // EXTRACT_ELEMENT of a constant int is also very common.
2483    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2484      unsigned ElementSize = VT.getSizeInBits();
2485      unsigned Shift = ElementSize * N2C->getZExtValue();
2486      APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2487      return getConstant(ShiftedVal.trunc(ElementSize), VT);
2488    }
2489    break;
2490  case ISD::EXTRACT_SUBVECTOR:
2491    if (N1.getValueType() == VT) // Trivial extraction.
2492      return N1;
2493    break;
2494  }
2495
2496  if (N1C) {
2497    if (N2C) {
2498      SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2499      if (SV.getNode()) return SV;
2500    } else {      // Cannonicalize constant to RHS if commutative
2501      if (isCommutativeBinOp(Opcode)) {
2502        std::swap(N1C, N2C);
2503        std::swap(N1, N2);
2504      }
2505    }
2506  }
2507
2508  // Constant fold FP operations.
2509  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2510  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2511  if (N1CFP) {
2512    if (!N2CFP && isCommutativeBinOp(Opcode)) {
2513      // Cannonicalize constant to RHS if commutative
2514      std::swap(N1CFP, N2CFP);
2515      std::swap(N1, N2);
2516    } else if (N2CFP && VT != MVT::ppcf128) {
2517      APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2518      APFloat::opStatus s;
2519      switch (Opcode) {
2520      case ISD::FADD:
2521        s = V1.add(V2, APFloat::rmNearestTiesToEven);
2522        if (s != APFloat::opInvalidOp)
2523          return getConstantFP(V1, VT);
2524        break;
2525      case ISD::FSUB:
2526        s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2527        if (s!=APFloat::opInvalidOp)
2528          return getConstantFP(V1, VT);
2529        break;
2530      case ISD::FMUL:
2531        s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2532        if (s!=APFloat::opInvalidOp)
2533          return getConstantFP(V1, VT);
2534        break;
2535      case ISD::FDIV:
2536        s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2537        if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2538          return getConstantFP(V1, VT);
2539        break;
2540      case ISD::FREM :
2541        s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2542        if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2543          return getConstantFP(V1, VT);
2544        break;
2545      case ISD::FCOPYSIGN:
2546        V1.copySign(V2);
2547        return getConstantFP(V1, VT);
2548      default: break;
2549      }
2550    }
2551  }
2552
2553  // Canonicalize an UNDEF to the RHS, even over a constant.
2554  if (N1.getOpcode() == ISD::UNDEF) {
2555    if (isCommutativeBinOp(Opcode)) {
2556      std::swap(N1, N2);
2557    } else {
2558      switch (Opcode) {
2559      case ISD::FP_ROUND_INREG:
2560      case ISD::SIGN_EXTEND_INREG:
2561      case ISD::SUB:
2562      case ISD::FSUB:
2563      case ISD::FDIV:
2564      case ISD::FREM:
2565      case ISD::SRA:
2566        return N1;     // fold op(undef, arg2) -> undef
2567      case ISD::UDIV:
2568      case ISD::SDIV:
2569      case ISD::UREM:
2570      case ISD::SREM:
2571      case ISD::SRL:
2572      case ISD::SHL:
2573        if (!VT.isVector())
2574          return getConstant(0, VT);    // fold op(undef, arg2) -> 0
2575        // For vectors, we can't easily build an all zero vector, just return
2576        // the LHS.
2577        return N2;
2578      }
2579    }
2580  }
2581
2582  // Fold a bunch of operators when the RHS is undef.
2583  if (N2.getOpcode() == ISD::UNDEF) {
2584    switch (Opcode) {
2585    case ISD::XOR:
2586      if (N1.getOpcode() == ISD::UNDEF)
2587        // Handle undef ^ undef -> 0 special case. This is a common
2588        // idiom (misuse).
2589        return getConstant(0, VT);
2590      // fallthrough
2591    case ISD::ADD:
2592    case ISD::ADDC:
2593    case ISD::ADDE:
2594    case ISD::SUB:
2595    case ISD::FADD:
2596    case ISD::FSUB:
2597    case ISD::FMUL:
2598    case ISD::FDIV:
2599    case ISD::FREM:
2600    case ISD::UDIV:
2601    case ISD::SDIV:
2602    case ISD::UREM:
2603    case ISD::SREM:
2604      return N2;       // fold op(arg1, undef) -> undef
2605    case ISD::MUL:
2606    case ISD::AND:
2607    case ISD::SRL:
2608    case ISD::SHL:
2609      if (!VT.isVector())
2610        return getConstant(0, VT);  // fold op(arg1, undef) -> 0
2611      // For vectors, we can't easily build an all zero vector, just return
2612      // the LHS.
2613      return N1;
2614    case ISD::OR:
2615      if (!VT.isVector())
2616        return getConstant(VT.getIntegerVTBitMask(), VT);
2617      // For vectors, we can't easily build an all one vector, just return
2618      // the LHS.
2619      return N1;
2620    case ISD::SRA:
2621      return N1;
2622    }
2623  }
2624
2625  // Memoize this node if possible.
2626  SDNode *N;
2627  SDVTList VTs = getVTList(VT);
2628  if (VT != MVT::Flag) {
2629    SDValue Ops[] = { N1, N2 };
2630    FoldingSetNodeID ID;
2631    AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2632    void *IP = 0;
2633    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2634      return SDValue(E, 0);
2635    N = NodeAllocator.Allocate<BinarySDNode>();
2636    new (N) BinarySDNode(Opcode, VTs, N1, N2);
2637    CSEMap.InsertNode(N, IP);
2638  } else {
2639    N = NodeAllocator.Allocate<BinarySDNode>();
2640    new (N) BinarySDNode(Opcode, VTs, N1, N2);
2641  }
2642
2643  AllNodes.push_back(N);
2644#ifndef NDEBUG
2645  VerifyNode(N);
2646#endif
2647  return SDValue(N, 0);
2648}
2649
2650SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2651                              SDValue N1, SDValue N2, SDValue N3) {
2652  // Perform various simplifications.
2653  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2654  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2655  switch (Opcode) {
2656  case ISD::CONCAT_VECTORS:
2657    // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2658    // one big BUILD_VECTOR.
2659    if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2660        N2.getOpcode() == ISD::BUILD_VECTOR &&
2661        N3.getOpcode() == ISD::BUILD_VECTOR) {
2662      SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2663      Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2664      Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
2665      return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
2666    }
2667    break;
2668  case ISD::SETCC: {
2669    // Use FoldSetCC to simplify SETCC's.
2670    SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2671    if (Simp.getNode()) return Simp;
2672    break;
2673  }
2674  case ISD::SELECT:
2675    if (N1C) {
2676     if (N1C->getZExtValue())
2677        return N2;             // select true, X, Y -> X
2678      else
2679        return N3;             // select false, X, Y -> Y
2680    }
2681
2682    if (N2 == N3) return N2;   // select C, X, X -> X
2683    break;
2684  case ISD::BRCOND:
2685    if (N2C) {
2686      if (N2C->getZExtValue()) // Unconditional branch
2687        return getNode(ISD::BR, MVT::Other, N1, N3);
2688      else
2689        return N1;         // Never-taken branch
2690    }
2691    break;
2692  case ISD::VECTOR_SHUFFLE:
2693    assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2694           VT.isVector() && N3.getValueType().isVector() &&
2695           N3.getOpcode() == ISD::BUILD_VECTOR &&
2696           VT.getVectorNumElements() == N3.getNumOperands() &&
2697           "Illegal VECTOR_SHUFFLE node!");
2698    break;
2699  case ISD::BIT_CONVERT:
2700    // Fold bit_convert nodes from a type to themselves.
2701    if (N1.getValueType() == VT)
2702      return N1;
2703    break;
2704  }
2705
2706  // Memoize node if it doesn't produce a flag.
2707  SDNode *N;
2708  SDVTList VTs = getVTList(VT);
2709  if (VT != MVT::Flag) {
2710    SDValue Ops[] = { N1, N2, N3 };
2711    FoldingSetNodeID ID;
2712    AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2713    void *IP = 0;
2714    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2715      return SDValue(E, 0);
2716    N = NodeAllocator.Allocate<TernarySDNode>();
2717    new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2718    CSEMap.InsertNode(N, IP);
2719  } else {
2720    N = NodeAllocator.Allocate<TernarySDNode>();
2721    new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2722  }
2723  AllNodes.push_back(N);
2724#ifndef NDEBUG
2725  VerifyNode(N);
2726#endif
2727  return SDValue(N, 0);
2728}
2729
2730SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2731                              SDValue N1, SDValue N2, SDValue N3,
2732                              SDValue N4) {
2733  SDValue Ops[] = { N1, N2, N3, N4 };
2734  return getNode(Opcode, VT, Ops, 4);
2735}
2736
2737SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2738                              SDValue N1, SDValue N2, SDValue N3,
2739                              SDValue N4, SDValue N5) {
2740  SDValue Ops[] = { N1, N2, N3, N4, N5 };
2741  return getNode(Opcode, VT, Ops, 5);
2742}
2743
2744/// getMemsetValue - Vectorized representation of the memset value
2745/// operand.
2746static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG) {
2747  unsigned NumBits = VT.isVector() ?
2748    VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2749  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2750    APInt Val = APInt(NumBits, C->getZExtValue() & 255);
2751    unsigned Shift = 8;
2752    for (unsigned i = NumBits; i > 8; i >>= 1) {
2753      Val = (Val << Shift) | Val;
2754      Shift <<= 1;
2755    }
2756    if (VT.isInteger())
2757      return DAG.getConstant(Val, VT);
2758    return DAG.getConstantFP(APFloat(Val), VT);
2759  }
2760
2761  Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2762  unsigned Shift = 8;
2763  for (unsigned i = NumBits; i > 8; i >>= 1) {
2764    Value = DAG.getNode(ISD::OR, VT,
2765                        DAG.getNode(ISD::SHL, VT, Value,
2766                                    DAG.getConstant(Shift, MVT::i8)), Value);
2767    Shift <<= 1;
2768  }
2769
2770  return Value;
2771}
2772
2773/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2774/// used when a memcpy is turned into a memset when the source is a constant
2775/// string ptr.
2776static SDValue getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2777                                    const TargetLowering &TLI,
2778                                    std::string &Str, unsigned Offset) {
2779  // Handle vector with all elements zero.
2780  if (Str.empty()) {
2781    if (VT.isInteger())
2782      return DAG.getConstant(0, VT);
2783    unsigned NumElts = VT.getVectorNumElements();
2784    MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2785    return DAG.getNode(ISD::BIT_CONVERT, VT,
2786                       DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2787  }
2788
2789  assert(!VT.isVector() && "Can't handle vector type here!");
2790  unsigned NumBits = VT.getSizeInBits();
2791  unsigned MSB = NumBits / 8;
2792  uint64_t Val = 0;
2793  if (TLI.isLittleEndian())
2794    Offset = Offset + MSB - 1;
2795  for (unsigned i = 0; i != MSB; ++i) {
2796    Val = (Val << 8) | (unsigned char)Str[Offset];
2797    Offset += TLI.isLittleEndian() ? -1 : 1;
2798  }
2799  return DAG.getConstant(Val, VT);
2800}
2801
2802/// getMemBasePlusOffset - Returns base and offset node for the
2803///
2804static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
2805                                      SelectionDAG &DAG) {
2806  MVT VT = Base.getValueType();
2807  return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2808}
2809
2810/// isMemSrcFromString - Returns true if memcpy source is a string constant.
2811///
2812static bool isMemSrcFromString(SDValue Src, std::string &Str) {
2813  unsigned SrcDelta = 0;
2814  GlobalAddressSDNode *G = NULL;
2815  if (Src.getOpcode() == ISD::GlobalAddress)
2816    G = cast<GlobalAddressSDNode>(Src);
2817  else if (Src.getOpcode() == ISD::ADD &&
2818           Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2819           Src.getOperand(1).getOpcode() == ISD::Constant) {
2820    G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2821    SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
2822  }
2823  if (!G)
2824    return false;
2825
2826  GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2827  if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2828    return true;
2829
2830  return false;
2831}
2832
2833/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2834/// to replace the memset / memcpy is below the threshold. It also returns the
2835/// types of the sequence of memory ops to perform memset / memcpy.
2836static
2837bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2838                              SDValue Dst, SDValue Src,
2839                              unsigned Limit, uint64_t Size, unsigned &Align,
2840                              std::string &Str, bool &isSrcStr,
2841                              SelectionDAG &DAG,
2842                              const TargetLowering &TLI) {
2843  isSrcStr = isMemSrcFromString(Src, Str);
2844  bool isSrcConst = isa<ConstantSDNode>(Src);
2845  bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2846  MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2847  if (VT != MVT::iAny) {
2848    unsigned NewAlign = (unsigned)
2849      TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2850    // If source is a string constant, this will require an unaligned load.
2851    if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2852      if (Dst.getOpcode() != ISD::FrameIndex) {
2853        // Can't change destination alignment. It requires a unaligned store.
2854        if (AllowUnalign)
2855          VT = MVT::iAny;
2856      } else {
2857        int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2858        MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2859        if (MFI->isFixedObjectIndex(FI)) {
2860          // Can't change destination alignment. It requires a unaligned store.
2861          if (AllowUnalign)
2862            VT = MVT::iAny;
2863        } else {
2864          // Give the stack frame object a larger alignment if needed.
2865          if (MFI->getObjectAlignment(FI) < NewAlign)
2866            MFI->setObjectAlignment(FI, NewAlign);
2867          Align = NewAlign;
2868        }
2869      }
2870    }
2871  }
2872
2873  if (VT == MVT::iAny) {
2874    if (AllowUnalign) {
2875      VT = MVT::i64;
2876    } else {
2877      switch (Align & 7) {
2878      case 0:  VT = MVT::i64; break;
2879      case 4:  VT = MVT::i32; break;
2880      case 2:  VT = MVT::i16; break;
2881      default: VT = MVT::i8;  break;
2882      }
2883    }
2884
2885    MVT LVT = MVT::i64;
2886    while (!TLI.isTypeLegal(LVT))
2887      LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2888    assert(LVT.isInteger());
2889
2890    if (VT.bitsGT(LVT))
2891      VT = LVT;
2892  }
2893
2894  unsigned NumMemOps = 0;
2895  while (Size != 0) {
2896    unsigned VTSize = VT.getSizeInBits() / 8;
2897    while (VTSize > Size) {
2898      // For now, only use non-vector load / store's for the left-over pieces.
2899      if (VT.isVector()) {
2900        VT = MVT::i64;
2901        while (!TLI.isTypeLegal(VT))
2902          VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2903        VTSize = VT.getSizeInBits() / 8;
2904      } else {
2905        VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2906        VTSize >>= 1;
2907      }
2908    }
2909
2910    if (++NumMemOps > Limit)
2911      return false;
2912    MemOps.push_back(VT);
2913    Size -= VTSize;
2914  }
2915
2916  return true;
2917}
2918
2919static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG,
2920                                         SDValue Chain, SDValue Dst,
2921                                         SDValue Src, uint64_t Size,
2922                                         unsigned Align, bool AlwaysInline,
2923                                         const Value *DstSV, uint64_t DstSVOff,
2924                                         const Value *SrcSV, uint64_t SrcSVOff){
2925  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2926
2927  // Expand memcpy to a series of load and store ops if the size operand falls
2928  // below a certain threshold.
2929  std::vector<MVT> MemOps;
2930  uint64_t Limit = -1;
2931  if (!AlwaysInline)
2932    Limit = TLI.getMaxStoresPerMemcpy();
2933  unsigned DstAlign = Align;  // Destination alignment can change.
2934  std::string Str;
2935  bool CopyFromStr;
2936  if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2937                                Str, CopyFromStr, DAG, TLI))
2938    return SDValue();
2939
2940
2941  bool isZeroStr = CopyFromStr && Str.empty();
2942  SmallVector<SDValue, 8> OutChains;
2943  unsigned NumMemOps = MemOps.size();
2944  uint64_t SrcOff = 0, DstOff = 0;
2945  for (unsigned i = 0; i < NumMemOps; i++) {
2946    MVT VT = MemOps[i];
2947    unsigned VTSize = VT.getSizeInBits() / 8;
2948    SDValue Value, Store;
2949
2950    if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2951      // It's unlikely a store of a vector immediate can be done in a single
2952      // instruction. It would require a load from a constantpool first.
2953      // We also handle store a vector with all zero's.
2954      // FIXME: Handle other cases where store of vector immediate is done in
2955      // a single instruction.
2956      Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2957      Store = DAG.getStore(Chain, Value,
2958                           getMemBasePlusOffset(Dst, DstOff, DAG),
2959                           DstSV, DstSVOff + DstOff, false, DstAlign);
2960    } else {
2961      Value = DAG.getLoad(VT, Chain,
2962                          getMemBasePlusOffset(Src, SrcOff, DAG),
2963                          SrcSV, SrcSVOff + SrcOff, false, Align);
2964      Store = DAG.getStore(Chain, Value,
2965                           getMemBasePlusOffset(Dst, DstOff, DAG),
2966                           DstSV, DstSVOff + DstOff, false, DstAlign);
2967    }
2968    OutChains.push_back(Store);
2969    SrcOff += VTSize;
2970    DstOff += VTSize;
2971  }
2972
2973  return DAG.getNode(ISD::TokenFactor, MVT::Other,
2974                     &OutChains[0], OutChains.size());
2975}
2976
2977static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG,
2978                                          SDValue Chain, SDValue Dst,
2979                                          SDValue Src, uint64_t Size,
2980                                          unsigned Align, bool AlwaysInline,
2981                                          const Value *DstSV, uint64_t DstSVOff,
2982                                          const Value *SrcSV, uint64_t SrcSVOff){
2983  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2984
2985  // Expand memmove to a series of load and store ops if the size operand falls
2986  // below a certain threshold.
2987  std::vector<MVT> MemOps;
2988  uint64_t Limit = -1;
2989  if (!AlwaysInline)
2990    Limit = TLI.getMaxStoresPerMemmove();
2991  unsigned DstAlign = Align;  // Destination alignment can change.
2992  std::string Str;
2993  bool CopyFromStr;
2994  if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2995                                Str, CopyFromStr, DAG, TLI))
2996    return SDValue();
2997
2998  uint64_t SrcOff = 0, DstOff = 0;
2999
3000  SmallVector<SDValue, 8> LoadValues;
3001  SmallVector<SDValue, 8> LoadChains;
3002  SmallVector<SDValue, 8> OutChains;
3003  unsigned NumMemOps = MemOps.size();
3004  for (unsigned i = 0; i < NumMemOps; i++) {
3005    MVT VT = MemOps[i];
3006    unsigned VTSize = VT.getSizeInBits() / 8;
3007    SDValue Value, Store;
3008
3009    Value = DAG.getLoad(VT, Chain,
3010                        getMemBasePlusOffset(Src, SrcOff, DAG),
3011                        SrcSV, SrcSVOff + SrcOff, false, Align);
3012    LoadValues.push_back(Value);
3013    LoadChains.push_back(Value.getValue(1));
3014    SrcOff += VTSize;
3015  }
3016  Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3017                      &LoadChains[0], LoadChains.size());
3018  OutChains.clear();
3019  for (unsigned i = 0; i < NumMemOps; i++) {
3020    MVT VT = MemOps[i];
3021    unsigned VTSize = VT.getSizeInBits() / 8;
3022    SDValue Value, Store;
3023
3024    Store = DAG.getStore(Chain, LoadValues[i],
3025                         getMemBasePlusOffset(Dst, DstOff, DAG),
3026                         DstSV, DstSVOff + DstOff, false, DstAlign);
3027    OutChains.push_back(Store);
3028    DstOff += VTSize;
3029  }
3030
3031  return DAG.getNode(ISD::TokenFactor, MVT::Other,
3032                     &OutChains[0], OutChains.size());
3033}
3034
3035static SDValue getMemsetStores(SelectionDAG &DAG,
3036                                 SDValue Chain, SDValue Dst,
3037                                 SDValue Src, uint64_t Size,
3038                                 unsigned Align,
3039                                 const Value *DstSV, uint64_t DstSVOff) {
3040  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3041
3042  // Expand memset to a series of load/store ops if the size operand
3043  // falls below a certain threshold.
3044  std::vector<MVT> MemOps;
3045  std::string Str;
3046  bool CopyFromStr;
3047  if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3048                                Size, Align, Str, CopyFromStr, DAG, TLI))
3049    return SDValue();
3050
3051  SmallVector<SDValue, 8> OutChains;
3052  uint64_t DstOff = 0;
3053
3054  unsigned NumMemOps = MemOps.size();
3055  for (unsigned i = 0; i < NumMemOps; i++) {
3056    MVT VT = MemOps[i];
3057    unsigned VTSize = VT.getSizeInBits() / 8;
3058    SDValue Value = getMemsetValue(Src, VT, DAG);
3059    SDValue Store = DAG.getStore(Chain, Value,
3060                                   getMemBasePlusOffset(Dst, DstOff, DAG),
3061                                   DstSV, DstSVOff + DstOff);
3062    OutChains.push_back(Store);
3063    DstOff += VTSize;
3064  }
3065
3066  return DAG.getNode(ISD::TokenFactor, MVT::Other,
3067                     &OutChains[0], OutChains.size());
3068}
3069
3070SDValue SelectionDAG::getMemcpy(SDValue Chain, SDValue Dst,
3071                                SDValue Src, SDValue Size,
3072                                unsigned Align, bool AlwaysInline,
3073                                const Value *DstSV, uint64_t DstSVOff,
3074                                const Value *SrcSV, uint64_t SrcSVOff) {
3075
3076  // Check to see if we should lower the memcpy to loads and stores first.
3077  // For cases within the target-specified limits, this is the best choice.
3078  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3079  if (ConstantSize) {
3080    // Memcpy with size zero? Just return the original chain.
3081    if (ConstantSize->isNullValue())
3082      return Chain;
3083
3084    SDValue Result =
3085      getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
3086                              ConstantSize->getZExtValue(),
3087                              Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3088    if (Result.getNode())
3089      return Result;
3090  }
3091
3092  // Then check to see if we should lower the memcpy with target-specific
3093  // code. If the target chooses to do this, this is the next best.
3094  SDValue Result =
3095    TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
3096                                AlwaysInline,
3097                                DstSV, DstSVOff, SrcSV, SrcSVOff);
3098  if (Result.getNode())
3099    return Result;
3100
3101  // If we really need inline code and the target declined to provide it,
3102  // use a (potentially long) sequence of loads and stores.
3103  if (AlwaysInline) {
3104    assert(ConstantSize && "AlwaysInline requires a constant size!");
3105    return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
3106                                   ConstantSize->getZExtValue(), Align, true,
3107                                   DstSV, DstSVOff, SrcSV, SrcSVOff);
3108  }
3109
3110  // Emit a library call.
3111  TargetLowering::ArgListTy Args;
3112  TargetLowering::ArgListEntry Entry;
3113  Entry.Ty = TLI.getTargetData()->getIntPtrType();
3114  Entry.Node = Dst; Args.push_back(Entry);
3115  Entry.Node = Src; Args.push_back(Entry);
3116  Entry.Node = Size; Args.push_back(Entry);
3117  std::pair<SDValue,SDValue> CallResult =
3118    TLI.LowerCallTo(Chain, Type::VoidTy,
3119                    false, false, false, false, CallingConv::C, false,
3120                    getExternalSymbol("memcpy", TLI.getPointerTy()),
3121                    Args, *this);
3122  return CallResult.second;
3123}
3124
3125SDValue SelectionDAG::getMemmove(SDValue Chain, SDValue Dst,
3126                                 SDValue Src, SDValue Size,
3127                                 unsigned Align,
3128                                 const Value *DstSV, uint64_t DstSVOff,
3129                                 const Value *SrcSV, uint64_t SrcSVOff) {
3130
3131  // Check to see if we should lower the memmove to loads and stores first.
3132  // For cases within the target-specified limits, this is the best choice.
3133  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3134  if (ConstantSize) {
3135    // Memmove with size zero? Just return the original chain.
3136    if (ConstantSize->isNullValue())
3137      return Chain;
3138
3139    SDValue Result =
3140      getMemmoveLoadsAndStores(*this, Chain, Dst, Src,
3141                               ConstantSize->getZExtValue(),
3142                               Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3143    if (Result.getNode())
3144      return Result;
3145  }
3146
3147  // Then check to see if we should lower the memmove with target-specific
3148  // code. If the target chooses to do this, this is the next best.
3149  SDValue Result =
3150    TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
3151                                 DstSV, DstSVOff, SrcSV, SrcSVOff);
3152  if (Result.getNode())
3153    return Result;
3154
3155  // Emit a library call.
3156  TargetLowering::ArgListTy Args;
3157  TargetLowering::ArgListEntry Entry;
3158  Entry.Ty = TLI.getTargetData()->getIntPtrType();
3159  Entry.Node = Dst; Args.push_back(Entry);
3160  Entry.Node = Src; Args.push_back(Entry);
3161  Entry.Node = Size; Args.push_back(Entry);
3162  std::pair<SDValue,SDValue> CallResult =
3163    TLI.LowerCallTo(Chain, Type::VoidTy,
3164                    false, false, false, false, CallingConv::C, false,
3165                    getExternalSymbol("memmove", TLI.getPointerTy()),
3166                    Args, *this);
3167  return CallResult.second;
3168}
3169
3170SDValue SelectionDAG::getMemset(SDValue Chain, SDValue Dst,
3171                                SDValue Src, SDValue Size,
3172                                unsigned Align,
3173                                const Value *DstSV, uint64_t DstSVOff) {
3174
3175  // Check to see if we should lower the memset to stores first.
3176  // For cases within the target-specified limits, this is the best choice.
3177  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3178  if (ConstantSize) {
3179    // Memset with size zero? Just return the original chain.
3180    if (ConstantSize->isNullValue())
3181      return Chain;
3182
3183    SDValue Result =
3184      getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getZExtValue(),
3185                      Align, DstSV, DstSVOff);
3186    if (Result.getNode())
3187      return Result;
3188  }
3189
3190  // Then check to see if we should lower the memset with target-specific
3191  // code. If the target chooses to do this, this is the next best.
3192  SDValue Result =
3193    TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3194                                DstSV, DstSVOff);
3195  if (Result.getNode())
3196    return Result;
3197
3198  // Emit a library call.
3199  const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3200  TargetLowering::ArgListTy Args;
3201  TargetLowering::ArgListEntry Entry;
3202  Entry.Node = Dst; Entry.Ty = IntPtrTy;
3203  Args.push_back(Entry);
3204  // Extend or truncate the argument to be an i32 value for the call.
3205  if (Src.getValueType().bitsGT(MVT::i32))
3206    Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3207  else
3208    Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3209  Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3210  Args.push_back(Entry);
3211  Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3212  Args.push_back(Entry);
3213  std::pair<SDValue,SDValue> CallResult =
3214    TLI.LowerCallTo(Chain, Type::VoidTy,
3215                    false, false, false, false, CallingConv::C, false,
3216                    getExternalSymbol("memset", TLI.getPointerTy()),
3217                    Args, *this);
3218  return CallResult.second;
3219}
3220
3221SDValue SelectionDAG::getAtomic(unsigned Opcode, SDValue Chain,
3222                                SDValue Ptr, SDValue Cmp,
3223                                SDValue Swp, const Value* PtrVal,
3224                                unsigned Alignment) {
3225  assert((Opcode == ISD::ATOMIC_CMP_SWAP_8  ||
3226          Opcode == ISD::ATOMIC_CMP_SWAP_16 ||
3227          Opcode == ISD::ATOMIC_CMP_SWAP_32 ||
3228          Opcode == ISD::ATOMIC_CMP_SWAP_64) && "Invalid Atomic Op");
3229  assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3230
3231  MVT VT = Cmp.getValueType();
3232
3233  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
3234    Alignment = getMVTAlignment(VT);
3235
3236  SDVTList VTs = getVTList(VT, MVT::Other);
3237  FoldingSetNodeID ID;
3238  SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3239  AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3240  void* IP = 0;
3241  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3242    return SDValue(E, 0);
3243  SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3244  new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3245  CSEMap.InsertNode(N, IP);
3246  AllNodes.push_back(N);
3247  return SDValue(N, 0);
3248}
3249
3250SDValue SelectionDAG::getAtomic(unsigned Opcode, SDValue Chain,
3251                                SDValue Ptr, SDValue Val,
3252                                const Value* PtrVal,
3253                                unsigned Alignment) {
3254  assert((Opcode == ISD::ATOMIC_LOAD_ADD_8 ||
3255          Opcode == ISD::ATOMIC_LOAD_SUB_8 ||
3256          Opcode == ISD::ATOMIC_LOAD_AND_8 ||
3257          Opcode == ISD::ATOMIC_LOAD_OR_8 ||
3258          Opcode == ISD::ATOMIC_LOAD_XOR_8 ||
3259          Opcode == ISD::ATOMIC_LOAD_NAND_8 ||
3260          Opcode == ISD::ATOMIC_LOAD_MIN_8 ||
3261          Opcode == ISD::ATOMIC_LOAD_MAX_8 ||
3262          Opcode == ISD::ATOMIC_LOAD_UMIN_8 ||
3263          Opcode == ISD::ATOMIC_LOAD_UMAX_8 ||
3264          Opcode == ISD::ATOMIC_SWAP_8 ||
3265          Opcode == ISD::ATOMIC_LOAD_ADD_16 ||
3266          Opcode == ISD::ATOMIC_LOAD_SUB_16 ||
3267          Opcode == ISD::ATOMIC_LOAD_AND_16 ||
3268          Opcode == ISD::ATOMIC_LOAD_OR_16 ||
3269          Opcode == ISD::ATOMIC_LOAD_XOR_16 ||
3270          Opcode == ISD::ATOMIC_LOAD_NAND_16 ||
3271          Opcode == ISD::ATOMIC_LOAD_MIN_16 ||
3272          Opcode == ISD::ATOMIC_LOAD_MAX_16 ||
3273          Opcode == ISD::ATOMIC_LOAD_UMIN_16 ||
3274          Opcode == ISD::ATOMIC_LOAD_UMAX_16 ||
3275          Opcode == ISD::ATOMIC_SWAP_16 ||
3276          Opcode == ISD::ATOMIC_LOAD_ADD_32 ||
3277          Opcode == ISD::ATOMIC_LOAD_SUB_32 ||
3278          Opcode == ISD::ATOMIC_LOAD_AND_32 ||
3279          Opcode == ISD::ATOMIC_LOAD_OR_32 ||
3280          Opcode == ISD::ATOMIC_LOAD_XOR_32 ||
3281          Opcode == ISD::ATOMIC_LOAD_NAND_32 ||
3282          Opcode == ISD::ATOMIC_LOAD_MIN_32 ||
3283          Opcode == ISD::ATOMIC_LOAD_MAX_32 ||
3284          Opcode == ISD::ATOMIC_LOAD_UMIN_32 ||
3285          Opcode == ISD::ATOMIC_LOAD_UMAX_32 ||
3286          Opcode == ISD::ATOMIC_SWAP_32 ||
3287          Opcode == ISD::ATOMIC_LOAD_ADD_64 ||
3288          Opcode == ISD::ATOMIC_LOAD_SUB_64 ||
3289          Opcode == ISD::ATOMIC_LOAD_AND_64 ||
3290          Opcode == ISD::ATOMIC_LOAD_OR_64 ||
3291          Opcode == ISD::ATOMIC_LOAD_XOR_64 ||
3292          Opcode == ISD::ATOMIC_LOAD_NAND_64 ||
3293          Opcode == ISD::ATOMIC_LOAD_MIN_64 ||
3294          Opcode == ISD::ATOMIC_LOAD_MAX_64 ||
3295          Opcode == ISD::ATOMIC_LOAD_UMIN_64 ||
3296          Opcode == ISD::ATOMIC_LOAD_UMAX_64 ||
3297          Opcode == ISD::ATOMIC_SWAP_64)        && "Invalid Atomic Op");
3298
3299  MVT VT = Val.getValueType();
3300
3301  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
3302    Alignment = getMVTAlignment(VT);
3303
3304  SDVTList VTs = getVTList(VT, MVT::Other);
3305  FoldingSetNodeID ID;
3306  SDValue Ops[] = {Chain, Ptr, Val};
3307  AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3308  void* IP = 0;
3309  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3310    return SDValue(E, 0);
3311  SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3312  new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, PtrVal, Alignment);
3313  CSEMap.InsertNode(N, IP);
3314  AllNodes.push_back(N);
3315  return SDValue(N, 0);
3316}
3317
3318/// getMergeValues - Create a MERGE_VALUES node from the given operands.
3319/// Allowed to return something different (and simpler) if Simplify is true.
3320SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3321                                     bool Simplify) {
3322  if (Simplify && NumOps == 1)
3323    return Ops[0];
3324
3325  SmallVector<MVT, 4> VTs;
3326  VTs.reserve(NumOps);
3327  for (unsigned i = 0; i < NumOps; ++i)
3328    VTs.push_back(Ops[i].getValueType());
3329  return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3330}
3331
3332SDValue
3333SelectionDAG::getCall(unsigned CallingConv, bool IsVarArgs, bool IsTailCall,
3334                      bool IsInreg, SDVTList VTs,
3335                      const SDValue *Operands, unsigned NumOperands) {
3336  // Do not include isTailCall in the folding set profile.
3337  FoldingSetNodeID ID;
3338  AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
3339  ID.AddInteger(CallingConv);
3340  ID.AddInteger(IsVarArgs);
3341  void *IP = 0;
3342  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3343    // Instead of including isTailCall in the folding set, we just
3344    // set the flag of the existing node.
3345    if (!IsTailCall)
3346      cast<CallSDNode>(E)->setNotTailCall();
3347    return SDValue(E, 0);
3348  }
3349  SDNode *N = NodeAllocator.Allocate<CallSDNode>();
3350  new (N) CallSDNode(CallingConv, IsVarArgs, IsTailCall, IsInreg,
3351                     VTs, Operands, NumOperands);
3352  CSEMap.InsertNode(N, IP);
3353  AllNodes.push_back(N);
3354  return SDValue(N, 0);
3355}
3356
3357SDValue
3358SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3359                      MVT VT, SDValue Chain,
3360                      SDValue Ptr, SDValue Offset,
3361                      const Value *SV, int SVOffset, MVT EVT,
3362                      bool isVolatile, unsigned Alignment) {
3363  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
3364    Alignment = getMVTAlignment(VT);
3365
3366  if (VT == EVT) {
3367    ExtType = ISD::NON_EXTLOAD;
3368  } else if (ExtType == ISD::NON_EXTLOAD) {
3369    assert(VT == EVT && "Non-extending load from different memory type!");
3370  } else {
3371    // Extending load.
3372    if (VT.isVector())
3373      assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3374             "Invalid vector extload!");
3375    else
3376      assert(EVT.bitsLT(VT) &&
3377             "Should only be an extending load, not truncating!");
3378    assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3379           "Cannot sign/zero extend a FP/Vector load!");
3380    assert(VT.isInteger() == EVT.isInteger() &&
3381           "Cannot convert from FP to Int or Int -> FP!");
3382  }
3383
3384  bool Indexed = AM != ISD::UNINDEXED;
3385  assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3386         "Unindexed load with an offset!");
3387
3388  SDVTList VTs = Indexed ?
3389    getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3390  SDValue Ops[] = { Chain, Ptr, Offset };
3391  FoldingSetNodeID ID;
3392  AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3393  ID.AddInteger(AM);
3394  ID.AddInteger(ExtType);
3395  ID.AddInteger(EVT.getRawBits());
3396  ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3397  void *IP = 0;
3398  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3399    return SDValue(E, 0);
3400  SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3401  new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3402                     Alignment, isVolatile);
3403  CSEMap.InsertNode(N, IP);
3404  AllNodes.push_back(N);
3405  return SDValue(N, 0);
3406}
3407
3408SDValue SelectionDAG::getLoad(MVT VT,
3409                              SDValue Chain, SDValue Ptr,
3410                              const Value *SV, int SVOffset,
3411                              bool isVolatile, unsigned Alignment) {
3412  SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3413  return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3414                 SV, SVOffset, VT, isVolatile, Alignment);
3415}
3416
3417SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3418                                 SDValue Chain, SDValue Ptr,
3419                                 const Value *SV,
3420                                 int SVOffset, MVT EVT,
3421                                 bool isVolatile, unsigned Alignment) {
3422  SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3423  return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3424                 SV, SVOffset, EVT, isVolatile, Alignment);
3425}
3426
3427SDValue
3428SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDValue Base,
3429                             SDValue Offset, ISD::MemIndexedMode AM) {
3430  LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3431  assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3432         "Load is already a indexed load!");
3433  return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3434                 LD->getChain(), Base, Offset, LD->getSrcValue(),
3435                 LD->getSrcValueOffset(), LD->getMemoryVT(),
3436                 LD->isVolatile(), LD->getAlignment());
3437}
3438
3439SDValue SelectionDAG::getStore(SDValue Chain, SDValue Val,
3440                               SDValue Ptr, const Value *SV, int SVOffset,
3441                               bool isVolatile, unsigned Alignment) {
3442  MVT VT = Val.getValueType();
3443
3444  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
3445    Alignment = getMVTAlignment(VT);
3446
3447  SDVTList VTs = getVTList(MVT::Other);
3448  SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3449  SDValue Ops[] = { Chain, Val, Ptr, Undef };
3450  FoldingSetNodeID ID;
3451  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3452  ID.AddInteger(ISD::UNINDEXED);
3453  ID.AddInteger(false);
3454  ID.AddInteger(VT.getRawBits());
3455  ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3456  void *IP = 0;
3457  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3458    return SDValue(E, 0);
3459  SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3460  new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3461                      VT, SV, SVOffset, Alignment, isVolatile);
3462  CSEMap.InsertNode(N, IP);
3463  AllNodes.push_back(N);
3464  return SDValue(N, 0);
3465}
3466
3467SDValue SelectionDAG::getTruncStore(SDValue Chain, SDValue Val,
3468                                    SDValue Ptr, const Value *SV,
3469                                    int SVOffset, MVT SVT,
3470                                    bool isVolatile, unsigned Alignment) {
3471  MVT VT = Val.getValueType();
3472
3473  if (VT == SVT)
3474    return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3475
3476  assert(VT.bitsGT(SVT) && "Not a truncation?");
3477  assert(VT.isInteger() == SVT.isInteger() &&
3478         "Can't do FP-INT conversion!");
3479
3480  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
3481    Alignment = getMVTAlignment(VT);
3482
3483  SDVTList VTs = getVTList(MVT::Other);
3484  SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3485  SDValue Ops[] = { Chain, Val, Ptr, Undef };
3486  FoldingSetNodeID ID;
3487  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3488  ID.AddInteger(ISD::UNINDEXED);
3489  ID.AddInteger(1);
3490  ID.AddInteger(SVT.getRawBits());
3491  ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3492  void *IP = 0;
3493  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3494    return SDValue(E, 0);
3495  SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3496  new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3497                      SVT, SV, SVOffset, Alignment, isVolatile);
3498  CSEMap.InsertNode(N, IP);
3499  AllNodes.push_back(N);
3500  return SDValue(N, 0);
3501}
3502
3503SDValue
3504SelectionDAG::getIndexedStore(SDValue OrigStore, SDValue Base,
3505                              SDValue Offset, ISD::MemIndexedMode AM) {
3506  StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3507  assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3508         "Store is already a indexed store!");
3509  SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3510  SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3511  FoldingSetNodeID ID;
3512  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3513  ID.AddInteger(AM);
3514  ID.AddInteger(ST->isTruncatingStore());
3515  ID.AddInteger(ST->getMemoryVT().getRawBits());
3516  ID.AddInteger(ST->getRawFlags());
3517  void *IP = 0;
3518  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3519    return SDValue(E, 0);
3520  SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3521  new (N) StoreSDNode(Ops, VTs, AM,
3522                      ST->isTruncatingStore(), ST->getMemoryVT(),
3523                      ST->getSrcValue(), ST->getSrcValueOffset(),
3524                      ST->getAlignment(), ST->isVolatile());
3525  CSEMap.InsertNode(N, IP);
3526  AllNodes.push_back(N);
3527  return SDValue(N, 0);
3528}
3529
3530SDValue SelectionDAG::getVAArg(MVT VT,
3531                               SDValue Chain, SDValue Ptr,
3532                               SDValue SV) {
3533  SDValue Ops[] = { Chain, Ptr, SV };
3534  return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3535}
3536
3537SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3538                              const SDUse *Ops, unsigned NumOps) {
3539  switch (NumOps) {
3540  case 0: return getNode(Opcode, VT);
3541  case 1: return getNode(Opcode, VT, Ops[0]);
3542  case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3543  case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3544  default: break;
3545  }
3546
3547  // Copy from an SDUse array into an SDValue array for use with
3548  // the regular getNode logic.
3549  SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
3550  return getNode(Opcode, VT, &NewOps[0], NumOps);
3551}
3552
3553SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3554                              const SDValue *Ops, unsigned NumOps) {
3555  switch (NumOps) {
3556  case 0: return getNode(Opcode, VT);
3557  case 1: return getNode(Opcode, VT, Ops[0]);
3558  case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3559  case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3560  default: break;
3561  }
3562
3563  switch (Opcode) {
3564  default: break;
3565  case ISD::SELECT_CC: {
3566    assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3567    assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3568           "LHS and RHS of condition must have same type!");
3569    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3570           "True and False arms of SelectCC must have same type!");
3571    assert(Ops[2].getValueType() == VT &&
3572           "select_cc node must be of same type as true and false value!");
3573    break;
3574  }
3575  case ISD::BR_CC: {
3576    assert(NumOps == 5 && "BR_CC takes 5 operands!");
3577    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3578           "LHS/RHS of comparison should match types!");
3579    break;
3580  }
3581  }
3582
3583  // Memoize nodes.
3584  SDNode *N;
3585  SDVTList VTs = getVTList(VT);
3586  if (VT != MVT::Flag) {
3587    FoldingSetNodeID ID;
3588    AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3589    void *IP = 0;
3590    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3591      return SDValue(E, 0);
3592    N = NodeAllocator.Allocate<SDNode>();
3593    new (N) SDNode(Opcode, VTs, Ops, NumOps);
3594    CSEMap.InsertNode(N, IP);
3595  } else {
3596    N = NodeAllocator.Allocate<SDNode>();
3597    new (N) SDNode(Opcode, VTs, Ops, NumOps);
3598  }
3599  AllNodes.push_back(N);
3600#ifndef NDEBUG
3601  VerifyNode(N);
3602#endif
3603  return SDValue(N, 0);
3604}
3605
3606SDValue SelectionDAG::getNode(unsigned Opcode,
3607                              const std::vector<MVT> &ResultTys,
3608                              const SDValue *Ops, unsigned NumOps) {
3609  return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3610                 Ops, NumOps);
3611}
3612
3613SDValue SelectionDAG::getNode(unsigned Opcode,
3614                              const MVT *VTs, unsigned NumVTs,
3615                              const SDValue *Ops, unsigned NumOps) {
3616  if (NumVTs == 1)
3617    return getNode(Opcode, VTs[0], Ops, NumOps);
3618  return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3619}
3620
3621SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3622                              const SDValue *Ops, unsigned NumOps) {
3623  if (VTList.NumVTs == 1)
3624    return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3625
3626  switch (Opcode) {
3627  // FIXME: figure out how to safely handle things like
3628  // int foo(int x) { return 1 << (x & 255); }
3629  // int bar() { return foo(256); }
3630#if 0
3631  case ISD::SRA_PARTS:
3632  case ISD::SRL_PARTS:
3633  case ISD::SHL_PARTS:
3634    if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3635        cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3636      return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3637    else if (N3.getOpcode() == ISD::AND)
3638      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3639        // If the and is only masking out bits that cannot effect the shift,
3640        // eliminate the and.
3641        unsigned NumBits = VT.getSizeInBits()*2;
3642        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3643          return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3644      }
3645    break;
3646#endif
3647  }
3648
3649  // Memoize the node unless it returns a flag.
3650  SDNode *N;
3651  if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3652    FoldingSetNodeID ID;
3653    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3654    void *IP = 0;
3655    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3656      return SDValue(E, 0);
3657    if (NumOps == 1) {
3658      N = NodeAllocator.Allocate<UnarySDNode>();
3659      new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3660    } else if (NumOps == 2) {
3661      N = NodeAllocator.Allocate<BinarySDNode>();
3662      new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3663    } else if (NumOps == 3) {
3664      N = NodeAllocator.Allocate<TernarySDNode>();
3665      new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3666    } else {
3667      N = NodeAllocator.Allocate<SDNode>();
3668      new (N) SDNode(Opcode, VTList, Ops, NumOps);
3669    }
3670    CSEMap.InsertNode(N, IP);
3671  } else {
3672    if (NumOps == 1) {
3673      N = NodeAllocator.Allocate<UnarySDNode>();
3674      new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3675    } else if (NumOps == 2) {
3676      N = NodeAllocator.Allocate<BinarySDNode>();
3677      new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3678    } else if (NumOps == 3) {
3679      N = NodeAllocator.Allocate<TernarySDNode>();
3680      new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3681    } else {
3682      N = NodeAllocator.Allocate<SDNode>();
3683      new (N) SDNode(Opcode, VTList, Ops, NumOps);
3684    }
3685  }
3686  AllNodes.push_back(N);
3687#ifndef NDEBUG
3688  VerifyNode(N);
3689#endif
3690  return SDValue(N, 0);
3691}
3692
3693SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3694  return getNode(Opcode, VTList, 0, 0);
3695}
3696
3697SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3698                                SDValue N1) {
3699  SDValue Ops[] = { N1 };
3700  return getNode(Opcode, VTList, Ops, 1);
3701}
3702
3703SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3704                              SDValue N1, SDValue N2) {
3705  SDValue Ops[] = { N1, N2 };
3706  return getNode(Opcode, VTList, Ops, 2);
3707}
3708
3709SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3710                              SDValue N1, SDValue N2, SDValue N3) {
3711  SDValue Ops[] = { N1, N2, N3 };
3712  return getNode(Opcode, VTList, Ops, 3);
3713}
3714
3715SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3716                              SDValue N1, SDValue N2, SDValue N3,
3717                              SDValue N4) {
3718  SDValue Ops[] = { N1, N2, N3, N4 };
3719  return getNode(Opcode, VTList, Ops, 4);
3720}
3721
3722SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3723                              SDValue N1, SDValue N2, SDValue N3,
3724                              SDValue N4, SDValue N5) {
3725  SDValue Ops[] = { N1, N2, N3, N4, N5 };
3726  return getNode(Opcode, VTList, Ops, 5);
3727}
3728
3729SDVTList SelectionDAG::getVTList(MVT VT) {
3730  return makeVTList(SDNode::getValueTypeList(VT), 1);
3731}
3732
3733SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3734  for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3735       E = VTList.rend(); I != E; ++I)
3736    if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
3737      return *I;
3738
3739  MVT *Array = Allocator.Allocate<MVT>(2);
3740  Array[0] = VT1;
3741  Array[1] = VT2;
3742  SDVTList Result = makeVTList(Array, 2);
3743  VTList.push_back(Result);
3744  return Result;
3745}
3746
3747SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
3748  for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3749       E = VTList.rend(); I != E; ++I)
3750    if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
3751                          I->VTs[2] == VT3)
3752      return *I;
3753
3754  MVT *Array = Allocator.Allocate<MVT>(3);
3755  Array[0] = VT1;
3756  Array[1] = VT2;
3757  Array[2] = VT3;
3758  SDVTList Result = makeVTList(Array, 3);
3759  VTList.push_back(Result);
3760  return Result;
3761}
3762
3763SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3764  switch (NumVTs) {
3765    case 0: assert(0 && "Cannot have nodes without results!");
3766    case 1: return getVTList(VTs[0]);
3767    case 2: return getVTList(VTs[0], VTs[1]);
3768    case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3769    default: break;
3770  }
3771
3772  for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3773       E = VTList.rend(); I != E; ++I) {
3774    if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
3775      continue;
3776
3777    bool NoMatch = false;
3778    for (unsigned i = 2; i != NumVTs; ++i)
3779      if (VTs[i] != I->VTs[i]) {
3780        NoMatch = true;
3781        break;
3782      }
3783    if (!NoMatch)
3784      return *I;
3785  }
3786
3787  MVT *Array = Allocator.Allocate<MVT>(NumVTs);
3788  std::copy(VTs, VTs+NumVTs, Array);
3789  SDVTList Result = makeVTList(Array, NumVTs);
3790  VTList.push_back(Result);
3791  return Result;
3792}
3793
3794
3795/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3796/// specified operands.  If the resultant node already exists in the DAG,
3797/// this does not modify the specified node, instead it returns the node that
3798/// already exists.  If the resultant node does not exist in the DAG, the
3799/// input node is returned.  As a degenerate case, if you specify the same
3800/// input operands as the node already has, the input node is returned.
3801SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
3802  SDNode *N = InN.getNode();
3803  assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3804
3805  // Check to see if there is no change.
3806  if (Op == N->getOperand(0)) return InN;
3807
3808  // See if the modified node already exists.
3809  void *InsertPos = 0;
3810  if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3811    return SDValue(Existing, InN.getResNo());
3812
3813  // Nope it doesn't.  Remove the node from its current place in the maps.
3814  if (InsertPos)
3815    if (!RemoveNodeFromCSEMaps(N))
3816      InsertPos = 0;
3817
3818  // Now we update the operands.
3819  N->OperandList[0].getVal()->removeUser(0, N);
3820  N->OperandList[0] = Op;
3821  N->OperandList[0].setUser(N);
3822  Op.getNode()->addUser(0, N);
3823
3824  // If this gets put into a CSE map, add it.
3825  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3826  return InN;
3827}
3828
3829SDValue SelectionDAG::
3830UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
3831  SDNode *N = InN.getNode();
3832  assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3833
3834  // Check to see if there is no change.
3835  if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3836    return InN;   // No operands changed, just return the input node.
3837
3838  // See if the modified node already exists.
3839  void *InsertPos = 0;
3840  if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3841    return SDValue(Existing, InN.getResNo());
3842
3843  // Nope it doesn't.  Remove the node from its current place in the maps.
3844  if (InsertPos)
3845    if (!RemoveNodeFromCSEMaps(N))
3846      InsertPos = 0;
3847
3848  // Now we update the operands.
3849  if (N->OperandList[0] != Op1) {
3850    N->OperandList[0].getVal()->removeUser(0, N);
3851    N->OperandList[0] = Op1;
3852    N->OperandList[0].setUser(N);
3853    Op1.getNode()->addUser(0, N);
3854  }
3855  if (N->OperandList[1] != Op2) {
3856    N->OperandList[1].getVal()->removeUser(1, N);
3857    N->OperandList[1] = Op2;
3858    N->OperandList[1].setUser(N);
3859    Op2.getNode()->addUser(1, N);
3860  }
3861
3862  // If this gets put into a CSE map, add it.
3863  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3864  return InN;
3865}
3866
3867SDValue SelectionDAG::
3868UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
3869  SDValue Ops[] = { Op1, Op2, Op3 };
3870  return UpdateNodeOperands(N, Ops, 3);
3871}
3872
3873SDValue SelectionDAG::
3874UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
3875                   SDValue Op3, SDValue Op4) {
3876  SDValue Ops[] = { Op1, Op2, Op3, Op4 };
3877  return UpdateNodeOperands(N, Ops, 4);
3878}
3879
3880SDValue SelectionDAG::
3881UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
3882                   SDValue Op3, SDValue Op4, SDValue Op5) {
3883  SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3884  return UpdateNodeOperands(N, Ops, 5);
3885}
3886
3887SDValue SelectionDAG::
3888UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
3889  SDNode *N = InN.getNode();
3890  assert(N->getNumOperands() == NumOps &&
3891         "Update with wrong number of operands");
3892
3893  // Check to see if there is no change.
3894  bool AnyChange = false;
3895  for (unsigned i = 0; i != NumOps; ++i) {
3896    if (Ops[i] != N->getOperand(i)) {
3897      AnyChange = true;
3898      break;
3899    }
3900  }
3901
3902  // No operands changed, just return the input node.
3903  if (!AnyChange) return InN;
3904
3905  // See if the modified node already exists.
3906  void *InsertPos = 0;
3907  if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3908    return SDValue(Existing, InN.getResNo());
3909
3910  // Nope it doesn't.  Remove the node from its current place in the maps.
3911  if (InsertPos)
3912    if (!RemoveNodeFromCSEMaps(N))
3913      InsertPos = 0;
3914
3915  // Now we update the operands.
3916  for (unsigned i = 0; i != NumOps; ++i) {
3917    if (N->OperandList[i] != Ops[i]) {
3918      N->OperandList[i].getVal()->removeUser(i, N);
3919      N->OperandList[i] = Ops[i];
3920      N->OperandList[i].setUser(N);
3921      Ops[i].getNode()->addUser(i, N);
3922    }
3923  }
3924
3925  // If this gets put into a CSE map, add it.
3926  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3927  return InN;
3928}
3929
3930/// DropOperands - Release the operands and set this node to have
3931/// zero operands.
3932void SDNode::DropOperands() {
3933  // Unlike the code in MorphNodeTo that does this, we don't need to
3934  // watch for dead nodes here.
3935  for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3936    I->getVal()->removeUser(std::distance(op_begin(), I), this);
3937
3938  NumOperands = 0;
3939}
3940
3941/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
3942/// machine opcode.
3943///
3944SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3945                                   MVT VT) {
3946  SDVTList VTs = getVTList(VT);
3947  return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
3948}
3949
3950SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3951                                   MVT VT, SDValue Op1) {
3952  SDVTList VTs = getVTList(VT);
3953  SDValue Ops[] = { Op1 };
3954  return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
3955}
3956
3957SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3958                                   MVT VT, SDValue Op1,
3959                                   SDValue Op2) {
3960  SDVTList VTs = getVTList(VT);
3961  SDValue Ops[] = { Op1, Op2 };
3962  return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
3963}
3964
3965SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3966                                   MVT VT, SDValue Op1,
3967                                   SDValue Op2, SDValue Op3) {
3968  SDVTList VTs = getVTList(VT);
3969  SDValue Ops[] = { Op1, Op2, Op3 };
3970  return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
3971}
3972
3973SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3974                                   MVT VT, const SDValue *Ops,
3975                                   unsigned NumOps) {
3976  SDVTList VTs = getVTList(VT);
3977  return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3978}
3979
3980SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3981                                   MVT VT1, MVT VT2, const SDValue *Ops,
3982                                   unsigned NumOps) {
3983  SDVTList VTs = getVTList(VT1, VT2);
3984  return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3985}
3986
3987SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3988                                   MVT VT1, MVT VT2) {
3989  SDVTList VTs = getVTList(VT1, VT2);
3990  return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
3991}
3992
3993SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3994                                   MVT VT1, MVT VT2, MVT VT3,
3995                                   const SDValue *Ops, unsigned NumOps) {
3996  SDVTList VTs = getVTList(VT1, VT2, VT3);
3997  return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3998}
3999
4000SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4001                                   MVT VT1, MVT VT2,
4002                                   SDValue Op1) {
4003  SDVTList VTs = getVTList(VT1, VT2);
4004  SDValue Ops[] = { Op1 };
4005  return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4006}
4007
4008SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4009                                   MVT VT1, MVT VT2,
4010                                   SDValue Op1, SDValue Op2) {
4011  SDVTList VTs = getVTList(VT1, VT2);
4012  SDValue Ops[] = { Op1, Op2 };
4013  return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4014}
4015
4016SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4017                                   MVT VT1, MVT VT2,
4018                                   SDValue Op1, SDValue Op2,
4019                                   SDValue Op3) {
4020  SDVTList VTs = getVTList(VT1, VT2);
4021  SDValue Ops[] = { Op1, Op2, Op3 };
4022  return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4023}
4024
4025SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4026                                   SDVTList VTs, const SDValue *Ops,
4027                                   unsigned NumOps) {
4028  return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4029}
4030
4031SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4032                                  MVT VT) {
4033  SDVTList VTs = getVTList(VT);
4034  return MorphNodeTo(N, Opc, VTs, 0, 0);
4035}
4036
4037SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4038                                  MVT VT, SDValue Op1) {
4039  SDVTList VTs = getVTList(VT);
4040  SDValue Ops[] = { Op1 };
4041  return MorphNodeTo(N, Opc, VTs, Ops, 1);
4042}
4043
4044SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4045                                  MVT VT, SDValue Op1,
4046                                  SDValue Op2) {
4047  SDVTList VTs = getVTList(VT);
4048  SDValue Ops[] = { Op1, Op2 };
4049  return MorphNodeTo(N, Opc, VTs, Ops, 2);
4050}
4051
4052SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4053                                  MVT VT, SDValue Op1,
4054                                  SDValue Op2, SDValue Op3) {
4055  SDVTList VTs = getVTList(VT);
4056  SDValue Ops[] = { Op1, Op2, Op3 };
4057  return MorphNodeTo(N, Opc, VTs, Ops, 3);
4058}
4059
4060SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4061                                  MVT VT, const SDValue *Ops,
4062                                  unsigned NumOps) {
4063  SDVTList VTs = getVTList(VT);
4064  return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4065}
4066
4067SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4068                                  MVT VT1, MVT VT2, const SDValue *Ops,
4069                                  unsigned NumOps) {
4070  SDVTList VTs = getVTList(VT1, VT2);
4071  return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4072}
4073
4074SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4075                                  MVT VT1, MVT VT2) {
4076  SDVTList VTs = getVTList(VT1, VT2);
4077  return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
4078}
4079
4080SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4081                                  MVT VT1, MVT VT2, MVT VT3,
4082                                  const SDValue *Ops, unsigned NumOps) {
4083  SDVTList VTs = getVTList(VT1, VT2, VT3);
4084  return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4085}
4086
4087SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4088                                  MVT VT1, MVT VT2,
4089                                  SDValue Op1) {
4090  SDVTList VTs = getVTList(VT1, VT2);
4091  SDValue Ops[] = { Op1 };
4092  return MorphNodeTo(N, Opc, VTs, Ops, 1);
4093}
4094
4095SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4096                                  MVT VT1, MVT VT2,
4097                                  SDValue Op1, SDValue Op2) {
4098  SDVTList VTs = getVTList(VT1, VT2);
4099  SDValue Ops[] = { Op1, Op2 };
4100  return MorphNodeTo(N, Opc, VTs, Ops, 2);
4101}
4102
4103SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4104                                  MVT VT1, MVT VT2,
4105                                  SDValue Op1, SDValue Op2,
4106                                  SDValue Op3) {
4107  SDVTList VTs = getVTList(VT1, VT2);
4108  SDValue Ops[] = { Op1, Op2, Op3 };
4109  return MorphNodeTo(N, Opc, VTs, Ops, 3);
4110}
4111
4112/// MorphNodeTo - These *mutate* the specified node to have the specified
4113/// return type, opcode, and operands.
4114///
4115/// Note that MorphNodeTo returns the resultant node.  If there is already a
4116/// node of the specified opcode and operands, it returns that node instead of
4117/// the current one.
4118///
4119/// Using MorphNodeTo is faster than creating a new node and swapping it in
4120/// with ReplaceAllUsesWith both because it often avoids allocating a new
4121/// node, and because it doesn't require CSE recalculation for any of
4122/// the node's users.
4123///
4124SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4125                                  SDVTList VTs, const SDValue *Ops,
4126                                  unsigned NumOps) {
4127  // If an identical node already exists, use it.
4128  void *IP = 0;
4129  if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4130    FoldingSetNodeID ID;
4131    AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4132    if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4133      return ON;
4134  }
4135
4136  if (!RemoveNodeFromCSEMaps(N))
4137    IP = 0;
4138
4139  // Start the morphing.
4140  N->NodeType = Opc;
4141  N->ValueList = VTs.VTs;
4142  N->NumValues = VTs.NumVTs;
4143
4144  // Clear the operands list, updating used nodes to remove this from their
4145  // use list.  Keep track of any operands that become dead as a result.
4146  SmallPtrSet<SDNode*, 16> DeadNodeSet;
4147  for (SDNode::op_iterator B = N->op_begin(), I = B, E = N->op_end();
4148       I != E; ++I) {
4149    SDNode *Used = I->getVal();
4150    Used->removeUser(std::distance(B, I), N);
4151    if (Used->use_empty())
4152      DeadNodeSet.insert(Used);
4153  }
4154
4155  // If NumOps is larger than the # of operands we currently have, reallocate
4156  // the operand list.
4157  if (NumOps > N->NumOperands) {
4158    if (N->OperandsNeedDelete)
4159      delete[] N->OperandList;
4160    if (N->isMachineOpcode()) {
4161      // We're creating a final node that will live unmorphed for the
4162      // remainder of the current SelectionDAG iteration, so we can allocate
4163      // the operands directly out of a pool with no recycling metadata.
4164      N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps);
4165      N->OperandsNeedDelete = false;
4166    } else {
4167      N->OperandList = new SDUse[NumOps];
4168      N->OperandsNeedDelete = true;
4169    }
4170  }
4171
4172  // Assign the new operands.
4173  N->NumOperands = NumOps;
4174  for (unsigned i = 0, e = NumOps; i != e; ++i) {
4175    N->OperandList[i] = Ops[i];
4176    N->OperandList[i].setUser(N);
4177    SDNode *ToUse = N->OperandList[i].getVal();
4178    ToUse->addUser(i, N);
4179  }
4180
4181  // Delete any nodes that are still dead after adding the uses for the
4182  // new operands.
4183  SmallVector<SDNode *, 16> DeadNodes;
4184  for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4185       E = DeadNodeSet.end(); I != E; ++I)
4186    if ((*I)->use_empty())
4187      DeadNodes.push_back(*I);
4188  RemoveDeadNodes(DeadNodes);
4189
4190  if (IP)
4191    CSEMap.InsertNode(N, IP);   // Memoize the new node.
4192  return N;
4193}
4194
4195
4196/// getTargetNode - These are used for target selectors to create a new node
4197/// with specified return type(s), target opcode, and operands.
4198///
4199/// Note that getTargetNode returns the resultant node.  If there is already a
4200/// node of the specified opcode and operands, it returns that node instead of
4201/// the current one.
4202SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
4203  return getNode(~Opcode, VT).getNode();
4204}
4205SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDValue Op1) {
4206  return getNode(~Opcode, VT, Op1).getNode();
4207}
4208SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4209                                    SDValue Op1, SDValue Op2) {
4210  return getNode(~Opcode, VT, Op1, Op2).getNode();
4211}
4212SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4213                                    SDValue Op1, SDValue Op2,
4214                                    SDValue Op3) {
4215  return getNode(~Opcode, VT, Op1, Op2, Op3).getNode();
4216}
4217SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4218                                    const SDValue *Ops, unsigned NumOps) {
4219  return getNode(~Opcode, VT, Ops, NumOps).getNode();
4220}
4221SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
4222  const MVT *VTs = getNodeValueTypes(VT1, VT2);
4223  SDValue Op;
4224  return getNode(~Opcode, VTs, 2, &Op, 0).getNode();
4225}
4226SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4227                                    MVT VT2, SDValue Op1) {
4228  const MVT *VTs = getNodeValueTypes(VT1, VT2);
4229  return getNode(~Opcode, VTs, 2, &Op1, 1).getNode();
4230}
4231SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4232                                    MVT VT2, SDValue Op1,
4233                                    SDValue Op2) {
4234  const MVT *VTs = getNodeValueTypes(VT1, VT2);
4235  SDValue Ops[] = { Op1, Op2 };
4236  return getNode(~Opcode, VTs, 2, Ops, 2).getNode();
4237}
4238SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4239                                    MVT VT2, SDValue Op1,
4240                                    SDValue Op2, SDValue Op3) {
4241  const MVT *VTs = getNodeValueTypes(VT1, VT2);
4242  SDValue Ops[] = { Op1, Op2, Op3 };
4243  return getNode(~Opcode, VTs, 2, Ops, 3).getNode();
4244}
4245SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
4246                                    const SDValue *Ops, unsigned NumOps) {
4247  const MVT *VTs = getNodeValueTypes(VT1, VT2);
4248  return getNode(~Opcode, VTs, 2, Ops, NumOps).getNode();
4249}
4250SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4251                                    SDValue Op1, SDValue Op2) {
4252  const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4253  SDValue Ops[] = { Op1, Op2 };
4254  return getNode(~Opcode, VTs, 3, Ops, 2).getNode();
4255}
4256SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4257                                    SDValue Op1, SDValue Op2,
4258                                    SDValue Op3) {
4259  const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4260  SDValue Ops[] = { Op1, Op2, Op3 };
4261  return getNode(~Opcode, VTs, 3, Ops, 3).getNode();
4262}
4263SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4264                                    const SDValue *Ops, unsigned NumOps) {
4265  const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4266  return getNode(~Opcode, VTs, 3, Ops, NumOps).getNode();
4267}
4268SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4269                                    MVT VT2, MVT VT3, MVT VT4,
4270                                    const SDValue *Ops, unsigned NumOps) {
4271  std::vector<MVT> VTList;
4272  VTList.push_back(VT1);
4273  VTList.push_back(VT2);
4274  VTList.push_back(VT3);
4275  VTList.push_back(VT4);
4276  const MVT *VTs = getNodeValueTypes(VTList);
4277  return getNode(~Opcode, VTs, 4, Ops, NumOps).getNode();
4278}
4279SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
4280                                    const std::vector<MVT> &ResultTys,
4281                                    const SDValue *Ops, unsigned NumOps) {
4282  const MVT *VTs = getNodeValueTypes(ResultTys);
4283  return getNode(~Opcode, VTs, ResultTys.size(),
4284                 Ops, NumOps).getNode();
4285}
4286
4287/// getNodeIfExists - Get the specified node if it's already available, or
4288/// else return NULL.
4289SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4290                                      const SDValue *Ops, unsigned NumOps) {
4291  if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4292    FoldingSetNodeID ID;
4293    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4294    void *IP = 0;
4295    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4296      return E;
4297  }
4298  return NULL;
4299}
4300
4301
4302/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4303/// This can cause recursive merging of nodes in the DAG.
4304///
4305/// This version assumes From has a single result value.
4306///
4307void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4308                                      DAGUpdateListener *UpdateListener) {
4309  SDNode *From = FromN.getNode();
4310  assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4311         "Cannot replace with this method!");
4312  assert(From != To.getNode() && "Cannot replace uses of with self");
4313
4314  while (!From->use_empty()) {
4315    SDNode::use_iterator UI = From->use_begin();
4316    SDNode *U = *UI;
4317
4318    // This node is about to morph, remove its old self from the CSE maps.
4319    RemoveNodeFromCSEMaps(U);
4320    int operandNum = 0;
4321    for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4322         I != E; ++I, ++operandNum)
4323      if (I->getVal() == From) {
4324        From->removeUser(operandNum, U);
4325        *I = To;
4326        I->setUser(U);
4327        To.getNode()->addUser(operandNum, U);
4328      }
4329
4330    // Now that we have modified U, add it back to the CSE maps.  If it already
4331    // exists there, recursively merge the results together.
4332    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4333      ReplaceAllUsesWith(U, Existing, UpdateListener);
4334      // U is now dead.  Inform the listener if it exists and delete it.
4335      if (UpdateListener)
4336        UpdateListener->NodeDeleted(U, Existing);
4337      DeleteNodeNotInCSEMaps(U);
4338    } else {
4339      // If the node doesn't already exist, we updated it.  Inform a listener if
4340      // it exists.
4341      if (UpdateListener)
4342        UpdateListener->NodeUpdated(U);
4343    }
4344  }
4345}
4346
4347/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4348/// This can cause recursive merging of nodes in the DAG.
4349///
4350/// This version assumes From/To have matching types and numbers of result
4351/// values.
4352///
4353void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4354                                      DAGUpdateListener *UpdateListener) {
4355  assert(From->getVTList().VTs == To->getVTList().VTs &&
4356         From->getNumValues() == To->getNumValues() &&
4357         "Cannot use this version of ReplaceAllUsesWith!");
4358
4359  // Handle the trivial case.
4360  if (From == To)
4361    return;
4362
4363  while (!From->use_empty()) {
4364    SDNode::use_iterator UI = From->use_begin();
4365    SDNode *U = *UI;
4366
4367    // This node is about to morph, remove its old self from the CSE maps.
4368    RemoveNodeFromCSEMaps(U);
4369    int operandNum = 0;
4370    for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4371         I != E; ++I, ++operandNum)
4372      if (I->getVal() == From) {
4373        From->removeUser(operandNum, U);
4374        I->getSDValue().setNode(To);
4375        To->addUser(operandNum, U);
4376      }
4377
4378    // Now that we have modified U, add it back to the CSE maps.  If it already
4379    // exists there, recursively merge the results together.
4380    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4381      ReplaceAllUsesWith(U, Existing, UpdateListener);
4382      // U is now dead.  Inform the listener if it exists and delete it.
4383      if (UpdateListener)
4384        UpdateListener->NodeDeleted(U, Existing);
4385      DeleteNodeNotInCSEMaps(U);
4386    } else {
4387      // If the node doesn't already exist, we updated it.  Inform a listener if
4388      // it exists.
4389      if (UpdateListener)
4390        UpdateListener->NodeUpdated(U);
4391    }
4392  }
4393}
4394
4395/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4396/// This can cause recursive merging of nodes in the DAG.
4397///
4398/// This version can replace From with any result values.  To must match the
4399/// number and types of values returned by From.
4400void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4401                                      const SDValue *To,
4402                                      DAGUpdateListener *UpdateListener) {
4403  if (From->getNumValues() == 1)  // Handle the simple case efficiently.
4404    return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4405
4406  while (!From->use_empty()) {
4407    SDNode::use_iterator UI = From->use_begin();
4408    SDNode *U = *UI;
4409
4410    // This node is about to morph, remove its old self from the CSE maps.
4411    RemoveNodeFromCSEMaps(U);
4412    int operandNum = 0;
4413    for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4414         I != E; ++I, ++operandNum)
4415      if (I->getVal() == From) {
4416        const SDValue &ToOp = To[I->getSDValue().getResNo()];
4417        From->removeUser(operandNum, U);
4418        *I = ToOp;
4419        I->setUser(U);
4420        ToOp.getNode()->addUser(operandNum, U);
4421      }
4422
4423    // Now that we have modified U, add it back to the CSE maps.  If it already
4424    // exists there, recursively merge the results together.
4425    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4426      ReplaceAllUsesWith(U, Existing, UpdateListener);
4427      // U is now dead.  Inform the listener if it exists and delete it.
4428      if (UpdateListener)
4429        UpdateListener->NodeDeleted(U, Existing);
4430      DeleteNodeNotInCSEMaps(U);
4431    } else {
4432      // If the node doesn't already exist, we updated it.  Inform a listener if
4433      // it exists.
4434      if (UpdateListener)
4435        UpdateListener->NodeUpdated(U);
4436    }
4437  }
4438}
4439
4440/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4441/// uses of other values produced by From.getVal() alone.  The Deleted vector is
4442/// handled the same way as for ReplaceAllUsesWith.
4443void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
4444                                             DAGUpdateListener *UpdateListener){
4445  // Handle the really simple, really trivial case efficiently.
4446  if (From == To) return;
4447
4448  // Handle the simple, trivial, case efficiently.
4449  if (From.getNode()->getNumValues() == 1) {
4450    ReplaceAllUsesWith(From, To, UpdateListener);
4451    return;
4452  }
4453
4454  // Get all of the users of From.getNode().  We want these in a nice,
4455  // deterministically ordered and uniqued set, so we use a SmallSetVector.
4456  SmallSetVector<SDNode*, 16> Users(From.getNode()->use_begin(), From.getNode()->use_end());
4457
4458  while (!Users.empty()) {
4459    // We know that this user uses some value of From.  If it is the right
4460    // value, update it.
4461    SDNode *User = Users.back();
4462    Users.pop_back();
4463
4464    // Scan for an operand that matches From.
4465    SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4466    for (; Op != E; ++Op)
4467      if (*Op == From) break;
4468
4469    // If there are no matches, the user must use some other result of From.
4470    if (Op == E) continue;
4471
4472    // Okay, we know this user needs to be updated.  Remove its old self
4473    // from the CSE maps.
4474    RemoveNodeFromCSEMaps(User);
4475
4476    // Update all operands that match "From" in case there are multiple uses.
4477    for (; Op != E; ++Op) {
4478      if (*Op == From) {
4479        From.getNode()->removeUser(Op-User->op_begin(), User);
4480        *Op = To;
4481        Op->setUser(User);
4482        To.getNode()->addUser(Op-User->op_begin(), User);
4483      }
4484    }
4485
4486    // Now that we have modified User, add it back to the CSE maps.  If it
4487    // already exists there, recursively merge the results together.
4488    SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4489    if (!Existing) {
4490      if (UpdateListener) UpdateListener->NodeUpdated(User);
4491      continue;  // Continue on to next user.
4492    }
4493
4494    // If there was already an existing matching node, use ReplaceAllUsesWith
4495    // to replace the dead one with the existing one.  This can cause
4496    // recursive merging of other unrelated nodes down the line.
4497    ReplaceAllUsesWith(User, Existing, UpdateListener);
4498
4499    // User is now dead.  Notify a listener if present.
4500    if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4501    DeleteNodeNotInCSEMaps(User);
4502  }
4503}
4504
4505/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
4506/// uses of other values produced by From.getVal() alone.  The same value may
4507/// appear in both the From and To list.  The Deleted vector is
4508/// handled the same way as for ReplaceAllUsesWith.
4509void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
4510                                              const SDValue *To,
4511                                              unsigned Num,
4512                                              DAGUpdateListener *UpdateListener){
4513  // Handle the simple, trivial case efficiently.
4514  if (Num == 1)
4515    return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
4516
4517  SmallVector<std::pair<SDNode *, unsigned>, 16> Users;
4518  for (unsigned i = 0; i != Num; ++i)
4519    for (SDNode::use_iterator UI = From[i].getNode()->use_begin(),
4520         E = From[i].getNode()->use_end(); UI != E; ++UI)
4521      Users.push_back(std::make_pair(*UI, i));
4522
4523  while (!Users.empty()) {
4524    // We know that this user uses some value of From.  If it is the right
4525    // value, update it.
4526    SDNode *User = Users.back().first;
4527    unsigned i = Users.back().second;
4528    Users.pop_back();
4529
4530    // Scan for an operand that matches From.
4531    SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4532    for (; Op != E; ++Op)
4533      if (*Op == From[i]) break;
4534
4535    // If there are no matches, the user must use some other result of From.
4536    if (Op == E) continue;
4537
4538    // Okay, we know this user needs to be updated.  Remove its old self
4539    // from the CSE maps.
4540    RemoveNodeFromCSEMaps(User);
4541
4542    // Update all operands that match "From" in case there are multiple uses.
4543    for (; Op != E; ++Op) {
4544      if (*Op == From[i]) {
4545        From[i].getNode()->removeUser(Op-User->op_begin(), User);
4546        *Op = To[i];
4547        Op->setUser(User);
4548        To[i].getNode()->addUser(Op-User->op_begin(), User);
4549      }
4550    }
4551
4552    // Now that we have modified User, add it back to the CSE maps.  If it
4553    // already exists there, recursively merge the results together.
4554    SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4555    if (!Existing) {
4556      if (UpdateListener) UpdateListener->NodeUpdated(User);
4557      continue;  // Continue on to next user.
4558    }
4559
4560    // If there was already an existing matching node, use ReplaceAllUsesWith
4561    // to replace the dead one with the existing one.  This can cause
4562    // recursive merging of other unrelated nodes down the line.
4563    ReplaceAllUsesWith(User, Existing, UpdateListener);
4564
4565    // User is now dead.  Notify a listener if present.
4566    if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4567    DeleteNodeNotInCSEMaps(User);
4568  }
4569}
4570
4571/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4572/// based on their topological order. It returns the maximum id and a vector
4573/// of the SDNodes* in assigned order by reference.
4574unsigned SelectionDAG::AssignTopologicalOrder() {
4575
4576  unsigned DAGSize = 0;
4577
4578  // SortedPos tracks the progress of the algorithm. Nodes before it are
4579  // sorted, nodes after it are unsorted. When the algorithm completes
4580  // it is at the end of the list.
4581  allnodes_iterator SortedPos = allnodes_begin();
4582
4583  // Visit all the nodes. Add nodes with no operands to the TopOrder result
4584  // array immediately. Annotate nodes that do have operands with their
4585  // operand count. Before we do this, the Node Id fields of the nodes
4586  // may contain arbitrary values. After, the Node Id fields for nodes
4587  // before SortedPos will contain the topological sort index, and the
4588  // Node Id fields for nodes At SortedPos and after will contain the
4589  // count of outstanding operands.
4590  for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
4591    SDNode *N = I++;
4592    unsigned Degree = N->getNumOperands();
4593    if (Degree == 0) {
4594      // A node with no uses, add it to the result array immediately.
4595      N->setNodeId(DAGSize++);
4596      allnodes_iterator Q = N;
4597      if (Q != SortedPos)
4598        SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
4599      ++SortedPos;
4600    } else {
4601      // Temporarily use the Node Id as scratch space for the degree count.
4602      N->setNodeId(Degree);
4603    }
4604  }
4605
4606  // Visit all the nodes. As we iterate, moves nodes into sorted order,
4607  // such that by the time the end is reached all nodes will be sorted.
4608  for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
4609    SDNode *N = I;
4610    for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4611         UI != UE; ++UI) {
4612      SDNode *P = *UI;
4613      unsigned Degree = P->getNodeId();
4614      --Degree;
4615      if (Degree == 0) {
4616        // All of P's operands are sorted, so P may sorted now.
4617        P->setNodeId(DAGSize++);
4618        if (P != SortedPos)
4619          SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
4620        ++SortedPos;
4621      } else {
4622        // Update P's outstanding operand count.
4623        P->setNodeId(Degree);
4624      }
4625    }
4626  }
4627
4628  assert(SortedPos == AllNodes.end() &&
4629         "Topological sort incomplete!");
4630  assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
4631         "First node in topological sort is not the entry token!");
4632  assert(AllNodes.front().getNodeId() == 0 &&
4633         "First node in topological sort has non-zero id!");
4634  assert(AllNodes.front().getNumOperands() == 0 &&
4635         "First node in topological sort has operands!");
4636  assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
4637         "Last node in topologic sort has unexpected id!");
4638  assert(AllNodes.back().use_empty() &&
4639         "Last node in topologic sort has users!");
4640  assert(DAGSize == allnodes_size() && "TopOrder result count mismatch!");
4641  return DAGSize;
4642}
4643
4644
4645
4646//===----------------------------------------------------------------------===//
4647//                              SDNode Class
4648//===----------------------------------------------------------------------===//
4649
4650// Out-of-line virtual method to give class a home.
4651void SDNode::ANCHOR() {}
4652void UnarySDNode::ANCHOR() {}
4653void BinarySDNode::ANCHOR() {}
4654void TernarySDNode::ANCHOR() {}
4655void HandleSDNode::ANCHOR() {}
4656void ConstantSDNode::ANCHOR() {}
4657void ConstantFPSDNode::ANCHOR() {}
4658void GlobalAddressSDNode::ANCHOR() {}
4659void FrameIndexSDNode::ANCHOR() {}
4660void JumpTableSDNode::ANCHOR() {}
4661void ConstantPoolSDNode::ANCHOR() {}
4662void BasicBlockSDNode::ANCHOR() {}
4663void SrcValueSDNode::ANCHOR() {}
4664void MemOperandSDNode::ANCHOR() {}
4665void RegisterSDNode::ANCHOR() {}
4666void DbgStopPointSDNode::ANCHOR() {}
4667void LabelSDNode::ANCHOR() {}
4668void ExternalSymbolSDNode::ANCHOR() {}
4669void CondCodeSDNode::ANCHOR() {}
4670void ARG_FLAGSSDNode::ANCHOR() {}
4671void VTSDNode::ANCHOR() {}
4672void MemSDNode::ANCHOR() {}
4673void LoadSDNode::ANCHOR() {}
4674void StoreSDNode::ANCHOR() {}
4675void AtomicSDNode::ANCHOR() {}
4676void CallSDNode::ANCHOR() {}
4677
4678HandleSDNode::~HandleSDNode() {
4679  DropOperands();
4680}
4681
4682GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4683                                         MVT VT, int o)
4684  : SDNode(isa<GlobalVariable>(GA) &&
4685           cast<GlobalVariable>(GA)->isThreadLocal() ?
4686           // Thread Local
4687           (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4688           // Non Thread Local
4689           (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4690           getSDVTList(VT)), Offset(o) {
4691  TheGlobal = const_cast<GlobalValue*>(GA);
4692}
4693
4694MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
4695                     const Value *srcValue, int SVO,
4696                     unsigned alignment, bool vol)
4697 : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
4698   Flags(encodeMemSDNodeFlags(vol, alignment)) {
4699
4700  assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4701  assert(getAlignment() == alignment && "Alignment representation error!");
4702  assert(isVolatile() == vol && "Volatile representation error!");
4703}
4704
4705/// getMemOperand - Return a MachineMemOperand object describing the memory
4706/// reference performed by this memory reference.
4707MachineMemOperand MemSDNode::getMemOperand() const {
4708  int Flags;
4709  if (isa<LoadSDNode>(this))
4710    Flags = MachineMemOperand::MOLoad;
4711  else if (isa<StoreSDNode>(this))
4712    Flags = MachineMemOperand::MOStore;
4713  else {
4714    assert(isa<AtomicSDNode>(this) && "Unknown MemSDNode opcode!");
4715    Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4716  }
4717
4718  int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4719  if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4720
4721  // Check if the memory reference references a frame index
4722  const FrameIndexSDNode *FI =
4723  dyn_cast<const FrameIndexSDNode>(getBasePtr().getNode());
4724  if (!getSrcValue() && FI)
4725    return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
4726                             Flags, 0, Size, getAlignment());
4727  else
4728    return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4729                             Size, getAlignment());
4730}
4731
4732/// Profile - Gather unique data for the node.
4733///
4734void SDNode::Profile(FoldingSetNodeID &ID) const {
4735  AddNodeIDNode(ID, this);
4736}
4737
4738/// getValueTypeList - Return a pointer to the specified value type.
4739///
4740const MVT *SDNode::getValueTypeList(MVT VT) {
4741  if (VT.isExtended()) {
4742    static std::set<MVT, MVT::compareRawBits> EVTs;
4743    return &(*EVTs.insert(VT).first);
4744  } else {
4745    static MVT VTs[MVT::LAST_VALUETYPE];
4746    VTs[VT.getSimpleVT()] = VT;
4747    return &VTs[VT.getSimpleVT()];
4748  }
4749}
4750
4751/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4752/// indicated value.  This method ignores uses of other values defined by this
4753/// operation.
4754bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4755  assert(Value < getNumValues() && "Bad value!");
4756
4757  // TODO: Only iterate over uses of a given value of the node
4758  for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4759    if (UI.getUse().getSDValue().getResNo() == Value) {
4760      if (NUses == 0)
4761        return false;
4762      --NUses;
4763    }
4764  }
4765
4766  // Found exactly the right number of uses?
4767  return NUses == 0;
4768}
4769
4770
4771/// hasAnyUseOfValue - Return true if there are any use of the indicated
4772/// value. This method ignores uses of other values defined by this operation.
4773bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4774  assert(Value < getNumValues() && "Bad value!");
4775
4776  for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
4777    if (UI.getUse().getSDValue().getResNo() == Value)
4778      return true;
4779
4780  return false;
4781}
4782
4783
4784/// isOnlyUserOf - Return true if this node is the only use of N.
4785///
4786bool SDNode::isOnlyUserOf(SDNode *N) const {
4787  bool Seen = false;
4788  for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4789    SDNode *User = *I;
4790    if (User == this)
4791      Seen = true;
4792    else
4793      return false;
4794  }
4795
4796  return Seen;
4797}
4798
4799/// isOperand - Return true if this node is an operand of N.
4800///
4801bool SDValue::isOperandOf(SDNode *N) const {
4802  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4803    if (*this == N->getOperand(i))
4804      return true;
4805  return false;
4806}
4807
4808bool SDNode::isOperandOf(SDNode *N) const {
4809  for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4810    if (this == N->OperandList[i].getVal())
4811      return true;
4812  return false;
4813}
4814
4815/// reachesChainWithoutSideEffects - Return true if this operand (which must
4816/// be a chain) reaches the specified operand without crossing any
4817/// side-effecting instructions.  In practice, this looks through token
4818/// factors and non-volatile loads.  In order to remain efficient, this only
4819/// looks a couple of nodes in, it does not do an exhaustive search.
4820bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
4821                                               unsigned Depth) const {
4822  if (*this == Dest) return true;
4823
4824  // Don't search too deeply, we just want to be able to see through
4825  // TokenFactor's etc.
4826  if (Depth == 0) return false;
4827
4828  // If this is a token factor, all inputs to the TF happen in parallel.  If any
4829  // of the operands of the TF reach dest, then we can do the xform.
4830  if (getOpcode() == ISD::TokenFactor) {
4831    for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4832      if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4833        return true;
4834    return false;
4835  }
4836
4837  // Loads don't have side effects, look through them.
4838  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4839    if (!Ld->isVolatile())
4840      return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4841  }
4842  return false;
4843}
4844
4845
4846static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4847                            SmallPtrSet<SDNode *, 32> &Visited) {
4848  if (found || !Visited.insert(N))
4849    return;
4850
4851  for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4852    SDNode *Op = N->getOperand(i).getNode();
4853    if (Op == P) {
4854      found = true;
4855      return;
4856    }
4857    findPredecessor(Op, P, found, Visited);
4858  }
4859}
4860
4861/// isPredecessorOf - Return true if this node is a predecessor of N. This node
4862/// is either an operand of N or it can be reached by recursively traversing
4863/// up the operands.
4864/// NOTE: this is an expensive method. Use it carefully.
4865bool SDNode::isPredecessorOf(SDNode *N) const {
4866  SmallPtrSet<SDNode *, 32> Visited;
4867  bool found = false;
4868  findPredecessor(N, this, found, Visited);
4869  return found;
4870}
4871
4872uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4873  assert(Num < NumOperands && "Invalid child # of SDNode!");
4874  return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
4875}
4876
4877std::string SDNode::getOperationName(const SelectionDAG *G) const {
4878  switch (getOpcode()) {
4879  default:
4880    if (getOpcode() < ISD::BUILTIN_OP_END)
4881      return "<<Unknown DAG Node>>";
4882    if (isMachineOpcode()) {
4883      if (G)
4884        if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4885          if (getMachineOpcode() < TII->getNumOpcodes())
4886            return TII->get(getMachineOpcode()).getName();
4887      return "<<Unknown Machine Node>>";
4888    }
4889    if (G) {
4890      TargetLowering &TLI = G->getTargetLoweringInfo();
4891      const char *Name = TLI.getTargetNodeName(getOpcode());
4892      if (Name) return Name;
4893      return "<<Unknown Target Node>>";
4894    }
4895    return "<<Unknown Node>>";
4896
4897#ifndef NDEBUG
4898  case ISD::DELETED_NODE:
4899    return "<<Deleted Node!>>";
4900#endif
4901  case ISD::PREFETCH:      return "Prefetch";
4902  case ISD::MEMBARRIER:    return "MemBarrier";
4903  case ISD::ATOMIC_CMP_SWAP_8:  return "AtomicCmpSwap8";
4904  case ISD::ATOMIC_SWAP_8:      return "AtomicSwap8";
4905  case ISD::ATOMIC_LOAD_ADD_8:  return "AtomicLoadAdd8";
4906  case ISD::ATOMIC_LOAD_SUB_8:  return "AtomicLoadSub8";
4907  case ISD::ATOMIC_LOAD_AND_8:  return "AtomicLoadAnd8";
4908  case ISD::ATOMIC_LOAD_OR_8:   return "AtomicLoadOr8";
4909  case ISD::ATOMIC_LOAD_XOR_8:  return "AtomicLoadXor8";
4910  case ISD::ATOMIC_LOAD_NAND_8: return "AtomicLoadNand8";
4911  case ISD::ATOMIC_LOAD_MIN_8:  return "AtomicLoadMin8";
4912  case ISD::ATOMIC_LOAD_MAX_8:  return "AtomicLoadMax8";
4913  case ISD::ATOMIC_LOAD_UMIN_8: return "AtomicLoadUMin8";
4914  case ISD::ATOMIC_LOAD_UMAX_8: return "AtomicLoadUMax8";
4915  case ISD::ATOMIC_CMP_SWAP_16:  return "AtomicCmpSwap16";
4916  case ISD::ATOMIC_SWAP_16:      return "AtomicSwap16";
4917  case ISD::ATOMIC_LOAD_ADD_16:  return "AtomicLoadAdd16";
4918  case ISD::ATOMIC_LOAD_SUB_16:  return "AtomicLoadSub16";
4919  case ISD::ATOMIC_LOAD_AND_16:  return "AtomicLoadAnd16";
4920  case ISD::ATOMIC_LOAD_OR_16:   return "AtomicLoadOr16";
4921  case ISD::ATOMIC_LOAD_XOR_16:  return "AtomicLoadXor16";
4922  case ISD::ATOMIC_LOAD_NAND_16: return "AtomicLoadNand16";
4923  case ISD::ATOMIC_LOAD_MIN_16:  return "AtomicLoadMin16";
4924  case ISD::ATOMIC_LOAD_MAX_16:  return "AtomicLoadMax16";
4925  case ISD::ATOMIC_LOAD_UMIN_16: return "AtomicLoadUMin16";
4926  case ISD::ATOMIC_LOAD_UMAX_16: return "AtomicLoadUMax16";
4927  case ISD::ATOMIC_CMP_SWAP_32:  return "AtomicCmpSwap32";
4928  case ISD::ATOMIC_SWAP_32:      return "AtomicSwap32";
4929  case ISD::ATOMIC_LOAD_ADD_32:  return "AtomicLoadAdd32";
4930  case ISD::ATOMIC_LOAD_SUB_32:  return "AtomicLoadSub32";
4931  case ISD::ATOMIC_LOAD_AND_32:  return "AtomicLoadAnd32";
4932  case ISD::ATOMIC_LOAD_OR_32:   return "AtomicLoadOr32";
4933  case ISD::ATOMIC_LOAD_XOR_32:  return "AtomicLoadXor32";
4934  case ISD::ATOMIC_LOAD_NAND_32: return "AtomicLoadNand32";
4935  case ISD::ATOMIC_LOAD_MIN_32:  return "AtomicLoadMin32";
4936  case ISD::ATOMIC_LOAD_MAX_32:  return "AtomicLoadMax32";
4937  case ISD::ATOMIC_LOAD_UMIN_32: return "AtomicLoadUMin32";
4938  case ISD::ATOMIC_LOAD_UMAX_32: return "AtomicLoadUMax32";
4939  case ISD::ATOMIC_CMP_SWAP_64:  return "AtomicCmpSwap64";
4940  case ISD::ATOMIC_SWAP_64:      return "AtomicSwap64";
4941  case ISD::ATOMIC_LOAD_ADD_64:  return "AtomicLoadAdd64";
4942  case ISD::ATOMIC_LOAD_SUB_64:  return "AtomicLoadSub64";
4943  case ISD::ATOMIC_LOAD_AND_64:  return "AtomicLoadAnd64";
4944  case ISD::ATOMIC_LOAD_OR_64:   return "AtomicLoadOr64";
4945  case ISD::ATOMIC_LOAD_XOR_64:  return "AtomicLoadXor64";
4946  case ISD::ATOMIC_LOAD_NAND_64: return "AtomicLoadNand64";
4947  case ISD::ATOMIC_LOAD_MIN_64:  return "AtomicLoadMin64";
4948  case ISD::ATOMIC_LOAD_MAX_64:  return "AtomicLoadMax64";
4949  case ISD::ATOMIC_LOAD_UMIN_64: return "AtomicLoadUMin64";
4950  case ISD::ATOMIC_LOAD_UMAX_64: return "AtomicLoadUMax64";
4951  case ISD::PCMARKER:      return "PCMarker";
4952  case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4953  case ISD::SRCVALUE:      return "SrcValue";
4954  case ISD::MEMOPERAND:    return "MemOperand";
4955  case ISD::EntryToken:    return "EntryToken";
4956  case ISD::TokenFactor:   return "TokenFactor";
4957  case ISD::AssertSext:    return "AssertSext";
4958  case ISD::AssertZext:    return "AssertZext";
4959
4960  case ISD::BasicBlock:    return "BasicBlock";
4961  case ISD::ARG_FLAGS:     return "ArgFlags";
4962  case ISD::VALUETYPE:     return "ValueType";
4963  case ISD::Register:      return "Register";
4964
4965  case ISD::Constant:      return "Constant";
4966  case ISD::ConstantFP:    return "ConstantFP";
4967  case ISD::GlobalAddress: return "GlobalAddress";
4968  case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4969  case ISD::FrameIndex:    return "FrameIndex";
4970  case ISD::JumpTable:     return "JumpTable";
4971  case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4972  case ISD::RETURNADDR: return "RETURNADDR";
4973  case ISD::FRAMEADDR: return "FRAMEADDR";
4974  case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4975  case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4976  case ISD::EHSELECTION: return "EHSELECTION";
4977  case ISD::EH_RETURN: return "EH_RETURN";
4978  case ISD::ConstantPool:  return "ConstantPool";
4979  case ISD::ExternalSymbol: return "ExternalSymbol";
4980  case ISD::INTRINSIC_WO_CHAIN: {
4981    unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue();
4982    return Intrinsic::getName((Intrinsic::ID)IID);
4983  }
4984  case ISD::INTRINSIC_VOID:
4985  case ISD::INTRINSIC_W_CHAIN: {
4986    unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue();
4987    return Intrinsic::getName((Intrinsic::ID)IID);
4988  }
4989
4990  case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
4991  case ISD::TargetConstant: return "TargetConstant";
4992  case ISD::TargetConstantFP:return "TargetConstantFP";
4993  case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4994  case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4995  case ISD::TargetFrameIndex: return "TargetFrameIndex";
4996  case ISD::TargetJumpTable:  return "TargetJumpTable";
4997  case ISD::TargetConstantPool:  return "TargetConstantPool";
4998  case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4999
5000  case ISD::CopyToReg:     return "CopyToReg";
5001  case ISD::CopyFromReg:   return "CopyFromReg";
5002  case ISD::UNDEF:         return "undef";
5003  case ISD::MERGE_VALUES:  return "merge_values";
5004  case ISD::INLINEASM:     return "inlineasm";
5005  case ISD::DBG_LABEL:     return "dbg_label";
5006  case ISD::EH_LABEL:      return "eh_label";
5007  case ISD::DECLARE:       return "declare";
5008  case ISD::HANDLENODE:    return "handlenode";
5009  case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
5010  case ISD::CALL:          return "call";
5011
5012  // Unary operators
5013  case ISD::FABS:   return "fabs";
5014  case ISD::FNEG:   return "fneg";
5015  case ISD::FSQRT:  return "fsqrt";
5016  case ISD::FSIN:   return "fsin";
5017  case ISD::FCOS:   return "fcos";
5018  case ISD::FPOWI:  return "fpowi";
5019  case ISD::FPOW:   return "fpow";
5020  case ISD::FTRUNC: return "ftrunc";
5021  case ISD::FFLOOR: return "ffloor";
5022  case ISD::FCEIL:  return "fceil";
5023  case ISD::FRINT:  return "frint";
5024  case ISD::FNEARBYINT: return "fnearbyint";
5025
5026  // Binary operators
5027  case ISD::ADD:    return "add";
5028  case ISD::SUB:    return "sub";
5029  case ISD::MUL:    return "mul";
5030  case ISD::MULHU:  return "mulhu";
5031  case ISD::MULHS:  return "mulhs";
5032  case ISD::SDIV:   return "sdiv";
5033  case ISD::UDIV:   return "udiv";
5034  case ISD::SREM:   return "srem";
5035  case ISD::UREM:   return "urem";
5036  case ISD::SMUL_LOHI:  return "smul_lohi";
5037  case ISD::UMUL_LOHI:  return "umul_lohi";
5038  case ISD::SDIVREM:    return "sdivrem";
5039  case ISD::UDIVREM:    return "udivrem";
5040  case ISD::AND:    return "and";
5041  case ISD::OR:     return "or";
5042  case ISD::XOR:    return "xor";
5043  case ISD::SHL:    return "shl";
5044  case ISD::SRA:    return "sra";
5045  case ISD::SRL:    return "srl";
5046  case ISD::ROTL:   return "rotl";
5047  case ISD::ROTR:   return "rotr";
5048  case ISD::FADD:   return "fadd";
5049  case ISD::FSUB:   return "fsub";
5050  case ISD::FMUL:   return "fmul";
5051  case ISD::FDIV:   return "fdiv";
5052  case ISD::FREM:   return "frem";
5053  case ISD::FCOPYSIGN: return "fcopysign";
5054  case ISD::FGETSIGN:  return "fgetsign";
5055
5056  case ISD::SETCC:       return "setcc";
5057  case ISD::VSETCC:      return "vsetcc";
5058  case ISD::SELECT:      return "select";
5059  case ISD::SELECT_CC:   return "select_cc";
5060  case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
5061  case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
5062  case ISD::CONCAT_VECTORS:      return "concat_vectors";
5063  case ISD::EXTRACT_SUBVECTOR:   return "extract_subvector";
5064  case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
5065  case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
5066  case ISD::CARRY_FALSE:         return "carry_false";
5067  case ISD::ADDC:        return "addc";
5068  case ISD::ADDE:        return "adde";
5069  case ISD::SUBC:        return "subc";
5070  case ISD::SUBE:        return "sube";
5071  case ISD::SHL_PARTS:   return "shl_parts";
5072  case ISD::SRA_PARTS:   return "sra_parts";
5073  case ISD::SRL_PARTS:   return "srl_parts";
5074
5075  case ISD::EXTRACT_SUBREG:     return "extract_subreg";
5076  case ISD::INSERT_SUBREG:      return "insert_subreg";
5077
5078  // Conversion operators.
5079  case ISD::SIGN_EXTEND: return "sign_extend";
5080  case ISD::ZERO_EXTEND: return "zero_extend";
5081  case ISD::ANY_EXTEND:  return "any_extend";
5082  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5083  case ISD::TRUNCATE:    return "truncate";
5084  case ISD::FP_ROUND:    return "fp_round";
5085  case ISD::FLT_ROUNDS_: return "flt_rounds";
5086  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5087  case ISD::FP_EXTEND:   return "fp_extend";
5088
5089  case ISD::SINT_TO_FP:  return "sint_to_fp";
5090  case ISD::UINT_TO_FP:  return "uint_to_fp";
5091  case ISD::FP_TO_SINT:  return "fp_to_sint";
5092  case ISD::FP_TO_UINT:  return "fp_to_uint";
5093  case ISD::BIT_CONVERT: return "bit_convert";
5094
5095    // Control flow instructions
5096  case ISD::BR:      return "br";
5097  case ISD::BRIND:   return "brind";
5098  case ISD::BR_JT:   return "br_jt";
5099  case ISD::BRCOND:  return "brcond";
5100  case ISD::BR_CC:   return "br_cc";
5101  case ISD::RET:     return "ret";
5102  case ISD::CALLSEQ_START:  return "callseq_start";
5103  case ISD::CALLSEQ_END:    return "callseq_end";
5104
5105    // Other operators
5106  case ISD::LOAD:               return "load";
5107  case ISD::STORE:              return "store";
5108  case ISD::VAARG:              return "vaarg";
5109  case ISD::VACOPY:             return "vacopy";
5110  case ISD::VAEND:              return "vaend";
5111  case ISD::VASTART:            return "vastart";
5112  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5113  case ISD::EXTRACT_ELEMENT:    return "extract_element";
5114  case ISD::BUILD_PAIR:         return "build_pair";
5115  case ISD::STACKSAVE:          return "stacksave";
5116  case ISD::STACKRESTORE:       return "stackrestore";
5117  case ISD::TRAP:               return "trap";
5118
5119  // Bit manipulation
5120  case ISD::BSWAP:   return "bswap";
5121  case ISD::CTPOP:   return "ctpop";
5122  case ISD::CTTZ:    return "cttz";
5123  case ISD::CTLZ:    return "ctlz";
5124
5125  // Debug info
5126  case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
5127  case ISD::DEBUG_LOC: return "debug_loc";
5128
5129  // Trampolines
5130  case ISD::TRAMPOLINE: return "trampoline";
5131
5132  case ISD::CONDCODE:
5133    switch (cast<CondCodeSDNode>(this)->get()) {
5134    default: assert(0 && "Unknown setcc condition!");
5135    case ISD::SETOEQ:  return "setoeq";
5136    case ISD::SETOGT:  return "setogt";
5137    case ISD::SETOGE:  return "setoge";
5138    case ISD::SETOLT:  return "setolt";
5139    case ISD::SETOLE:  return "setole";
5140    case ISD::SETONE:  return "setone";
5141
5142    case ISD::SETO:    return "seto";
5143    case ISD::SETUO:   return "setuo";
5144    case ISD::SETUEQ:  return "setue";
5145    case ISD::SETUGT:  return "setugt";
5146    case ISD::SETUGE:  return "setuge";
5147    case ISD::SETULT:  return "setult";
5148    case ISD::SETULE:  return "setule";
5149    case ISD::SETUNE:  return "setune";
5150
5151    case ISD::SETEQ:   return "seteq";
5152    case ISD::SETGT:   return "setgt";
5153    case ISD::SETGE:   return "setge";
5154    case ISD::SETLT:   return "setlt";
5155    case ISD::SETLE:   return "setle";
5156    case ISD::SETNE:   return "setne";
5157    }
5158  }
5159}
5160
5161const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5162  switch (AM) {
5163  default:
5164    return "";
5165  case ISD::PRE_INC:
5166    return "<pre-inc>";
5167  case ISD::PRE_DEC:
5168    return "<pre-dec>";
5169  case ISD::POST_INC:
5170    return "<post-inc>";
5171  case ISD::POST_DEC:
5172    return "<post-dec>";
5173  }
5174}
5175
5176std::string ISD::ArgFlagsTy::getArgFlagsString() {
5177  std::string S = "< ";
5178
5179  if (isZExt())
5180    S += "zext ";
5181  if (isSExt())
5182    S += "sext ";
5183  if (isInReg())
5184    S += "inreg ";
5185  if (isSRet())
5186    S += "sret ";
5187  if (isByVal())
5188    S += "byval ";
5189  if (isNest())
5190    S += "nest ";
5191  if (getByValAlign())
5192    S += "byval-align:" + utostr(getByValAlign()) + " ";
5193  if (getOrigAlign())
5194    S += "orig-align:" + utostr(getOrigAlign()) + " ";
5195  if (getByValSize())
5196    S += "byval-size:" + utostr(getByValSize()) + " ";
5197  return S + ">";
5198}
5199
5200void SDNode::dump() const { dump(0); }
5201void SDNode::dump(const SelectionDAG *G) const {
5202  print(errs(), G);
5203  errs().flush();
5204}
5205
5206void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5207  OS << (void*)this << ": ";
5208
5209  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5210    if (i) OS << ",";
5211    if (getValueType(i) == MVT::Other)
5212      OS << "ch";
5213    else
5214      OS << getValueType(i).getMVTString();
5215  }
5216  OS << " = " << getOperationName(G);
5217
5218  OS << " ";
5219  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5220    if (i) OS << ", ";
5221    OS << (void*)getOperand(i).getNode();
5222    if (unsigned RN = getOperand(i).getResNo())
5223      OS << ":" << RN;
5224  }
5225
5226  if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
5227    SDNode *Mask = getOperand(2).getNode();
5228    OS << "<";
5229    for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
5230      if (i) OS << ",";
5231      if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
5232        OS << "u";
5233      else
5234        OS << cast<ConstantSDNode>(Mask->getOperand(i))->getZExtValue();
5235    }
5236    OS << ">";
5237  }
5238
5239  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5240    OS << '<' << CSDN->getAPIntValue() << '>';
5241  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5242    if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5243      OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5244    else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5245      OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5246    else {
5247      OS << "<APFloat(";
5248      CSDN->getValueAPF().convertToAPInt().dump();
5249      OS << ")>";
5250    }
5251  } else if (const GlobalAddressSDNode *GADN =
5252             dyn_cast<GlobalAddressSDNode>(this)) {
5253    int offset = GADN->getOffset();
5254    OS << '<';
5255    WriteAsOperand(OS, GADN->getGlobal());
5256    OS << '>';
5257    if (offset > 0)
5258      OS << " + " << offset;
5259    else
5260      OS << " " << offset;
5261  } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5262    OS << "<" << FIDN->getIndex() << ">";
5263  } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5264    OS << "<" << JTDN->getIndex() << ">";
5265  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5266    int offset = CP->getOffset();
5267    if (CP->isMachineConstantPoolEntry())
5268      OS << "<" << *CP->getMachineCPVal() << ">";
5269    else
5270      OS << "<" << *CP->getConstVal() << ">";
5271    if (offset > 0)
5272      OS << " + " << offset;
5273    else
5274      OS << " " << offset;
5275  } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5276    OS << "<";
5277    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5278    if (LBB)
5279      OS << LBB->getName() << " ";
5280    OS << (const void*)BBDN->getBasicBlock() << ">";
5281  } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5282    if (G && R->getReg() &&
5283        TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5284      OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5285    } else {
5286      OS << " #" << R->getReg();
5287    }
5288  } else if (const ExternalSymbolSDNode *ES =
5289             dyn_cast<ExternalSymbolSDNode>(this)) {
5290    OS << "'" << ES->getSymbol() << "'";
5291  } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5292    if (M->getValue())
5293      OS << "<" << M->getValue() << ">";
5294    else
5295      OS << "<null>";
5296  } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
5297    if (M->MO.getValue())
5298      OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
5299    else
5300      OS << "<null:" << M->MO.getOffset() << ">";
5301  } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
5302    OS << N->getArgFlags().getArgFlagsString();
5303  } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5304    OS << ":" << N->getVT().getMVTString();
5305  }
5306  else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5307    const Value *SrcValue = LD->getSrcValue();
5308    int SrcOffset = LD->getSrcValueOffset();
5309    OS << " <";
5310    if (SrcValue)
5311      OS << SrcValue;
5312    else
5313      OS << "null";
5314    OS << ":" << SrcOffset << ">";
5315
5316    bool doExt = true;
5317    switch (LD->getExtensionType()) {
5318    default: doExt = false; break;
5319    case ISD::EXTLOAD: OS << " <anyext "; break;
5320    case ISD::SEXTLOAD: OS << " <sext "; break;
5321    case ISD::ZEXTLOAD: OS << " <zext "; break;
5322    }
5323    if (doExt)
5324      OS << LD->getMemoryVT().getMVTString() << ">";
5325
5326    const char *AM = getIndexedModeName(LD->getAddressingMode());
5327    if (*AM)
5328      OS << " " << AM;
5329    if (LD->isVolatile())
5330      OS << " <volatile>";
5331    OS << " alignment=" << LD->getAlignment();
5332  } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5333    const Value *SrcValue = ST->getSrcValue();
5334    int SrcOffset = ST->getSrcValueOffset();
5335    OS << " <";
5336    if (SrcValue)
5337      OS << SrcValue;
5338    else
5339      OS << "null";
5340    OS << ":" << SrcOffset << ">";
5341
5342    if (ST->isTruncatingStore())
5343      OS << " <trunc " << ST->getMemoryVT().getMVTString() << ">";
5344
5345    const char *AM = getIndexedModeName(ST->getAddressingMode());
5346    if (*AM)
5347      OS << " " << AM;
5348    if (ST->isVolatile())
5349      OS << " <volatile>";
5350    OS << " alignment=" << ST->getAlignment();
5351  } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
5352    const Value *SrcValue = AT->getSrcValue();
5353    int SrcOffset = AT->getSrcValueOffset();
5354    OS << " <";
5355    if (SrcValue)
5356      OS << SrcValue;
5357    else
5358      OS << "null";
5359    OS << ":" << SrcOffset << ">";
5360    if (AT->isVolatile())
5361      OS << " <volatile>";
5362    OS << " alignment=" << AT->getAlignment();
5363  }
5364}
5365
5366static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5367  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5368    if (N->getOperand(i).getNode()->hasOneUse())
5369      DumpNodes(N->getOperand(i).getNode(), indent+2, G);
5370    else
5371      cerr << "\n" << std::string(indent+2, ' ')
5372           << (void*)N->getOperand(i).getNode() << ": <multiple use>";
5373
5374
5375  cerr << "\n" << std::string(indent, ' ');
5376  N->dump(G);
5377}
5378
5379void SelectionDAG::dump() const {
5380  cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
5381
5382  for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5383       I != E; ++I) {
5384    const SDNode *N = I;
5385    if (!N->hasOneUse() && N != getRoot().getNode())
5386      DumpNodes(N, 2, this);
5387  }
5388
5389  if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
5390
5391  cerr << "\n\n";
5392}
5393
5394const Type *ConstantPoolSDNode::getType() const {
5395  if (isMachineConstantPoolEntry())
5396    return Val.MachineCPVal->getType();
5397  return Val.ConstVal->getType();
5398}
5399