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