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