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