SelectionDAG.cpp revision ce87215131efcc68dcf7fca61055ad783a7aeb0e
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::SCALAR_TO_VECTOR:
1096    assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1097           MVT::getVectorBaseType(VT) == Operand.getValueType() &&
1098           "Illegal SCALAR_TO_VECTOR node!");
1099    break;
1100  case ISD::FNEG:
1101    if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
1102      return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1103                     Operand.Val->getOperand(0));
1104    if (OpOpcode == ISD::FNEG)  // --X -> X
1105      return Operand.Val->getOperand(0);
1106    break;
1107  case ISD::FABS:
1108    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
1109      return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1110    break;
1111  }
1112
1113  SDNode *N;
1114  if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1115    SDNode *&E = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
1116    if (E) return SDOperand(E, 0);
1117    E = N = new SDNode(Opcode, Operand);
1118  } else {
1119    N = new SDNode(Opcode, Operand);
1120  }
1121  N->setValueTypes(VT);
1122  AllNodes.push_back(N);
1123  return SDOperand(N, 0);
1124}
1125
1126
1127
1128SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1129                                SDOperand N1, SDOperand N2) {
1130#ifndef NDEBUG
1131  switch (Opcode) {
1132  case ISD::TokenFactor:
1133    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1134           N2.getValueType() == MVT::Other && "Invalid token factor!");
1135    break;
1136  case ISD::AND:
1137  case ISD::OR:
1138  case ISD::XOR:
1139  case ISD::UDIV:
1140  case ISD::UREM:
1141  case ISD::MULHU:
1142  case ISD::MULHS:
1143    assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1144    // fall through
1145  case ISD::ADD:
1146  case ISD::SUB:
1147  case ISD::MUL:
1148  case ISD::SDIV:
1149  case ISD::SREM:
1150    assert(MVT::isInteger(N1.getValueType()) && "Should use F* for FP ops");
1151    // fall through.
1152  case ISD::FADD:
1153  case ISD::FSUB:
1154  case ISD::FMUL:
1155  case ISD::FDIV:
1156  case ISD::FREM:
1157    assert(N1.getValueType() == N2.getValueType() &&
1158           N1.getValueType() == VT && "Binary operator types must match!");
1159    break;
1160  case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
1161    assert(N1.getValueType() == VT &&
1162           MVT::isFloatingPoint(N1.getValueType()) &&
1163           MVT::isFloatingPoint(N2.getValueType()) &&
1164           "Invalid FCOPYSIGN!");
1165    break;
1166  case ISD::SHL:
1167  case ISD::SRA:
1168  case ISD::SRL:
1169  case ISD::ROTL:
1170  case ISD::ROTR:
1171    assert(VT == N1.getValueType() &&
1172           "Shift operators return type must be the same as their first arg");
1173    assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1174           VT != MVT::i1 && "Shifts only work on integers");
1175    break;
1176  case ISD::FP_ROUND_INREG: {
1177    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1178    assert(VT == N1.getValueType() && "Not an inreg round!");
1179    assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1180           "Cannot FP_ROUND_INREG integer types");
1181    assert(EVT <= VT && "Not rounding down!");
1182    break;
1183  }
1184  case ISD::AssertSext:
1185  case ISD::AssertZext:
1186  case ISD::SIGN_EXTEND_INREG: {
1187    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1188    assert(VT == N1.getValueType() && "Not an inreg extend!");
1189    assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1190           "Cannot *_EXTEND_INREG FP types");
1191    assert(EVT <= VT && "Not extending!");
1192  }
1193
1194  default: break;
1195  }
1196#endif
1197
1198  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1199  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1200  if (N1C) {
1201    if (N2C) {
1202      uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
1203      switch (Opcode) {
1204      case ISD::ADD: return getConstant(C1 + C2, VT);
1205      case ISD::SUB: return getConstant(C1 - C2, VT);
1206      case ISD::MUL: return getConstant(C1 * C2, VT);
1207      case ISD::UDIV:
1208        if (C2) return getConstant(C1 / C2, VT);
1209        break;
1210      case ISD::UREM :
1211        if (C2) return getConstant(C1 % C2, VT);
1212        break;
1213      case ISD::SDIV :
1214        if (C2) return getConstant(N1C->getSignExtended() /
1215                                   N2C->getSignExtended(), VT);
1216        break;
1217      case ISD::SREM :
1218        if (C2) return getConstant(N1C->getSignExtended() %
1219                                   N2C->getSignExtended(), VT);
1220        break;
1221      case ISD::AND  : return getConstant(C1 & C2, VT);
1222      case ISD::OR   : return getConstant(C1 | C2, VT);
1223      case ISD::XOR  : return getConstant(C1 ^ C2, VT);
1224      case ISD::SHL  : return getConstant(C1 << C2, VT);
1225      case ISD::SRL  : return getConstant(C1 >> C2, VT);
1226      case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
1227      case ISD::ROTL :
1228        return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
1229                           VT);
1230      case ISD::ROTR :
1231        return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)),
1232                           VT);
1233      default: break;
1234      }
1235    } else {      // Cannonicalize constant to RHS if commutative
1236      if (isCommutativeBinOp(Opcode)) {
1237        std::swap(N1C, N2C);
1238        std::swap(N1, N2);
1239      }
1240    }
1241  }
1242
1243  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1244  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1245  if (N1CFP) {
1246    if (N2CFP) {
1247      double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
1248      switch (Opcode) {
1249      case ISD::FADD: return getConstantFP(C1 + C2, VT);
1250      case ISD::FSUB: return getConstantFP(C1 - C2, VT);
1251      case ISD::FMUL: return getConstantFP(C1 * C2, VT);
1252      case ISD::FDIV:
1253        if (C2) return getConstantFP(C1 / C2, VT);
1254        break;
1255      case ISD::FREM :
1256        if (C2) return getConstantFP(fmod(C1, C2), VT);
1257        break;
1258      case ISD::FCOPYSIGN: {
1259        union {
1260          double   F;
1261          uint64_t I;
1262        } u1;
1263        union {
1264          double  F;
1265          int64_t I;
1266        } u2;
1267        u1.F = C1;
1268        u2.F = C2;
1269        if (u2.I < 0)  // Sign bit of RHS set?
1270          u1.I |= 1ULL << 63;      // Set the sign bit of the LHS.
1271        else
1272          u1.I &= (1ULL << 63)-1;  // Clear the sign bit of the LHS.
1273        return getConstantFP(u1.F, VT);
1274      }
1275      default: break;
1276      }
1277    } else {      // Cannonicalize constant to RHS if commutative
1278      if (isCommutativeBinOp(Opcode)) {
1279        std::swap(N1CFP, N2CFP);
1280        std::swap(N1, N2);
1281      }
1282    }
1283  }
1284
1285  // Finally, fold operations that do not require constants.
1286  switch (Opcode) {
1287  case ISD::FP_ROUND_INREG:
1288    if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
1289    break;
1290  case ISD::SIGN_EXTEND_INREG: {
1291    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1292    if (EVT == VT) return N1;  // Not actually extending
1293    break;
1294  }
1295
1296  // FIXME: figure out how to safely handle things like
1297  // int foo(int x) { return 1 << (x & 255); }
1298  // int bar() { return foo(256); }
1299#if 0
1300  case ISD::SHL:
1301  case ISD::SRL:
1302  case ISD::SRA:
1303    if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1304        cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
1305      return getNode(Opcode, VT, N1, N2.getOperand(0));
1306    else if (N2.getOpcode() == ISD::AND)
1307      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
1308        // If the and is only masking out bits that cannot effect the shift,
1309        // eliminate the and.
1310        unsigned NumBits = MVT::getSizeInBits(VT);
1311        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1312          return getNode(Opcode, VT, N1, N2.getOperand(0));
1313      }
1314    break;
1315#endif
1316  }
1317
1318  // Memoize this node if possible.
1319  SDNode *N;
1320  if (VT != MVT::Flag) {
1321    SDNode *&BON = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
1322    if (BON) return SDOperand(BON, 0);
1323
1324    BON = N = new SDNode(Opcode, N1, N2);
1325  } else {
1326    N = new SDNode(Opcode, N1, N2);
1327  }
1328
1329  N->setValueTypes(VT);
1330  AllNodes.push_back(N);
1331  return SDOperand(N, 0);
1332}
1333
1334SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1335                                SDOperand N1, SDOperand N2, SDOperand N3) {
1336  // Perform various simplifications.
1337  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1338  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1339  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
1340  switch (Opcode) {
1341  case ISD::SETCC: {
1342    // Use SimplifySetCC  to simplify SETCC's.
1343    SDOperand Simp = SimplifySetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
1344    if (Simp.Val) return Simp;
1345    break;
1346  }
1347  case ISD::SELECT:
1348    if (N1C)
1349      if (N1C->getValue())
1350        return N2;             // select true, X, Y -> X
1351      else
1352        return N3;             // select false, X, Y -> Y
1353
1354    if (N2 == N3) return N2;   // select C, X, X -> X
1355    break;
1356  case ISD::BRCOND:
1357    if (N2C)
1358      if (N2C->getValue()) // Unconditional branch
1359        return getNode(ISD::BR, MVT::Other, N1, N3);
1360      else
1361        return N1;         // Never-taken branch
1362    break;
1363  }
1364
1365  std::vector<SDOperand> Ops;
1366  Ops.reserve(3);
1367  Ops.push_back(N1);
1368  Ops.push_back(N2);
1369  Ops.push_back(N3);
1370
1371  // Memoize node if it doesn't produce a flag.
1372  SDNode *N;
1373  if (VT != MVT::Flag) {
1374    SDNode *&E = OneResultNodes[std::make_pair(Opcode,std::make_pair(VT, Ops))];
1375    if (E) return SDOperand(E, 0);
1376    E = N = new SDNode(Opcode, N1, N2, N3);
1377  } else {
1378    N = new SDNode(Opcode, N1, N2, N3);
1379  }
1380  N->setValueTypes(VT);
1381  AllNodes.push_back(N);
1382  return SDOperand(N, 0);
1383}
1384
1385SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1386                                SDOperand N1, SDOperand N2, SDOperand N3,
1387                                SDOperand N4) {
1388  std::vector<SDOperand> Ops;
1389  Ops.reserve(4);
1390  Ops.push_back(N1);
1391  Ops.push_back(N2);
1392  Ops.push_back(N3);
1393  Ops.push_back(N4);
1394  return getNode(Opcode, VT, Ops);
1395}
1396
1397SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1398                                SDOperand N1, SDOperand N2, SDOperand N3,
1399                                SDOperand N4, SDOperand N5) {
1400  std::vector<SDOperand> Ops;
1401  Ops.reserve(5);
1402  Ops.push_back(N1);
1403  Ops.push_back(N2);
1404  Ops.push_back(N3);
1405  Ops.push_back(N4);
1406  Ops.push_back(N5);
1407  return getNode(Opcode, VT, Ops);
1408}
1409
1410SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
1411                                SDOperand Chain, SDOperand Ptr,
1412                                SDOperand SV) {
1413  SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
1414  if (N) return SDOperand(N, 0);
1415  N = new SDNode(ISD::LOAD, Chain, Ptr, SV);
1416
1417  // Loads have a token chain.
1418  setNodeValueTypes(N, VT, MVT::Other);
1419  AllNodes.push_back(N);
1420  return SDOperand(N, 0);
1421}
1422
1423SDOperand SelectionDAG::getVecLoad(unsigned Count, MVT::ValueType EVT,
1424                                   SDOperand Chain, SDOperand Ptr,
1425                                   SDOperand SV) {
1426  SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, EVT))];
1427  if (N) return SDOperand(N, 0);
1428  std::vector<SDOperand> Ops;
1429  Ops.reserve(5);
1430  Ops.push_back(Chain);
1431  Ops.push_back(Ptr);
1432  Ops.push_back(SV);
1433  Ops.push_back(getConstant(Count, MVT::i32));
1434  Ops.push_back(getValueType(EVT));
1435  std::vector<MVT::ValueType> VTs;
1436  VTs.reserve(2);
1437  VTs.push_back(MVT::Vector); VTs.push_back(MVT::Other);  // Add token chain.
1438  return getNode(ISD::VLOAD, VTs, Ops);
1439}
1440
1441SDOperand SelectionDAG::getExtLoad(unsigned Opcode, MVT::ValueType VT,
1442                                   SDOperand Chain, SDOperand Ptr, SDOperand SV,
1443                                   MVT::ValueType EVT) {
1444  std::vector<SDOperand> Ops;
1445  Ops.reserve(4);
1446  Ops.push_back(Chain);
1447  Ops.push_back(Ptr);
1448  Ops.push_back(SV);
1449  Ops.push_back(getValueType(EVT));
1450  std::vector<MVT::ValueType> VTs;
1451  VTs.reserve(2);
1452  VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
1453  return getNode(Opcode, VTs, Ops);
1454}
1455
1456SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
1457  assert((!V || isa<PointerType>(V->getType())) &&
1458         "SrcValue is not a pointer?");
1459  SDNode *&N = ValueNodes[std::make_pair(V, Offset)];
1460  if (N) return SDOperand(N, 0);
1461
1462  N = new SrcValueSDNode(V, Offset);
1463  AllNodes.push_back(N);
1464  return SDOperand(N, 0);
1465}
1466
1467SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
1468                                 SDOperand Chain, SDOperand Ptr,
1469                                 SDOperand SV) {
1470  std::vector<SDOperand> Ops;
1471  Ops.reserve(3);
1472  Ops.push_back(Chain);
1473  Ops.push_back(Ptr);
1474  Ops.push_back(SV);
1475  std::vector<MVT::ValueType> VTs;
1476  VTs.reserve(2);
1477  VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
1478  return getNode(ISD::VAARG, VTs, Ops);
1479}
1480
1481SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1482                                std::vector<SDOperand> &Ops) {
1483  switch (Ops.size()) {
1484  case 0: return getNode(Opcode, VT);
1485  case 1: return getNode(Opcode, VT, Ops[0]);
1486  case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
1487  case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
1488  default: break;
1489  }
1490
1491  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Ops[1].Val);
1492  switch (Opcode) {
1493  default: break;
1494  case ISD::TRUNCSTORE: {
1495    assert(Ops.size() == 5 && "TRUNCSTORE takes 5 operands!");
1496    MVT::ValueType EVT = cast<VTSDNode>(Ops[4])->getVT();
1497#if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1498    // If this is a truncating store of a constant, convert to the desired type
1499    // and store it instead.
1500    if (isa<Constant>(Ops[0])) {
1501      SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1502      if (isa<Constant>(Op))
1503        N1 = Op;
1504    }
1505    // Also for ConstantFP?
1506#endif
1507    if (Ops[0].getValueType() == EVT)       // Normal store?
1508      return getNode(ISD::STORE, VT, Ops[0], Ops[1], Ops[2], Ops[3]);
1509    assert(Ops[1].getValueType() > EVT && "Not a truncation?");
1510    assert(MVT::isInteger(Ops[1].getValueType()) == MVT::isInteger(EVT) &&
1511           "Can't do FP-INT conversion!");
1512    break;
1513  }
1514  case ISD::SELECT_CC: {
1515    assert(Ops.size() == 5 && "SELECT_CC takes 5 operands!");
1516    assert(Ops[0].getValueType() == Ops[1].getValueType() &&
1517           "LHS and RHS of condition must have same type!");
1518    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1519           "True and False arms of SelectCC must have same type!");
1520    assert(Ops[2].getValueType() == VT &&
1521           "select_cc node must be of same type as true and false value!");
1522    break;
1523  }
1524  case ISD::BR_CC: {
1525    assert(Ops.size() == 5 && "BR_CC takes 5 operands!");
1526    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1527           "LHS/RHS of comparison should match types!");
1528    break;
1529  }
1530  }
1531
1532  // Memoize nodes.
1533  SDNode *N;
1534  if (VT != MVT::Flag) {
1535    SDNode *&E =
1536      OneResultNodes[std::make_pair(Opcode, std::make_pair(VT, Ops))];
1537    if (E) return SDOperand(E, 0);
1538    E = N = new SDNode(Opcode, Ops);
1539  } else {
1540    N = new SDNode(Opcode, Ops);
1541  }
1542  N->setValueTypes(VT);
1543  AllNodes.push_back(N);
1544  return SDOperand(N, 0);
1545}
1546
1547SDOperand SelectionDAG::getNode(unsigned Opcode,
1548                                std::vector<MVT::ValueType> &ResultTys,
1549                                std::vector<SDOperand> &Ops) {
1550  if (ResultTys.size() == 1)
1551    return getNode(Opcode, ResultTys[0], Ops);
1552
1553  switch (Opcode) {
1554  case ISD::EXTLOAD:
1555  case ISD::SEXTLOAD:
1556  case ISD::ZEXTLOAD: {
1557    MVT::ValueType EVT = cast<VTSDNode>(Ops[3])->getVT();
1558    assert(Ops.size() == 4 && ResultTys.size() == 2 && "Bad *EXTLOAD!");
1559    // If they are asking for an extending load from/to the same thing, return a
1560    // normal load.
1561    if (ResultTys[0] == EVT)
1562      return getLoad(ResultTys[0], Ops[0], Ops[1], Ops[2]);
1563    if (MVT::isVector(ResultTys[0])) {
1564      assert(EVT == MVT::getVectorBaseType(ResultTys[0]) &&
1565             "Invalid vector extload!");
1566    } else {
1567      assert(EVT < ResultTys[0] &&
1568             "Should only be an extending load, not truncating!");
1569    }
1570    assert((Opcode == ISD::EXTLOAD || MVT::isInteger(ResultTys[0])) &&
1571           "Cannot sign/zero extend a FP/Vector load!");
1572    assert(MVT::isInteger(ResultTys[0]) == MVT::isInteger(EVT) &&
1573           "Cannot convert from FP to Int or Int -> FP!");
1574    break;
1575  }
1576
1577  // FIXME: figure out how to safely handle things like
1578  // int foo(int x) { return 1 << (x & 255); }
1579  // int bar() { return foo(256); }
1580#if 0
1581  case ISD::SRA_PARTS:
1582  case ISD::SRL_PARTS:
1583  case ISD::SHL_PARTS:
1584    if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1585        cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
1586      return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1587    else if (N3.getOpcode() == ISD::AND)
1588      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
1589        // If the and is only masking out bits that cannot effect the shift,
1590        // eliminate the and.
1591        unsigned NumBits = MVT::getSizeInBits(VT)*2;
1592        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1593          return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1594      }
1595    break;
1596#endif
1597  }
1598
1599  // Memoize the node unless it returns a flag.
1600  SDNode *N;
1601  if (ResultTys.back() != MVT::Flag) {
1602    SDNode *&E =
1603      ArbitraryNodes[std::make_pair(Opcode, std::make_pair(ResultTys, Ops))];
1604    if (E) return SDOperand(E, 0);
1605    E = N = new SDNode(Opcode, Ops);
1606  } else {
1607    N = new SDNode(Opcode, Ops);
1608  }
1609  setNodeValueTypes(N, ResultTys);
1610  AllNodes.push_back(N);
1611  return SDOperand(N, 0);
1612}
1613
1614void SelectionDAG::setNodeValueTypes(SDNode *N,
1615                                     std::vector<MVT::ValueType> &RetVals) {
1616  switch (RetVals.size()) {
1617  case 0: return;
1618  case 1: N->setValueTypes(RetVals[0]); return;
1619  case 2: setNodeValueTypes(N, RetVals[0], RetVals[1]); return;
1620  default: break;
1621  }
1622
1623  std::list<std::vector<MVT::ValueType> >::iterator I =
1624    std::find(VTList.begin(), VTList.end(), RetVals);
1625  if (I == VTList.end()) {
1626    VTList.push_front(RetVals);
1627    I = VTList.begin();
1628  }
1629
1630  N->setValueTypes(&(*I)[0], I->size());
1631}
1632
1633void SelectionDAG::setNodeValueTypes(SDNode *N, MVT::ValueType VT1,
1634                                     MVT::ValueType VT2) {
1635  for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
1636       E = VTList.end(); I != E; ++I) {
1637    if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2) {
1638      N->setValueTypes(&(*I)[0], 2);
1639      return;
1640    }
1641  }
1642  std::vector<MVT::ValueType> V;
1643  V.push_back(VT1);
1644  V.push_back(VT2);
1645  VTList.push_front(V);
1646  N->setValueTypes(&(*VTList.begin())[0], 2);
1647}
1648
1649/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
1650/// specified operands.  If the resultant node already exists in the DAG,
1651/// this does not modify the specified node, instead it returns the node that
1652/// already exists.  If the resultant node does not exist in the DAG, the
1653/// input node is returned.  As a degenerate case, if you specify the same
1654/// input operands as the node already has, the input node is returned.
1655SDOperand SelectionDAG::
1656UpdateNodeOperands(SDOperand InN, SDOperand Op) {
1657  SDNode *N = InN.Val;
1658  assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
1659
1660  // Check to see if there is no change.
1661  if (Op == N->getOperand(0)) return InN;
1662
1663  // See if the modified node already exists.
1664  SDNode **NewSlot = FindModifiedNodeSlot(N, Op);
1665  if (NewSlot && *NewSlot)
1666    return SDOperand(*NewSlot, InN.ResNo);
1667
1668  // Nope it doesn't.  Remove the node from it's current place in the maps.
1669  if (NewSlot)
1670    RemoveNodeFromCSEMaps(N);
1671
1672  // Now we update the operands.
1673  N->OperandList[0].Val->removeUser(N);
1674  Op.Val->addUser(N);
1675  N->OperandList[0] = Op;
1676
1677  // If this gets put into a CSE map, add it.
1678  if (NewSlot) *NewSlot = N;
1679  return InN;
1680}
1681
1682SDOperand SelectionDAG::
1683UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
1684  SDNode *N = InN.Val;
1685  assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
1686
1687  // Check to see if there is no change.
1688  bool AnyChange = false;
1689  if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
1690    return InN;   // No operands changed, just return the input node.
1691
1692  // See if the modified node already exists.
1693  SDNode **NewSlot = FindModifiedNodeSlot(N, Op1, Op2);
1694  if (NewSlot && *NewSlot)
1695    return SDOperand(*NewSlot, InN.ResNo);
1696
1697  // Nope it doesn't.  Remove the node from it's current place in the maps.
1698  if (NewSlot)
1699    RemoveNodeFromCSEMaps(N);
1700
1701  // Now we update the operands.
1702  if (N->OperandList[0] != Op1) {
1703    N->OperandList[0].Val->removeUser(N);
1704    Op1.Val->addUser(N);
1705    N->OperandList[0] = Op1;
1706  }
1707  if (N->OperandList[1] != Op2) {
1708    N->OperandList[1].Val->removeUser(N);
1709    Op2.Val->addUser(N);
1710    N->OperandList[1] = Op2;
1711  }
1712
1713  // If this gets put into a CSE map, add it.
1714  if (NewSlot) *NewSlot = N;
1715  return InN;
1716}
1717
1718SDOperand SelectionDAG::
1719UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
1720  std::vector<SDOperand> Ops;
1721  Ops.push_back(Op1);
1722  Ops.push_back(Op2);
1723  Ops.push_back(Op3);
1724  return UpdateNodeOperands(N, Ops);
1725}
1726
1727SDOperand SelectionDAG::
1728UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
1729                   SDOperand Op3, SDOperand Op4) {
1730  std::vector<SDOperand> Ops;
1731  Ops.push_back(Op1);
1732  Ops.push_back(Op2);
1733  Ops.push_back(Op3);
1734  Ops.push_back(Op4);
1735  return UpdateNodeOperands(N, Ops);
1736}
1737
1738SDOperand SelectionDAG::
1739UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
1740                   SDOperand Op3, SDOperand Op4, SDOperand Op5) {
1741  std::vector<SDOperand> Ops;
1742  Ops.push_back(Op1);
1743  Ops.push_back(Op2);
1744  Ops.push_back(Op3);
1745  Ops.push_back(Op4);
1746  Ops.push_back(Op5);
1747  return UpdateNodeOperands(N, Ops);
1748}
1749
1750
1751SDOperand SelectionDAG::
1752UpdateNodeOperands(SDOperand InN, const std::vector<SDOperand> &Ops) {
1753  SDNode *N = InN.Val;
1754  assert(N->getNumOperands() == Ops.size() &&
1755         "Update with wrong number of operands");
1756
1757  // Check to see if there is no change.
1758  unsigned NumOps = Ops.size();
1759  bool AnyChange = false;
1760  for (unsigned i = 0; i != NumOps; ++i) {
1761    if (Ops[i] != N->getOperand(i)) {
1762      AnyChange = true;
1763      break;
1764    }
1765  }
1766
1767  // No operands changed, just return the input node.
1768  if (!AnyChange) return InN;
1769
1770  // See if the modified node already exists.
1771  SDNode **NewSlot = FindModifiedNodeSlot(N, Ops);
1772  if (NewSlot && *NewSlot)
1773    return SDOperand(*NewSlot, InN.ResNo);
1774
1775  // Nope it doesn't.  Remove the node from it's current place in the maps.
1776  if (NewSlot)
1777    RemoveNodeFromCSEMaps(N);
1778
1779  // Now we update the operands.
1780  for (unsigned i = 0; i != NumOps; ++i) {
1781    if (N->OperandList[i] != Ops[i]) {
1782      N->OperandList[i].Val->removeUser(N);
1783      Ops[i].Val->addUser(N);
1784      N->OperandList[i] = Ops[i];
1785    }
1786  }
1787
1788  // If this gets put into a CSE map, add it.
1789  if (NewSlot) *NewSlot = N;
1790  return InN;
1791}
1792
1793
1794
1795
1796/// SelectNodeTo - These are used for target selectors to *mutate* the
1797/// specified node to have the specified return type, Target opcode, and
1798/// operands.  Note that target opcodes are stored as
1799/// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
1800///
1801/// Note that SelectNodeTo returns the resultant node.  If there is already a
1802/// node of the specified opcode and operands, it returns that node instead of
1803/// the current one.
1804SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1805                                     MVT::ValueType VT) {
1806  // If an identical node already exists, use it.
1807  SDNode *&ON = NullaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, VT)];
1808  if (ON) return SDOperand(ON, 0);
1809
1810  RemoveNodeFromCSEMaps(N);
1811
1812  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1813  N->setValueTypes(VT);
1814
1815  ON = N;   // Memoize the new node.
1816  return SDOperand(N, 0);
1817}
1818
1819SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1820                                     MVT::ValueType VT, SDOperand Op1) {
1821  // If an identical node already exists, use it.
1822  SDNode *&ON = UnaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1823                                        std::make_pair(Op1, VT))];
1824  if (ON) return SDOperand(ON, 0);
1825
1826  RemoveNodeFromCSEMaps(N);
1827  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1828  N->setValueTypes(VT);
1829  N->setOperands(Op1);
1830
1831  ON = N;   // Memoize the new node.
1832  return SDOperand(N, 0);
1833}
1834
1835SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1836                                     MVT::ValueType VT, SDOperand Op1,
1837                                     SDOperand Op2) {
1838  // If an identical node already exists, use it.
1839  SDNode *&ON = BinaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1840                                         std::make_pair(Op1, Op2))];
1841  if (ON) return SDOperand(ON, 0);
1842
1843  RemoveNodeFromCSEMaps(N);
1844  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1845  N->setValueTypes(VT);
1846  N->setOperands(Op1, Op2);
1847
1848  ON = N;   // Memoize the new node.
1849  return SDOperand(N, 0);
1850}
1851
1852SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1853                                     MVT::ValueType VT, SDOperand Op1,
1854                                     SDOperand Op2, SDOperand Op3) {
1855  // If an identical node already exists, use it.
1856  std::vector<SDOperand> OpList;
1857  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1858  SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1859                                              std::make_pair(VT, OpList))];
1860  if (ON) return SDOperand(ON, 0);
1861
1862  RemoveNodeFromCSEMaps(N);
1863  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1864  N->setValueTypes(VT);
1865  N->setOperands(Op1, Op2, Op3);
1866
1867  ON = N;   // Memoize the new node.
1868  return SDOperand(N, 0);
1869}
1870
1871SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1872                                     MVT::ValueType VT, SDOperand Op1,
1873                                     SDOperand Op2, SDOperand Op3,
1874                                     SDOperand Op4) {
1875  // If an identical node already exists, use it.
1876  std::vector<SDOperand> OpList;
1877  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1878  OpList.push_back(Op4);
1879  SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1880                                              std::make_pair(VT, OpList))];
1881  if (ON) return SDOperand(ON, 0);
1882
1883  RemoveNodeFromCSEMaps(N);
1884  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1885  N->setValueTypes(VT);
1886  N->setOperands(Op1, Op2, Op3, Op4);
1887
1888  ON = N;   // Memoize the new node.
1889  return SDOperand(N, 0);
1890}
1891
1892SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1893                                     MVT::ValueType VT, SDOperand Op1,
1894                                     SDOperand Op2, SDOperand Op3,SDOperand Op4,
1895                                     SDOperand Op5) {
1896  // If an identical node already exists, use it.
1897  std::vector<SDOperand> OpList;
1898  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1899  OpList.push_back(Op4); OpList.push_back(Op5);
1900  SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1901                                              std::make_pair(VT, OpList))];
1902  if (ON) return SDOperand(ON, 0);
1903
1904  RemoveNodeFromCSEMaps(N);
1905  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1906  N->setValueTypes(VT);
1907  N->setOperands(Op1, Op2, Op3, Op4, Op5);
1908
1909  ON = N;   // Memoize the new node.
1910  return SDOperand(N, 0);
1911}
1912
1913SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1914                                     MVT::ValueType VT, SDOperand Op1,
1915                                     SDOperand Op2, SDOperand Op3,SDOperand Op4,
1916                                     SDOperand Op5, SDOperand Op6) {
1917  // If an identical node already exists, use it.
1918  std::vector<SDOperand> OpList;
1919  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1920  OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6);
1921  SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1922                                              std::make_pair(VT, OpList))];
1923  if (ON) return SDOperand(ON, 0);
1924
1925  RemoveNodeFromCSEMaps(N);
1926  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1927  N->setValueTypes(VT);
1928  N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6);
1929
1930  ON = N;   // Memoize the new node.
1931  return SDOperand(N, 0);
1932}
1933
1934SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1935                                     MVT::ValueType VT, SDOperand Op1,
1936                                     SDOperand Op2, SDOperand Op3,SDOperand Op4,
1937                                     SDOperand Op5, SDOperand Op6,
1938				     SDOperand Op7) {
1939  // If an identical node already exists, use it.
1940  std::vector<SDOperand> OpList;
1941  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1942  OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6);
1943  OpList.push_back(Op7);
1944  SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1945                                              std::make_pair(VT, OpList))];
1946  if (ON) return SDOperand(ON, 0);
1947
1948  RemoveNodeFromCSEMaps(N);
1949  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1950  N->setValueTypes(VT);
1951  N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6, Op7);
1952
1953  ON = N;   // Memoize the new node.
1954  return SDOperand(N, 0);
1955}
1956SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1957                                     MVT::ValueType VT, SDOperand Op1,
1958                                     SDOperand Op2, SDOperand Op3,SDOperand Op4,
1959                                     SDOperand Op5, SDOperand Op6,
1960				     SDOperand Op7, SDOperand Op8) {
1961  // If an identical node already exists, use it.
1962  std::vector<SDOperand> OpList;
1963  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1964  OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6);
1965  OpList.push_back(Op7); OpList.push_back(Op8);
1966  SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1967                                              std::make_pair(VT, OpList))];
1968  if (ON) return SDOperand(ON, 0);
1969
1970  RemoveNodeFromCSEMaps(N);
1971  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1972  N->setValueTypes(VT);
1973  N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6, Op7, Op8);
1974
1975  ON = N;   // Memoize the new node.
1976  return SDOperand(N, 0);
1977}
1978
1979SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1980                                     MVT::ValueType VT1, MVT::ValueType VT2,
1981                                     SDOperand Op1, SDOperand Op2) {
1982  // If an identical node already exists, use it.
1983  std::vector<SDOperand> OpList;
1984  OpList.push_back(Op1); OpList.push_back(Op2);
1985  std::vector<MVT::ValueType> VTList;
1986  VTList.push_back(VT1); VTList.push_back(VT2);
1987  SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1988                                              std::make_pair(VTList, OpList))];
1989  if (ON) return SDOperand(ON, 0);
1990
1991  RemoveNodeFromCSEMaps(N);
1992  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1993  setNodeValueTypes(N, VT1, VT2);
1994  N->setOperands(Op1, Op2);
1995
1996  ON = N;   // Memoize the new node.
1997  return SDOperand(N, 0);
1998}
1999
2000SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2001                                     MVT::ValueType VT1, MVT::ValueType VT2,
2002                                     SDOperand Op1, SDOperand Op2,
2003                                     SDOperand Op3) {
2004  // If an identical node already exists, use it.
2005  std::vector<SDOperand> OpList;
2006  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
2007  std::vector<MVT::ValueType> VTList;
2008  VTList.push_back(VT1); VTList.push_back(VT2);
2009  SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
2010                                              std::make_pair(VTList, OpList))];
2011  if (ON) return SDOperand(ON, 0);
2012
2013  RemoveNodeFromCSEMaps(N);
2014  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2015  setNodeValueTypes(N, VT1, VT2);
2016  N->setOperands(Op1, Op2, Op3);
2017
2018  ON = N;   // Memoize the new node.
2019  return SDOperand(N, 0);
2020}
2021
2022SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2023                                     MVT::ValueType VT1, MVT::ValueType VT2,
2024                                     SDOperand Op1, SDOperand Op2,
2025                                     SDOperand Op3, SDOperand Op4) {
2026  // If an identical node already exists, use it.
2027  std::vector<SDOperand> OpList;
2028  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
2029  OpList.push_back(Op4);
2030  std::vector<MVT::ValueType> VTList;
2031  VTList.push_back(VT1); VTList.push_back(VT2);
2032  SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
2033                                              std::make_pair(VTList, OpList))];
2034  if (ON) return SDOperand(ON, 0);
2035
2036  RemoveNodeFromCSEMaps(N);
2037  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2038  setNodeValueTypes(N, VT1, VT2);
2039  N->setOperands(Op1, Op2, Op3, Op4);
2040
2041  ON = N;   // Memoize the new node.
2042  return SDOperand(N, 0);
2043}
2044
2045SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2046                                     MVT::ValueType VT1, MVT::ValueType VT2,
2047                                     SDOperand Op1, SDOperand Op2,
2048                                     SDOperand Op3, SDOperand Op4,
2049                                     SDOperand Op5) {
2050  // If an identical node already exists, use it.
2051  std::vector<SDOperand> OpList;
2052  OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
2053  OpList.push_back(Op4); OpList.push_back(Op5);
2054  std::vector<MVT::ValueType> VTList;
2055  VTList.push_back(VT1); VTList.push_back(VT2);
2056  SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
2057                                              std::make_pair(VTList, OpList))];
2058  if (ON) return SDOperand(ON, 0);
2059
2060  RemoveNodeFromCSEMaps(N);
2061  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2062  setNodeValueTypes(N, VT1, VT2);
2063  N->setOperands(Op1, Op2, Op3, Op4, Op5);
2064
2065  ON = N;   // Memoize the new node.
2066  return SDOperand(N, 0);
2067}
2068
2069/// getTargetNode - These are used for target selectors to create a new node
2070/// with specified return type(s), target opcode, and operands.
2071///
2072/// Note that getTargetNode returns the resultant node.  If there is already a
2073/// node of the specified opcode and operands, it returns that node instead of
2074/// the current one.
2075SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
2076  return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
2077}
2078SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2079                                    SDOperand Op1) {
2080  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
2081}
2082SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2083                                    SDOperand Op1, SDOperand Op2) {
2084  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
2085}
2086SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2087                                    SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2088  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
2089}
2090SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2091                                    SDOperand Op1, SDOperand Op2, SDOperand Op3,
2092                                    SDOperand Op4) {
2093  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3, Op4).Val;
2094}
2095SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2096                                    SDOperand Op1, SDOperand Op2, SDOperand Op3,
2097                                    SDOperand Op4, SDOperand Op5) {
2098  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3, Op4, Op5).Val;
2099}
2100SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2101                                    SDOperand Op1, SDOperand Op2, SDOperand Op3,
2102                                    SDOperand Op4, SDOperand Op5, SDOperand Op6) {
2103  std::vector<SDOperand> Ops;
2104  Ops.reserve(6);
2105  Ops.push_back(Op1);
2106  Ops.push_back(Op2);
2107  Ops.push_back(Op3);
2108  Ops.push_back(Op4);
2109  Ops.push_back(Op5);
2110  Ops.push_back(Op6);
2111  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
2112}
2113SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2114                                    SDOperand Op1, SDOperand Op2, SDOperand Op3,
2115                                    SDOperand Op4, SDOperand Op5, SDOperand Op6,
2116                                    SDOperand Op7) {
2117  std::vector<SDOperand> Ops;
2118  Ops.reserve(7);
2119  Ops.push_back(Op1);
2120  Ops.push_back(Op2);
2121  Ops.push_back(Op3);
2122  Ops.push_back(Op4);
2123  Ops.push_back(Op5);
2124  Ops.push_back(Op6);
2125  Ops.push_back(Op7);
2126  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
2127}
2128SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2129                                    SDOperand Op1, SDOperand Op2, SDOperand Op3,
2130                                    SDOperand Op4, SDOperand Op5, SDOperand Op6,
2131                                    SDOperand Op7, SDOperand Op8) {
2132  std::vector<SDOperand> Ops;
2133  Ops.reserve(8);
2134  Ops.push_back(Op1);
2135  Ops.push_back(Op2);
2136  Ops.push_back(Op3);
2137  Ops.push_back(Op4);
2138  Ops.push_back(Op5);
2139  Ops.push_back(Op6);
2140  Ops.push_back(Op7);
2141  Ops.push_back(Op8);
2142  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
2143}
2144SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2145                                    std::vector<SDOperand> &Ops) {
2146  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
2147}
2148SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2149                                    MVT::ValueType VT2, SDOperand Op1) {
2150  std::vector<MVT::ValueType> ResultTys;
2151  ResultTys.push_back(VT1);
2152  ResultTys.push_back(VT2);
2153  std::vector<SDOperand> Ops;
2154  Ops.push_back(Op1);
2155  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2156}
2157SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2158                                    MVT::ValueType VT2, SDOperand Op1, SDOperand Op2) {
2159  std::vector<MVT::ValueType> ResultTys;
2160  ResultTys.push_back(VT1);
2161  ResultTys.push_back(VT2);
2162  std::vector<SDOperand> Ops;
2163  Ops.push_back(Op1);
2164  Ops.push_back(Op2);
2165  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2166}
2167SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2168                                    MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2169                                    SDOperand Op3) {
2170  std::vector<MVT::ValueType> ResultTys;
2171  ResultTys.push_back(VT1);
2172  ResultTys.push_back(VT2);
2173  std::vector<SDOperand> Ops;
2174  Ops.push_back(Op1);
2175  Ops.push_back(Op2);
2176  Ops.push_back(Op3);
2177  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2178}
2179SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2180                                    MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2181                                    SDOperand Op3, SDOperand Op4) {
2182  std::vector<MVT::ValueType> ResultTys;
2183  ResultTys.push_back(VT1);
2184  ResultTys.push_back(VT2);
2185  std::vector<SDOperand> Ops;
2186  Ops.push_back(Op1);
2187  Ops.push_back(Op2);
2188  Ops.push_back(Op3);
2189  Ops.push_back(Op4);
2190  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2191}
2192SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2193                                    MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2194                                    SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2195  std::vector<MVT::ValueType> ResultTys;
2196  ResultTys.push_back(VT1);
2197  ResultTys.push_back(VT2);
2198  std::vector<SDOperand> Ops;
2199  Ops.push_back(Op1);
2200  Ops.push_back(Op2);
2201  Ops.push_back(Op3);
2202  Ops.push_back(Op4);
2203  Ops.push_back(Op5);
2204  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2205}
2206SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2207                                    MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2208                                    SDOperand Op3, SDOperand Op4, SDOperand Op5,
2209                                    SDOperand Op6) {
2210  std::vector<MVT::ValueType> ResultTys;
2211  ResultTys.push_back(VT1);
2212  ResultTys.push_back(VT2);
2213  std::vector<SDOperand> Ops;
2214  Ops.push_back(Op1);
2215  Ops.push_back(Op2);
2216  Ops.push_back(Op3);
2217  Ops.push_back(Op4);
2218  Ops.push_back(Op5);
2219  Ops.push_back(Op6);
2220  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2221}
2222SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2223                                    MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2224                                    SDOperand Op3, SDOperand Op4, SDOperand Op5,
2225                                    SDOperand Op6, SDOperand Op7) {
2226  std::vector<MVT::ValueType> ResultTys;
2227  ResultTys.push_back(VT1);
2228  ResultTys.push_back(VT2);
2229  std::vector<SDOperand> Ops;
2230  Ops.push_back(Op1);
2231  Ops.push_back(Op2);
2232  Ops.push_back(Op3);
2233  Ops.push_back(Op4);
2234  Ops.push_back(Op5);
2235  Ops.push_back(Op6);
2236  Ops.push_back(Op7);
2237  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2238}
2239SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2240                                    MVT::ValueType VT2, MVT::ValueType VT3,
2241                                    SDOperand Op1, SDOperand Op2) {
2242  std::vector<MVT::ValueType> ResultTys;
2243  ResultTys.push_back(VT1);
2244  ResultTys.push_back(VT2);
2245  ResultTys.push_back(VT3);
2246  std::vector<SDOperand> Ops;
2247  Ops.push_back(Op1);
2248  Ops.push_back(Op2);
2249  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2250}
2251SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2252                                    MVT::ValueType VT2, MVT::ValueType VT3,
2253                                    SDOperand Op1, SDOperand Op2,
2254                                    SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2255  std::vector<MVT::ValueType> ResultTys;
2256  ResultTys.push_back(VT1);
2257  ResultTys.push_back(VT2);
2258  ResultTys.push_back(VT3);
2259  std::vector<SDOperand> Ops;
2260  Ops.push_back(Op1);
2261  Ops.push_back(Op2);
2262  Ops.push_back(Op3);
2263  Ops.push_back(Op4);
2264  Ops.push_back(Op5);
2265  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2266}
2267SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2268                                    MVT::ValueType VT2, MVT::ValueType VT3,
2269                                    SDOperand Op1, SDOperand Op2,
2270                                    SDOperand Op3, SDOperand Op4, SDOperand Op5,
2271                                    SDOperand Op6) {
2272  std::vector<MVT::ValueType> ResultTys;
2273  ResultTys.push_back(VT1);
2274  ResultTys.push_back(VT2);
2275  ResultTys.push_back(VT3);
2276  std::vector<SDOperand> Ops;
2277  Ops.push_back(Op1);
2278  Ops.push_back(Op2);
2279  Ops.push_back(Op3);
2280  Ops.push_back(Op4);
2281  Ops.push_back(Op5);
2282  Ops.push_back(Op6);
2283  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2284}
2285SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2286                                    MVT::ValueType VT2, MVT::ValueType VT3,
2287                                    SDOperand Op1, SDOperand Op2,
2288                                    SDOperand Op3, SDOperand Op4, SDOperand Op5,
2289                                    SDOperand Op6, SDOperand Op7) {
2290  std::vector<MVT::ValueType> ResultTys;
2291  ResultTys.push_back(VT1);
2292  ResultTys.push_back(VT2);
2293  ResultTys.push_back(VT3);
2294  std::vector<SDOperand> Ops;
2295  Ops.push_back(Op1);
2296  Ops.push_back(Op2);
2297  Ops.push_back(Op3);
2298  Ops.push_back(Op4);
2299  Ops.push_back(Op5);
2300  Ops.push_back(Op6);
2301  Ops.push_back(Op7);
2302  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2303}
2304SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2305                                    MVT::ValueType VT2, std::vector<SDOperand> &Ops) {
2306  std::vector<MVT::ValueType> ResultTys;
2307  ResultTys.push_back(VT1);
2308  ResultTys.push_back(VT2);
2309  return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2310}
2311
2312// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2313/// This can cause recursive merging of nodes in the DAG.
2314///
2315/// This version assumes From/To have a single result value.
2316///
2317void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
2318                                      std::vector<SDNode*> *Deleted) {
2319  SDNode *From = FromN.Val, *To = ToN.Val;
2320  assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
2321         "Cannot replace with this method!");
2322  assert(From != To && "Cannot replace uses of with self");
2323
2324  while (!From->use_empty()) {
2325    // Process users until they are all gone.
2326    SDNode *U = *From->use_begin();
2327
2328    // This node is about to morph, remove its old self from the CSE maps.
2329    RemoveNodeFromCSEMaps(U);
2330
2331    for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
2332         I != E; ++I)
2333      if (I->Val == From) {
2334        From->removeUser(U);
2335        I->Val = To;
2336        To->addUser(U);
2337      }
2338
2339    // Now that we have modified U, add it back to the CSE maps.  If it already
2340    // exists there, recursively merge the results together.
2341    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2342      ReplaceAllUsesWith(U, Existing, Deleted);
2343      // U is now dead.
2344      if (Deleted) Deleted->push_back(U);
2345      DeleteNodeNotInCSEMaps(U);
2346    }
2347  }
2348}
2349
2350/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2351/// This can cause recursive merging of nodes in the DAG.
2352///
2353/// This version assumes From/To have matching types and numbers of result
2354/// values.
2355///
2356void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
2357                                      std::vector<SDNode*> *Deleted) {
2358  assert(From != To && "Cannot replace uses of with self");
2359  assert(From->getNumValues() == To->getNumValues() &&
2360         "Cannot use this version of ReplaceAllUsesWith!");
2361  if (From->getNumValues() == 1) {  // If possible, use the faster version.
2362    ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
2363    return;
2364  }
2365
2366  while (!From->use_empty()) {
2367    // Process users until they are all gone.
2368    SDNode *U = *From->use_begin();
2369
2370    // This node is about to morph, remove its old self from the CSE maps.
2371    RemoveNodeFromCSEMaps(U);
2372
2373    for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
2374         I != E; ++I)
2375      if (I->Val == From) {
2376        From->removeUser(U);
2377        I->Val = To;
2378        To->addUser(U);
2379      }
2380
2381    // Now that we have modified U, add it back to the CSE maps.  If it already
2382    // exists there, recursively merge the results together.
2383    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2384      ReplaceAllUsesWith(U, Existing, Deleted);
2385      // U is now dead.
2386      if (Deleted) Deleted->push_back(U);
2387      DeleteNodeNotInCSEMaps(U);
2388    }
2389  }
2390}
2391
2392/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2393/// This can cause recursive merging of nodes in the DAG.
2394///
2395/// This version can replace From with any result values.  To must match the
2396/// number and types of values returned by From.
2397void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
2398                                      const std::vector<SDOperand> &To,
2399                                      std::vector<SDNode*> *Deleted) {
2400  assert(From->getNumValues() == To.size() &&
2401         "Incorrect number of values to replace with!");
2402  if (To.size() == 1 && To[0].Val->getNumValues() == 1) {
2403    // Degenerate case handled above.
2404    ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
2405    return;
2406  }
2407
2408  while (!From->use_empty()) {
2409    // Process users until they are all gone.
2410    SDNode *U = *From->use_begin();
2411
2412    // This node is about to morph, remove its old self from the CSE maps.
2413    RemoveNodeFromCSEMaps(U);
2414
2415    for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
2416         I != E; ++I)
2417      if (I->Val == From) {
2418        const SDOperand &ToOp = To[I->ResNo];
2419        From->removeUser(U);
2420        *I = ToOp;
2421        ToOp.Val->addUser(U);
2422      }
2423
2424    // Now that we have modified U, add it back to the CSE maps.  If it already
2425    // exists there, recursively merge the results together.
2426    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2427      ReplaceAllUsesWith(U, Existing, Deleted);
2428      // U is now dead.
2429      if (Deleted) Deleted->push_back(U);
2430      DeleteNodeNotInCSEMaps(U);
2431    }
2432  }
2433}
2434
2435/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
2436/// uses of other values produced by From.Val alone.  The Deleted vector is
2437/// handled the same was as for ReplaceAllUsesWith.
2438void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
2439                                             std::vector<SDNode*> &Deleted) {
2440  assert(From != To && "Cannot replace a value with itself");
2441  // Handle the simple, trivial, case efficiently.
2442  if (From.Val->getNumValues() == 1 && To.Val->getNumValues() == 1) {
2443    ReplaceAllUsesWith(From, To, &Deleted);
2444    return;
2445  }
2446
2447  // Get all of the users in a nice, deterministically ordered, uniqued set.
2448  SetVector<SDNode*> Users(From.Val->use_begin(), From.Val->use_end());
2449
2450  while (!Users.empty()) {
2451    // We know that this user uses some value of From.  If it is the right
2452    // value, update it.
2453    SDNode *User = Users.back();
2454    Users.pop_back();
2455
2456    for (SDOperand *Op = User->OperandList,
2457         *E = User->OperandList+User->NumOperands; Op != E; ++Op) {
2458      if (*Op == From) {
2459        // Okay, we know this user needs to be updated.  Remove its old self
2460        // from the CSE maps.
2461        RemoveNodeFromCSEMaps(User);
2462
2463        // Update all operands that match "From".
2464        for (; Op != E; ++Op) {
2465          if (*Op == From) {
2466            From.Val->removeUser(User);
2467            *Op = To;
2468            To.Val->addUser(User);
2469          }
2470        }
2471
2472        // Now that we have modified User, add it back to the CSE maps.  If it
2473        // already exists there, recursively merge the results together.
2474        if (SDNode *Existing = AddNonLeafNodeToCSEMaps(User)) {
2475          unsigned NumDeleted = Deleted.size();
2476          ReplaceAllUsesWith(User, Existing, &Deleted);
2477
2478          // User is now dead.
2479          Deleted.push_back(User);
2480          DeleteNodeNotInCSEMaps(User);
2481
2482          // We have to be careful here, because ReplaceAllUsesWith could have
2483          // deleted a user of From, which means there may be dangling pointers
2484          // in the "Users" setvector.  Scan over the deleted node pointers and
2485          // remove them from the setvector.
2486          for (unsigned i = NumDeleted, e = Deleted.size(); i != e; ++i)
2487            Users.remove(Deleted[i]);
2488        }
2489        break;   // Exit the operand scanning loop.
2490      }
2491    }
2492  }
2493}
2494
2495
2496//===----------------------------------------------------------------------===//
2497//                              SDNode Class
2498//===----------------------------------------------------------------------===//
2499
2500
2501/// getValueTypeList - Return a pointer to the specified value type.
2502///
2503MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
2504  static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
2505  VTs[VT] = VT;
2506  return &VTs[VT];
2507}
2508
2509/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
2510/// indicated value.  This method ignores uses of other values defined by this
2511/// operation.
2512bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
2513  assert(Value < getNumValues() && "Bad value!");
2514
2515  // If there is only one value, this is easy.
2516  if (getNumValues() == 1)
2517    return use_size() == NUses;
2518  if (Uses.size() < NUses) return false;
2519
2520  SDOperand TheValue(const_cast<SDNode *>(this), Value);
2521
2522  std::set<SDNode*> UsersHandled;
2523
2524  for (std::vector<SDNode*>::const_iterator UI = Uses.begin(), E = Uses.end();
2525       UI != E; ++UI) {
2526    SDNode *User = *UI;
2527    if (User->getNumOperands() == 1 ||
2528        UsersHandled.insert(User).second)     // First time we've seen this?
2529      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
2530        if (User->getOperand(i) == TheValue) {
2531          if (NUses == 0)
2532            return false;   // too many uses
2533          --NUses;
2534        }
2535  }
2536
2537  // Found exactly the right number of uses?
2538  return NUses == 0;
2539}
2540
2541
2542// isOnlyUse - Return true if this node is the only use of N.
2543bool SDNode::isOnlyUse(SDNode *N) const {
2544  bool Seen = false;
2545  for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
2546    SDNode *User = *I;
2547    if (User == this)
2548      Seen = true;
2549    else
2550      return false;
2551  }
2552
2553  return Seen;
2554}
2555
2556// isOperand - Return true if this node is an operand of N.
2557bool SDOperand::isOperand(SDNode *N) const {
2558  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2559    if (*this == N->getOperand(i))
2560      return true;
2561  return false;
2562}
2563
2564bool SDNode::isOperand(SDNode *N) const {
2565  for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
2566    if (this == N->OperandList[i].Val)
2567      return true;
2568  return false;
2569}
2570
2571const char *SDNode::getOperationName(const SelectionDAG *G) const {
2572  switch (getOpcode()) {
2573  default:
2574    if (getOpcode() < ISD::BUILTIN_OP_END)
2575      return "<<Unknown DAG Node>>";
2576    else {
2577      if (G) {
2578        if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
2579          if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
2580            return TII->getName(getOpcode()-ISD::BUILTIN_OP_END);
2581
2582        TargetLowering &TLI = G->getTargetLoweringInfo();
2583        const char *Name =
2584          TLI.getTargetNodeName(getOpcode());
2585        if (Name) return Name;
2586      }
2587
2588      return "<<Unknown Target Node>>";
2589    }
2590
2591  case ISD::PCMARKER:      return "PCMarker";
2592  case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
2593  case ISD::SRCVALUE:      return "SrcValue";
2594  case ISD::EntryToken:    return "EntryToken";
2595  case ISD::TokenFactor:   return "TokenFactor";
2596  case ISD::AssertSext:    return "AssertSext";
2597  case ISD::AssertZext:    return "AssertZext";
2598
2599  case ISD::STRING:        return "String";
2600  case ISD::BasicBlock:    return "BasicBlock";
2601  case ISD::VALUETYPE:     return "ValueType";
2602  case ISD::Register:      return "Register";
2603
2604  case ISD::Constant:      return "Constant";
2605  case ISD::ConstantFP:    return "ConstantFP";
2606  case ISD::GlobalAddress: return "GlobalAddress";
2607  case ISD::FrameIndex:    return "FrameIndex";
2608  case ISD::ConstantPool:  return "ConstantPool";
2609  case ISD::ExternalSymbol: return "ExternalSymbol";
2610
2611  case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
2612  case ISD::TargetConstant: return "TargetConstant";
2613  case ISD::TargetConstantFP:return "TargetConstantFP";
2614  case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
2615  case ISD::TargetFrameIndex: return "TargetFrameIndex";
2616  case ISD::TargetConstantPool:  return "TargetConstantPool";
2617  case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
2618  case ISD::VBUILD_VECTOR: return "VBUILD_VECTOR";
2619
2620  case ISD::CopyToReg:     return "CopyToReg";
2621  case ISD::CopyFromReg:   return "CopyFromReg";
2622  case ISD::UNDEF:         return "undef";
2623  case ISD::MERGE_VALUES:  return "mergevalues";
2624  case ISD::INLINEASM:     return "inlineasm";
2625  case ISD::HANDLENODE:    return "handlenode";
2626
2627  // Unary operators
2628  case ISD::FABS:   return "fabs";
2629  case ISD::FNEG:   return "fneg";
2630  case ISD::FSQRT:  return "fsqrt";
2631  case ISD::FSIN:   return "fsin";
2632  case ISD::FCOS:   return "fcos";
2633
2634  // Binary operators
2635  case ISD::ADD:    return "add";
2636  case ISD::SUB:    return "sub";
2637  case ISD::MUL:    return "mul";
2638  case ISD::MULHU:  return "mulhu";
2639  case ISD::MULHS:  return "mulhs";
2640  case ISD::SDIV:   return "sdiv";
2641  case ISD::UDIV:   return "udiv";
2642  case ISD::SREM:   return "srem";
2643  case ISD::UREM:   return "urem";
2644  case ISD::AND:    return "and";
2645  case ISD::OR:     return "or";
2646  case ISD::XOR:    return "xor";
2647  case ISD::SHL:    return "shl";
2648  case ISD::SRA:    return "sra";
2649  case ISD::SRL:    return "srl";
2650  case ISD::ROTL:   return "rotl";
2651  case ISD::ROTR:   return "rotr";
2652  case ISD::FADD:   return "fadd";
2653  case ISD::FSUB:   return "fsub";
2654  case ISD::FMUL:   return "fmul";
2655  case ISD::FDIV:   return "fdiv";
2656  case ISD::FREM:   return "frem";
2657  case ISD::FCOPYSIGN: return "fcopysign";
2658  case ISD::VADD:   return "vadd";
2659  case ISD::VSUB:   return "vsub";
2660  case ISD::VMUL:   return "vmul";
2661
2662  case ISD::SETCC:       return "setcc";
2663  case ISD::SELECT:      return "select";
2664  case ISD::SELECT_CC:   return "select_cc";
2665  case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
2666  case ISD::VINSERT_VECTOR_ELT: return "vinsert_vector_elt";
2667  case ISD::SCALAR_TO_VECTOR:   return "scalar_to_vector";
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::BR_CC:   return "br_cc";
2696  case ISD::RET:     return "ret";
2697  case ISD::CALLSEQ_START:  return "callseq_start";
2698  case ISD::CALLSEQ_END:    return "callseq_end";
2699
2700    // Other operators
2701  case ISD::LOAD:               return "load";
2702  case ISD::STORE:              return "store";
2703  case ISD::VLOAD:              return "vload";
2704  case ISD::EXTLOAD:            return "extload";
2705  case ISD::SEXTLOAD:           return "sextload";
2706  case ISD::ZEXTLOAD:           return "zextload";
2707  case ISD::TRUNCSTORE:         return "truncstore";
2708  case ISD::VAARG:              return "vaarg";
2709  case ISD::VACOPY:             return "vacopy";
2710  case ISD::VAEND:              return "vaend";
2711  case ISD::VASTART:            return "vastart";
2712  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
2713  case ISD::EXTRACT_ELEMENT:    return "extract_element";
2714  case ISD::BUILD_PAIR:         return "build_pair";
2715  case ISD::STACKSAVE:          return "stacksave";
2716  case ISD::STACKRESTORE:       return "stackrestore";
2717
2718  // Block memory operations.
2719  case ISD::MEMSET:  return "memset";
2720  case ISD::MEMCPY:  return "memcpy";
2721  case ISD::MEMMOVE: return "memmove";
2722
2723  // Bit manipulation
2724  case ISD::BSWAP:   return "bswap";
2725  case ISD::CTPOP:   return "ctpop";
2726  case ISD::CTTZ:    return "cttz";
2727  case ISD::CTLZ:    return "ctlz";
2728
2729  // Debug info
2730  case ISD::LOCATION: return "location";
2731  case ISD::DEBUG_LOC: return "debug_loc";
2732  case ISD::DEBUG_LABEL: return "debug_label";
2733
2734  case ISD::CONDCODE:
2735    switch (cast<CondCodeSDNode>(this)->get()) {
2736    default: assert(0 && "Unknown setcc condition!");
2737    case ISD::SETOEQ:  return "setoeq";
2738    case ISD::SETOGT:  return "setogt";
2739    case ISD::SETOGE:  return "setoge";
2740    case ISD::SETOLT:  return "setolt";
2741    case ISD::SETOLE:  return "setole";
2742    case ISD::SETONE:  return "setone";
2743
2744    case ISD::SETO:    return "seto";
2745    case ISD::SETUO:   return "setuo";
2746    case ISD::SETUEQ:  return "setue";
2747    case ISD::SETUGT:  return "setugt";
2748    case ISD::SETUGE:  return "setuge";
2749    case ISD::SETULT:  return "setult";
2750    case ISD::SETULE:  return "setule";
2751    case ISD::SETUNE:  return "setune";
2752
2753    case ISD::SETEQ:   return "seteq";
2754    case ISD::SETGT:   return "setgt";
2755    case ISD::SETGE:   return "setge";
2756    case ISD::SETLT:   return "setlt";
2757    case ISD::SETLE:   return "setle";
2758    case ISD::SETNE:   return "setne";
2759    }
2760  }
2761}
2762
2763void SDNode::dump() const { dump(0); }
2764void SDNode::dump(const SelectionDAG *G) const {
2765  std::cerr << (void*)this << ": ";
2766
2767  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
2768    if (i) std::cerr << ",";
2769    if (getValueType(i) == MVT::Other)
2770      std::cerr << "ch";
2771    else
2772      std::cerr << MVT::getValueTypeString(getValueType(i));
2773  }
2774  std::cerr << " = " << getOperationName(G);
2775
2776  std::cerr << " ";
2777  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2778    if (i) std::cerr << ", ";
2779    std::cerr << (void*)getOperand(i).Val;
2780    if (unsigned RN = getOperand(i).ResNo)
2781      std::cerr << ":" << RN;
2782  }
2783
2784  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
2785    std::cerr << "<" << CSDN->getValue() << ">";
2786  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
2787    std::cerr << "<" << CSDN->getValue() << ">";
2788  } else if (const GlobalAddressSDNode *GADN =
2789             dyn_cast<GlobalAddressSDNode>(this)) {
2790    int offset = GADN->getOffset();
2791    std::cerr << "<";
2792    WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
2793    if (offset > 0)
2794      std::cerr << " + " << offset;
2795    else
2796      std::cerr << " " << offset;
2797  } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
2798    std::cerr << "<" << FIDN->getIndex() << ">";
2799  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
2800    int offset = CP->getOffset();
2801    std::cerr << "<" << *CP->get() << ">";
2802    if (offset > 0)
2803      std::cerr << " + " << offset;
2804    else
2805      std::cerr << " " << offset;
2806  } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
2807    std::cerr << "<";
2808    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
2809    if (LBB)
2810      std::cerr << LBB->getName() << " ";
2811    std::cerr << (const void*)BBDN->getBasicBlock() << ">";
2812  } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
2813    if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
2814      std::cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
2815    } else {
2816      std::cerr << " #" << R->getReg();
2817    }
2818  } else if (const ExternalSymbolSDNode *ES =
2819             dyn_cast<ExternalSymbolSDNode>(this)) {
2820    std::cerr << "'" << ES->getSymbol() << "'";
2821  } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
2822    if (M->getValue())
2823      std::cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
2824    else
2825      std::cerr << "<null:" << M->getOffset() << ">";
2826  } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
2827    std::cerr << ":" << getValueTypeString(N->getVT());
2828  }
2829}
2830
2831static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
2832  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2833    if (N->getOperand(i).Val->hasOneUse())
2834      DumpNodes(N->getOperand(i).Val, indent+2, G);
2835    else
2836      std::cerr << "\n" << std::string(indent+2, ' ')
2837                << (void*)N->getOperand(i).Val << ": <multiple use>";
2838
2839
2840  std::cerr << "\n" << std::string(indent, ' ');
2841  N->dump(G);
2842}
2843
2844void SelectionDAG::dump() const {
2845  std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
2846  std::vector<const SDNode*> Nodes;
2847  for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
2848       I != E; ++I)
2849    Nodes.push_back(I);
2850
2851  std::sort(Nodes.begin(), Nodes.end());
2852
2853  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2854    if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
2855      DumpNodes(Nodes[i], 2, this);
2856  }
2857
2858  DumpNodes(getRoot().Val, 2, this);
2859
2860  std::cerr << "\n\n";
2861}
2862
2863/// InsertISelMapEntry - A helper function to insert a key / element pair
2864/// into a SDOperand to SDOperand map. This is added to avoid the map
2865/// insertion operator from being inlined.
2866void SelectionDAG::InsertISelMapEntry(std::map<SDOperand, SDOperand> &Map,
2867                                      SDNode *Key, unsigned KeyResNo,
2868                                      SDNode *Element, unsigned ElementResNo) {
2869  Map.insert(std::make_pair(SDOperand(Key, KeyResNo),
2870                            SDOperand(Element, ElementResNo)));
2871}
2872