SelectionDAG.cpp revision f469cb654600969db1131eb80002fc7ff53d1f5e
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 <iostream>
25#include <set>
26#include <cmath>
27#include <algorithm>
28using namespace llvm;
29
30static bool isCommutativeBinOp(unsigned Opcode) {
31  switch (Opcode) {
32  case ISD::ADD:
33  case ISD::MUL:
34  case ISD::FADD:
35  case ISD::FMUL:
36  case ISD::AND:
37  case ISD::OR:
38  case ISD::XOR: return true;
39  default: return false; // FIXME: Need commutative info for user ops!
40  }
41}
42
43static bool isAssociativeBinOp(unsigned Opcode) {
44  switch (Opcode) {
45  case ISD::ADD:
46  case ISD::MUL:
47  case ISD::AND:
48  case ISD::OR:
49  case ISD::XOR: return true;
50  default: return false; // FIXME: Need associative info for user ops!
51  }
52}
53
54// isInvertibleForFree - Return true if there is no cost to emitting the logical
55// inverse of this node.
56static bool isInvertibleForFree(SDOperand N) {
57  if (isa<ConstantSDNode>(N.Val)) return true;
58  if (N.Val->getOpcode() == ISD::SETCC && N.Val->hasOneUse())
59    return true;
60  return false;
61}
62
63//===----------------------------------------------------------------------===//
64//                              ConstantFPSDNode Class
65//===----------------------------------------------------------------------===//
66
67/// isExactlyValue - We don't rely on operator== working on double values, as
68/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
69/// As such, this method can be used to do an exact bit-for-bit comparison of
70/// two floating point values.
71bool ConstantFPSDNode::isExactlyValue(double V) const {
72  return DoubleToBits(V) == DoubleToBits(Value);
73}
74
75//===----------------------------------------------------------------------===//
76//                              ISD Class
77//===----------------------------------------------------------------------===//
78
79/// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
80/// when given the operation for (X op Y).
81ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
82  // To perform this operation, we just need to swap the L and G bits of the
83  // operation.
84  unsigned OldL = (Operation >> 2) & 1;
85  unsigned OldG = (Operation >> 1) & 1;
86  return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
87                       (OldL << 1) |       // New G bit
88                       (OldG << 2));        // New L bit.
89}
90
91/// getSetCCInverse - Return the operation corresponding to !(X op Y), where
92/// 'op' is a valid SetCC operation.
93ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
94  unsigned Operation = Op;
95  if (isInteger)
96    Operation ^= 7;   // Flip L, G, E bits, but not U.
97  else
98    Operation ^= 15;  // Flip all of the condition bits.
99  if (Operation > ISD::SETTRUE2)
100    Operation &= ~8;     // Don't let N and U bits get set.
101  return ISD::CondCode(Operation);
102}
103
104
105/// isSignedOp - For an integer comparison, return 1 if the comparison is a
106/// signed operation and 2 if the result is an unsigned comparison.  Return zero
107/// if the operation does not depend on the sign of the input (setne and seteq).
108static int isSignedOp(ISD::CondCode Opcode) {
109  switch (Opcode) {
110  default: assert(0 && "Illegal integer setcc operation!");
111  case ISD::SETEQ:
112  case ISD::SETNE: return 0;
113  case ISD::SETLT:
114  case ISD::SETLE:
115  case ISD::SETGT:
116  case ISD::SETGE: return 1;
117  case ISD::SETULT:
118  case ISD::SETULE:
119  case ISD::SETUGT:
120  case ISD::SETUGE: return 2;
121  }
122}
123
124/// getSetCCOrOperation - Return the result of a logical OR between different
125/// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
126/// returns SETCC_INVALID if it is not possible to represent the resultant
127/// comparison.
128ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
129                                       bool isInteger) {
130  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
131    // Cannot fold a signed integer setcc with an unsigned integer setcc.
132    return ISD::SETCC_INVALID;
133
134  unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
135
136  // If the N and U bits get set then the resultant comparison DOES suddenly
137  // care about orderedness, and is true when ordered.
138  if (Op > ISD::SETTRUE2)
139    Op &= ~16;     // Clear the N bit.
140  return ISD::CondCode(Op);
141}
142
143/// getSetCCAndOperation - Return the result of a logical AND between different
144/// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
145/// function returns zero if it is not possible to represent the resultant
146/// comparison.
147ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
148                                        bool isInteger) {
149  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
150    // Cannot fold a signed setcc with an unsigned setcc.
151    return ISD::SETCC_INVALID;
152
153  // Combine all of the condition bits.
154  return ISD::CondCode(Op1 & Op2);
155}
156
157const TargetMachine &SelectionDAG::getTarget() const {
158  return TLI.getTargetMachine();
159}
160
161//===----------------------------------------------------------------------===//
162//                              SelectionDAG Class
163//===----------------------------------------------------------------------===//
164
165/// RemoveDeadNodes - This method deletes all unreachable nodes in the
166/// SelectionDAG, including nodes (like loads) that have uses of their token
167/// chain but no other uses and no side effect.  If a node is passed in as an
168/// argument, it is used as the seed for node deletion.
169void SelectionDAG::RemoveDeadNodes(SDNode *N) {
170  // Create a dummy node (which is not added to allnodes), that adds a reference
171  // to the root node, preventing it from being deleted.
172  HandleSDNode Dummy(getRoot());
173
174  bool MadeChange = false;
175
176  // If we have a hint to start from, use it.
177  if (N && N->use_empty()) {
178    DestroyDeadNode(N);
179    MadeChange = true;
180  }
181
182  for (unsigned i = 0, e = AllNodes.size(); i != e; ++i) {
183    // Try to delete this node.
184    SDNode *N = AllNodes[i];
185    if (N->use_empty() && N->getOpcode() != 65535) {
186      DestroyDeadNode(N);
187      MadeChange = true;
188    }
189  }
190
191  // Walk the nodes list, removing the nodes we've marked as dead.
192  if (MadeChange) {
193    for (unsigned i = 0, e = AllNodes.size(); i != e; ++i)
194      if (AllNodes[i]->use_empty()) {
195        delete AllNodes[i];
196        AllNodes[i] = AllNodes.back();
197        AllNodes.pop_back();
198        --i; --e;
199      }
200  }
201
202  // If the root changed (e.g. it was a dead load, update the root).
203  setRoot(Dummy.getValue());
204}
205
206/// DestroyDeadNode - We know that N is dead.  Nuke it from the CSE maps for the
207/// graph.  If it is the last user of any of its operands, recursively process
208/// them the same way.
209///
210void SelectionDAG::DestroyDeadNode(SDNode *N) {
211  // Okay, we really are going to delete this node.  First take this out of the
212  // appropriate CSE map.
213  RemoveNodeFromCSEMaps(N);
214
215  // Next, brutally remove the operand list.  This is safe to do, as there are
216  // no cycles in the graph.
217  while (!N->Operands.empty()) {
218    SDNode *O = N->Operands.back().Val;
219    N->Operands.pop_back();
220    O->removeUser(N);
221
222    // Now that we removed this operand, see if there are no uses of it left.
223    if (O->use_empty())
224      DestroyDeadNode(O);
225  }
226
227  // Mark the node as dead.
228  N->MorphNodeTo(65535);
229}
230
231void SelectionDAG::DeleteNode(SDNode *N) {
232  assert(N->use_empty() && "Cannot delete a node that is not dead!");
233
234  // First take this out of the appropriate CSE map.
235  RemoveNodeFromCSEMaps(N);
236
237  // Finally, remove uses due to operands of this node, remove from the
238  // AllNodes list, and delete the node.
239  DeleteNodeNotInCSEMaps(N);
240}
241
242void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
243
244  // Remove it from the AllNodes list.
245  for (std::vector<SDNode*>::iterator I = AllNodes.begin(); ; ++I) {
246    assert(I != AllNodes.end() && "Node not in AllNodes list??");
247    if (*I == N) {
248      // Erase from the vector, which is not ordered.
249      std::swap(*I, AllNodes.back());
250      AllNodes.pop_back();
251      break;
252    }
253  }
254
255  // Drop all of the operands and decrement used nodes use counts.
256  while (!N->Operands.empty()) {
257    SDNode *O = N->Operands.back().Val;
258    N->Operands.pop_back();
259    O->removeUser(N);
260  }
261
262  delete N;
263}
264
265/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
266/// correspond to it.  This is useful when we're about to delete or repurpose
267/// the node.  We don't want future request for structurally identical nodes
268/// to return N anymore.
269void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
270  bool Erased = false;
271  switch (N->getOpcode()) {
272  case ISD::HANDLENODE: return;  // noop.
273  case ISD::Constant:
274    Erased = Constants.erase(std::make_pair(cast<ConstantSDNode>(N)->getValue(),
275                                            N->getValueType(0)));
276    break;
277  case ISD::TargetConstant:
278    Erased = TargetConstants.erase(std::make_pair(
279                                    cast<ConstantSDNode>(N)->getValue(),
280                                                  N->getValueType(0)));
281    break;
282  case ISD::ConstantFP: {
283    uint64_t V = DoubleToBits(cast<ConstantFPSDNode>(N)->getValue());
284    Erased = ConstantFPs.erase(std::make_pair(V, N->getValueType(0)));
285    break;
286  }
287  case ISD::CONDCODE:
288    assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
289           "Cond code doesn't exist!");
290    Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
291    CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
292    break;
293  case ISD::GlobalAddress:
294    Erased = GlobalValues.erase(cast<GlobalAddressSDNode>(N)->getGlobal());
295    break;
296  case ISD::TargetGlobalAddress:
297    Erased =TargetGlobalValues.erase(cast<GlobalAddressSDNode>(N)->getGlobal());
298    break;
299  case ISD::FrameIndex:
300    Erased = FrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
301    break;
302  case ISD::TargetFrameIndex:
303    Erased = TargetFrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
304    break;
305  case ISD::ConstantPool:
306    Erased = ConstantPoolIndices.erase(cast<ConstantPoolSDNode>(N)->get());
307    break;
308  case ISD::TargetConstantPool:
309    Erased =TargetConstantPoolIndices.erase(cast<ConstantPoolSDNode>(N)->get());
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 = TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
319    break;
320  case ISD::VALUETYPE:
321    Erased = ValueTypeNodes[cast<VTSDNode>(N)->getVT()] != 0;
322    ValueTypeNodes[cast<VTSDNode>(N)->getVT()] = 0;
323    break;
324  case ISD::Register:
325    Erased = RegNodes.erase(std::make_pair(cast<RegisterSDNode>(N)->getReg(),
326                                           N->getValueType(0)));
327    break;
328  case ISD::SRCVALUE: {
329    SrcValueSDNode *SVN = cast<SrcValueSDNode>(N);
330    Erased =ValueNodes.erase(std::make_pair(SVN->getValue(), SVN->getOffset()));
331    break;
332  }
333  case ISD::LOAD:
334    Erased = Loads.erase(std::make_pair(N->getOperand(1),
335                                        std::make_pair(N->getOperand(0),
336                                                       N->getValueType(0))));
337    break;
338  default:
339    if (N->getNumValues() == 1) {
340      if (N->getNumOperands() == 0) {
341        Erased = NullaryOps.erase(std::make_pair(N->getOpcode(),
342                                                 N->getValueType(0)));
343      } else if (N->getNumOperands() == 1) {
344        Erased =
345          UnaryOps.erase(std::make_pair(N->getOpcode(),
346                                        std::make_pair(N->getOperand(0),
347                                                       N->getValueType(0))));
348      } else if (N->getNumOperands() == 2) {
349        Erased =
350          BinaryOps.erase(std::make_pair(N->getOpcode(),
351                                         std::make_pair(N->getOperand(0),
352                                                        N->getOperand(1))));
353      } else {
354        std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
355        Erased =
356          OneResultNodes.erase(std::make_pair(N->getOpcode(),
357                                              std::make_pair(N->getValueType(0),
358                                                             Ops)));
359      }
360    } else {
361      // Remove the node from the ArbitraryNodes map.
362      std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
363      std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
364      Erased =
365        ArbitraryNodes.erase(std::make_pair(N->getOpcode(),
366                                            std::make_pair(RV, Ops)));
367    }
368    break;
369  }
370#ifndef NDEBUG
371  // Verify that the node was actually in one of the CSE maps, unless it has a
372  // flag result (which cannot be CSE'd) or is one of the special cases that are
373  // not subject to CSE.
374  if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
375      N->getOpcode() != ISD::CALL && N->getOpcode() != ISD::CALLSEQ_START &&
376      N->getOpcode() != ISD::CALLSEQ_END && !N->isTargetOpcode()) {
377
378    N->dump();
379    assert(0 && "Node is not in map!");
380  }
381#endif
382}
383
384/// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
385/// has been taken out and modified in some way.  If the specified node already
386/// exists in the CSE maps, do not modify the maps, but return the existing node
387/// instead.  If it doesn't exist, add it and return null.
388///
389SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
390  assert(N->getNumOperands() && "This is a leaf node!");
391  if (N->getOpcode() == ISD::LOAD) {
392    SDNode *&L = Loads[std::make_pair(N->getOperand(1),
393                                      std::make_pair(N->getOperand(0),
394                                                     N->getValueType(0)))];
395    if (L) return L;
396    L = N;
397  } else if (N->getOpcode() == ISD::HANDLENODE) {
398    return 0;  // never add it.
399  } else 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 if (N->getNumValues() == 1) {
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  } else {
418    // Remove the node from the ArbitraryNodes map.
419    std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
420    std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
421    SDNode *&AN = ArbitraryNodes[std::make_pair(N->getOpcode(),
422                                                std::make_pair(RV, Ops))];
423    if (AN) return AN;
424    AN = N;
425  }
426  return 0;
427
428}
429
430
431
432SelectionDAG::~SelectionDAG() {
433  for (unsigned i = 0, e = AllNodes.size(); i != e; ++i)
434    delete AllNodes[i];
435}
436
437SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
438  if (Op.getValueType() == VT) return Op;
439  int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
440  return getNode(ISD::AND, Op.getValueType(), Op,
441                 getConstant(Imm, Op.getValueType()));
442}
443
444SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT) {
445  assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
446  // Mask out any bits that are not valid for this constant.
447  if (VT != MVT::i64)
448    Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
449
450  SDNode *&N = Constants[std::make_pair(Val, VT)];
451  if (N) return SDOperand(N, 0);
452  N = new ConstantSDNode(false, Val, VT);
453  AllNodes.push_back(N);
454  return SDOperand(N, 0);
455}
456
457SDOperand SelectionDAG::getTargetConstant(uint64_t Val, MVT::ValueType VT) {
458  assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
459  // Mask out any bits that are not valid for this constant.
460  if (VT != MVT::i64)
461    Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
462
463  SDNode *&N = TargetConstants[std::make_pair(Val, VT)];
464  if (N) return SDOperand(N, 0);
465  N = new ConstantSDNode(true, Val, VT);
466  AllNodes.push_back(N);
467  return SDOperand(N, 0);
468}
469
470SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT) {
471  assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
472  if (VT == MVT::f32)
473    Val = (float)Val;  // Mask out extra precision.
474
475  // Do the map lookup using the actual bit pattern for the floating point
476  // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
477  // we don't have issues with SNANs.
478  SDNode *&N = ConstantFPs[std::make_pair(DoubleToBits(Val), VT)];
479  if (N) return SDOperand(N, 0);
480  N = new ConstantFPSDNode(Val, VT);
481  AllNodes.push_back(N);
482  return SDOperand(N, 0);
483}
484
485
486
487SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
488                                         MVT::ValueType VT) {
489  SDNode *&N = GlobalValues[GV];
490  if (N) return SDOperand(N, 0);
491  N = new GlobalAddressSDNode(false, GV, VT);
492  AllNodes.push_back(N);
493  return SDOperand(N, 0);
494}
495
496SDOperand SelectionDAG::getTargetGlobalAddress(const GlobalValue *GV,
497                                               MVT::ValueType VT) {
498  SDNode *&N = TargetGlobalValues[GV];
499  if (N) return SDOperand(N, 0);
500  N = new GlobalAddressSDNode(true, GV, VT);
501  AllNodes.push_back(N);
502  return SDOperand(N, 0);
503}
504
505SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT) {
506  SDNode *&N = FrameIndices[FI];
507  if (N) return SDOperand(N, 0);
508  N = new FrameIndexSDNode(FI, VT, false);
509  AllNodes.push_back(N);
510  return SDOperand(N, 0);
511}
512
513SDOperand SelectionDAG::getTargetFrameIndex(int FI, MVT::ValueType VT) {
514  SDNode *&N = TargetFrameIndices[FI];
515  if (N) return SDOperand(N, 0);
516  N = new FrameIndexSDNode(FI, VT, true);
517  AllNodes.push_back(N);
518  return SDOperand(N, 0);
519}
520
521SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT) {
522  SDNode *&N = ConstantPoolIndices[C];
523  if (N) return SDOperand(N, 0);
524  N = new ConstantPoolSDNode(C, VT, false);
525  AllNodes.push_back(N);
526  return SDOperand(N, 0);
527}
528
529SDOperand SelectionDAG::getTargetConstantPool(Constant *C, MVT::ValueType VT) {
530  SDNode *&N = TargetConstantPoolIndices[C];
531  if (N) return SDOperand(N, 0);
532  N = new ConstantPoolSDNode(C, VT, true);
533  AllNodes.push_back(N);
534  return SDOperand(N, 0);
535}
536
537SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
538  SDNode *&N = BBNodes[MBB];
539  if (N) return SDOperand(N, 0);
540  N = new BasicBlockSDNode(MBB);
541  AllNodes.push_back(N);
542  return SDOperand(N, 0);
543}
544
545SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
546  if ((unsigned)VT >= ValueTypeNodes.size())
547    ValueTypeNodes.resize(VT+1);
548  if (ValueTypeNodes[VT] == 0) {
549    ValueTypeNodes[VT] = new VTSDNode(VT);
550    AllNodes.push_back(ValueTypeNodes[VT]);
551  }
552
553  return SDOperand(ValueTypeNodes[VT], 0);
554}
555
556SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
557  SDNode *&N = ExternalSymbols[Sym];
558  if (N) return SDOperand(N, 0);
559  N = new ExternalSymbolSDNode(false, Sym, VT);
560  AllNodes.push_back(N);
561  return SDOperand(N, 0);
562}
563
564SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT::ValueType VT) {
565  SDNode *&N = TargetExternalSymbols[Sym];
566  if (N) return SDOperand(N, 0);
567  N = new ExternalSymbolSDNode(true, Sym, VT);
568  AllNodes.push_back(N);
569  return SDOperand(N, 0);
570}
571
572SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
573  if ((unsigned)Cond >= CondCodeNodes.size())
574    CondCodeNodes.resize(Cond+1);
575
576  if (CondCodeNodes[Cond] == 0) {
577    CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
578    AllNodes.push_back(CondCodeNodes[Cond]);
579  }
580  return SDOperand(CondCodeNodes[Cond], 0);
581}
582
583SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
584  RegisterSDNode *&Reg = RegNodes[std::make_pair(RegNo, VT)];
585  if (!Reg) {
586    Reg = new RegisterSDNode(RegNo, VT);
587    AllNodes.push_back(Reg);
588  }
589  return SDOperand(Reg, 0);
590}
591
592SDOperand SelectionDAG::SimplifySetCC(MVT::ValueType VT, SDOperand N1,
593                                      SDOperand N2, ISD::CondCode Cond) {
594  // These setcc operations always fold.
595  switch (Cond) {
596  default: break;
597  case ISD::SETFALSE:
598  case ISD::SETFALSE2: return getConstant(0, VT);
599  case ISD::SETTRUE:
600  case ISD::SETTRUE2:  return getConstant(1, VT);
601  }
602
603  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
604    uint64_t C2 = N2C->getValue();
605    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
606      uint64_t C1 = N1C->getValue();
607
608      // Sign extend the operands if required
609      if (ISD::isSignedIntSetCC(Cond)) {
610        C1 = N1C->getSignExtended();
611        C2 = N2C->getSignExtended();
612      }
613
614      switch (Cond) {
615      default: assert(0 && "Unknown integer setcc!");
616      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
617      case ISD::SETNE:  return getConstant(C1 != C2, VT);
618      case ISD::SETULT: return getConstant(C1 <  C2, VT);
619      case ISD::SETUGT: return getConstant(C1 >  C2, VT);
620      case ISD::SETULE: return getConstant(C1 <= C2, VT);
621      case ISD::SETUGE: return getConstant(C1 >= C2, VT);
622      case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
623      case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
624      case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
625      case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
626      }
627    } else {
628      // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
629      if (N1.getOpcode() == ISD::ZERO_EXTEND) {
630        unsigned InSize = MVT::getSizeInBits(N1.getOperand(0).getValueType());
631
632        // If the comparison constant has bits in the upper part, the
633        // zero-extended value could never match.
634        if (C2 & (~0ULL << InSize)) {
635          unsigned VSize = MVT::getSizeInBits(N1.getValueType());
636          switch (Cond) {
637          case ISD::SETUGT:
638          case ISD::SETUGE:
639          case ISD::SETEQ: return getConstant(0, VT);
640          case ISD::SETULT:
641          case ISD::SETULE:
642          case ISD::SETNE: return getConstant(1, VT);
643          case ISD::SETGT:
644          case ISD::SETGE:
645            // True if the sign bit of C2 is set.
646            return getConstant((C2 & (1ULL << VSize)) != 0, VT);
647          case ISD::SETLT:
648          case ISD::SETLE:
649            // True if the sign bit of C2 isn't set.
650            return getConstant((C2 & (1ULL << VSize)) == 0, VT);
651          default:
652            break;
653          }
654        }
655
656        // Otherwise, we can perform the comparison with the low bits.
657        switch (Cond) {
658        case ISD::SETEQ:
659        case ISD::SETNE:
660        case ISD::SETUGT:
661        case ISD::SETUGE:
662        case ISD::SETULT:
663        case ISD::SETULE:
664          return getSetCC(VT, N1.getOperand(0),
665                          getConstant(C2, N1.getOperand(0).getValueType()),
666                          Cond);
667        default:
668          break;   // todo, be more careful with signed comparisons
669        }
670      } else if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG &&
671                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
672        MVT::ValueType ExtSrcTy = cast<VTSDNode>(N1.getOperand(1))->getVT();
673        unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
674        MVT::ValueType ExtDstTy = N1.getValueType();
675        unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
676
677        // If the extended part has any inconsistent bits, it cannot ever
678        // compare equal.  In other words, they have to be all ones or all
679        // zeros.
680        uint64_t ExtBits =
681          (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
682        if ((C2 & ExtBits) != 0 && (C2 & ExtBits) != ExtBits)
683          return getConstant(Cond == ISD::SETNE, VT);
684
685        // Otherwise, make this a use of a zext.
686        return getSetCC(VT, getZeroExtendInReg(N1.getOperand(0), ExtSrcTy),
687                        getConstant(C2 & (~0ULL>>(64-ExtSrcTyBits)), ExtDstTy),
688                        Cond);
689      }
690
691      uint64_t MinVal, MaxVal;
692      unsigned OperandBitSize = MVT::getSizeInBits(N2C->getValueType(0));
693      if (ISD::isSignedIntSetCC(Cond)) {
694        MinVal = 1ULL << (OperandBitSize-1);
695        if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
696          MaxVal = ~0ULL >> (65-OperandBitSize);
697        else
698          MaxVal = 0;
699      } else {
700        MinVal = 0;
701        MaxVal = ~0ULL >> (64-OperandBitSize);
702      }
703
704      // Canonicalize GE/LE comparisons to use GT/LT comparisons.
705      if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
706        if (C2 == MinVal) return getConstant(1, VT);   // X >= MIN --> true
707        --C2;                                          // X >= C1 --> X > (C1-1)
708        return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
709                        (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
710      }
711
712      if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
713        if (C2 == MaxVal) return getConstant(1, VT);   // X <= MAX --> true
714        ++C2;                                          // X <= C1 --> X < (C1+1)
715        return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
716                        (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
717      }
718
719      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal)
720        return getConstant(0, VT);      // X < MIN --> false
721
722      // Canonicalize setgt X, Min --> setne X, Min
723      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MinVal)
724        return getSetCC(VT, N1, N2, ISD::SETNE);
725
726      // If we have setult X, 1, turn it into seteq X, 0
727      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal+1)
728        return getSetCC(VT, N1, getConstant(MinVal, N1.getValueType()),
729                        ISD::SETEQ);
730      // If we have setugt X, Max-1, turn it into seteq X, Max
731      else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MaxVal-1)
732        return getSetCC(VT, N1, getConstant(MaxVal, N1.getValueType()),
733                        ISD::SETEQ);
734
735      // If we have "setcc X, C1", check to see if we can shrink the immediate
736      // by changing cc.
737
738      // SETUGT X, SINTMAX  -> SETLT X, 0
739      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
740          C2 == (~0ULL >> (65-OperandBitSize)))
741        return getSetCC(VT, N1, getConstant(0, N2.getValueType()), ISD::SETLT);
742
743      // FIXME: Implement the rest of these.
744
745
746      // Fold bit comparisons when we can.
747      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
748          VT == N1.getValueType() && N1.getOpcode() == ISD::AND)
749        if (ConstantSDNode *AndRHS =
750                    dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
751          if (Cond == ISD::SETNE && C2 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
752            // Perform the xform if the AND RHS is a single bit.
753            if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
754              return getNode(ISD::SRL, VT, N1,
755                             getConstant(Log2_64(AndRHS->getValue()),
756                                                   TLI.getShiftAmountTy()));
757            }
758          } else if (Cond == ISD::SETEQ && C2 == AndRHS->getValue()) {
759            // (X & 8) == 8  -->  (X & 8) >> 3
760            // Perform the xform if C2 is a single bit.
761            if ((C2 & (C2-1)) == 0) {
762              return getNode(ISD::SRL, VT, N1,
763                             getConstant(Log2_64(C2),TLI.getShiftAmountTy()));
764            }
765          }
766        }
767    }
768  } else if (isa<ConstantSDNode>(N1.Val)) {
769      // Ensure that the constant occurs on the RHS.
770    return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
771  }
772
773  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
774    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
775      double C1 = N1C->getValue(), C2 = N2C->getValue();
776
777      switch (Cond) {
778      default: break; // FIXME: Implement the rest of these!
779      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
780      case ISD::SETNE:  return getConstant(C1 != C2, VT);
781      case ISD::SETLT:  return getConstant(C1 < C2, VT);
782      case ISD::SETGT:  return getConstant(C1 > C2, VT);
783      case ISD::SETLE:  return getConstant(C1 <= C2, VT);
784      case ISD::SETGE:  return getConstant(C1 >= C2, VT);
785      }
786    } else {
787      // Ensure that the constant occurs on the RHS.
788      return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
789    }
790
791  // Could not fold it.
792  return SDOperand();
793}
794
795/// getNode - Gets or creates the specified node.
796///
797SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
798  SDNode *&N = NullaryOps[std::make_pair(Opcode, VT)];
799  if (!N) {
800    N = new SDNode(Opcode, VT);
801    AllNodes.push_back(N);
802  }
803  return SDOperand(N, 0);
804}
805
806SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
807                                SDOperand Operand) {
808  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
809    uint64_t Val = C->getValue();
810    switch (Opcode) {
811    default: break;
812    case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
813    case ISD::ANY_EXTEND:
814    case ISD::ZERO_EXTEND: return getConstant(Val, VT);
815    case ISD::TRUNCATE:    return getConstant(Val, VT);
816    case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
817    case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
818    }
819  }
820
821  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
822    switch (Opcode) {
823    case ISD::FNEG:
824      return getConstantFP(-C->getValue(), VT);
825    case ISD::FP_ROUND:
826    case ISD::FP_EXTEND:
827      return getConstantFP(C->getValue(), VT);
828    case ISD::FP_TO_SINT:
829      return getConstant((int64_t)C->getValue(), VT);
830    case ISD::FP_TO_UINT:
831      return getConstant((uint64_t)C->getValue(), VT);
832    }
833
834  unsigned OpOpcode = Operand.Val->getOpcode();
835  switch (Opcode) {
836  case ISD::TokenFactor:
837    return Operand;         // Factor of one node?  No factor.
838  case ISD::SIGN_EXTEND:
839    if (Operand.getValueType() == VT) return Operand;   // noop extension
840    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
841      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
842    break;
843  case ISD::ZERO_EXTEND:
844    if (Operand.getValueType() == VT) return Operand;   // noop extension
845    if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
846      return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
847    break;
848  case ISD::ANY_EXTEND:
849    if (Operand.getValueType() == VT) return Operand;   // noop extension
850    if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
851      // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
852      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
853    break;
854  case ISD::TRUNCATE:
855    if (Operand.getValueType() == VT) return Operand;   // noop truncate
856    if (OpOpcode == ISD::TRUNCATE)
857      return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
858    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
859             OpOpcode == ISD::ANY_EXTEND) {
860      // If the source is smaller than the dest, we still need an extend.
861      if (Operand.Val->getOperand(0).getValueType() < VT)
862        return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
863      else if (Operand.Val->getOperand(0).getValueType() > VT)
864        return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
865      else
866        return Operand.Val->getOperand(0);
867    }
868    break;
869  case ISD::FNEG:
870    if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
871      return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
872                     Operand.Val->getOperand(0));
873    if (OpOpcode == ISD::FNEG)  // --X -> X
874      return Operand.Val->getOperand(0);
875    break;
876  case ISD::FABS:
877    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
878      return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
879    break;
880  }
881
882  SDNode *N;
883  if (VT != MVT::Flag) { // Don't CSE flag producing nodes
884    SDNode *&E = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
885    if (E) return SDOperand(E, 0);
886    E = N = new SDNode(Opcode, Operand);
887  } else {
888    N = new SDNode(Opcode, Operand);
889  }
890  N->setValueTypes(VT);
891  AllNodes.push_back(N);
892  return SDOperand(N, 0);
893}
894
895
896
897SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
898                                SDOperand N1, SDOperand N2) {
899#ifndef NDEBUG
900  switch (Opcode) {
901  case ISD::TokenFactor:
902    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
903           N2.getValueType() == MVT::Other && "Invalid token factor!");
904    break;
905  case ISD::AND:
906  case ISD::OR:
907  case ISD::XOR:
908  case ISD::UDIV:
909  case ISD::UREM:
910  case ISD::MULHU:
911  case ISD::MULHS:
912    assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
913    // fall through
914  case ISD::ADD:
915  case ISD::SUB:
916  case ISD::MUL:
917  case ISD::SDIV:
918  case ISD::SREM:
919    assert(MVT::isInteger(N1.getValueType()) && "Should use F* for FP ops");
920    // fall through.
921  case ISD::FADD:
922  case ISD::FSUB:
923  case ISD::FMUL:
924  case ISD::FDIV:
925  case ISD::FREM:
926    assert(N1.getValueType() == N2.getValueType() &&
927           N1.getValueType() == VT && "Binary operator types must match!");
928    break;
929
930  case ISD::SHL:
931  case ISD::SRA:
932  case ISD::SRL:
933    assert(VT == N1.getValueType() &&
934           "Shift operators return type must be the same as their first arg");
935    assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
936           VT != MVT::i1 && "Shifts only work on integers");
937    break;
938  case ISD::FP_ROUND_INREG: {
939    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
940    assert(VT == N1.getValueType() && "Not an inreg round!");
941    assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
942           "Cannot FP_ROUND_INREG integer types");
943    assert(EVT <= VT && "Not rounding down!");
944    break;
945  }
946  case ISD::AssertSext:
947  case ISD::AssertZext:
948  case ISD::SIGN_EXTEND_INREG: {
949    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
950    assert(VT == N1.getValueType() && "Not an inreg extend!");
951    assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
952           "Cannot *_EXTEND_INREG FP types");
953    assert(EVT <= VT && "Not extending!");
954  }
955
956  default: break;
957  }
958#endif
959
960  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
961  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
962  if (N1C) {
963    if (N2C) {
964      uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
965      switch (Opcode) {
966      case ISD::ADD: return getConstant(C1 + C2, VT);
967      case ISD::SUB: return getConstant(C1 - C2, VT);
968      case ISD::MUL: return getConstant(C1 * C2, VT);
969      case ISD::UDIV:
970        if (C2) return getConstant(C1 / C2, VT);
971        break;
972      case ISD::UREM :
973        if (C2) return getConstant(C1 % C2, VT);
974        break;
975      case ISD::SDIV :
976        if (C2) return getConstant(N1C->getSignExtended() /
977                                   N2C->getSignExtended(), VT);
978        break;
979      case ISD::SREM :
980        if (C2) return getConstant(N1C->getSignExtended() %
981                                   N2C->getSignExtended(), VT);
982        break;
983      case ISD::AND  : return getConstant(C1 & C2, VT);
984      case ISD::OR   : return getConstant(C1 | C2, VT);
985      case ISD::XOR  : return getConstant(C1 ^ C2, VT);
986      case ISD::SHL  : return getConstant(C1 << C2, VT);
987      case ISD::SRL  : return getConstant(C1 >> C2, VT);
988      case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
989      default: break;
990      }
991    } else {      // Cannonicalize constant to RHS if commutative
992      if (isCommutativeBinOp(Opcode)) {
993        std::swap(N1C, N2C);
994        std::swap(N1, N2);
995      }
996    }
997  }
998
999  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1000  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1001  if (N1CFP) {
1002    if (N2CFP) {
1003      double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
1004      switch (Opcode) {
1005      case ISD::FADD: return getConstantFP(C1 + C2, VT);
1006      case ISD::FSUB: return getConstantFP(C1 - C2, VT);
1007      case ISD::FMUL: return getConstantFP(C1 * C2, VT);
1008      case ISD::FDIV:
1009        if (C2) return getConstantFP(C1 / C2, VT);
1010        break;
1011      case ISD::FREM :
1012        if (C2) return getConstantFP(fmod(C1, C2), VT);
1013        break;
1014      default: break;
1015      }
1016    } else {      // Cannonicalize constant to RHS if commutative
1017      if (isCommutativeBinOp(Opcode)) {
1018        std::swap(N1CFP, N2CFP);
1019        std::swap(N1, N2);
1020      }
1021    }
1022  }
1023
1024  // Finally, fold operations that do not require constants.
1025  switch (Opcode) {
1026  case ISD::FP_ROUND_INREG:
1027    if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
1028    break;
1029  case ISD::SIGN_EXTEND_INREG: {
1030    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1031    if (EVT == VT) return N1;  // Not actually extending
1032    break;
1033  }
1034
1035  // FIXME: figure out how to safely handle things like
1036  // int foo(int x) { return 1 << (x & 255); }
1037  // int bar() { return foo(256); }
1038#if 0
1039  case ISD::SHL:
1040  case ISD::SRL:
1041  case ISD::SRA:
1042    if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1043        cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
1044      return getNode(Opcode, VT, N1, N2.getOperand(0));
1045    else if (N2.getOpcode() == ISD::AND)
1046      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
1047        // If the and is only masking out bits that cannot effect the shift,
1048        // eliminate the and.
1049        unsigned NumBits = MVT::getSizeInBits(VT);
1050        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1051          return getNode(Opcode, VT, N1, N2.getOperand(0));
1052      }
1053    break;
1054#endif
1055  }
1056
1057  // Memoize this node if possible.
1058  SDNode *N;
1059  if (Opcode != ISD::CALLSEQ_START && Opcode != ISD::CALLSEQ_END &&
1060      VT != MVT::Flag) {
1061    SDNode *&BON = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
1062    if (BON) return SDOperand(BON, 0);
1063
1064    BON = N = new SDNode(Opcode, N1, N2);
1065  } else {
1066    N = new SDNode(Opcode, N1, N2);
1067  }
1068
1069  N->setValueTypes(VT);
1070  AllNodes.push_back(N);
1071  return SDOperand(N, 0);
1072}
1073
1074// setAdjCallChain - This method changes the token chain of an
1075// CALLSEQ_START/END node to be the specified operand.
1076void SDNode::setAdjCallChain(SDOperand N) {
1077  assert(N.getValueType() == MVT::Other);
1078  assert((getOpcode() == ISD::CALLSEQ_START ||
1079          getOpcode() == ISD::CALLSEQ_END) && "Cannot adjust this node!");
1080
1081  Operands[0].Val->removeUser(this);
1082  Operands[0] = N;
1083  N.Val->Uses.push_back(this);
1084}
1085
1086
1087
1088SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
1089                                SDOperand Chain, SDOperand Ptr,
1090                                SDOperand SV) {
1091  SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
1092  if (N) return SDOperand(N, 0);
1093  N = new SDNode(ISD::LOAD, Chain, Ptr, SV);
1094
1095  // Loads have a token chain.
1096  N->setValueTypes(VT, MVT::Other);
1097  AllNodes.push_back(N);
1098  return SDOperand(N, 0);
1099}
1100
1101
1102SDOperand SelectionDAG::getExtLoad(unsigned Opcode, MVT::ValueType VT,
1103                                   SDOperand Chain, SDOperand Ptr, SDOperand SV,
1104                                   MVT::ValueType EVT) {
1105  std::vector<SDOperand> Ops;
1106  Ops.reserve(4);
1107  Ops.push_back(Chain);
1108  Ops.push_back(Ptr);
1109  Ops.push_back(SV);
1110  Ops.push_back(getValueType(EVT));
1111  std::vector<MVT::ValueType> VTs;
1112  VTs.reserve(2);
1113  VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
1114  return getNode(Opcode, VTs, Ops);
1115}
1116
1117SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1118                                SDOperand N1, SDOperand N2, SDOperand N3) {
1119  // Perform various simplifications.
1120  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1121  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1122  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
1123  switch (Opcode) {
1124  case ISD::SETCC: {
1125    // Use SimplifySetCC  to simplify SETCC's.
1126    SDOperand Simp = SimplifySetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
1127    if (Simp.Val) return Simp;
1128    break;
1129  }
1130  case ISD::SELECT:
1131    if (N1C)
1132      if (N1C->getValue())
1133        return N2;             // select true, X, Y -> X
1134      else
1135        return N3;             // select false, X, Y -> Y
1136
1137    if (N2 == N3) return N2;   // select C, X, X -> X
1138    break;
1139  case ISD::BRCOND:
1140    if (N2C)
1141      if (N2C->getValue()) // Unconditional branch
1142        return getNode(ISD::BR, MVT::Other, N1, N3);
1143      else
1144        return N1;         // Never-taken branch
1145    break;
1146  }
1147
1148  std::vector<SDOperand> Ops;
1149  Ops.reserve(3);
1150  Ops.push_back(N1);
1151  Ops.push_back(N2);
1152  Ops.push_back(N3);
1153
1154  // Memoize node if it doesn't produce a flag.
1155  SDNode *N;
1156  if (VT != MVT::Flag) {
1157    SDNode *&E = OneResultNodes[std::make_pair(Opcode,std::make_pair(VT, Ops))];
1158    if (E) return SDOperand(E, 0);
1159    E = N = new SDNode(Opcode, N1, N2, N3);
1160  } else {
1161    N = new SDNode(Opcode, N1, N2, N3);
1162  }
1163  N->setValueTypes(VT);
1164  AllNodes.push_back(N);
1165  return SDOperand(N, 0);
1166}
1167
1168SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1169                                SDOperand N1, SDOperand N2, SDOperand N3,
1170                                SDOperand N4) {
1171  std::vector<SDOperand> Ops;
1172  Ops.reserve(4);
1173  Ops.push_back(N1);
1174  Ops.push_back(N2);
1175  Ops.push_back(N3);
1176  Ops.push_back(N4);
1177  return getNode(Opcode, VT, Ops);
1178}
1179
1180SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1181                                SDOperand N1, SDOperand N2, SDOperand N3,
1182                                SDOperand N4, SDOperand N5) {
1183  std::vector<SDOperand> Ops;
1184  Ops.reserve(5);
1185  Ops.push_back(N1);
1186  Ops.push_back(N2);
1187  Ops.push_back(N3);
1188  Ops.push_back(N4);
1189  Ops.push_back(N5);
1190  return getNode(Opcode, VT, Ops);
1191}
1192
1193
1194SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
1195  assert((!V || isa<PointerType>(V->getType())) &&
1196         "SrcValue is not a pointer?");
1197  SDNode *&N = ValueNodes[std::make_pair(V, Offset)];
1198  if (N) return SDOperand(N, 0);
1199
1200  N = new SrcValueSDNode(V, Offset);
1201  AllNodes.push_back(N);
1202  return SDOperand(N, 0);
1203}
1204
1205SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1206                                std::vector<SDOperand> &Ops) {
1207  switch (Ops.size()) {
1208  case 0: return getNode(Opcode, VT);
1209  case 1: return getNode(Opcode, VT, Ops[0]);
1210  case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
1211  case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
1212  default: break;
1213  }
1214
1215  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Ops[1].Val);
1216  switch (Opcode) {
1217  default: break;
1218  case ISD::BRCONDTWOWAY:
1219    if (N1C)
1220      if (N1C->getValue()) // Unconditional branch to true dest.
1221        return getNode(ISD::BR, MVT::Other, Ops[0], Ops[2]);
1222      else                 // Unconditional branch to false dest.
1223        return getNode(ISD::BR, MVT::Other, Ops[0], Ops[3]);
1224    break;
1225  case ISD::BRTWOWAY_CC:
1226    assert(Ops.size() == 6 && "BRTWOWAY_CC takes 6 operands!");
1227    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1228           "LHS and RHS of comparison must have same type!");
1229    break;
1230  case ISD::TRUNCSTORE: {
1231    assert(Ops.size() == 5 && "TRUNCSTORE takes 5 operands!");
1232    MVT::ValueType EVT = cast<VTSDNode>(Ops[4])->getVT();
1233#if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1234    // If this is a truncating store of a constant, convert to the desired type
1235    // and store it instead.
1236    if (isa<Constant>(Ops[0])) {
1237      SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1238      if (isa<Constant>(Op))
1239        N1 = Op;
1240    }
1241    // Also for ConstantFP?
1242#endif
1243    if (Ops[0].getValueType() == EVT)       // Normal store?
1244      return getNode(ISD::STORE, VT, Ops[0], Ops[1], Ops[2], Ops[3]);
1245    assert(Ops[1].getValueType() > EVT && "Not a truncation?");
1246    assert(MVT::isInteger(Ops[1].getValueType()) == MVT::isInteger(EVT) &&
1247           "Can't do FP-INT conversion!");
1248    break;
1249  }
1250  case ISD::SELECT_CC: {
1251    assert(Ops.size() == 5 && "SELECT_CC takes 5 operands!");
1252    assert(Ops[0].getValueType() == Ops[1].getValueType() &&
1253           "LHS and RHS of condition must have same type!");
1254    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1255           "True and False arms of SelectCC must have same type!");
1256    assert(Ops[2].getValueType() == VT &&
1257           "select_cc node must be of same type as true and false value!");
1258    break;
1259  }
1260  case ISD::BR_CC: {
1261    assert(Ops.size() == 5 && "BR_CC takes 5 operands!");
1262    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1263           "LHS/RHS of comparison should match types!");
1264    break;
1265  }
1266  }
1267
1268  // Memoize nodes.
1269  SDNode *N;
1270  if (VT != MVT::Flag) {
1271    SDNode *&E =
1272      OneResultNodes[std::make_pair(Opcode, std::make_pair(VT, Ops))];
1273    if (E) return SDOperand(E, 0);
1274    E = N = new SDNode(Opcode, Ops);
1275  } else {
1276    N = new SDNode(Opcode, Ops);
1277  }
1278  N->setValueTypes(VT);
1279  AllNodes.push_back(N);
1280  return SDOperand(N, 0);
1281}
1282
1283SDOperand SelectionDAG::getNode(unsigned Opcode,
1284                                std::vector<MVT::ValueType> &ResultTys,
1285                                std::vector<SDOperand> &Ops) {
1286  if (ResultTys.size() == 1)
1287    return getNode(Opcode, ResultTys[0], Ops);
1288
1289  switch (Opcode) {
1290  case ISD::EXTLOAD:
1291  case ISD::SEXTLOAD:
1292  case ISD::ZEXTLOAD: {
1293    MVT::ValueType EVT = cast<VTSDNode>(Ops[3])->getVT();
1294    assert(Ops.size() == 4 && ResultTys.size() == 2 && "Bad *EXTLOAD!");
1295    // If they are asking for an extending load from/to the same thing, return a
1296    // normal load.
1297    if (ResultTys[0] == EVT)
1298      return getLoad(ResultTys[0], Ops[0], Ops[1], Ops[2]);
1299    assert(EVT < ResultTys[0] &&
1300           "Should only be an extending load, not truncating!");
1301    assert((Opcode == ISD::EXTLOAD || MVT::isInteger(ResultTys[0])) &&
1302           "Cannot sign/zero extend a FP load!");
1303    assert(MVT::isInteger(ResultTys[0]) == MVT::isInteger(EVT) &&
1304           "Cannot convert from FP to Int or Int -> FP!");
1305    break;
1306  }
1307
1308  // FIXME: figure out how to safely handle things like
1309  // int foo(int x) { return 1 << (x & 255); }
1310  // int bar() { return foo(256); }
1311#if 0
1312  case ISD::SRA_PARTS:
1313  case ISD::SRL_PARTS:
1314  case ISD::SHL_PARTS:
1315    if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1316        cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
1317      return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1318    else if (N3.getOpcode() == ISD::AND)
1319      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
1320        // If the and is only masking out bits that cannot effect the shift,
1321        // eliminate the and.
1322        unsigned NumBits = MVT::getSizeInBits(VT)*2;
1323        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1324          return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1325      }
1326    break;
1327#endif
1328  }
1329
1330  // Memoize the node unless it returns a flag.
1331  SDNode *N;
1332  if (ResultTys.back() != MVT::Flag) {
1333    SDNode *&E =
1334      ArbitraryNodes[std::make_pair(Opcode, std::make_pair(ResultTys, Ops))];
1335    if (E) return SDOperand(E, 0);
1336    E = N = new SDNode(Opcode, Ops);
1337  } else {
1338    N = new SDNode(Opcode, Ops);
1339  }
1340  N->setValueTypes(ResultTys);
1341  AllNodes.push_back(N);
1342  return SDOperand(N, 0);
1343}
1344
1345
1346/// SelectNodeTo - These are used for target selectors to *mutate* the
1347/// specified node to have the specified return type, Target opcode, and
1348/// operands.  Note that target opcodes are stored as
1349/// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
1350void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1351                                MVT::ValueType VT) {
1352  RemoveNodeFromCSEMaps(N);
1353  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1354  N->setValueTypes(VT);
1355}
1356void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1357                                MVT::ValueType VT, SDOperand Op1) {
1358  RemoveNodeFromCSEMaps(N);
1359  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1360  N->setValueTypes(VT);
1361  N->setOperands(Op1);
1362}
1363void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1364                                MVT::ValueType VT, SDOperand Op1,
1365                                SDOperand Op2) {
1366  RemoveNodeFromCSEMaps(N);
1367  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1368  N->setValueTypes(VT);
1369  N->setOperands(Op1, Op2);
1370}
1371void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1372                                MVT::ValueType VT1, MVT::ValueType VT2,
1373                                SDOperand Op1, SDOperand Op2) {
1374  RemoveNodeFromCSEMaps(N);
1375  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1376  N->setValueTypes(VT1, VT2);
1377  N->setOperands(Op1, Op2);
1378}
1379void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1380                                MVT::ValueType VT, SDOperand Op1,
1381                                SDOperand Op2, SDOperand Op3) {
1382  RemoveNodeFromCSEMaps(N);
1383  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1384  N->setValueTypes(VT);
1385  N->setOperands(Op1, Op2, Op3);
1386}
1387void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1388                                MVT::ValueType VT1, MVT::ValueType VT2,
1389                                SDOperand Op1, SDOperand Op2, SDOperand Op3) {
1390  RemoveNodeFromCSEMaps(N);
1391  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1392  N->setValueTypes(VT1, VT2);
1393  N->setOperands(Op1, Op2, Op3);
1394}
1395
1396void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1397                                MVT::ValueType VT, SDOperand Op1,
1398                                SDOperand Op2, SDOperand Op3, SDOperand Op4) {
1399  RemoveNodeFromCSEMaps(N);
1400  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1401  N->setValueTypes(VT);
1402  N->setOperands(Op1, Op2, Op3, Op4);
1403}
1404void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1405                                MVT::ValueType VT, SDOperand Op1,
1406                                SDOperand Op2, SDOperand Op3, SDOperand Op4,
1407                                SDOperand Op5) {
1408  RemoveNodeFromCSEMaps(N);
1409  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1410  N->setValueTypes(VT);
1411  N->setOperands(Op1, Op2, Op3, Op4, Op5);
1412}
1413
1414/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
1415/// This can cause recursive merging of nodes in the DAG.
1416///
1417/// This version assumes From/To have a single result value.
1418///
1419void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
1420                                      std::vector<SDNode*> *Deleted) {
1421  SDNode *From = FromN.Val, *To = ToN.Val;
1422  assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
1423         "Cannot replace with this method!");
1424  assert(From != To && "Cannot replace uses of with self");
1425
1426  while (!From->use_empty()) {
1427    // Process users until they are all gone.
1428    SDNode *U = *From->use_begin();
1429
1430    // This node is about to morph, remove its old self from the CSE maps.
1431    RemoveNodeFromCSEMaps(U);
1432
1433    for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i)
1434      if (U->getOperand(i).Val == From) {
1435        From->removeUser(U);
1436        U->Operands[i].Val = To;
1437        To->addUser(U);
1438      }
1439
1440    // Now that we have modified U, add it back to the CSE maps.  If it already
1441    // exists there, recursively merge the results together.
1442    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
1443      ReplaceAllUsesWith(U, Existing, Deleted);
1444      // U is now dead.
1445      if (Deleted) Deleted->push_back(U);
1446      DeleteNodeNotInCSEMaps(U);
1447    }
1448  }
1449}
1450
1451/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
1452/// This can cause recursive merging of nodes in the DAG.
1453///
1454/// This version assumes From/To have matching types and numbers of result
1455/// values.
1456///
1457void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
1458                                      std::vector<SDNode*> *Deleted) {
1459  assert(From != To && "Cannot replace uses of with self");
1460  assert(From->getNumValues() == To->getNumValues() &&
1461         "Cannot use this version of ReplaceAllUsesWith!");
1462  if (From->getNumValues() == 1) {  // If possible, use the faster version.
1463    ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
1464    return;
1465  }
1466
1467  while (!From->use_empty()) {
1468    // Process users until they are all gone.
1469    SDNode *U = *From->use_begin();
1470
1471    // This node is about to morph, remove its old self from the CSE maps.
1472    RemoveNodeFromCSEMaps(U);
1473
1474    for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i)
1475      if (U->getOperand(i).Val == From) {
1476        From->removeUser(U);
1477        U->Operands[i].Val = To;
1478        To->addUser(U);
1479      }
1480
1481    // Now that we have modified U, add it back to the CSE maps.  If it already
1482    // exists there, recursively merge the results together.
1483    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
1484      ReplaceAllUsesWith(U, Existing, Deleted);
1485      // U is now dead.
1486      if (Deleted) Deleted->push_back(U);
1487      DeleteNodeNotInCSEMaps(U);
1488    }
1489  }
1490}
1491
1492/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
1493/// This can cause recursive merging of nodes in the DAG.
1494///
1495/// This version can replace From with any result values.  To must match the
1496/// number and types of values returned by From.
1497void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
1498                                      const std::vector<SDOperand> &To,
1499                                      std::vector<SDNode*> *Deleted) {
1500  assert(From->getNumValues() == To.size() &&
1501         "Incorrect number of values to replace with!");
1502  if (To.size() == 1 && To[0].Val->getNumValues() == 1) {
1503    // Degenerate case handled above.
1504    ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
1505    return;
1506  }
1507
1508  while (!From->use_empty()) {
1509    // Process users until they are all gone.
1510    SDNode *U = *From->use_begin();
1511
1512    // This node is about to morph, remove its old self from the CSE maps.
1513    RemoveNodeFromCSEMaps(U);
1514
1515    for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i)
1516      if (U->getOperand(i).Val == From) {
1517        const SDOperand &ToOp = To[U->getOperand(i).ResNo];
1518        From->removeUser(U);
1519        U->Operands[i] = ToOp;
1520        ToOp.Val->addUser(U);
1521      }
1522
1523    // Now that we have modified U, add it back to the CSE maps.  If it already
1524    // exists there, recursively merge the results together.
1525    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
1526      ReplaceAllUsesWith(U, Existing, Deleted);
1527      // U is now dead.
1528      if (Deleted) Deleted->push_back(U);
1529      DeleteNodeNotInCSEMaps(U);
1530    }
1531  }
1532}
1533
1534
1535//===----------------------------------------------------------------------===//
1536//                              SDNode Class
1537//===----------------------------------------------------------------------===//
1538
1539/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
1540/// indicated value.  This method ignores uses of other values defined by this
1541/// operation.
1542bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) {
1543  assert(Value < getNumValues() && "Bad value!");
1544
1545  // If there is only one value, this is easy.
1546  if (getNumValues() == 1)
1547    return use_size() == NUses;
1548  if (Uses.size() < NUses) return false;
1549
1550  SDOperand TheValue(this, Value);
1551
1552  std::set<SDNode*> UsersHandled;
1553
1554  for (std::vector<SDNode*>::iterator UI = Uses.begin(), E = Uses.end();
1555       UI != E; ++UI) {
1556    SDNode *User = *UI;
1557    if (User->getNumOperands() == 1 ||
1558        UsersHandled.insert(User).second)     // First time we've seen this?
1559      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1560        if (User->getOperand(i) == TheValue) {
1561          if (NUses == 0)
1562            return false;   // too many uses
1563          --NUses;
1564        }
1565  }
1566
1567  // Found exactly the right number of uses?
1568  return NUses == 0;
1569}
1570
1571
1572const char *SDNode::getOperationName(const SelectionDAG *G) const {
1573  switch (getOpcode()) {
1574  default:
1575    if (getOpcode() < ISD::BUILTIN_OP_END)
1576      return "<<Unknown DAG Node>>";
1577    else {
1578      if (G)
1579        if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
1580          if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
1581            return TII->getName(getOpcode()-ISD::BUILTIN_OP_END);
1582      return "<<Unknown Target Node>>";
1583    }
1584
1585  case ISD::PCMARKER:      return "PCMarker";
1586  case ISD::SRCVALUE:      return "SrcValue";
1587  case ISD::VALUETYPE:     return "ValueType";
1588  case ISD::EntryToken:    return "EntryToken";
1589  case ISD::TokenFactor:   return "TokenFactor";
1590  case ISD::AssertSext:    return "AssertSext";
1591  case ISD::AssertZext:    return "AssertZext";
1592  case ISD::Constant:      return "Constant";
1593  case ISD::TargetConstant: return "TargetConstant";
1594  case ISD::ConstantFP:    return "ConstantFP";
1595  case ISD::GlobalAddress: return "GlobalAddress";
1596  case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
1597  case ISD::FrameIndex:    return "FrameIndex";
1598  case ISD::TargetFrameIndex: return "TargetFrameIndex";
1599  case ISD::BasicBlock:    return "BasicBlock";
1600  case ISD::Register:      return "Register";
1601  case ISD::ExternalSymbol: return "ExternalSymbol";
1602  case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
1603  case ISD::ConstantPool:  return "ConstantPool";
1604  case ISD::TargetConstantPool:  return "TargetConstantPool";
1605  case ISD::CopyToReg:     return "CopyToReg";
1606  case ISD::CopyFromReg:   return "CopyFromReg";
1607  case ISD::ImplicitDef:   return "ImplicitDef";
1608  case ISD::UNDEF:         return "undef";
1609
1610  // Unary operators
1611  case ISD::FABS:   return "fabs";
1612  case ISD::FNEG:   return "fneg";
1613  case ISD::FSQRT:  return "fsqrt";
1614  case ISD::FSIN:   return "fsin";
1615  case ISD::FCOS:   return "fcos";
1616
1617  // Binary operators
1618  case ISD::ADD:    return "add";
1619  case ISD::SUB:    return "sub";
1620  case ISD::MUL:    return "mul";
1621  case ISD::MULHU:  return "mulhu";
1622  case ISD::MULHS:  return "mulhs";
1623  case ISD::SDIV:   return "sdiv";
1624  case ISD::UDIV:   return "udiv";
1625  case ISD::SREM:   return "srem";
1626  case ISD::UREM:   return "urem";
1627  case ISD::AND:    return "and";
1628  case ISD::OR:     return "or";
1629  case ISD::XOR:    return "xor";
1630  case ISD::SHL:    return "shl";
1631  case ISD::SRA:    return "sra";
1632  case ISD::SRL:    return "srl";
1633  case ISD::FADD:   return "fadd";
1634  case ISD::FSUB:   return "fsub";
1635  case ISD::FMUL:   return "fmul";
1636  case ISD::FDIV:   return "fdiv";
1637  case ISD::FREM:   return "frem";
1638
1639  case ISD::SETCC:       return "setcc";
1640  case ISD::SELECT:      return "select";
1641  case ISD::SELECT_CC:   return "select_cc";
1642  case ISD::ADD_PARTS:   return "add_parts";
1643  case ISD::SUB_PARTS:   return "sub_parts";
1644  case ISD::SHL_PARTS:   return "shl_parts";
1645  case ISD::SRA_PARTS:   return "sra_parts";
1646  case ISD::SRL_PARTS:   return "srl_parts";
1647
1648  // Conversion operators.
1649  case ISD::SIGN_EXTEND: return "sign_extend";
1650  case ISD::ZERO_EXTEND: return "zero_extend";
1651  case ISD::ANY_EXTEND:  return "any_extend";
1652  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
1653  case ISD::TRUNCATE:    return "truncate";
1654  case ISD::FP_ROUND:    return "fp_round";
1655  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
1656  case ISD::FP_EXTEND:   return "fp_extend";
1657
1658  case ISD::SINT_TO_FP:  return "sint_to_fp";
1659  case ISD::UINT_TO_FP:  return "uint_to_fp";
1660  case ISD::FP_TO_SINT:  return "fp_to_sint";
1661  case ISD::FP_TO_UINT:  return "fp_to_uint";
1662
1663    // Control flow instructions
1664  case ISD::BR:      return "br";
1665  case ISD::BRCOND:  return "brcond";
1666  case ISD::BRCONDTWOWAY:  return "brcondtwoway";
1667  case ISD::BR_CC:  return "br_cc";
1668  case ISD::BRTWOWAY_CC:  return "brtwoway_cc";
1669  case ISD::RET:     return "ret";
1670  case ISD::CALL:    return "call";
1671  case ISD::TAILCALL:return "tailcall";
1672  case ISD::CALLSEQ_START:  return "callseq_start";
1673  case ISD::CALLSEQ_END:    return "callseq_end";
1674
1675    // Other operators
1676  case ISD::LOAD:    return "load";
1677  case ISD::STORE:   return "store";
1678  case ISD::EXTLOAD:    return "extload";
1679  case ISD::SEXTLOAD:   return "sextload";
1680  case ISD::ZEXTLOAD:   return "zextload";
1681  case ISD::TRUNCSTORE: return "truncstore";
1682
1683  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
1684  case ISD::EXTRACT_ELEMENT: return "extract_element";
1685  case ISD::BUILD_PAIR: return "build_pair";
1686  case ISD::MEMSET:  return "memset";
1687  case ISD::MEMCPY:  return "memcpy";
1688  case ISD::MEMMOVE: return "memmove";
1689
1690  // Bit counting
1691  case ISD::CTPOP:   return "ctpop";
1692  case ISD::CTTZ:    return "cttz";
1693  case ISD::CTLZ:    return "ctlz";
1694
1695  // IO Intrinsics
1696  case ISD::READPORT: return "readport";
1697  case ISD::WRITEPORT: return "writeport";
1698  case ISD::READIO: return "readio";
1699  case ISD::WRITEIO: return "writeio";
1700
1701  case ISD::CONDCODE:
1702    switch (cast<CondCodeSDNode>(this)->get()) {
1703    default: assert(0 && "Unknown setcc condition!");
1704    case ISD::SETOEQ:  return "setoeq";
1705    case ISD::SETOGT:  return "setogt";
1706    case ISD::SETOGE:  return "setoge";
1707    case ISD::SETOLT:  return "setolt";
1708    case ISD::SETOLE:  return "setole";
1709    case ISD::SETONE:  return "setone";
1710
1711    case ISD::SETO:    return "seto";
1712    case ISD::SETUO:   return "setuo";
1713    case ISD::SETUEQ:  return "setue";
1714    case ISD::SETUGT:  return "setugt";
1715    case ISD::SETUGE:  return "setuge";
1716    case ISD::SETULT:  return "setult";
1717    case ISD::SETULE:  return "setule";
1718    case ISD::SETUNE:  return "setune";
1719
1720    case ISD::SETEQ:   return "seteq";
1721    case ISD::SETGT:   return "setgt";
1722    case ISD::SETGE:   return "setge";
1723    case ISD::SETLT:   return "setlt";
1724    case ISD::SETLE:   return "setle";
1725    case ISD::SETNE:   return "setne";
1726    }
1727  }
1728}
1729
1730void SDNode::dump() const { dump(0); }
1731void SDNode::dump(const SelectionDAG *G) const {
1732  std::cerr << (void*)this << ": ";
1733
1734  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
1735    if (i) std::cerr << ",";
1736    if (getValueType(i) == MVT::Other)
1737      std::cerr << "ch";
1738    else
1739      std::cerr << MVT::getValueTypeString(getValueType(i));
1740  }
1741  std::cerr << " = " << getOperationName(G);
1742
1743  std::cerr << " ";
1744  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1745    if (i) std::cerr << ", ";
1746    std::cerr << (void*)getOperand(i).Val;
1747    if (unsigned RN = getOperand(i).ResNo)
1748      std::cerr << ":" << RN;
1749  }
1750
1751  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
1752    std::cerr << "<" << CSDN->getValue() << ">";
1753  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
1754    std::cerr << "<" << CSDN->getValue() << ">";
1755  } else if (const GlobalAddressSDNode *GADN =
1756             dyn_cast<GlobalAddressSDNode>(this)) {
1757    std::cerr << "<";
1758    WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
1759  } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
1760    std::cerr << "<" << FIDN->getIndex() << ">";
1761  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
1762    std::cerr << "<" << *CP->get() << ">";
1763  } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
1764    std::cerr << "<";
1765    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
1766    if (LBB)
1767      std::cerr << LBB->getName() << " ";
1768    std::cerr << (const void*)BBDN->getBasicBlock() << ">";
1769  } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
1770    if (G && MRegisterInfo::isPhysicalRegister(R->getReg())) {
1771      std::cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
1772    } else {
1773      std::cerr << " #" << R->getReg();
1774    }
1775  } else if (const ExternalSymbolSDNode *ES =
1776             dyn_cast<ExternalSymbolSDNode>(this)) {
1777    std::cerr << "'" << ES->getSymbol() << "'";
1778  } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
1779    if (M->getValue())
1780      std::cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
1781    else
1782      std::cerr << "<null:" << M->getOffset() << ">";
1783  } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
1784    std::cerr << ":" << getValueTypeString(N->getVT());
1785  }
1786}
1787
1788static void DumpNodes(SDNode *N, unsigned indent, const SelectionDAG *G) {
1789  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1790    if (N->getOperand(i).Val->hasOneUse())
1791      DumpNodes(N->getOperand(i).Val, indent+2, G);
1792    else
1793      std::cerr << "\n" << std::string(indent+2, ' ')
1794                << (void*)N->getOperand(i).Val << ": <multiple use>";
1795
1796
1797  std::cerr << "\n" << std::string(indent, ' ');
1798  N->dump(G);
1799}
1800
1801void SelectionDAG::dump() const {
1802  std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
1803  std::vector<SDNode*> Nodes(AllNodes);
1804  std::sort(Nodes.begin(), Nodes.end());
1805
1806  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1807    if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
1808      DumpNodes(Nodes[i], 2, this);
1809  }
1810
1811  DumpNodes(getRoot().Val, 2, this);
1812
1813  std::cerr << "\n\n";
1814}
1815
1816