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