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