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