SelectionDAG.cpp revision 28b5b1c7b54c2065882b98af2406c38a3bcee802
1//===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAG class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/SelectionDAG.h"
15#include "llvm/Constants.h"
16#include "llvm/GlobalValue.h"
17#include "llvm/Assembly/Writer.h"
18#include "llvm/CodeGen/MachineBasicBlock.h"
19#include "llvm/Support/MathExtras.h"
20#include "llvm/Target/MRegisterInfo.h"
21#include "llvm/Target/TargetLowering.h"
22#include "llvm/Target/TargetInstrInfo.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/ADT/SetVector.h"
25#include "llvm/ADT/StringExtras.h"
26#include <iostream>
27#include <set>
28#include <cmath>
29#include <algorithm>
30using namespace llvm;
31
32static bool isCommutativeBinOp(unsigned Opcode) {
33  switch (Opcode) {
34  case ISD::ADD:
35  case ISD::MUL:
36  case ISD::MULHU:
37  case ISD::MULHS:
38  case ISD::FADD:
39  case ISD::FMUL:
40  case ISD::AND:
41  case ISD::OR:
42  case ISD::XOR: return true;
43  default: return false; // FIXME: Need commutative info for user ops!
44  }
45}
46
47// isInvertibleForFree - Return true if there is no cost to emitting the logical
48// inverse of this node.
49static bool isInvertibleForFree(SDOperand N) {
50  if (isa<ConstantSDNode>(N.Val)) return true;
51  if (N.Val->getOpcode() == ISD::SETCC && N.Val->hasOneUse())
52    return true;
53  return false;
54}
55
56//===----------------------------------------------------------------------===//
57//                              ConstantFPSDNode Class
58//===----------------------------------------------------------------------===//
59
60/// isExactlyValue - We don't rely on operator== working on double values, as
61/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
62/// As such, this method can be used to do an exact bit-for-bit comparison of
63/// two floating point values.
64bool ConstantFPSDNode::isExactlyValue(double V) const {
65  return DoubleToBits(V) == DoubleToBits(Value);
66}
67
68//===----------------------------------------------------------------------===//
69//                              ISD Class
70//===----------------------------------------------------------------------===//
71
72/// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
73/// when given the operation for (X op Y).
74ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
75  // To perform this operation, we just need to swap the L and G bits of the
76  // operation.
77  unsigned OldL = (Operation >> 2) & 1;
78  unsigned OldG = (Operation >> 1) & 1;
79  return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
80                       (OldL << 1) |       // New G bit
81                       (OldG << 2));        // New L bit.
82}
83
84/// getSetCCInverse - Return the operation corresponding to !(X op Y), where
85/// 'op' is a valid SetCC operation.
86ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
87  unsigned Operation = Op;
88  if (isInteger)
89    Operation ^= 7;   // Flip L, G, E bits, but not U.
90  else
91    Operation ^= 15;  // Flip all of the condition bits.
92  if (Operation > ISD::SETTRUE2)
93    Operation &= ~8;     // Don't let N and U bits get set.
94  return ISD::CondCode(Operation);
95}
96
97
98/// isSignedOp - For an integer comparison, return 1 if the comparison is a
99/// signed operation and 2 if the result is an unsigned comparison.  Return zero
100/// if the operation does not depend on the sign of the input (setne and seteq).
101static int isSignedOp(ISD::CondCode Opcode) {
102  switch (Opcode) {
103  default: assert(0 && "Illegal integer setcc operation!");
104  case ISD::SETEQ:
105  case ISD::SETNE: return 0;
106  case ISD::SETLT:
107  case ISD::SETLE:
108  case ISD::SETGT:
109  case ISD::SETGE: return 1;
110  case ISD::SETULT:
111  case ISD::SETULE:
112  case ISD::SETUGT:
113  case ISD::SETUGE: return 2;
114  }
115}
116
117/// getSetCCOrOperation - Return the result of a logical OR between different
118/// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
119/// returns SETCC_INVALID if it is not possible to represent the resultant
120/// comparison.
121ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
122                                       bool isInteger) {
123  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
124    // Cannot fold a signed integer setcc with an unsigned integer setcc.
125    return ISD::SETCC_INVALID;
126
127  unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
128
129  // If the N and U bits get set then the resultant comparison DOES suddenly
130  // care about orderedness, and is true when ordered.
131  if (Op > ISD::SETTRUE2)
132    Op &= ~16;     // Clear the N bit.
133  return ISD::CondCode(Op);
134}
135
136/// getSetCCAndOperation - Return the result of a logical AND between different
137/// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
138/// function returns zero if it is not possible to represent the resultant
139/// comparison.
140ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
141                                        bool isInteger) {
142  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
143    // Cannot fold a signed setcc with an unsigned setcc.
144    return ISD::SETCC_INVALID;
145
146  // Combine all of the condition bits.
147  return ISD::CondCode(Op1 & Op2);
148}
149
150const TargetMachine &SelectionDAG::getTarget() const {
151  return TLI.getTargetMachine();
152}
153
154//===----------------------------------------------------------------------===//
155//                              SelectionDAG Class
156//===----------------------------------------------------------------------===//
157
158/// RemoveDeadNodes - This method deletes all unreachable nodes in the
159/// SelectionDAG, including nodes (like loads) that have uses of their token
160/// chain but no other uses and no side effect.  If a node is passed in as an
161/// argument, it is used as the seed for node deletion.
162void SelectionDAG::RemoveDeadNodes(SDNode *N) {
163  // Create a dummy node (which is not added to allnodes), that adds a reference
164  // to the root node, preventing it from being deleted.
165  HandleSDNode Dummy(getRoot());
166
167  bool MadeChange = false;
168
169  // If we have a hint to start from, use it.
170  if (N && N->use_empty()) {
171    DestroyDeadNode(N);
172    MadeChange = true;
173  }
174
175  for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
176    if (I->use_empty() && I->getOpcode() != 65535) {
177      // Node is dead, recursively delete newly dead uses.
178      DestroyDeadNode(I);
179      MadeChange = true;
180    }
181
182  // Walk the nodes list, removing the nodes we've marked as dead.
183  if (MadeChange) {
184    for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ) {
185      SDNode *N = I++;
186      if (N->use_empty())
187        AllNodes.erase(N);
188    }
189  }
190
191  // If the root changed (e.g. it was a dead load, update the root).
192  setRoot(Dummy.getValue());
193}
194
195/// DestroyDeadNode - We know that N is dead.  Nuke it from the CSE maps for the
196/// graph.  If it is the last user of any of its operands, recursively process
197/// them the same way.
198///
199void SelectionDAG::DestroyDeadNode(SDNode *N) {
200  // Okay, we really are going to delete this node.  First take this out of the
201  // appropriate CSE map.
202  RemoveNodeFromCSEMaps(N);
203
204  // Next, brutally remove the operand list.  This is safe to do, as there are
205  // no cycles in the graph.
206  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
207    SDNode *O = I->Val;
208    O->removeUser(N);
209
210    // Now that we removed this operand, see if there are no uses of it left.
211    if (O->use_empty())
212      DestroyDeadNode(O);
213  }
214  delete[] N->OperandList;
215  N->OperandList = 0;
216  N->NumOperands = 0;
217
218  // Mark the node as dead.
219  N->MorphNodeTo(65535);
220}
221
222void SelectionDAG::DeleteNode(SDNode *N) {
223  assert(N->use_empty() && "Cannot delete a node that is not dead!");
224
225  // First take this out of the appropriate CSE map.
226  RemoveNodeFromCSEMaps(N);
227
228  // Finally, remove uses due to operands of this node, remove from the
229  // AllNodes list, and delete the node.
230  DeleteNodeNotInCSEMaps(N);
231}
232
233void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
234
235  // Remove it from the AllNodes list.
236  AllNodes.remove(N);
237
238  // Drop all of the operands and decrement used nodes use counts.
239  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
240    I->Val->removeUser(N);
241  delete[] N->OperandList;
242  N->OperandList = 0;
243  N->NumOperands = 0;
244
245  delete N;
246}
247
248/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
249/// correspond to it.  This is useful when we're about to delete or repurpose
250/// the node.  We don't want future request for structurally identical nodes
251/// to return N anymore.
252void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
253  bool Erased = false;
254  switch (N->getOpcode()) {
255  case ISD::HANDLENODE: return;  // noop.
256  case ISD::Constant:
257    Erased = Constants.erase(std::make_pair(cast<ConstantSDNode>(N)->getValue(),
258                                            N->getValueType(0)));
259    break;
260  case ISD::TargetConstant:
261    Erased = TargetConstants.erase(std::make_pair(
262                                    cast<ConstantSDNode>(N)->getValue(),
263                                                  N->getValueType(0)));
264    break;
265  case ISD::ConstantFP: {
266    uint64_t V = DoubleToBits(cast<ConstantFPSDNode>(N)->getValue());
267    Erased = ConstantFPs.erase(std::make_pair(V, N->getValueType(0)));
268    break;
269  }
270  case ISD::TargetConstantFP: {
271    uint64_t V = DoubleToBits(cast<ConstantFPSDNode>(N)->getValue());
272    Erased = TargetConstantFPs.erase(std::make_pair(V, N->getValueType(0)));
273    break;
274  }
275  case ISD::STRING:
276    Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
277    break;
278  case ISD::CONDCODE:
279    assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
280           "Cond code doesn't exist!");
281    Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
282    CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
283    break;
284  case ISD::GlobalAddress: {
285    GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(N);
286    Erased = GlobalValues.erase(std::make_pair(GN->getGlobal(),
287                                               GN->getOffset()));
288    break;
289  }
290  case ISD::TargetGlobalAddress: {
291    GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(N);
292    Erased =TargetGlobalValues.erase(std::make_pair(GN->getGlobal(),
293                                                    GN->getOffset()));
294    break;
295  }
296  case ISD::FrameIndex:
297    Erased = FrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
298    break;
299  case ISD::TargetFrameIndex:
300    Erased = TargetFrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
301    break;
302  case ISD::ConstantPool:
303    Erased = ConstantPoolIndices.
304      erase(std::make_pair(cast<ConstantPoolSDNode>(N)->get(),
305                        std::make_pair(cast<ConstantPoolSDNode>(N)->getOffset(),
306                                 cast<ConstantPoolSDNode>(N)->getAlignment())));
307    break;
308  case ISD::TargetConstantPool:
309    Erased = TargetConstantPoolIndices.
310      erase(std::make_pair(cast<ConstantPoolSDNode>(N)->get(),
311                        std::make_pair(cast<ConstantPoolSDNode>(N)->getOffset(),
312                                 cast<ConstantPoolSDNode>(N)->getAlignment())));
313    break;
314  case ISD::BasicBlock:
315    Erased = BBNodes.erase(cast<BasicBlockSDNode>(N)->getBasicBlock());
316    break;
317  case ISD::ExternalSymbol:
318    Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
319    break;
320  case ISD::TargetExternalSymbol:
321    Erased =
322      TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
323    break;
324  case ISD::VALUETYPE:
325    Erased = ValueTypeNodes[cast<VTSDNode>(N)->getVT()] != 0;
326    ValueTypeNodes[cast<VTSDNode>(N)->getVT()] = 0;
327    break;
328  case ISD::Register:
329    Erased = RegNodes.erase(std::make_pair(cast<RegisterSDNode>(N)->getReg(),
330                                           N->getValueType(0)));
331    break;
332  case ISD::SRCVALUE: {
333    SrcValueSDNode *SVN = cast<SrcValueSDNode>(N);
334    Erased =ValueNodes.erase(std::make_pair(SVN->getValue(), SVN->getOffset()));
335    break;
336  }
337  case ISD::LOAD:
338    Erased = Loads.erase(std::make_pair(N->getOperand(1),
339                                        std::make_pair(N->getOperand(0),
340                                                       N->getValueType(0))));
341    break;
342  default:
343    if (N->getNumValues() == 1) {
344      if (N->getNumOperands() == 0) {
345        Erased = NullaryOps.erase(std::make_pair(N->getOpcode(),
346                                                 N->getValueType(0)));
347      } else if (N->getNumOperands() == 1) {
348        Erased =
349          UnaryOps.erase(std::make_pair(N->getOpcode(),
350                                        std::make_pair(N->getOperand(0),
351                                                       N->getValueType(0))));
352      } else if (N->getNumOperands() == 2) {
353        Erased =
354          BinaryOps.erase(std::make_pair(N->getOpcode(),
355                                         std::make_pair(N->getOperand(0),
356                                                        N->getOperand(1))));
357      } else {
358        std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
359        Erased =
360          OneResultNodes.erase(std::make_pair(N->getOpcode(),
361                                              std::make_pair(N->getValueType(0),
362                                                             Ops)));
363      }
364    } else {
365      // Remove the node from the ArbitraryNodes map.
366      std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
367      std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
368      Erased =
369        ArbitraryNodes.erase(std::make_pair(N->getOpcode(),
370                                            std::make_pair(RV, Ops)));
371    }
372    break;
373  }
374#ifndef NDEBUG
375  // Verify that the node was actually in one of the CSE maps, unless it has a
376  // flag result (which cannot be CSE'd) or is one of the special cases that are
377  // not subject to CSE.
378  if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
379      !N->isTargetOpcode()) {
380    N->dump();
381    assert(0 && "Node is not in map!");
382  }
383#endif
384}
385
386/// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
387/// has been taken out and modified in some way.  If the specified node already
388/// exists in the CSE maps, do not modify the maps, but return the existing node
389/// instead.  If it doesn't exist, add it and return null.
390///
391SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
392  assert(N->getNumOperands() && "This is a leaf node!");
393  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
394    return 0;    // Never add these nodes.
395
396  // Check that remaining values produced are not flags.
397  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
398    if (N->getValueType(i) == MVT::Flag)
399      return 0;   // Never CSE anything that produces a flag.
400
401  if (N->getNumValues() == 1) {
402    if (N->getNumOperands() == 1) {
403      SDNode *&U = UnaryOps[std::make_pair(N->getOpcode(),
404                                           std::make_pair(N->getOperand(0),
405                                                          N->getValueType(0)))];
406      if (U) return U;
407      U = N;
408    } else if (N->getNumOperands() == 2) {
409      SDNode *&B = BinaryOps[std::make_pair(N->getOpcode(),
410                                            std::make_pair(N->getOperand(0),
411                                                           N->getOperand(1)))];
412      if (B) return B;
413      B = N;
414    } else {
415      std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
416      SDNode *&ORN = OneResultNodes[std::make_pair(N->getOpcode(),
417                                      std::make_pair(N->getValueType(0), Ops))];
418      if (ORN) return ORN;
419      ORN = N;
420    }
421  } else {
422    if (N->getOpcode() == ISD::LOAD) {
423      SDNode *&L = Loads[std::make_pair(N->getOperand(1),
424                                        std::make_pair(N->getOperand(0),
425                                                       N->getValueType(0)))];
426      if (L) return L;
427      L = N;
428    } else {
429      // Remove the node from the ArbitraryNodes map.
430      std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
431      std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
432      SDNode *&AN = ArbitraryNodes[std::make_pair(N->getOpcode(),
433                                                  std::make_pair(RV, Ops))];
434      if (AN) return AN;
435      AN = N;
436    }
437  }
438  return 0;
439}
440
441/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
442/// were replaced with those specified.  If this node is never memoized,
443/// return null, otherwise return a pointer to the slot it would take.  If a
444/// node already exists with these operands, the slot will be non-null.
445SDNode **SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op) {
446  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
447    return 0;    // Never add these nodes.
448
449  // Check that remaining values produced are not flags.
450  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
451    if (N->getValueType(i) == MVT::Flag)
452      return 0;   // Never CSE anything that produces a flag.
453
454  if (N->getNumValues() == 1) {
455    return &UnaryOps[std::make_pair(N->getOpcode(),
456                                    std::make_pair(Op, N->getValueType(0)))];
457  } else {
458    // Remove the node from the ArbitraryNodes map.
459    std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
460    std::vector<SDOperand> Ops;
461    Ops.push_back(Op);
462    return &ArbitraryNodes[std::make_pair(N->getOpcode(),
463                                          std::make_pair(RV, Ops))];
464  }
465  return 0;
466}
467
468/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
469/// were replaced with those specified.  If this node is never memoized,
470/// return null, otherwise return a pointer to the slot it would take.  If a
471/// node already exists with these operands, the slot will be non-null.
472SDNode **SelectionDAG::FindModifiedNodeSlot(SDNode *N,
473                                            SDOperand Op1, SDOperand Op2) {
474  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
475    return 0;    // Never add these nodes.
476
477  // Check that remaining values produced are not flags.
478  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
479    if (N->getValueType(i) == MVT::Flag)
480      return 0;   // Never CSE anything that produces a flag.
481
482  if (N->getNumValues() == 1) {
483    return &BinaryOps[std::make_pair(N->getOpcode(),
484                                     std::make_pair(Op1, Op2))];
485  } else {
486    std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
487    std::vector<SDOperand> Ops;
488    Ops.push_back(Op1);
489    Ops.push_back(Op2);
490    return &ArbitraryNodes[std::make_pair(N->getOpcode(),
491                                          std::make_pair(RV, Ops))];
492  }
493  return 0;
494}
495
496
497/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
498/// were replaced with those specified.  If this node is never memoized,
499/// return null, otherwise return a pointer to the slot it would take.  If a
500/// node already exists with these operands, the slot will be non-null.
501SDNode **SelectionDAG::FindModifiedNodeSlot(SDNode *N,
502                                            const std::vector<SDOperand> &Ops) {
503  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
504    return 0;    // Never add these nodes.
505
506  // Check that remaining values produced are not flags.
507  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
508    if (N->getValueType(i) == MVT::Flag)
509      return 0;   // Never CSE anything that produces a flag.
510
511  if (N->getNumValues() == 1) {
512    if (N->getNumOperands() == 1) {
513      return &UnaryOps[std::make_pair(N->getOpcode(),
514                                      std::make_pair(Ops[0],
515                                                     N->getValueType(0)))];
516    } else if (N->getNumOperands() == 2) {
517      return &BinaryOps[std::make_pair(N->getOpcode(),
518                                       std::make_pair(Ops[0], Ops[1]))];
519    } else {
520      return &OneResultNodes[std::make_pair(N->getOpcode(),
521                                            std::make_pair(N->getValueType(0),
522                                                           Ops))];
523    }
524  } else {
525    if (N->getOpcode() == ISD::LOAD) {
526      return &Loads[std::make_pair(Ops[1],
527                                   std::make_pair(Ops[0], N->getValueType(0)))];
528    } else {
529      std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
530      return &ArbitraryNodes[std::make_pair(N->getOpcode(),
531                                            std::make_pair(RV, Ops))];
532    }
533  }
534  return 0;
535}
536
537
538SelectionDAG::~SelectionDAG() {
539  while (!AllNodes.empty()) {
540    SDNode *N = AllNodes.begin();
541    delete [] N->OperandList;
542    N->OperandList = 0;
543    N->NumOperands = 0;
544    AllNodes.pop_front();
545  }
546}
547
548SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
549  if (Op.getValueType() == VT) return Op;
550  int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
551  return getNode(ISD::AND, Op.getValueType(), Op,
552                 getConstant(Imm, Op.getValueType()));
553}
554
555SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT) {
556  assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
557  // Mask out any bits that are not valid for this constant.
558  if (VT != MVT::i64)
559    Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
560
561  SDNode *&N = Constants[std::make_pair(Val, VT)];
562  if (N) return SDOperand(N, 0);
563  N = new ConstantSDNode(false, Val, VT);
564  AllNodes.push_back(N);
565  return SDOperand(N, 0);
566}
567
568SDOperand SelectionDAG::getString(const std::string &Val) {
569  StringSDNode *&N = StringNodes[Val];
570  if (!N) {
571    N = new StringSDNode(Val);
572    AllNodes.push_back(N);
573  }
574  return SDOperand(N, 0);
575}
576
577SDOperand SelectionDAG::getTargetConstant(uint64_t Val, MVT::ValueType VT) {
578  assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
579  // Mask out any bits that are not valid for this constant.
580  if (VT != MVT::i64)
581    Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
582
583  SDNode *&N = TargetConstants[std::make_pair(Val, VT)];
584  if (N) return SDOperand(N, 0);
585  N = new ConstantSDNode(true, Val, VT);
586  AllNodes.push_back(N);
587  return SDOperand(N, 0);
588}
589
590SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT) {
591  assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
592  if (VT == MVT::f32)
593    Val = (float)Val;  // Mask out extra precision.
594
595  // Do the map lookup using the actual bit pattern for the floating point
596  // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
597  // we don't have issues with SNANs.
598  SDNode *&N = ConstantFPs[std::make_pair(DoubleToBits(Val), VT)];
599  if (N) return SDOperand(N, 0);
600  N = new ConstantFPSDNode(false, Val, VT);
601  AllNodes.push_back(N);
602  return SDOperand(N, 0);
603}
604
605SDOperand SelectionDAG::getTargetConstantFP(double Val, MVT::ValueType VT) {
606  assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
607  if (VT == MVT::f32)
608    Val = (float)Val;  // Mask out extra precision.
609
610  // Do the map lookup using the actual bit pattern for the floating point
611  // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
612  // we don't have issues with SNANs.
613  SDNode *&N = TargetConstantFPs[std::make_pair(DoubleToBits(Val), VT)];
614  if (N) return SDOperand(N, 0);
615  N = new ConstantFPSDNode(true, Val, VT);
616  AllNodes.push_back(N);
617  return SDOperand(N, 0);
618}
619
620SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
621                                         MVT::ValueType VT, int offset) {
622  SDNode *&N = GlobalValues[std::make_pair(GV, offset)];
623  if (N) return SDOperand(N, 0);
624  N = new GlobalAddressSDNode(false, GV, VT, offset);
625  AllNodes.push_back(N);
626  return SDOperand(N, 0);
627}
628
629SDOperand SelectionDAG::getTargetGlobalAddress(const GlobalValue *GV,
630                                               MVT::ValueType VT, int offset) {
631  SDNode *&N = TargetGlobalValues[std::make_pair(GV, offset)];
632  if (N) return SDOperand(N, 0);
633  N = new GlobalAddressSDNode(true, GV, VT, offset);
634  AllNodes.push_back(N);
635  return SDOperand(N, 0);
636}
637
638SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT) {
639  SDNode *&N = FrameIndices[FI];
640  if (N) return SDOperand(N, 0);
641  N = new FrameIndexSDNode(FI, VT, false);
642  AllNodes.push_back(N);
643  return SDOperand(N, 0);
644}
645
646SDOperand SelectionDAG::getTargetFrameIndex(int FI, MVT::ValueType VT) {
647  SDNode *&N = TargetFrameIndices[FI];
648  if (N) return SDOperand(N, 0);
649  N = new FrameIndexSDNode(FI, VT, true);
650  AllNodes.push_back(N);
651  return SDOperand(N, 0);
652}
653
654SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
655                                        unsigned Alignment,  int Offset) {
656  SDNode *&N = ConstantPoolIndices[std::make_pair(C,
657                                            std::make_pair(Offset, Alignment))];
658  if (N) return SDOperand(N, 0);
659  N = new ConstantPoolSDNode(false, C, VT, Offset, Alignment);
660  AllNodes.push_back(N);
661  return SDOperand(N, 0);
662}
663
664SDOperand SelectionDAG::getTargetConstantPool(Constant *C, MVT::ValueType VT,
665                                             unsigned Alignment,  int Offset) {
666  SDNode *&N = TargetConstantPoolIndices[std::make_pair(C,
667                                            std::make_pair(Offset, Alignment))];
668  if (N) return SDOperand(N, 0);
669  N = new ConstantPoolSDNode(true, C, VT, Offset, Alignment);
670  AllNodes.push_back(N);
671  return SDOperand(N, 0);
672}
673
674SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
675  SDNode *&N = BBNodes[MBB];
676  if (N) return SDOperand(N, 0);
677  N = new BasicBlockSDNode(MBB);
678  AllNodes.push_back(N);
679  return SDOperand(N, 0);
680}
681
682SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
683  if ((unsigned)VT >= ValueTypeNodes.size())
684    ValueTypeNodes.resize(VT+1);
685  if (ValueTypeNodes[VT] == 0) {
686    ValueTypeNodes[VT] = new VTSDNode(VT);
687    AllNodes.push_back(ValueTypeNodes[VT]);
688  }
689
690  return SDOperand(ValueTypeNodes[VT], 0);
691}
692
693SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
694  SDNode *&N = ExternalSymbols[Sym];
695  if (N) return SDOperand(N, 0);
696  N = new ExternalSymbolSDNode(false, Sym, VT);
697  AllNodes.push_back(N);
698  return SDOperand(N, 0);
699}
700
701SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
702                                                MVT::ValueType VT) {
703  SDNode *&N = TargetExternalSymbols[Sym];
704  if (N) return SDOperand(N, 0);
705  N = new ExternalSymbolSDNode(true, Sym, VT);
706  AllNodes.push_back(N);
707  return SDOperand(N, 0);
708}
709
710SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
711  if ((unsigned)Cond >= CondCodeNodes.size())
712    CondCodeNodes.resize(Cond+1);
713
714  if (CondCodeNodes[Cond] == 0) {
715    CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
716    AllNodes.push_back(CondCodeNodes[Cond]);
717  }
718  return SDOperand(CondCodeNodes[Cond], 0);
719}
720
721SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
722  RegisterSDNode *&Reg = RegNodes[std::make_pair(RegNo, VT)];
723  if (!Reg) {
724    Reg = new RegisterSDNode(RegNo, VT);
725    AllNodes.push_back(Reg);
726  }
727  return SDOperand(Reg, 0);
728}
729
730SDOperand SelectionDAG::SimplifySetCC(MVT::ValueType VT, SDOperand N1,
731                                      SDOperand N2, ISD::CondCode Cond) {
732  // These setcc operations always fold.
733  switch (Cond) {
734  default: break;
735  case ISD::SETFALSE:
736  case ISD::SETFALSE2: return getConstant(0, VT);
737  case ISD::SETTRUE:
738  case ISD::SETTRUE2:  return getConstant(1, VT);
739  }
740
741  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
742    uint64_t C2 = N2C->getValue();
743    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
744      uint64_t C1 = N1C->getValue();
745
746      // Sign extend the operands if required
747      if (ISD::isSignedIntSetCC(Cond)) {
748        C1 = N1C->getSignExtended();
749        C2 = N2C->getSignExtended();
750      }
751
752      switch (Cond) {
753      default: assert(0 && "Unknown integer setcc!");
754      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
755      case ISD::SETNE:  return getConstant(C1 != C2, VT);
756      case ISD::SETULT: return getConstant(C1 <  C2, VT);
757      case ISD::SETUGT: return getConstant(C1 >  C2, VT);
758      case ISD::SETULE: return getConstant(C1 <= C2, VT);
759      case ISD::SETUGE: return getConstant(C1 >= C2, VT);
760      case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
761      case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
762      case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
763      case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
764      }
765    } else {
766      // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
767      if (N1.getOpcode() == ISD::ZERO_EXTEND) {
768        unsigned InSize = MVT::getSizeInBits(N1.getOperand(0).getValueType());
769
770        // If the comparison constant has bits in the upper part, the
771        // zero-extended value could never match.
772        if (C2 & (~0ULL << InSize)) {
773          unsigned VSize = MVT::getSizeInBits(N1.getValueType());
774          switch (Cond) {
775          case ISD::SETUGT:
776          case ISD::SETUGE:
777          case ISD::SETEQ: return getConstant(0, VT);
778          case ISD::SETULT:
779          case ISD::SETULE:
780          case ISD::SETNE: return getConstant(1, VT);
781          case ISD::SETGT:
782          case ISD::SETGE:
783            // True if the sign bit of C2 is set.
784            return getConstant((C2 & (1ULL << VSize)) != 0, VT);
785          case ISD::SETLT:
786          case ISD::SETLE:
787            // True if the sign bit of C2 isn't set.
788            return getConstant((C2 & (1ULL << VSize)) == 0, VT);
789          default:
790            break;
791          }
792        }
793
794        // Otherwise, we can perform the comparison with the low bits.
795        switch (Cond) {
796        case ISD::SETEQ:
797        case ISD::SETNE:
798        case ISD::SETUGT:
799        case ISD::SETUGE:
800        case ISD::SETULT:
801        case ISD::SETULE:
802          return getSetCC(VT, N1.getOperand(0),
803                          getConstant(C2, N1.getOperand(0).getValueType()),
804                          Cond);
805        default:
806          break;   // todo, be more careful with signed comparisons
807        }
808      } else if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG &&
809                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
810        MVT::ValueType ExtSrcTy = cast<VTSDNode>(N1.getOperand(1))->getVT();
811        unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
812        MVT::ValueType ExtDstTy = N1.getValueType();
813        unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
814
815        // If the extended part has any inconsistent bits, it cannot ever
816        // compare equal.  In other words, they have to be all ones or all
817        // zeros.
818        uint64_t ExtBits =
819          (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
820        if ((C2 & ExtBits) != 0 && (C2 & ExtBits) != ExtBits)
821          return getConstant(Cond == ISD::SETNE, VT);
822
823        // Otherwise, make this a use of a zext.
824        return getSetCC(VT, getZeroExtendInReg(N1.getOperand(0), ExtSrcTy),
825                        getConstant(C2 & (~0ULL>>(64-ExtSrcTyBits)), ExtDstTy),
826                        Cond);
827      }
828
829      uint64_t MinVal, MaxVal;
830      unsigned OperandBitSize = MVT::getSizeInBits(N2C->getValueType(0));
831      if (ISD::isSignedIntSetCC(Cond)) {
832        MinVal = 1ULL << (OperandBitSize-1);
833        if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
834          MaxVal = ~0ULL >> (65-OperandBitSize);
835        else
836          MaxVal = 0;
837      } else {
838        MinVal = 0;
839        MaxVal = ~0ULL >> (64-OperandBitSize);
840      }
841
842      // Canonicalize GE/LE comparisons to use GT/LT comparisons.
843      if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
844        if (C2 == MinVal) return getConstant(1, VT);   // X >= MIN --> true
845        --C2;                                          // X >= C1 --> X > (C1-1)
846        return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
847                        (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
848      }
849
850      if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
851        if (C2 == MaxVal) return getConstant(1, VT);   // X <= MAX --> true
852        ++C2;                                          // X <= C1 --> X < (C1+1)
853        return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
854                        (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
855      }
856
857      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal)
858        return getConstant(0, VT);      // X < MIN --> false
859
860      // Canonicalize setgt X, Min --> setne X, Min
861      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MinVal)
862        return getSetCC(VT, N1, N2, ISD::SETNE);
863
864      // If we have setult X, 1, turn it into seteq X, 0
865      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal+1)
866        return getSetCC(VT, N1, getConstant(MinVal, N1.getValueType()),
867                        ISD::SETEQ);
868      // If we have setugt X, Max-1, turn it into seteq X, Max
869      else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MaxVal-1)
870        return getSetCC(VT, N1, getConstant(MaxVal, N1.getValueType()),
871                        ISD::SETEQ);
872
873      // If we have "setcc X, C1", check to see if we can shrink the immediate
874      // by changing cc.
875
876      // SETUGT X, SINTMAX  -> SETLT X, 0
877      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
878          C2 == (~0ULL >> (65-OperandBitSize)))
879        return getSetCC(VT, N1, getConstant(0, N2.getValueType()), ISD::SETLT);
880
881      // FIXME: Implement the rest of these.
882
883
884      // Fold bit comparisons when we can.
885      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
886          VT == N1.getValueType() && N1.getOpcode() == ISD::AND)
887        if (ConstantSDNode *AndRHS =
888                    dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
889          if (Cond == ISD::SETNE && C2 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
890            // Perform the xform if the AND RHS is a single bit.
891            if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
892              return getNode(ISD::SRL, VT, N1,
893                             getConstant(Log2_64(AndRHS->getValue()),
894                                                   TLI.getShiftAmountTy()));
895            }
896          } else if (Cond == ISD::SETEQ && C2 == AndRHS->getValue()) {
897            // (X & 8) == 8  -->  (X & 8) >> 3
898            // Perform the xform if C2 is a single bit.
899            if ((C2 & (C2-1)) == 0) {
900              return getNode(ISD::SRL, VT, N1,
901                             getConstant(Log2_64(C2),TLI.getShiftAmountTy()));
902            }
903          }
904        }
905    }
906  } else if (isa<ConstantSDNode>(N1.Val)) {
907      // Ensure that the constant occurs on the RHS.
908    return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
909  }
910
911  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
912    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
913      double C1 = N1C->getValue(), C2 = N2C->getValue();
914
915      switch (Cond) {
916      default: break; // FIXME: Implement the rest of these!
917      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
918      case ISD::SETNE:  return getConstant(C1 != C2, VT);
919      case ISD::SETLT:  return getConstant(C1 < C2, VT);
920      case ISD::SETGT:  return getConstant(C1 > C2, VT);
921      case ISD::SETLE:  return getConstant(C1 <= C2, VT);
922      case ISD::SETGE:  return getConstant(C1 >= C2, VT);
923      }
924    } else {
925      // Ensure that the constant occurs on the RHS.
926      return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
927    }
928
929  // Could not fold it.
930  return SDOperand();
931}
932
933/// getNode - Gets or creates the specified node.
934///
935SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
936  SDNode *&N = NullaryOps[std::make_pair(Opcode, VT)];
937  if (!N) {
938    N = new SDNode(Opcode, VT);
939    AllNodes.push_back(N);
940  }
941  return SDOperand(N, 0);
942}
943
944SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
945                                SDOperand Operand) {
946  unsigned Tmp1;
947  // Constant fold unary operations with an integer constant operand.
948  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
949    uint64_t Val = C->getValue();
950    switch (Opcode) {
951    default: break;
952    case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
953    case ISD::ANY_EXTEND:
954    case ISD::ZERO_EXTEND: return getConstant(Val, VT);
955    case ISD::TRUNCATE:    return getConstant(Val, VT);
956    case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
957    case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
958    case ISD::BIT_CONVERT:
959      if (VT == MVT::f32) {
960        assert(C->getValueType(0) == MVT::i32 && "Invalid bit_convert!");
961        return getConstantFP(BitsToFloat(Val), VT);
962      } else if (VT == MVT::f64) {
963        assert(C->getValueType(0) == MVT::i64 && "Invalid bit_convert!");
964        return getConstantFP(BitsToDouble(Val), VT);
965      }
966      break;
967    case ISD::BSWAP:
968      switch(VT) {
969      default: assert(0 && "Invalid bswap!"); break;
970      case MVT::i16: return getConstant(ByteSwap_16((unsigned short)Val), VT);
971      case MVT::i32: return getConstant(ByteSwap_32((unsigned)Val), VT);
972      case MVT::i64: return getConstant(ByteSwap_64(Val), VT);
973      }
974      break;
975    case ISD::CTPOP:
976      switch(VT) {
977      default: assert(0 && "Invalid ctpop!"); break;
978      case MVT::i1: return getConstant(Val != 0, VT);
979      case MVT::i8:
980        Tmp1 = (unsigned)Val & 0xFF;
981        return getConstant(CountPopulation_32(Tmp1), VT);
982      case MVT::i16:
983        Tmp1 = (unsigned)Val & 0xFFFF;
984        return getConstant(CountPopulation_32(Tmp1), VT);
985      case MVT::i32:
986        return getConstant(CountPopulation_32((unsigned)Val), VT);
987      case MVT::i64:
988        return getConstant(CountPopulation_64(Val), VT);
989      }
990    case ISD::CTLZ:
991      switch(VT) {
992      default: assert(0 && "Invalid ctlz!"); break;
993      case MVT::i1: return getConstant(Val == 0, VT);
994      case MVT::i8:
995        Tmp1 = (unsigned)Val & 0xFF;
996        return getConstant(CountLeadingZeros_32(Tmp1)-24, VT);
997      case MVT::i16:
998        Tmp1 = (unsigned)Val & 0xFFFF;
999        return getConstant(CountLeadingZeros_32(Tmp1)-16, VT);
1000      case MVT::i32:
1001        return getConstant(CountLeadingZeros_32((unsigned)Val), VT);
1002      case MVT::i64:
1003        return getConstant(CountLeadingZeros_64(Val), VT);
1004      }
1005    case ISD::CTTZ:
1006      switch(VT) {
1007      default: assert(0 && "Invalid cttz!"); break;
1008      case MVT::i1: return getConstant(Val == 0, VT);
1009      case MVT::i8:
1010        Tmp1 = (unsigned)Val | 0x100;
1011        return getConstant(CountTrailingZeros_32(Tmp1), VT);
1012      case MVT::i16:
1013        Tmp1 = (unsigned)Val | 0x10000;
1014        return getConstant(CountTrailingZeros_32(Tmp1), VT);
1015      case MVT::i32:
1016        return getConstant(CountTrailingZeros_32((unsigned)Val), VT);
1017      case MVT::i64:
1018        return getConstant(CountTrailingZeros_64(Val), VT);
1019      }
1020    }
1021  }
1022
1023  // Constant fold unary operations with an floating point constant operand.
1024  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
1025    switch (Opcode) {
1026    case ISD::FNEG:
1027      return getConstantFP(-C->getValue(), VT);
1028    case ISD::FABS:
1029      return getConstantFP(fabs(C->getValue()), VT);
1030    case ISD::FP_ROUND:
1031    case ISD::FP_EXTEND:
1032      return getConstantFP(C->getValue(), VT);
1033    case ISD::FP_TO_SINT:
1034      return getConstant((int64_t)C->getValue(), VT);
1035    case ISD::FP_TO_UINT:
1036      return getConstant((uint64_t)C->getValue(), VT);
1037    case ISD::BIT_CONVERT:
1038      if (VT == MVT::i32) {
1039        assert(C->getValueType(0) == MVT::f32 && "Invalid bit_convert!");
1040        return getConstant(FloatToBits(C->getValue()), VT);
1041      } else if (VT == MVT::i64) {
1042        assert(C->getValueType(0) == MVT::f64 && "Invalid bit_convert!");
1043        return getConstant(DoubleToBits(C->getValue()), VT);
1044      }
1045      break;
1046    }
1047
1048  unsigned OpOpcode = Operand.Val->getOpcode();
1049  switch (Opcode) {
1050  case ISD::TokenFactor:
1051    return Operand;         // Factor of one node?  No factor.
1052  case ISD::SIGN_EXTEND:
1053    if (Operand.getValueType() == VT) return Operand;   // noop extension
1054    assert(Operand.getValueType() < VT && "Invalid sext node, dst < src!");
1055    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1056      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1057    break;
1058  case ISD::ZERO_EXTEND:
1059    if (Operand.getValueType() == VT) return Operand;   // noop extension
1060    assert(Operand.getValueType() < VT && "Invalid zext node, dst < src!");
1061    if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
1062      return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1063    break;
1064  case ISD::ANY_EXTEND:
1065    if (Operand.getValueType() == VT) return Operand;   // noop extension
1066    assert(Operand.getValueType() < VT && "Invalid anyext node, dst < src!");
1067    if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1068      // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
1069      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1070    break;
1071  case ISD::TRUNCATE:
1072    if (Operand.getValueType() == VT) return Operand;   // noop truncate
1073    assert(Operand.getValueType() > VT && "Invalid truncate node, src < dst!");
1074    if (OpOpcode == ISD::TRUNCATE)
1075      return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1076    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1077             OpOpcode == ISD::ANY_EXTEND) {
1078      // If the source is smaller than the dest, we still need an extend.
1079      if (Operand.Val->getOperand(0).getValueType() < VT)
1080        return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1081      else if (Operand.Val->getOperand(0).getValueType() > VT)
1082        return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1083      else
1084        return Operand.Val->getOperand(0);
1085    }
1086    break;
1087  case ISD::BIT_CONVERT:
1088    // Basic sanity checking.
1089    assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
1090           && "Cannot BIT_CONVERT between two different types!");
1091    if (VT == Operand.getValueType()) return Operand;  // noop conversion.
1092    if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
1093      return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1094    break;
1095  case ISD::FNEG:
1096    if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
1097      return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1098                     Operand.Val->getOperand(0));
1099    if (OpOpcode == ISD::FNEG)  // --X -> X
1100      return Operand.Val->getOperand(0);
1101    break;
1102  case ISD::FABS:
1103    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
1104      return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1105    break;
1106  }
1107
1108  SDNode *N;
1109  if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1110    SDNode *&E = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
1111    if (E) return SDOperand(E, 0);
1112    E = N = new SDNode(Opcode, Operand);
1113  } else {
1114    N = new SDNode(Opcode, Operand);
1115  }
1116  N->setValueTypes(VT);
1117  AllNodes.push_back(N);
1118  return SDOperand(N, 0);
1119}
1120
1121
1122
1123SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1124                                SDOperand N1, SDOperand N2) {
1125#ifndef NDEBUG
1126  switch (Opcode) {
1127  case ISD::TokenFactor:
1128    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1129           N2.getValueType() == MVT::Other && "Invalid token factor!");
1130    break;
1131  case ISD::AND:
1132  case ISD::OR:
1133  case ISD::XOR:
1134  case ISD::UDIV:
1135  case ISD::UREM:
1136  case ISD::MULHU:
1137  case ISD::MULHS:
1138    assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1139    // fall through
1140  case ISD::ADD:
1141  case ISD::SUB:
1142  case ISD::MUL:
1143  case ISD::SDIV:
1144  case ISD::SREM:
1145    assert(MVT::isInteger(N1.getValueType()) && "Should use F* for FP ops");
1146    // fall through.
1147  case ISD::FADD:
1148  case ISD::FSUB:
1149  case ISD::FMUL:
1150  case ISD::FDIV:
1151  case ISD::FREM:
1152    assert(N1.getValueType() == N2.getValueType() &&
1153           N1.getValueType() == VT && "Binary operator types must match!");
1154    break;
1155  case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
1156    assert(N1.getValueType() == VT &&
1157           MVT::isFloatingPoint(N1.getValueType()) &&
1158           MVT::isFloatingPoint(N2.getValueType()) &&
1159           "Invalid FCOPYSIGN!");
1160    break;
1161  case ISD::SHL:
1162  case ISD::SRA:
1163  case ISD::SRL:
1164  case ISD::ROTL:
1165  case ISD::ROTR:
1166    assert(VT == N1.getValueType() &&
1167           "Shift operators return type must be the same as their first arg");
1168    assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1169           VT != MVT::i1 && "Shifts only work on integers");
1170    break;
1171  case ISD::FP_ROUND_INREG: {
1172    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1173    assert(VT == N1.getValueType() && "Not an inreg round!");
1174    assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1175           "Cannot FP_ROUND_INREG integer types");
1176    assert(EVT <= VT && "Not rounding down!");
1177    break;
1178  }
1179  case ISD::AssertSext:
1180  case ISD::AssertZext:
1181  case ISD::SIGN_EXTEND_INREG: {
1182    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1183    assert(VT == N1.getValueType() && "Not an inreg extend!");
1184    assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1185           "Cannot *_EXTEND_INREG FP types");
1186    assert(EVT <= VT && "Not extending!");
1187  }
1188
1189  default: break;
1190  }
1191#endif
1192
1193  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1194  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1195  if (N1C) {
1196    if (N2C) {
1197      uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
1198      switch (Opcode) {
1199      case ISD::ADD: return getConstant(C1 + C2, VT);
1200      case ISD::SUB: return getConstant(C1 - C2, VT);
1201      case ISD::MUL: return getConstant(C1 * C2, VT);
1202      case ISD::UDIV:
1203        if (C2) return getConstant(C1 / C2, VT);
1204        break;
1205      case ISD::UREM :
1206        if (C2) return getConstant(C1 % C2, VT);
1207        break;
1208      case ISD::SDIV :
1209        if (C2) return getConstant(N1C->getSignExtended() /
1210                                   N2C->getSignExtended(), VT);
1211        break;
1212      case ISD::SREM :
1213        if (C2) return getConstant(N1C->getSignExtended() %
1214                                   N2C->getSignExtended(), VT);
1215        break;
1216      case ISD::AND  : return getConstant(C1 & C2, VT);
1217      case ISD::OR   : return getConstant(C1 | C2, VT);
1218      case ISD::XOR  : return getConstant(C1 ^ C2, VT);
1219      case ISD::SHL  : return getConstant(C1 << C2, VT);
1220      case ISD::SRL  : return getConstant(C1 >> C2, VT);
1221      case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
1222      case ISD::ROTL :
1223        return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
1224                           VT);
1225      case ISD::ROTR :
1226        return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)),
1227                           VT);
1228      default: break;
1229      }
1230    } else {      // Cannonicalize constant to RHS if commutative
1231      if (isCommutativeBinOp(Opcode)) {
1232        std::swap(N1C, N2C);
1233        std::swap(N1, N2);
1234      }
1235    }
1236  }
1237
1238  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1239  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1240  if (N1CFP) {
1241    if (N2CFP) {
1242      double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
1243      switch (Opcode) {
1244      case ISD::FADD: return getConstantFP(C1 + C2, VT);
1245      case ISD::FSUB: return getConstantFP(C1 - C2, VT);
1246      case ISD::FMUL: return getConstantFP(C1 * C2, VT);
1247      case ISD::FDIV:
1248        if (C2) return getConstantFP(C1 / C2, VT);
1249        break;
1250      case ISD::FREM :
1251        if (C2) return getConstantFP(fmod(C1, C2), VT);
1252        break;
1253      case ISD::FCOPYSIGN: {
1254        union {
1255          double   F;
1256          uint64_t I;
1257        } u1;
1258        union {
1259          double  F;
1260          int64_t I;
1261        } u2;
1262        u1.F = C1;
1263        u2.F = C2;
1264        if (u2.I < 0)  // Sign bit of RHS set?
1265          u1.I |= 1ULL << 63;      // Set the sign bit of the LHS.
1266        else
1267          u1.I &= (1ULL << 63)-1;  // Clear the sign bit of the LHS.
1268        return getConstantFP(u1.F, VT);
1269      }
1270      default: break;
1271      }
1272    } else {      // Cannonicalize constant to RHS if commutative
1273      if (isCommutativeBinOp(Opcode)) {
1274        std::swap(N1CFP, N2CFP);
1275        std::swap(N1, N2);
1276      }
1277    }
1278  }
1279
1280  // Finally, fold operations that do not require constants.
1281  switch (Opcode) {
1282  case ISD::FP_ROUND_INREG:
1283    if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
1284    break;
1285  case ISD::SIGN_EXTEND_INREG: {
1286    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1287    if (EVT == VT) return N1;  // Not actually extending
1288    break;
1289  }
1290
1291  // FIXME: figure out how to safely handle things like
1292  // int foo(int x) { return 1 << (x & 255); }
1293  // int bar() { return foo(256); }
1294#if 0
1295  case ISD::SHL:
1296  case ISD::SRL:
1297  case ISD::SRA:
1298    if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1299        cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
1300      return getNode(Opcode, VT, N1, N2.getOperand(0));
1301    else if (N2.getOpcode() == ISD::AND)
1302      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
1303        // If the and is only masking out bits that cannot effect the shift,
1304        // eliminate the and.
1305        unsigned NumBits = MVT::getSizeInBits(VT);
1306        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1307          return getNode(Opcode, VT, N1, N2.getOperand(0));
1308      }
1309    break;
1310#endif
1311  }
1312
1313  // Memoize this node if possible.
1314  SDNode *N;
1315  if (VT != MVT::Flag) {
1316    SDNode *&BON = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
1317    if (BON) return SDOperand(BON, 0);
1318
1319    BON = N = new SDNode(Opcode, N1, N2);
1320  } else {
1321    N = new SDNode(Opcode, N1, N2);
1322  }
1323
1324  N->setValueTypes(VT);
1325  AllNodes.push_back(N);
1326  return SDOperand(N, 0);
1327}
1328
1329SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1330                                SDOperand N1, SDOperand N2, SDOperand N3) {
1331  // Perform various simplifications.
1332  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1333  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1334  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
1335  switch (Opcode) {
1336  case ISD::SETCC: {
1337    // Use SimplifySetCC  to simplify SETCC's.
1338    SDOperand Simp = SimplifySetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
1339    if (Simp.Val) return Simp;
1340    break;
1341  }
1342  case ISD::SELECT:
1343    if (N1C)
1344      if (N1C->getValue())
1345        return N2;             // select true, X, Y -> X
1346      else
1347        return N3;             // select false, X, Y -> Y
1348
1349    if (N2 == N3) return N2;   // select C, X, X -> X
1350    break;
1351  case ISD::BRCOND:
1352    if (N2C)
1353      if (N2C->getValue()) // Unconditional branch
1354        return getNode(ISD::BR, MVT::Other, N1, N3);
1355      else
1356        return N1;         // Never-taken branch
1357    break;
1358  }
1359
1360  std::vector<SDOperand> Ops;
1361  Ops.reserve(3);
1362  Ops.push_back(N1);
1363  Ops.push_back(N2);
1364  Ops.push_back(N3);
1365
1366  // Memoize node if it doesn't produce a flag.
1367  SDNode *N;
1368  if (VT != MVT::Flag) {
1369    SDNode *&E = OneResultNodes[std::make_pair(Opcode,std::make_pair(VT, Ops))];
1370    if (E) return SDOperand(E, 0);
1371    E = N = new SDNode(Opcode, N1, N2, N3);
1372  } else {
1373    N = new SDNode(Opcode, N1, N2, N3);
1374  }
1375  N->setValueTypes(VT);
1376  AllNodes.push_back(N);
1377  return SDOperand(N, 0);
1378}
1379
1380SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1381                                SDOperand N1, SDOperand N2, SDOperand N3,
1382                                SDOperand N4) {
1383  std::vector<SDOperand> Ops;
1384  Ops.reserve(4);
1385  Ops.push_back(N1);
1386  Ops.push_back(N2);
1387  Ops.push_back(N3);
1388  Ops.push_back(N4);
1389  return getNode(Opcode, VT, Ops);
1390}
1391
1392SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1393                                SDOperand N1, SDOperand N2, SDOperand N3,
1394                                SDOperand N4, SDOperand N5) {
1395  std::vector<SDOperand> Ops;
1396  Ops.reserve(5);
1397  Ops.push_back(N1);
1398  Ops.push_back(N2);
1399  Ops.push_back(N3);
1400  Ops.push_back(N4);
1401  Ops.push_back(N5);
1402  return getNode(Opcode, VT, Ops);
1403}
1404
1405SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
1406                                SDOperand Chain, SDOperand Ptr,
1407                                SDOperand SV) {
1408  SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
1409  if (N) return SDOperand(N, 0);
1410  N = new SDNode(ISD::LOAD, Chain, Ptr, SV);
1411
1412  // Loads have a token chain.
1413  setNodeValueTypes(N, VT, MVT::Other);
1414  AllNodes.push_back(N);
1415  return SDOperand(N, 0);
1416}
1417
1418SDOperand SelectionDAG::getVecLoad(unsigned Count, MVT::ValueType EVT,
1419                                   SDOperand Chain, SDOperand Ptr,
1420                                   SDOperand SV) {
1421  SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, EVT))];
1422  if (N) return SDOperand(N, 0);
1423  std::vector<SDOperand> Ops;
1424  Ops.reserve(5);
1425  Ops.push_back(getConstant(Count, MVT::i32));
1426  Ops.push_back(getValueType(EVT));
1427  Ops.push_back(Chain);
1428  Ops.push_back(Ptr);
1429  Ops.push_back(SV);
1430  std::vector<MVT::ValueType> VTs;
1431  VTs.reserve(2);
1432  VTs.push_back(MVT::Vector); VTs.push_back(MVT::Other);  // Add token chain.
1433  return getNode(ISD::VLOAD, VTs, Ops);
1434}
1435
1436SDOperand SelectionDAG::getExtLoad(unsigned Opcode, MVT::ValueType VT,
1437                                   SDOperand Chain, SDOperand Ptr, SDOperand SV,
1438                                   MVT::ValueType EVT) {
1439  std::vector<SDOperand> Ops;
1440  Ops.reserve(4);
1441  Ops.push_back(Chain);
1442  Ops.push_back(Ptr);
1443  Ops.push_back(SV);
1444  Ops.push_back(getValueType(EVT));
1445  std::vector<MVT::ValueType> VTs;
1446  VTs.reserve(2);
1447  VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
1448  return getNode(Opcode, VTs, Ops);
1449}
1450
1451SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
1452  assert((!V || isa<PointerType>(V->getType())) &&
1453         "SrcValue is not a pointer?");
1454  SDNode *&N = ValueNodes[std::make_pair(V, Offset)];
1455  if (N) return SDOperand(N, 0);
1456
1457  N = new SrcValueSDNode(V, Offset);
1458  AllNodes.push_back(N);
1459  return SDOperand(N, 0);
1460}
1461
1462SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
1463                                 SDOperand Chain, SDOperand Ptr,
1464                                 SDOperand SV) {
1465  std::vector<SDOperand> Ops;
1466  Ops.reserve(3);
1467  Ops.push_back(Chain);
1468  Ops.push_back(Ptr);
1469  Ops.push_back(SV);
1470  std::vector<MVT::ValueType> VTs;
1471  VTs.reserve(2);
1472  VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
1473  return getNode(ISD::VAARG, VTs, Ops);
1474}
1475
1476SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1477                                std::vector<SDOperand> &Ops) {
1478  switch (Ops.size()) {
1479  case 0: return getNode(Opcode, VT);
1480  case 1: return getNode(Opcode, VT, Ops[0]);
1481  case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
1482  case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
1483  default: break;
1484  }
1485
1486  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Ops[1].Val);
1487  switch (Opcode) {
1488  default: break;
1489  case ISD::BRCONDTWOWAY:
1490    if (N1C)
1491      if (N1C->getValue()) // Unconditional branch to true dest.
1492        return getNode(ISD::BR, MVT::Other, Ops[0], Ops[2]);
1493      else                 // Unconditional branch to false dest.
1494        return getNode(ISD::BR, MVT::Other, Ops[0], Ops[3]);
1495    break;
1496  case ISD::BRTWOWAY_CC:
1497    assert(Ops.size() == 6 && "BRTWOWAY_CC takes 6 operands!");
1498    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1499           "LHS and RHS of comparison must have same type!");
1500    break;
1501  case ISD::TRUNCSTORE: {
1502    assert(Ops.size() == 5 && "TRUNCSTORE takes 5 operands!");
1503    MVT::ValueType EVT = cast<VTSDNode>(Ops[4])->getVT();
1504#if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1505    // If this is a truncating store of a constant, convert to the desired type
1506    // and store it instead.
1507    if (isa<Constant>(Ops[0])) {
1508      SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1509      if (isa<Constant>(Op))
1510        N1 = Op;
1511    }
1512    // Also for ConstantFP?
1513#endif
1514    if (Ops[0].getValueType() == EVT)       // Normal store?
1515      return getNode(ISD::STORE, VT, Ops[0], Ops[1], Ops[2], Ops[3]);
1516    assert(Ops[1].getValueType() > EVT && "Not a truncation?");
1517    assert(MVT::isInteger(Ops[1].getValueType()) == MVT::isInteger(EVT) &&
1518           "Can't do FP-INT conversion!");
1519    break;
1520  }
1521  case ISD::SELECT_CC: {
1522    assert(Ops.size() == 5 && "SELECT_CC takes 5 operands!");
1523    assert(Ops[0].getValueType() == Ops[1].getValueType() &&
1524           "LHS and RHS of condition must have same type!");
1525    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1526           "True and False arms of SelectCC must have same type!");
1527    assert(Ops[2].getValueType() == VT &&
1528           "select_cc node must be of same type as true and false value!");
1529    break;
1530  }
1531  case ISD::BR_CC: {
1532    assert(Ops.size() == 5 && "BR_CC takes 5 operands!");
1533    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1534           "LHS/RHS of comparison should match types!");
1535    break;
1536  }
1537  }
1538
1539  // Memoize nodes.
1540  SDNode *N;
1541  if (VT != MVT::Flag) {
1542    SDNode *&E =
1543      OneResultNodes[std::make_pair(Opcode, std::make_pair(VT, Ops))];
1544    if (E) return SDOperand(E, 0);
1545    E = N = new SDNode(Opcode, Ops);
1546  } else {
1547    N = new SDNode(Opcode, Ops);
1548  }
1549  N->setValueTypes(VT);
1550  AllNodes.push_back(N);
1551  return SDOperand(N, 0);
1552}
1553
1554SDOperand SelectionDAG::getNode(unsigned Opcode,
1555                                std::vector<MVT::ValueType> &ResultTys,
1556                                std::vector<SDOperand> &Ops) {
1557  if (ResultTys.size() == 1)
1558    return getNode(Opcode, ResultTys[0], Ops);
1559
1560  switch (Opcode) {
1561  case ISD::EXTLOAD:
1562  case ISD::SEXTLOAD:
1563  case ISD::ZEXTLOAD: {
1564    MVT::ValueType EVT = cast<VTSDNode>(Ops[3])->getVT();
1565    assert(Ops.size() == 4 && ResultTys.size() == 2 && "Bad *EXTLOAD!");
1566    // If they are asking for an extending load from/to the same thing, return a
1567    // normal load.
1568    if (ResultTys[0] == EVT)
1569      return getLoad(ResultTys[0], Ops[0], Ops[1], Ops[2]);
1570    assert(EVT < ResultTys[0] &&
1571           "Should only be an extending load, not truncating!");
1572    assert((Opcode == ISD::EXTLOAD || MVT::isInteger(ResultTys[0])) &&
1573           "Cannot sign/zero extend a FP load!");
1574    assert(MVT::isInteger(ResultTys[0]) == MVT::isInteger(EVT) &&
1575           "Cannot convert from FP to Int or Int -> FP!");
1576    break;
1577  }
1578
1579  // FIXME: figure out how to safely handle things like
1580  // int foo(int x) { return 1 << (x & 255); }
1581  // int bar() { return foo(256); }
1582#if 0
1583  case ISD::SRA_PARTS:
1584  case ISD::SRL_PARTS:
1585  case ISD::SHL_PARTS:
1586    if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1587        cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
1588      return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1589    else if (N3.getOpcode() == ISD::AND)
1590      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
1591        // If the and is only masking out bits that cannot effect the shift,
1592        // eliminate the and.
1593        unsigned NumBits = MVT::getSizeInBits(VT)*2;
1594        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1595          return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1596      }
1597    break;
1598#endif
1599  }
1600
1601  // Memoize the node unless it returns a flag.
1602  SDNode *N;
1603  if (ResultTys.back() != MVT::Flag) {
1604    SDNode *&E =
1605      ArbitraryNodes[std::make_pair(Opcode, std::make_pair(ResultTys, Ops))];
1606    if (E) return SDOperand(E, 0);
1607    E = N = new SDNode(Opcode, Ops);
1608  } else {
1609    N = new SDNode(Opcode, Ops);
1610  }
1611  setNodeValueTypes(N, ResultTys);
1612  AllNodes.push_back(N);
1613  return SDOperand(N, 0);
1614}
1615
1616void SelectionDAG::setNodeValueTypes(SDNode *N,
1617                                     std::vector<MVT::ValueType> &RetVals) {
1618  switch (RetVals.size()) {
1619  case 0: return;
1620  case 1: N->setValueTypes(RetVals[0]); return;
1621  case 2: setNodeValueTypes(N, RetVals[0], RetVals[1]); return;
1622  default: break;
1623  }
1624
1625  std::list<std::vector<MVT::ValueType> >::iterator I =
1626    std::find(VTList.begin(), VTList.end(), RetVals);
1627  if (I == VTList.end()) {
1628    VTList.push_front(RetVals);
1629    I = VTList.begin();
1630  }
1631
1632  N->setValueTypes(&(*I)[0], I->size());
1633}
1634
1635void SelectionDAG::setNodeValueTypes(SDNode *N, MVT::ValueType VT1,
1636                                     MVT::ValueType VT2) {
1637  for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
1638       E = VTList.end(); I != E; ++I) {
1639    if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2) {
1640      N->setValueTypes(&(*I)[0], 2);
1641      return;
1642    }
1643  }
1644  std::vector<MVT::ValueType> V;
1645  V.push_back(VT1);
1646  V.push_back(VT2);
1647  VTList.push_front(V);
1648  N->setValueTypes(&(*VTList.begin())[0], 2);
1649}
1650
1651/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
1652/// specified operands.  If the resultant node already exists in the DAG,
1653/// this does not modify the specified node, instead it returns the node that
1654/// already exists.  If the resultant node does not exist in the DAG, the
1655/// input node is returned.  As a degenerate case, if you specify the same
1656/// input operands as the node already has, the input node is returned.
1657SDOperand SelectionDAG::
1658UpdateNodeOperands(SDOperand InN, SDOperand Op) {
1659  SDNode *N = InN.Val;
1660  assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
1661
1662  // Check to see if there is no change.
1663  if (Op == N->getOperand(0)) return InN;
1664
1665  // See if the modified node already exists.
1666  SDNode **NewSlot = FindModifiedNodeSlot(N, Op);
1667  if (NewSlot && *NewSlot)
1668    return SDOperand(*NewSlot, InN.ResNo);
1669
1670  // Nope it doesn't.  Remove the node from it's current place in the maps.
1671  if (NewSlot)
1672    RemoveNodeFromCSEMaps(N);
1673
1674  // Now we update the operands.
1675  N->OperandList[0].Val->removeUser(N);
1676  Op.Val->addUser(N);
1677  N->OperandList[0] = Op;
1678
1679  // If this gets put into a CSE map, add it.
1680  if (NewSlot) *NewSlot = N;
1681  return InN;
1682}
1683
1684SDOperand SelectionDAG::
1685UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
1686  SDNode *N = InN.Val;
1687  assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
1688
1689  // Check to see if there is no change.
1690  bool AnyChange = false;
1691  if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
1692    return InN;   // No operands changed, just return the input node.
1693
1694  // See if the modified node already exists.
1695  SDNode **NewSlot = FindModifiedNodeSlot(N, Op1, Op2);
1696  if (NewSlot && *NewSlot)
1697    return SDOperand(*NewSlot, InN.ResNo);
1698
1699  // Nope it doesn't.  Remove the node from it's current place in the maps.
1700  if (NewSlot)
1701    RemoveNodeFromCSEMaps(N);
1702
1703  // Now we update the operands.
1704  if (N->OperandList[0] != Op1) {
1705    N->OperandList[0].Val->removeUser(N);
1706    Op1.Val->addUser(N);
1707    N->OperandList[0] = Op1;
1708  }
1709  if (N->OperandList[1] != Op2) {
1710    N->OperandList[1].Val->removeUser(N);
1711    Op2.Val->addUser(N);
1712    N->OperandList[1] = Op2;
1713  }
1714
1715  // If this gets put into a CSE map, add it.
1716  if (NewSlot) *NewSlot = N;
1717  return InN;
1718}
1719
1720SDOperand SelectionDAG::
1721UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
1722  std::vector<SDOperand> Ops;
1723  Ops.push_back(Op1);
1724  Ops.push_back(Op2);
1725  Ops.push_back(Op3);
1726  return UpdateNodeOperands(N, Ops);
1727}
1728
1729SDOperand SelectionDAG::
1730UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
1731                   SDOperand Op3, SDOperand Op4) {
1732  std::vector<SDOperand> Ops;
1733  Ops.push_back(Op1);
1734  Ops.push_back(Op2);
1735  Ops.push_back(Op3);
1736  Ops.push_back(Op4);
1737  return UpdateNodeOperands(N, Ops);
1738}
1739
1740SDOperand SelectionDAG::
1741UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
1742                   SDOperand Op3, SDOperand Op4, SDOperand Op5) {
1743  std::vector<SDOperand> Ops;
1744  Ops.push_back(Op1);
1745  Ops.push_back(Op2);
1746  Ops.push_back(Op3);
1747  Ops.push_back(Op4);
1748  Ops.push_back(Op5);
1749  return UpdateNodeOperands(N, Ops);
1750}
1751
1752
1753SDOperand SelectionDAG::
1754UpdateNodeOperands(SDOperand InN, const std::vector<SDOperand> &Ops) {
1755  SDNode *N = InN.Val;
1756  assert(N->getNumOperands() == Ops.size() &&
1757         "Update with wrong number of operands");
1758
1759  // Check to see if there is no change.
1760  unsigned NumOps = Ops.size();
1761  bool AnyChange = false;
1762  for (unsigned i = 0; i != NumOps; ++i) {
1763    if (Ops[i] != N->getOperand(i)) {
1764      AnyChange = true;
1765      break;
1766    }
1767  }
1768
1769  // No operands changed, just return the input node.
1770  if (!AnyChange) return InN;
1771
1772  // See if the modified node already exists.
1773  SDNode **NewSlot = FindModifiedNodeSlot(N, Ops);
1774  if (NewSlot && *NewSlot)
1775    return SDOperand(*NewSlot, InN.ResNo);
1776
1777  // Nope it doesn't.  Remove the node from it's current place in the maps.
1778  if (NewSlot)
1779    RemoveNodeFromCSEMaps(N);
1780
1781  // Now we update the operands.
1782  for (unsigned i = 0; i != NumOps; ++i) {
1783    if (N->OperandList[i] != Ops[i]) {
1784      N->OperandList[i].Val->removeUser(N);
1785      Ops[i].Val->addUser(N);
1786      N->OperandList[i] = Ops[i];
1787    }
1788  }
1789
1790  // If this gets put into a CSE map, add it.
1791  if (NewSlot) *NewSlot = N;
1792  return InN;
1793}
1794
1795
1796
1797
1798/// SelectNodeTo - These are used for target selectors to *mutate* the
1799/// specified node to have the specified return type, Target opcode, and
1800/// operands.  Note that target opcodes are stored as
1801/// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
1802///
1803/// Note that SelectNodeTo returns the resultant node.  If there is already a
1804/// node of the specified opcode and operands, it returns that node instead of
1805/// the current one.
1806SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1807                                     MVT::ValueType VT) {
1808  // If an identical node already exists, use it.
1809  SDNode *&ON = NullaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, VT)];
1810  if (ON) return SDOperand(ON, 0);
1811
1812  RemoveNodeFromCSEMaps(N);
1813
1814  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1815  N->setValueTypes(VT);
1816
1817  ON = N;   // Memoize the new node.
1818  return SDOperand(N, 0);
1819}
1820
1821SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1822                                     MVT::ValueType VT, SDOperand Op1) {
1823  // If an identical node already exists, use it.
1824  SDNode *&ON = UnaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1825                                        std::make_pair(Op1, VT))];
1826  if (ON) return SDOperand(ON, 0);
1827
1828  RemoveNodeFromCSEMaps(N);
1829  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1830  N->setValueTypes(VT);
1831  N->setOperands(Op1);
1832
1833  ON = N;   // Memoize the new node.
1834  return SDOperand(N, 0);
1835}
1836
1837SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1838                                     MVT::ValueType VT, SDOperand Op1,
1839                                     SDOperand Op2) {
1840  // If an identical node already exists, use it.
1841  SDNode *&ON = BinaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1842                                         std::make_pair(Op1, Op2))];
1843  if (ON) return SDOperand(ON, 0);
1844
1845  RemoveNodeFromCSEMaps(N);
1846  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1847  N->setValueTypes(VT);
1848  N->setOperands(Op1, Op2);
1849
1850  ON = N;   // Memoize the new node.
1851  return SDOperand(N, 0);
1852}
1853
1854SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1855                                     MVT::ValueType VT, SDOperand Op1,
1856                                     SDOperand Op2, SDOperand Op3) {
1857  // If an identical node already exists, use it.
1858  std::vector<SDOperand> OpList;
1859  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1860  SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1861                                              std::make_pair(VT, OpList))];
1862  if (ON) return SDOperand(ON, 0);
1863
1864  RemoveNodeFromCSEMaps(N);
1865  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1866  N->setValueTypes(VT);
1867  N->setOperands(Op1, Op2, Op3);
1868
1869  ON = N;   // Memoize the new node.
1870  return SDOperand(N, 0);
1871}
1872
1873SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1874                                     MVT::ValueType VT, SDOperand Op1,
1875                                     SDOperand Op2, SDOperand Op3,
1876                                     SDOperand Op4) {
1877  // If an identical node already exists, use it.
1878  std::vector<SDOperand> OpList;
1879  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1880  OpList.push_back(Op4);
1881  SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1882                                              std::make_pair(VT, OpList))];
1883  if (ON) return SDOperand(ON, 0);
1884
1885  RemoveNodeFromCSEMaps(N);
1886  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1887  N->setValueTypes(VT);
1888  N->setOperands(Op1, Op2, Op3, Op4);
1889
1890  ON = N;   // Memoize the new node.
1891  return SDOperand(N, 0);
1892}
1893
1894SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1895                                     MVT::ValueType VT, SDOperand Op1,
1896                                     SDOperand Op2, SDOperand Op3,SDOperand Op4,
1897                                     SDOperand Op5) {
1898  // If an identical node already exists, use it.
1899  std::vector<SDOperand> OpList;
1900  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1901  OpList.push_back(Op4); OpList.push_back(Op5);
1902  SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1903                                              std::make_pair(VT, OpList))];
1904  if (ON) return SDOperand(ON, 0);
1905
1906  RemoveNodeFromCSEMaps(N);
1907  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1908  N->setValueTypes(VT);
1909  N->setOperands(Op1, Op2, Op3, Op4, Op5);
1910
1911  ON = N;   // Memoize the new node.
1912  return SDOperand(N, 0);
1913}
1914
1915SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1916                                     MVT::ValueType VT, SDOperand Op1,
1917                                     SDOperand Op2, SDOperand Op3,SDOperand Op4,
1918                                     SDOperand Op5, SDOperand Op6) {
1919  // If an identical node already exists, use it.
1920  std::vector<SDOperand> OpList;
1921  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1922  OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6);
1923  SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1924                                              std::make_pair(VT, OpList))];
1925  if (ON) return SDOperand(ON, 0);
1926
1927  RemoveNodeFromCSEMaps(N);
1928  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1929  N->setValueTypes(VT);
1930  N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6);
1931
1932  ON = N;   // Memoize the new node.
1933  return SDOperand(N, 0);
1934}
1935
1936SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1937                                     MVT::ValueType VT, SDOperand Op1,
1938                                     SDOperand Op2, SDOperand Op3,SDOperand Op4,
1939                                     SDOperand Op5, SDOperand Op6,
1940				     SDOperand Op7) {
1941  // If an identical node already exists, use it.
1942  std::vector<SDOperand> OpList;
1943  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1944  OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6);
1945  OpList.push_back(Op7);
1946  SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1947                                              std::make_pair(VT, OpList))];
1948  if (ON) return SDOperand(ON, 0);
1949
1950  RemoveNodeFromCSEMaps(N);
1951  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1952  N->setValueTypes(VT);
1953  N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6, Op7);
1954
1955  ON = N;   // Memoize the new node.
1956  return SDOperand(N, 0);
1957}
1958SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1959                                     MVT::ValueType VT, SDOperand Op1,
1960                                     SDOperand Op2, SDOperand Op3,SDOperand Op4,
1961                                     SDOperand Op5, SDOperand Op6,
1962				     SDOperand Op7, SDOperand Op8) {
1963  // If an identical node already exists, use it.
1964  std::vector<SDOperand> OpList;
1965  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1966  OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6);
1967  OpList.push_back(Op7); OpList.push_back(Op8);
1968  SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1969                                              std::make_pair(VT, OpList))];
1970  if (ON) return SDOperand(ON, 0);
1971
1972  RemoveNodeFromCSEMaps(N);
1973  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1974  N->setValueTypes(VT);
1975  N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6, Op7, Op8);
1976
1977  ON = N;   // Memoize the new node.
1978  return SDOperand(N, 0);
1979}
1980
1981SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1982                                     MVT::ValueType VT1, MVT::ValueType VT2,
1983                                     SDOperand Op1, SDOperand Op2) {
1984  // If an identical node already exists, use it.
1985  std::vector<SDOperand> OpList;
1986  OpList.push_back(Op1); OpList.push_back(Op2);
1987  std::vector<MVT::ValueType> VTList;
1988  VTList.push_back(VT1); VTList.push_back(VT2);
1989  SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1990                                              std::make_pair(VTList, OpList))];
1991  if (ON) return SDOperand(ON, 0);
1992
1993  RemoveNodeFromCSEMaps(N);
1994  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1995  setNodeValueTypes(N, VT1, VT2);
1996  N->setOperands(Op1, Op2);
1997
1998  ON = N;   // Memoize the new node.
1999  return SDOperand(N, 0);
2000}
2001
2002SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2003                                     MVT::ValueType VT1, MVT::ValueType VT2,
2004                                     SDOperand Op1, SDOperand Op2,
2005                                     SDOperand Op3) {
2006  // If an identical node already exists, use it.
2007  std::vector<SDOperand> OpList;
2008  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
2009  std::vector<MVT::ValueType> VTList;
2010  VTList.push_back(VT1); VTList.push_back(VT2);
2011  SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
2012                                              std::make_pair(VTList, OpList))];
2013  if (ON) return SDOperand(ON, 0);
2014
2015  RemoveNodeFromCSEMaps(N);
2016  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2017  setNodeValueTypes(N, VT1, VT2);
2018  N->setOperands(Op1, Op2, Op3);
2019
2020  ON = N;   // Memoize the new node.
2021  return SDOperand(N, 0);
2022}
2023
2024SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2025                                     MVT::ValueType VT1, MVT::ValueType VT2,
2026                                     SDOperand Op1, SDOperand Op2,
2027                                     SDOperand Op3, SDOperand Op4) {
2028  // If an identical node already exists, use it.
2029  std::vector<SDOperand> OpList;
2030  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
2031  OpList.push_back(Op4);
2032  std::vector<MVT::ValueType> VTList;
2033  VTList.push_back(VT1); VTList.push_back(VT2);
2034  SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
2035                                              std::make_pair(VTList, OpList))];
2036  if (ON) return SDOperand(ON, 0);
2037
2038  RemoveNodeFromCSEMaps(N);
2039  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2040  setNodeValueTypes(N, VT1, VT2);
2041  N->setOperands(Op1, Op2, Op3, Op4);
2042
2043  ON = N;   // Memoize the new node.
2044  return SDOperand(N, 0);
2045}
2046
2047SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2048                                     MVT::ValueType VT1, MVT::ValueType VT2,
2049                                     SDOperand Op1, SDOperand Op2,
2050                                     SDOperand Op3, SDOperand Op4,
2051                                     SDOperand Op5) {
2052  // If an identical node already exists, use it.
2053  std::vector<SDOperand> OpList;
2054  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
2055  OpList.push_back(Op4); OpList.push_back(Op5);
2056  std::vector<MVT::ValueType> VTList;
2057  VTList.push_back(VT1); VTList.push_back(VT2);
2058  SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
2059                                              std::make_pair(VTList, OpList))];
2060  if (ON) return SDOperand(ON, 0);
2061
2062  RemoveNodeFromCSEMaps(N);
2063  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2064  setNodeValueTypes(N, VT1, VT2);
2065  N->setOperands(Op1, Op2, Op3, Op4, Op5);
2066
2067  ON = N;   // Memoize the new node.
2068  return SDOperand(N, 0);
2069}
2070
2071/// getTargetNode - These are used for target selectors to create a new node
2072/// with specified return type(s), target opcode, and operands.
2073///
2074/// Note that getTargetNode returns the resultant node.  If there is already a
2075/// node of the specified opcode and operands, it returns that node instead of
2076/// the current one.
2077SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
2078  return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
2079}
2080SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2081                                    SDOperand Op1) {
2082  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
2083}
2084SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2085                                    SDOperand Op1, SDOperand Op2) {
2086  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
2087}
2088SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2089                                    SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2090  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
2091}
2092SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2093                                    SDOperand Op1, SDOperand Op2, SDOperand Op3,
2094                                    SDOperand Op4) {
2095  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3, Op4).Val;
2096}
2097SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2098                                    SDOperand Op1, SDOperand Op2, SDOperand Op3,
2099                                    SDOperand Op4, SDOperand Op5) {
2100  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3, Op4, Op5).Val;
2101}
2102SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2103                                    SDOperand Op1, SDOperand Op2, SDOperand Op3,
2104                                    SDOperand Op4, SDOperand Op5, SDOperand Op6) {
2105  std::vector<SDOperand> Ops;
2106  Ops.reserve(6);
2107  Ops.push_back(Op1);
2108  Ops.push_back(Op2);
2109  Ops.push_back(Op3);
2110  Ops.push_back(Op4);
2111  Ops.push_back(Op5);
2112  Ops.push_back(Op6);
2113  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
2114}
2115SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2116                                    SDOperand Op1, SDOperand Op2, SDOperand Op3,
2117                                    SDOperand Op4, SDOperand Op5, SDOperand Op6,
2118                                    SDOperand Op7) {
2119  std::vector<SDOperand> Ops;
2120  Ops.reserve(7);
2121  Ops.push_back(Op1);
2122  Ops.push_back(Op2);
2123  Ops.push_back(Op3);
2124  Ops.push_back(Op4);
2125  Ops.push_back(Op5);
2126  Ops.push_back(Op6);
2127  Ops.push_back(Op7);
2128  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
2129}
2130SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2131                                    SDOperand Op1, SDOperand Op2, SDOperand Op3,
2132                                    SDOperand Op4, SDOperand Op5, SDOperand Op6,
2133                                    SDOperand Op7, SDOperand Op8) {
2134  std::vector<SDOperand> Ops;
2135  Ops.reserve(8);
2136  Ops.push_back(Op1);
2137  Ops.push_back(Op2);
2138  Ops.push_back(Op3);
2139  Ops.push_back(Op4);
2140  Ops.push_back(Op5);
2141  Ops.push_back(Op6);
2142  Ops.push_back(Op7);
2143  Ops.push_back(Op8);
2144  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
2145}
2146SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2147                                    std::vector<SDOperand> &Ops) {
2148  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
2149}
2150SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2151                                    MVT::ValueType VT2, SDOperand Op1) {
2152  std::vector<MVT::ValueType> ResultTys;
2153  ResultTys.push_back(VT1);
2154  ResultTys.push_back(VT2);
2155  std::vector<SDOperand> Ops;
2156  Ops.push_back(Op1);
2157  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2158}
2159SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2160                                    MVT::ValueType VT2, SDOperand Op1, SDOperand Op2) {
2161  std::vector<MVT::ValueType> ResultTys;
2162  ResultTys.push_back(VT1);
2163  ResultTys.push_back(VT2);
2164  std::vector<SDOperand> Ops;
2165  Ops.push_back(Op1);
2166  Ops.push_back(Op2);
2167  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2168}
2169SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2170                                    MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2171                                    SDOperand Op3) {
2172  std::vector<MVT::ValueType> ResultTys;
2173  ResultTys.push_back(VT1);
2174  ResultTys.push_back(VT2);
2175  std::vector<SDOperand> Ops;
2176  Ops.push_back(Op1);
2177  Ops.push_back(Op2);
2178  Ops.push_back(Op3);
2179  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2180}
2181SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2182                                    MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2183                                    SDOperand Op3, SDOperand Op4) {
2184  std::vector<MVT::ValueType> ResultTys;
2185  ResultTys.push_back(VT1);
2186  ResultTys.push_back(VT2);
2187  std::vector<SDOperand> Ops;
2188  Ops.push_back(Op1);
2189  Ops.push_back(Op2);
2190  Ops.push_back(Op3);
2191  Ops.push_back(Op4);
2192  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2193}
2194SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2195                                    MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2196                                    SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2197  std::vector<MVT::ValueType> ResultTys;
2198  ResultTys.push_back(VT1);
2199  ResultTys.push_back(VT2);
2200  std::vector<SDOperand> Ops;
2201  Ops.push_back(Op1);
2202  Ops.push_back(Op2);
2203  Ops.push_back(Op3);
2204  Ops.push_back(Op4);
2205  Ops.push_back(Op5);
2206  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2207}
2208SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2209                                    MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2210                                    SDOperand Op3, SDOperand Op4, SDOperand Op5,
2211                                    SDOperand Op6) {
2212  std::vector<MVT::ValueType> ResultTys;
2213  ResultTys.push_back(VT1);
2214  ResultTys.push_back(VT2);
2215  std::vector<SDOperand> Ops;
2216  Ops.push_back(Op1);
2217  Ops.push_back(Op2);
2218  Ops.push_back(Op3);
2219  Ops.push_back(Op4);
2220  Ops.push_back(Op5);
2221  Ops.push_back(Op6);
2222  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2223}
2224SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2225                                    MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2226                                    SDOperand Op3, SDOperand Op4, SDOperand Op5,
2227                                    SDOperand Op6, SDOperand Op7) {
2228  std::vector<MVT::ValueType> ResultTys;
2229  ResultTys.push_back(VT1);
2230  ResultTys.push_back(VT2);
2231  std::vector<SDOperand> Ops;
2232  Ops.push_back(Op1);
2233  Ops.push_back(Op2);
2234  Ops.push_back(Op3);
2235  Ops.push_back(Op4);
2236  Ops.push_back(Op5);
2237  Ops.push_back(Op6);
2238  Ops.push_back(Op7);
2239  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2240}
2241SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2242                                    MVT::ValueType VT2, MVT::ValueType VT3,
2243                                    SDOperand Op1, SDOperand Op2) {
2244  std::vector<MVT::ValueType> ResultTys;
2245  ResultTys.push_back(VT1);
2246  ResultTys.push_back(VT2);
2247  ResultTys.push_back(VT3);
2248  std::vector<SDOperand> Ops;
2249  Ops.push_back(Op1);
2250  Ops.push_back(Op2);
2251  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2252}
2253SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2254                                    MVT::ValueType VT2, MVT::ValueType VT3,
2255                                    SDOperand Op1, SDOperand Op2,
2256                                    SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2257  std::vector<MVT::ValueType> ResultTys;
2258  ResultTys.push_back(VT1);
2259  ResultTys.push_back(VT2);
2260  ResultTys.push_back(VT3);
2261  std::vector<SDOperand> Ops;
2262  Ops.push_back(Op1);
2263  Ops.push_back(Op2);
2264  Ops.push_back(Op3);
2265  Ops.push_back(Op4);
2266  Ops.push_back(Op5);
2267  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2268}
2269SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2270                                    MVT::ValueType VT2, MVT::ValueType VT3,
2271                                    SDOperand Op1, SDOperand Op2,
2272                                    SDOperand Op3, SDOperand Op4, SDOperand Op5,
2273                                    SDOperand Op6) {
2274  std::vector<MVT::ValueType> ResultTys;
2275  ResultTys.push_back(VT1);
2276  ResultTys.push_back(VT2);
2277  ResultTys.push_back(VT3);
2278  std::vector<SDOperand> Ops;
2279  Ops.push_back(Op1);
2280  Ops.push_back(Op2);
2281  Ops.push_back(Op3);
2282  Ops.push_back(Op4);
2283  Ops.push_back(Op5);
2284  Ops.push_back(Op6);
2285  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2286}
2287SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2288                                    MVT::ValueType VT2, MVT::ValueType VT3,
2289                                    SDOperand Op1, SDOperand Op2,
2290                                    SDOperand Op3, SDOperand Op4, SDOperand Op5,
2291                                    SDOperand Op6, SDOperand Op7) {
2292  std::vector<MVT::ValueType> ResultTys;
2293  ResultTys.push_back(VT1);
2294  ResultTys.push_back(VT2);
2295  ResultTys.push_back(VT3);
2296  std::vector<SDOperand> Ops;
2297  Ops.push_back(Op1);
2298  Ops.push_back(Op2);
2299  Ops.push_back(Op3);
2300  Ops.push_back(Op4);
2301  Ops.push_back(Op5);
2302  Ops.push_back(Op6);
2303  Ops.push_back(Op7);
2304  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2305}
2306SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2307                                    MVT::ValueType VT2, std::vector<SDOperand> &Ops) {
2308  std::vector<MVT::ValueType> ResultTys;
2309  ResultTys.push_back(VT1);
2310  ResultTys.push_back(VT2);
2311  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2312}
2313
2314// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2315/// This can cause recursive merging of nodes in the DAG.
2316///
2317/// This version assumes From/To have a single result value.
2318///
2319void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
2320                                      std::vector<SDNode*> *Deleted) {
2321  SDNode *From = FromN.Val, *To = ToN.Val;
2322  assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
2323         "Cannot replace with this method!");
2324  assert(From != To && "Cannot replace uses of with self");
2325
2326  while (!From->use_empty()) {
2327    // Process users until they are all gone.
2328    SDNode *U = *From->use_begin();
2329
2330    // This node is about to morph, remove its old self from the CSE maps.
2331    RemoveNodeFromCSEMaps(U);
2332
2333    for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
2334         I != E; ++I)
2335      if (I->Val == From) {
2336        From->removeUser(U);
2337        I->Val = To;
2338        To->addUser(U);
2339      }
2340
2341    // Now that we have modified U, add it back to the CSE maps.  If it already
2342    // exists there, recursively merge the results together.
2343    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2344      ReplaceAllUsesWith(U, Existing, Deleted);
2345      // U is now dead.
2346      if (Deleted) Deleted->push_back(U);
2347      DeleteNodeNotInCSEMaps(U);
2348    }
2349  }
2350}
2351
2352/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2353/// This can cause recursive merging of nodes in the DAG.
2354///
2355/// This version assumes From/To have matching types and numbers of result
2356/// values.
2357///
2358void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
2359                                      std::vector<SDNode*> *Deleted) {
2360  assert(From != To && "Cannot replace uses of with self");
2361  assert(From->getNumValues() == To->getNumValues() &&
2362         "Cannot use this version of ReplaceAllUsesWith!");
2363  if (From->getNumValues() == 1) {  // If possible, use the faster version.
2364    ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
2365    return;
2366  }
2367
2368  while (!From->use_empty()) {
2369    // Process users until they are all gone.
2370    SDNode *U = *From->use_begin();
2371
2372    // This node is about to morph, remove its old self from the CSE maps.
2373    RemoveNodeFromCSEMaps(U);
2374
2375    for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
2376         I != E; ++I)
2377      if (I->Val == From) {
2378        From->removeUser(U);
2379        I->Val = To;
2380        To->addUser(U);
2381      }
2382
2383    // Now that we have modified U, add it back to the CSE maps.  If it already
2384    // exists there, recursively merge the results together.
2385    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2386      ReplaceAllUsesWith(U, Existing, Deleted);
2387      // U is now dead.
2388      if (Deleted) Deleted->push_back(U);
2389      DeleteNodeNotInCSEMaps(U);
2390    }
2391  }
2392}
2393
2394/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2395/// This can cause recursive merging of nodes in the DAG.
2396///
2397/// This version can replace From with any result values.  To must match the
2398/// number and types of values returned by From.
2399void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
2400                                      const std::vector<SDOperand> &To,
2401                                      std::vector<SDNode*> *Deleted) {
2402  assert(From->getNumValues() == To.size() &&
2403         "Incorrect number of values to replace with!");
2404  if (To.size() == 1 && To[0].Val->getNumValues() == 1) {
2405    // Degenerate case handled above.
2406    ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
2407    return;
2408  }
2409
2410  while (!From->use_empty()) {
2411    // Process users until they are all gone.
2412    SDNode *U = *From->use_begin();
2413
2414    // This node is about to morph, remove its old self from the CSE maps.
2415    RemoveNodeFromCSEMaps(U);
2416
2417    for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
2418         I != E; ++I)
2419      if (I->Val == From) {
2420        const SDOperand &ToOp = To[I->ResNo];
2421        From->removeUser(U);
2422        *I = ToOp;
2423        ToOp.Val->addUser(U);
2424      }
2425
2426    // Now that we have modified U, add it back to the CSE maps.  If it already
2427    // exists there, recursively merge the results together.
2428    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2429      ReplaceAllUsesWith(U, Existing, Deleted);
2430      // U is now dead.
2431      if (Deleted) Deleted->push_back(U);
2432      DeleteNodeNotInCSEMaps(U);
2433    }
2434  }
2435}
2436
2437/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
2438/// uses of other values produced by From.Val alone.  The Deleted vector is
2439/// handled the same was as for ReplaceAllUsesWith.
2440void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
2441                                             std::vector<SDNode*> &Deleted) {
2442  assert(From != To && "Cannot replace a value with itself");
2443  // Handle the simple, trivial, case efficiently.
2444  if (From.Val->getNumValues() == 1 && To.Val->getNumValues() == 1) {
2445    ReplaceAllUsesWith(From, To, &Deleted);
2446    return;
2447  }
2448
2449  // Get all of the users in a nice, deterministically ordered, uniqued set.
2450  SetVector<SDNode*> Users(From.Val->use_begin(), From.Val->use_end());
2451
2452  while (!Users.empty()) {
2453    // We know that this user uses some value of From.  If it is the right
2454    // value, update it.
2455    SDNode *User = Users.back();
2456    Users.pop_back();
2457
2458    for (SDOperand *Op = User->OperandList,
2459         *E = User->OperandList+User->NumOperands; Op != E; ++Op) {
2460      if (*Op == From) {
2461        // Okay, we know this user needs to be updated.  Remove its old self
2462        // from the CSE maps.
2463        RemoveNodeFromCSEMaps(User);
2464
2465        // Update all operands that match "From".
2466        for (; Op != E; ++Op) {
2467          if (*Op == From) {
2468            From.Val->removeUser(User);
2469            *Op = To;
2470            To.Val->addUser(User);
2471          }
2472        }
2473
2474        // Now that we have modified User, add it back to the CSE maps.  If it
2475        // already exists there, recursively merge the results together.
2476        if (SDNode *Existing = AddNonLeafNodeToCSEMaps(User)) {
2477          unsigned NumDeleted = Deleted.size();
2478          ReplaceAllUsesWith(User, Existing, &Deleted);
2479
2480          // User is now dead.
2481          Deleted.push_back(User);
2482          DeleteNodeNotInCSEMaps(User);
2483
2484          // We have to be careful here, because ReplaceAllUsesWith could have
2485          // deleted a user of From, which means there may be dangling pointers
2486          // in the "Users" setvector.  Scan over the deleted node pointers and
2487          // remove them from the setvector.
2488          for (unsigned i = NumDeleted, e = Deleted.size(); i != e; ++i)
2489            Users.remove(Deleted[i]);
2490        }
2491        break;   // Exit the operand scanning loop.
2492      }
2493    }
2494  }
2495}
2496
2497
2498//===----------------------------------------------------------------------===//
2499//                              SDNode Class
2500//===----------------------------------------------------------------------===//
2501
2502
2503/// getValueTypeList - Return a pointer to the specified value type.
2504///
2505MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
2506  static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
2507  VTs[VT] = VT;
2508  return &VTs[VT];
2509}
2510
2511/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
2512/// indicated value.  This method ignores uses of other values defined by this
2513/// operation.
2514bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
2515  assert(Value < getNumValues() && "Bad value!");
2516
2517  // If there is only one value, this is easy.
2518  if (getNumValues() == 1)
2519    return use_size() == NUses;
2520  if (Uses.size() < NUses) return false;
2521
2522  SDOperand TheValue(const_cast<SDNode *>(this), Value);
2523
2524  std::set<SDNode*> UsersHandled;
2525
2526  for (std::vector<SDNode*>::const_iterator UI = Uses.begin(), E = Uses.end();
2527       UI != E; ++UI) {
2528    SDNode *User = *UI;
2529    if (User->getNumOperands() == 1 ||
2530        UsersHandled.insert(User).second)     // First time we've seen this?
2531      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
2532        if (User->getOperand(i) == TheValue) {
2533          if (NUses == 0)
2534            return false;   // too many uses
2535          --NUses;
2536        }
2537  }
2538
2539  // Found exactly the right number of uses?
2540  return NUses == 0;
2541}
2542
2543
2544// isOnlyUse - Return true if this node is the only use of N.
2545bool SDNode::isOnlyUse(SDNode *N) const {
2546  bool Seen = false;
2547  for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
2548    SDNode *User = *I;
2549    if (User == this)
2550      Seen = true;
2551    else
2552      return false;
2553  }
2554
2555  return Seen;
2556}
2557
2558// isOperand - Return true if this node is an operand of N.
2559bool SDOperand::isOperand(SDNode *N) const {
2560  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2561    if (*this == N->getOperand(i))
2562      return true;
2563  return false;
2564}
2565
2566bool SDNode::isOperand(SDNode *N) const {
2567  for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
2568    if (this == N->OperandList[i].Val)
2569      return true;
2570  return false;
2571}
2572
2573const char *SDNode::getOperationName(const SelectionDAG *G) const {
2574  switch (getOpcode()) {
2575  default:
2576    if (getOpcode() < ISD::BUILTIN_OP_END)
2577      return "<<Unknown DAG Node>>";
2578    else {
2579      if (G) {
2580        if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
2581          if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
2582            return TII->getName(getOpcode()-ISD::BUILTIN_OP_END);
2583
2584        TargetLowering &TLI = G->getTargetLoweringInfo();
2585        const char *Name =
2586          TLI.getTargetNodeName(getOpcode());
2587        if (Name) return Name;
2588      }
2589
2590      return "<<Unknown Target Node>>";
2591    }
2592
2593  case ISD::PCMARKER:      return "PCMarker";
2594  case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
2595  case ISD::SRCVALUE:      return "SrcValue";
2596  case ISD::EntryToken:    return "EntryToken";
2597  case ISD::TokenFactor:   return "TokenFactor";
2598  case ISD::AssertSext:    return "AssertSext";
2599  case ISD::AssertZext:    return "AssertZext";
2600
2601  case ISD::STRING:        return "String";
2602  case ISD::BasicBlock:    return "BasicBlock";
2603  case ISD::VALUETYPE:     return "ValueType";
2604  case ISD::Register:      return "Register";
2605
2606  case ISD::Constant:      return "Constant";
2607  case ISD::ConstantFP:    return "ConstantFP";
2608  case ISD::GlobalAddress: return "GlobalAddress";
2609  case ISD::FrameIndex:    return "FrameIndex";
2610  case ISD::ConstantPool:  return "ConstantPool";
2611  case ISD::ExternalSymbol: return "ExternalSymbol";
2612
2613  case ISD::ConstantVec:   return "ConstantVec";
2614  case ISD::TargetConstant: return "TargetConstant";
2615  case ISD::TargetConstantFP:return "TargetConstantFP";
2616  case ISD::TargetConstantVec:return "TargetConstantVec";
2617  case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
2618  case ISD::TargetFrameIndex: return "TargetFrameIndex";
2619  case ISD::TargetConstantPool:  return "TargetConstantPool";
2620  case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
2621  case ISD::VConstant:     return "VConstant";
2622
2623  case ISD::CopyToReg:     return "CopyToReg";
2624  case ISD::CopyFromReg:   return "CopyFromReg";
2625  case ISD::UNDEF:         return "undef";
2626  case ISD::MERGE_VALUES:  return "mergevalues";
2627  case ISD::INLINEASM:     return "inlineasm";
2628  case ISD::HANDLENODE:    return "handlenode";
2629
2630  // Unary operators
2631  case ISD::FABS:   return "fabs";
2632  case ISD::FNEG:   return "fneg";
2633  case ISD::FSQRT:  return "fsqrt";
2634  case ISD::FSIN:   return "fsin";
2635  case ISD::FCOS:   return "fcos";
2636
2637  // Binary operators
2638  case ISD::ADD:    return "add";
2639  case ISD::SUB:    return "sub";
2640  case ISD::MUL:    return "mul";
2641  case ISD::MULHU:  return "mulhu";
2642  case ISD::MULHS:  return "mulhs";
2643  case ISD::SDIV:   return "sdiv";
2644  case ISD::UDIV:   return "udiv";
2645  case ISD::SREM:   return "srem";
2646  case ISD::UREM:   return "urem";
2647  case ISD::AND:    return "and";
2648  case ISD::OR:     return "or";
2649  case ISD::XOR:    return "xor";
2650  case ISD::SHL:    return "shl";
2651  case ISD::SRA:    return "sra";
2652  case ISD::SRL:    return "srl";
2653  case ISD::ROTL:   return "rotl";
2654  case ISD::ROTR:   return "rotr";
2655  case ISD::FADD:   return "fadd";
2656  case ISD::FSUB:   return "fsub";
2657  case ISD::FMUL:   return "fmul";
2658  case ISD::FDIV:   return "fdiv";
2659  case ISD::FREM:   return "frem";
2660  case ISD::FCOPYSIGN: return "fcopysign";
2661  case ISD::VADD:   return "vadd";
2662  case ISD::VSUB:   return "vsub";
2663  case ISD::VMUL:   return "vmul";
2664
2665  case ISD::SETCC:       return "setcc";
2666  case ISD::SELECT:      return "select";
2667  case ISD::SELECT_CC:   return "select_cc";
2668  case ISD::ADDC:        return "addc";
2669  case ISD::ADDE:        return "adde";
2670  case ISD::SUBC:        return "subc";
2671  case ISD::SUBE:        return "sube";
2672  case ISD::SHL_PARTS:   return "shl_parts";
2673  case ISD::SRA_PARTS:   return "sra_parts";
2674  case ISD::SRL_PARTS:   return "srl_parts";
2675
2676  // Conversion operators.
2677  case ISD::SIGN_EXTEND: return "sign_extend";
2678  case ISD::ZERO_EXTEND: return "zero_extend";
2679  case ISD::ANY_EXTEND:  return "any_extend";
2680  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
2681  case ISD::TRUNCATE:    return "truncate";
2682  case ISD::FP_ROUND:    return "fp_round";
2683  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
2684  case ISD::FP_EXTEND:   return "fp_extend";
2685
2686  case ISD::SINT_TO_FP:  return "sint_to_fp";
2687  case ISD::UINT_TO_FP:  return "uint_to_fp";
2688  case ISD::FP_TO_SINT:  return "fp_to_sint";
2689  case ISD::FP_TO_UINT:  return "fp_to_uint";
2690  case ISD::BIT_CONVERT: return "bit_convert";
2691
2692    // Control flow instructions
2693  case ISD::BR:      return "br";
2694  case ISD::BRCOND:  return "brcond";
2695  case ISD::BRCONDTWOWAY:  return "brcondtwoway";
2696  case ISD::BR_CC:  return "br_cc";
2697  case ISD::BRTWOWAY_CC:  return "brtwoway_cc";
2698  case ISD::RET:     return "ret";
2699  case ISD::CALLSEQ_START:  return "callseq_start";
2700  case ISD::CALLSEQ_END:    return "callseq_end";
2701
2702    // Other operators
2703  case ISD::LOAD:               return "load";
2704  case ISD::STORE:              return "store";
2705  case ISD::VLOAD:              return "vload";
2706  case ISD::EXTLOAD:            return "extload";
2707  case ISD::SEXTLOAD:           return "sextload";
2708  case ISD::ZEXTLOAD:           return "zextload";
2709  case ISD::TRUNCSTORE:         return "truncstore";
2710  case ISD::VAARG:              return "vaarg";
2711  case ISD::VACOPY:             return "vacopy";
2712  case ISD::VAEND:              return "vaend";
2713  case ISD::VASTART:            return "vastart";
2714  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
2715  case ISD::EXTRACT_ELEMENT:    return "extract_element";
2716  case ISD::BUILD_PAIR:         return "build_pair";
2717  case ISD::STACKSAVE:          return "stacksave";
2718  case ISD::STACKRESTORE:       return "stackrestore";
2719
2720  // Block memory operations.
2721  case ISD::MEMSET:  return "memset";
2722  case ISD::MEMCPY:  return "memcpy";
2723  case ISD::MEMMOVE: return "memmove";
2724
2725  // Bit manipulation
2726  case ISD::BSWAP:   return "bswap";
2727  case ISD::CTPOP:   return "ctpop";
2728  case ISD::CTTZ:    return "cttz";
2729  case ISD::CTLZ:    return "ctlz";
2730
2731  // Debug info
2732  case ISD::LOCATION: return "location";
2733  case ISD::DEBUG_LOC: return "debug_loc";
2734  case ISD::DEBUG_LABEL: return "debug_label";
2735
2736  case ISD::CONDCODE:
2737    switch (cast<CondCodeSDNode>(this)->get()) {
2738    default: assert(0 && "Unknown setcc condition!");
2739    case ISD::SETOEQ:  return "setoeq";
2740    case ISD::SETOGT:  return "setogt";
2741    case ISD::SETOGE:  return "setoge";
2742    case ISD::SETOLT:  return "setolt";
2743    case ISD::SETOLE:  return "setole";
2744    case ISD::SETONE:  return "setone";
2745
2746    case ISD::SETO:    return "seto";
2747    case ISD::SETUO:   return "setuo";
2748    case ISD::SETUEQ:  return "setue";
2749    case ISD::SETUGT:  return "setugt";
2750    case ISD::SETUGE:  return "setuge";
2751    case ISD::SETULT:  return "setult";
2752    case ISD::SETULE:  return "setule";
2753    case ISD::SETUNE:  return "setune";
2754
2755    case ISD::SETEQ:   return "seteq";
2756    case ISD::SETGT:   return "setgt";
2757    case ISD::SETGE:   return "setge";
2758    case ISD::SETLT:   return "setlt";
2759    case ISD::SETLE:   return "setle";
2760    case ISD::SETNE:   return "setne";
2761    }
2762  }
2763}
2764
2765void SDNode::dump() const { dump(0); }
2766void SDNode::dump(const SelectionDAG *G) const {
2767  std::cerr << (void*)this << ": ";
2768
2769  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
2770    if (i) std::cerr << ",";
2771    if (getValueType(i) == MVT::Other)
2772      std::cerr << "ch";
2773    else
2774      std::cerr << MVT::getValueTypeString(getValueType(i));
2775  }
2776  std::cerr << " = " << getOperationName(G);
2777
2778  std::cerr << " ";
2779  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2780    if (i) std::cerr << ", ";
2781    std::cerr << (void*)getOperand(i).Val;
2782    if (unsigned RN = getOperand(i).ResNo)
2783      std::cerr << ":" << RN;
2784  }
2785
2786  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
2787    std::cerr << "<" << CSDN->getValue() << ">";
2788  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
2789    std::cerr << "<" << CSDN->getValue() << ">";
2790  } else if (const GlobalAddressSDNode *GADN =
2791             dyn_cast<GlobalAddressSDNode>(this)) {
2792    int offset = GADN->getOffset();
2793    std::cerr << "<";
2794    WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
2795    if (offset > 0)
2796      std::cerr << " + " << offset;
2797    else
2798      std::cerr << " " << offset;
2799  } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
2800    std::cerr << "<" << FIDN->getIndex() << ">";
2801  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
2802    int offset = CP->getOffset();
2803    std::cerr << "<" << *CP->get() << ">";
2804    if (offset > 0)
2805      std::cerr << " + " << offset;
2806    else
2807      std::cerr << " " << offset;
2808  } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
2809    std::cerr << "<";
2810    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
2811    if (LBB)
2812      std::cerr << LBB->getName() << " ";
2813    std::cerr << (const void*)BBDN->getBasicBlock() << ">";
2814  } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
2815    if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
2816      std::cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
2817    } else {
2818      std::cerr << " #" << R->getReg();
2819    }
2820  } else if (const ExternalSymbolSDNode *ES =
2821             dyn_cast<ExternalSymbolSDNode>(this)) {
2822    std::cerr << "'" << ES->getSymbol() << "'";
2823  } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
2824    if (M->getValue())
2825      std::cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
2826    else
2827      std::cerr << "<null:" << M->getOffset() << ">";
2828  } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
2829    std::cerr << ":" << getValueTypeString(N->getVT());
2830  }
2831}
2832
2833static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
2834  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2835    if (N->getOperand(i).Val->hasOneUse())
2836      DumpNodes(N->getOperand(i).Val, indent+2, G);
2837    else
2838      std::cerr << "\n" << std::string(indent+2, ' ')
2839                << (void*)N->getOperand(i).Val << ": <multiple use>";
2840
2841
2842  std::cerr << "\n" << std::string(indent, ' ');
2843  N->dump(G);
2844}
2845
2846void SelectionDAG::dump() const {
2847  std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
2848  std::vector<const SDNode*> Nodes;
2849  for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
2850       I != E; ++I)
2851    Nodes.push_back(I);
2852
2853  std::sort(Nodes.begin(), Nodes.end());
2854
2855  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2856    if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
2857      DumpNodes(Nodes[i], 2, this);
2858  }
2859
2860  DumpNodes(getRoot().Val, 2, this);
2861
2862  std::cerr << "\n\n";
2863}
2864
2865/// InsertISelMapEntry - A helper function to insert a key / element pair
2866/// into a SDOperand to SDOperand map. This is added to avoid the map
2867/// insertion operator from being inlined.
2868void SelectionDAG::InsertISelMapEntry(std::map<SDOperand, SDOperand> &Map,
2869                                      SDNode *Key, unsigned KeyResNo,
2870                                      SDNode *Element, unsigned ElementResNo) {
2871  Map.insert(std::make_pair(SDOperand(Key, KeyResNo),
2872                            SDOperand(Element, ElementResNo)));
2873}
2874