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