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