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