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