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