DAGCombiner.cpp revision c33baaafb6fb59eb4077f7b2cadff6cf743ce605
1//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11// both before and after the DAG is legalized.
12//
13// FIXME: Missing folds
14// sdiv, udiv, srem, urem (X, const) where X is an integer can be expanded into
15//  a sequence of multiplies, shifts, and adds.  This should be controlled by
16//  some kind of hint from the target that int div is expensive.
17// various folds of mulh[s,u] by constants such as -1, powers of 2, etc.
18//
19// FIXME: Should add a corresponding version of fold AND with
20// ZERO_EXTEND/SIGN_EXTEND by converting them to an ANY_EXTEND node which
21// we don't have yet.
22//
23// FIXME: select C, pow2, pow2 -> something smart
24// FIXME: trunc(select X, Y, Z) -> select X, trunc(Y), trunc(Z)
25// FIXME: Dead stores -> nuke
26// FIXME: shr X, (and Y,31) -> shr X, Y   (TRICKY!)
27// FIXME: mul (x, const) -> shifts + adds
28// FIXME: undef values
29// FIXME: make truncate see through SIGN_EXTEND and AND
30// FIXME: (sra (sra x, c1), c2) -> (sra x, c1+c2)
31// FIXME: verify that getNode can't return extends with an operand whose type
32//        is >= to that of the extend.
33// FIXME: divide by zero is currently left unfolded.  do we want to turn this
34//        into an undef?
35// FIXME: select ne (select cc, 1, 0), 0, true, false -> select cc, true, false
36// FIXME: reassociate (X+C)+Y  into (X+Y)+C  if the inner expression has one use
37//
38//===----------------------------------------------------------------------===//
39
40#define DEBUG_TYPE "dagcombine"
41#include "llvm/ADT/Statistic.h"
42#include "llvm/CodeGen/SelectionDAG.h"
43#include "llvm/Support/Debug.h"
44#include "llvm/Support/MathExtras.h"
45#include "llvm/Target/TargetLowering.h"
46#include <algorithm>
47#include <cmath>
48using namespace llvm;
49
50namespace {
51  Statistic<> NodesCombined ("dagcombiner", "Number of dag nodes combined");
52
53  class DAGCombiner {
54    SelectionDAG &DAG;
55    TargetLowering &TLI;
56    bool AfterLegalize;
57
58    // Worklist of all of the nodes that need to be simplified.
59    std::vector<SDNode*> WorkList;
60
61    /// AddUsersToWorkList - When an instruction is simplified, add all users of
62    /// the instruction to the work lists because they might get more simplified
63    /// now.
64    ///
65    void AddUsersToWorkList(SDNode *N) {
66      for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
67           UI != UE; ++UI)
68        WorkList.push_back(*UI);
69    }
70
71    /// removeFromWorkList - remove all instances of N from the worklist.
72    void removeFromWorkList(SDNode *N) {
73      WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
74                     WorkList.end());
75    }
76
77    SDOperand CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
78      ++NodesCombined;
79      DEBUG(std::cerr << "\nReplacing "; N->dump();
80            std::cerr << "\nWith: "; To[0].Val->dump();
81            std::cerr << " and " << To.size()-1 << " other values\n");
82      std::vector<SDNode*> NowDead;
83      DAG.ReplaceAllUsesWith(N, To, &NowDead);
84
85      // Push the new nodes and any users onto the worklist
86      for (unsigned i = 0, e = To.size(); i != e; ++i) {
87        WorkList.push_back(To[i].Val);
88        AddUsersToWorkList(To[i].Val);
89      }
90
91      // Nodes can end up on the worklist more than once.  Make sure we do
92      // not process a node that has been replaced.
93      removeFromWorkList(N);
94      for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
95        removeFromWorkList(NowDead[i]);
96
97      // Finally, since the node is now dead, remove it from the graph.
98      DAG.DeleteNode(N);
99      return SDOperand(N, 0);
100    }
101
102    SDOperand CombineTo(SDNode *N, SDOperand Res) {
103      std::vector<SDOperand> To;
104      To.push_back(Res);
105      return CombineTo(N, To);
106    }
107
108    SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
109      std::vector<SDOperand> To;
110      To.push_back(Res0);
111      To.push_back(Res1);
112      return CombineTo(N, To);
113    }
114
115    /// visit - call the node-specific routine that knows how to fold each
116    /// particular type of node.
117    SDOperand visit(SDNode *N);
118
119    // Visitation implementation - Implement dag node combining for different
120    // node types.  The semantics are as follows:
121    // Return Value:
122    //   SDOperand.Val == 0   - No change was made
123    //   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
124    //   otherwise            - N should be replaced by the returned Operand.
125    //
126    SDOperand visitTokenFactor(SDNode *N);
127    SDOperand visitADD(SDNode *N);
128    SDOperand visitSUB(SDNode *N);
129    SDOperand visitMUL(SDNode *N);
130    SDOperand visitSDIV(SDNode *N);
131    SDOperand visitUDIV(SDNode *N);
132    SDOperand visitSREM(SDNode *N);
133    SDOperand visitUREM(SDNode *N);
134    SDOperand visitMULHU(SDNode *N);
135    SDOperand visitMULHS(SDNode *N);
136    SDOperand visitAND(SDNode *N);
137    SDOperand visitOR(SDNode *N);
138    SDOperand visitXOR(SDNode *N);
139    SDOperand visitSHL(SDNode *N);
140    SDOperand visitSRA(SDNode *N);
141    SDOperand visitSRL(SDNode *N);
142    SDOperand visitCTLZ(SDNode *N);
143    SDOperand visitCTTZ(SDNode *N);
144    SDOperand visitCTPOP(SDNode *N);
145    SDOperand visitSELECT(SDNode *N);
146    SDOperand visitSELECT_CC(SDNode *N);
147    SDOperand visitSETCC(SDNode *N);
148    SDOperand visitADD_PARTS(SDNode *N);
149    SDOperand visitSUB_PARTS(SDNode *N);
150    SDOperand visitSIGN_EXTEND(SDNode *N);
151    SDOperand visitZERO_EXTEND(SDNode *N);
152    SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
153    SDOperand visitTRUNCATE(SDNode *N);
154    SDOperand visitBIT_CONVERT(SDNode *N);
155
156    SDOperand visitFADD(SDNode *N);
157    SDOperand visitFSUB(SDNode *N);
158    SDOperand visitFMUL(SDNode *N);
159    SDOperand visitFDIV(SDNode *N);
160    SDOperand visitFREM(SDNode *N);
161    SDOperand visitSINT_TO_FP(SDNode *N);
162    SDOperand visitUINT_TO_FP(SDNode *N);
163    SDOperand visitFP_TO_SINT(SDNode *N);
164    SDOperand visitFP_TO_UINT(SDNode *N);
165    SDOperand visitFP_ROUND(SDNode *N);
166    SDOperand visitFP_ROUND_INREG(SDNode *N);
167    SDOperand visitFP_EXTEND(SDNode *N);
168    SDOperand visitFNEG(SDNode *N);
169    SDOperand visitFABS(SDNode *N);
170    SDOperand visitBRCOND(SDNode *N);
171    SDOperand visitBRCONDTWOWAY(SDNode *N);
172    SDOperand visitBR_CC(SDNode *N);
173    SDOperand visitBRTWOWAY_CC(SDNode *N);
174
175    SDOperand visitLOAD(SDNode *N);
176    SDOperand visitSTORE(SDNode *N);
177
178    bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
179    SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
180    SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
181                               SDOperand N3, ISD::CondCode CC);
182    SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
183                            ISD::CondCode Cond, bool foldBooleans = true);
184
185    SDOperand BuildSDIV(SDNode *N);
186    SDOperand BuildUDIV(SDNode *N);
187public:
188    DAGCombiner(SelectionDAG &D)
189      : DAG(D), TLI(D.getTargetLoweringInfo()), AfterLegalize(false) {}
190
191    /// Run - runs the dag combiner on all nodes in the work list
192    void Run(bool RunningAfterLegalize);
193  };
194}
195
196struct ms {
197  int64_t m;  // magic number
198  int64_t s;  // shift amount
199};
200
201struct mu {
202  uint64_t m; // magic number
203  int64_t a;  // add indicator
204  int64_t s;  // shift amount
205};
206
207/// magic - calculate the magic numbers required to codegen an integer sdiv as
208/// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
209/// or -1.
210static ms magic32(int32_t d) {
211  int32_t p;
212  uint32_t ad, anc, delta, q1, r1, q2, r2, t;
213  const uint32_t two31 = 0x80000000U;
214  struct ms mag;
215
216  ad = abs(d);
217  t = two31 + ((uint32_t)d >> 31);
218  anc = t - 1 - t%ad;   // absolute value of nc
219  p = 31;               // initialize p
220  q1 = two31/anc;       // initialize q1 = 2p/abs(nc)
221  r1 = two31 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
222  q2 = two31/ad;        // initialize q2 = 2p/abs(d)
223  r2 = two31 - q2*ad;   // initialize r2 = rem(2p,abs(d))
224  do {
225    p = p + 1;
226    q1 = 2*q1;        // update q1 = 2p/abs(nc)
227    r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
228    if (r1 >= anc) {  // must be unsigned comparison
229      q1 = q1 + 1;
230      r1 = r1 - anc;
231    }
232    q2 = 2*q2;        // update q2 = 2p/abs(d)
233    r2 = 2*r2;        // update r2 = rem(2p/abs(d))
234    if (r2 >= ad) {   // must be unsigned comparison
235      q2 = q2 + 1;
236      r2 = r2 - ad;
237    }
238    delta = ad - r2;
239  } while (q1 < delta || (q1 == delta && r1 == 0));
240
241  mag.m = (int32_t)(q2 + 1); // make sure to sign extend
242  if (d < 0) mag.m = -mag.m; // resulting magic number
243  mag.s = p - 32;            // resulting shift
244  return mag;
245}
246
247/// magicu - calculate the magic numbers required to codegen an integer udiv as
248/// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
249static mu magicu32(uint32_t d) {
250  int32_t p;
251  uint32_t nc, delta, q1, r1, q2, r2;
252  struct mu magu;
253  magu.a = 0;               // initialize "add" indicator
254  nc = - 1 - (-d)%d;
255  p = 31;                   // initialize p
256  q1 = 0x80000000/nc;       // initialize q1 = 2p/nc
257  r1 = 0x80000000 - q1*nc;  // initialize r1 = rem(2p,nc)
258  q2 = 0x7FFFFFFF/d;        // initialize q2 = (2p-1)/d
259  r2 = 0x7FFFFFFF - q2*d;   // initialize r2 = rem((2p-1),d)
260  do {
261    p = p + 1;
262    if (r1 >= nc - r1 ) {
263      q1 = 2*q1 + 1;  // update q1
264      r1 = 2*r1 - nc; // update r1
265    }
266    else {
267      q1 = 2*q1; // update q1
268      r1 = 2*r1; // update r1
269    }
270    if (r2 + 1 >= d - r2) {
271      if (q2 >= 0x7FFFFFFF) magu.a = 1;
272      q2 = 2*q2 + 1;     // update q2
273      r2 = 2*r2 + 1 - d; // update r2
274    }
275    else {
276      if (q2 >= 0x80000000) magu.a = 1;
277      q2 = 2*q2;     // update q2
278      r2 = 2*r2 + 1; // update r2
279    }
280    delta = d - 1 - r2;
281  } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
282  magu.m = q2 + 1; // resulting magic number
283  magu.s = p - 32;  // resulting shift
284  return magu;
285}
286
287/// magic - calculate the magic numbers required to codegen an integer sdiv as
288/// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
289/// or -1.
290static ms magic64(int64_t d) {
291  int64_t p;
292  uint64_t ad, anc, delta, q1, r1, q2, r2, t;
293  const uint64_t two63 = 9223372036854775808ULL; // 2^63
294  struct ms mag;
295
296  ad = d >= 0 ? d : -d;
297  t = two63 + ((uint64_t)d >> 63);
298  anc = t - 1 - t%ad;   // absolute value of nc
299  p = 63;               // initialize p
300  q1 = two63/anc;       // initialize q1 = 2p/abs(nc)
301  r1 = two63 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
302  q2 = two63/ad;        // initialize q2 = 2p/abs(d)
303  r2 = two63 - q2*ad;   // initialize r2 = rem(2p,abs(d))
304  do {
305    p = p + 1;
306    q1 = 2*q1;        // update q1 = 2p/abs(nc)
307    r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
308    if (r1 >= anc) {  // must be unsigned comparison
309      q1 = q1 + 1;
310      r1 = r1 - anc;
311    }
312    q2 = 2*q2;        // update q2 = 2p/abs(d)
313    r2 = 2*r2;        // update r2 = rem(2p/abs(d))
314    if (r2 >= ad) {   // must be unsigned comparison
315      q2 = q2 + 1;
316      r2 = r2 - ad;
317    }
318    delta = ad - r2;
319  } while (q1 < delta || (q1 == delta && r1 == 0));
320
321  mag.m = q2 + 1;
322  if (d < 0) mag.m = -mag.m; // resulting magic number
323  mag.s = p - 64;            // resulting shift
324  return mag;
325}
326
327/// magicu - calculate the magic numbers required to codegen an integer udiv as
328/// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
329static mu magicu64(uint64_t d)
330{
331  int64_t p;
332  uint64_t nc, delta, q1, r1, q2, r2;
333  struct mu magu;
334  magu.a = 0;               // initialize "add" indicator
335  nc = - 1 - (-d)%d;
336  p = 63;                   // initialize p
337  q1 = 0x8000000000000000ull/nc;       // initialize q1 = 2p/nc
338  r1 = 0x8000000000000000ull - q1*nc;  // initialize r1 = rem(2p,nc)
339  q2 = 0x7FFFFFFFFFFFFFFFull/d;        // initialize q2 = (2p-1)/d
340  r2 = 0x7FFFFFFFFFFFFFFFull - q2*d;   // initialize r2 = rem((2p-1),d)
341  do {
342    p = p + 1;
343    if (r1 >= nc - r1 ) {
344      q1 = 2*q1 + 1;  // update q1
345      r1 = 2*r1 - nc; // update r1
346    }
347    else {
348      q1 = 2*q1; // update q1
349      r1 = 2*r1; // update r1
350    }
351    if (r2 + 1 >= d - r2) {
352      if (q2 >= 0x7FFFFFFFFFFFFFFFull) magu.a = 1;
353      q2 = 2*q2 + 1;     // update q2
354      r2 = 2*r2 + 1 - d; // update r2
355    }
356    else {
357      if (q2 >= 0x8000000000000000ull) magu.a = 1;
358      q2 = 2*q2;     // update q2
359      r2 = 2*r2 + 1; // update r2
360    }
361    delta = d - 1 - r2;
362  } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
363  magu.m = q2 + 1; // resulting magic number
364  magu.s = p - 64;  // resulting shift
365  return magu;
366}
367
368/// MaskedValueIsZero - Return true if 'Op & Mask' is known to be zero.  We use
369/// this predicate to simplify operations downstream.  Op and Mask are known to
370/// be the same type.
371static bool MaskedValueIsZero(const SDOperand &Op, uint64_t Mask,
372                              const TargetLowering &TLI) {
373  unsigned SrcBits;
374  if (Mask == 0) return true;
375
376  // If we know the result of a setcc has the top bits zero, use this info.
377  switch (Op.getOpcode()) {
378  case ISD::Constant:
379    return (cast<ConstantSDNode>(Op)->getValue() & Mask) == 0;
380  case ISD::SETCC:
381    return ((Mask & 1) == 0) &&
382    TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult;
383  case ISD::ZEXTLOAD:
384    SrcBits = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(3))->getVT());
385    return (Mask & ((1ULL << SrcBits)-1)) == 0; // Returning only the zext bits.
386  case ISD::ZERO_EXTEND:
387    SrcBits = MVT::getSizeInBits(Op.getOperand(0).getValueType());
388    return MaskedValueIsZero(Op.getOperand(0),Mask & (~0ULL >> (64-SrcBits)),TLI);
389  case ISD::AssertZext:
390    SrcBits = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
391    return (Mask & ((1ULL << SrcBits)-1)) == 0; // Returning only the zext bits.
392  case ISD::AND:
393    // If either of the operands has zero bits, the result will too.
394    if (MaskedValueIsZero(Op.getOperand(1), Mask, TLI) ||
395        MaskedValueIsZero(Op.getOperand(0), Mask, TLI))
396      return true;
397    // (X & C1) & C2 == 0   iff   C1 & C2 == 0.
398    if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
399      return MaskedValueIsZero(Op.getOperand(0),AndRHS->getValue() & Mask, TLI);
400    return false;
401  case ISD::OR:
402  case ISD::XOR:
403    return MaskedValueIsZero(Op.getOperand(0), Mask, TLI) &&
404    MaskedValueIsZero(Op.getOperand(1), Mask, TLI);
405  case ISD::SELECT:
406    return MaskedValueIsZero(Op.getOperand(1), Mask, TLI) &&
407    MaskedValueIsZero(Op.getOperand(2), Mask, TLI);
408  case ISD::SELECT_CC:
409    return MaskedValueIsZero(Op.getOperand(2), Mask, TLI) &&
410    MaskedValueIsZero(Op.getOperand(3), Mask, TLI);
411  case ISD::SRL:
412    // (ushr X, C1) & C2 == 0   iff  X & (C2 << C1) == 0
413    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
414      uint64_t NewVal = Mask << ShAmt->getValue();
415      SrcBits = MVT::getSizeInBits(Op.getValueType());
416      if (SrcBits != 64) NewVal &= (1ULL << SrcBits)-1;
417      return MaskedValueIsZero(Op.getOperand(0), NewVal, TLI);
418    }
419    return false;
420  case ISD::SHL:
421    // (ushl X, C1) & C2 == 0   iff  X & (C2 >> C1) == 0
422    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
423      uint64_t NewVal = Mask >> ShAmt->getValue();
424      return MaskedValueIsZero(Op.getOperand(0), NewVal, TLI);
425    }
426    return false;
427  case ISD::ADD:
428    // (add X, Y) & C == 0 iff (X&C)|(Y&C) == 0 and all bits are low bits.
429    if ((Mask&(Mask+1)) == 0) {  // All low bits
430      if (MaskedValueIsZero(Op.getOperand(0), Mask, TLI) &&
431          MaskedValueIsZero(Op.getOperand(1), Mask, TLI))
432        return true;
433    }
434    break;
435  case ISD::SUB:
436    if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
437      // We know that the top bits of C-X are clear if X contains less bits
438      // than C (i.e. no wrap-around can happen).  For example, 20-X is
439      // positive if we can prove that X is >= 0 and < 16.
440      unsigned Bits = MVT::getSizeInBits(CLHS->getValueType(0));
441      if ((CLHS->getValue() & (1 << (Bits-1))) == 0) {  // sign bit clear
442        unsigned NLZ = CountLeadingZeros_64(CLHS->getValue()+1);
443        uint64_t MaskV = (1ULL << (63-NLZ))-1;
444        if (MaskedValueIsZero(Op.getOperand(1), ~MaskV, TLI)) {
445          // High bits are clear this value is known to be >= C.
446          unsigned NLZ2 = CountLeadingZeros_64(CLHS->getValue());
447          if ((Mask & ((1ULL << (64-NLZ2))-1)) == 0)
448            return true;
449        }
450      }
451    }
452    break;
453  case ISD::CTTZ:
454  case ISD::CTLZ:
455  case ISD::CTPOP:
456    // Bit counting instructions can not set the high bits of the result
457    // register.  The max number of bits sets depends on the input.
458    return (Mask & (MVT::getSizeInBits(Op.getValueType())*2-1)) == 0;
459  default:
460    if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
461      return TLI.isMaskedValueZeroForTargetNode(Op, Mask);
462    break;
463  }
464  return false;
465}
466
467// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
468// that selects between the values 1 and 0, making it equivalent to a setcc.
469// Also, set the incoming LHS, RHS, and CC references to the appropriate
470// nodes based on the type of node we are checking.  This simplifies life a
471// bit for the callers.
472static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
473                              SDOperand &CC) {
474  if (N.getOpcode() == ISD::SETCC) {
475    LHS = N.getOperand(0);
476    RHS = N.getOperand(1);
477    CC  = N.getOperand(2);
478    return true;
479  }
480  if (N.getOpcode() == ISD::SELECT_CC &&
481      N.getOperand(2).getOpcode() == ISD::Constant &&
482      N.getOperand(3).getOpcode() == ISD::Constant &&
483      cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
484      cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
485    LHS = N.getOperand(0);
486    RHS = N.getOperand(1);
487    CC  = N.getOperand(4);
488    return true;
489  }
490  return false;
491}
492
493// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
494// one use.  If this is true, it allows the users to invert the operation for
495// free when it is profitable to do so.
496static bool isOneUseSetCC(SDOperand N) {
497  SDOperand N0, N1, N2;
498  if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
499    return true;
500  return false;
501}
502
503// FIXME: This should probably go in the ISD class rather than being duplicated
504// in several files.
505static bool isCommutativeBinOp(unsigned Opcode) {
506  switch (Opcode) {
507    case ISD::ADD:
508    case ISD::MUL:
509    case ISD::AND:
510    case ISD::OR:
511    case ISD::XOR: return true;
512    default: return false; // FIXME: Need commutative info for user ops!
513  }
514}
515
516void DAGCombiner::Run(bool RunningAfterLegalize) {
517  // set the instance variable, so that the various visit routines may use it.
518  AfterLegalize = RunningAfterLegalize;
519
520  // Add all the dag nodes to the worklist.
521  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
522       E = DAG.allnodes_end(); I != E; ++I)
523    WorkList.push_back(I);
524
525  // Create a dummy node (which is not added to allnodes), that adds a reference
526  // to the root node, preventing it from being deleted, and tracking any
527  // changes of the root.
528  HandleSDNode Dummy(DAG.getRoot());
529
530  // while the worklist isn't empty, inspect the node on the end of it and
531  // try and combine it.
532  while (!WorkList.empty()) {
533    SDNode *N = WorkList.back();
534    WorkList.pop_back();
535
536    // If N has no uses, it is dead.  Make sure to revisit all N's operands once
537    // N is deleted from the DAG, since they too may now be dead or may have a
538    // reduced number of uses, allowing other xforms.
539    if (N->use_empty() && N != &Dummy) {
540      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
541        WorkList.push_back(N->getOperand(i).Val);
542
543      removeFromWorkList(N);
544      DAG.DeleteNode(N);
545      continue;
546    }
547
548    SDOperand RV = visit(N);
549    if (RV.Val) {
550      ++NodesCombined;
551      // If we get back the same node we passed in, rather than a new node or
552      // zero, we know that the node must have defined multiple values and
553      // CombineTo was used.  Since CombineTo takes care of the worklist
554      // mechanics for us, we have no work to do in this case.
555      if (RV.Val != N) {
556        DEBUG(std::cerr << "\nReplacing "; N->dump();
557              std::cerr << "\nWith: "; RV.Val->dump();
558              std::cerr << '\n');
559        std::vector<SDNode*> NowDead;
560        DAG.ReplaceAllUsesWith(N, std::vector<SDOperand>(1, RV), &NowDead);
561
562        // Push the new node and any users onto the worklist
563        WorkList.push_back(RV.Val);
564        AddUsersToWorkList(RV.Val);
565
566        // Nodes can end up on the worklist more than once.  Make sure we do
567        // not process a node that has been replaced.
568        removeFromWorkList(N);
569        for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
570          removeFromWorkList(NowDead[i]);
571
572        // Finally, since the node is now dead, remove it from the graph.
573        DAG.DeleteNode(N);
574      }
575    }
576  }
577
578  // If the root changed (e.g. it was a dead load, update the root).
579  DAG.setRoot(Dummy.getValue());
580}
581
582SDOperand DAGCombiner::visit(SDNode *N) {
583  switch(N->getOpcode()) {
584  default: break;
585  case ISD::TokenFactor:        return visitTokenFactor(N);
586  case ISD::ADD:                return visitADD(N);
587  case ISD::SUB:                return visitSUB(N);
588  case ISD::MUL:                return visitMUL(N);
589  case ISD::SDIV:               return visitSDIV(N);
590  case ISD::UDIV:               return visitUDIV(N);
591  case ISD::SREM:               return visitSREM(N);
592  case ISD::UREM:               return visitUREM(N);
593  case ISD::MULHU:              return visitMULHU(N);
594  case ISD::MULHS:              return visitMULHS(N);
595  case ISD::AND:                return visitAND(N);
596  case ISD::OR:                 return visitOR(N);
597  case ISD::XOR:                return visitXOR(N);
598  case ISD::SHL:                return visitSHL(N);
599  case ISD::SRA:                return visitSRA(N);
600  case ISD::SRL:                return visitSRL(N);
601  case ISD::CTLZ:               return visitCTLZ(N);
602  case ISD::CTTZ:               return visitCTTZ(N);
603  case ISD::CTPOP:              return visitCTPOP(N);
604  case ISD::SELECT:             return visitSELECT(N);
605  case ISD::SELECT_CC:          return visitSELECT_CC(N);
606  case ISD::SETCC:              return visitSETCC(N);
607  case ISD::ADD_PARTS:          return visitADD_PARTS(N);
608  case ISD::SUB_PARTS:          return visitSUB_PARTS(N);
609  case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
610  case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
611  case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
612  case ISD::TRUNCATE:           return visitTRUNCATE(N);
613  case ISD::BIT_CONVERT:        return visitBIT_CONVERT(N);
614  case ISD::FADD:               return visitFADD(N);
615  case ISD::FSUB:               return visitFSUB(N);
616  case ISD::FMUL:               return visitFMUL(N);
617  case ISD::FDIV:               return visitFDIV(N);
618  case ISD::FREM:               return visitFREM(N);
619  case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
620  case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
621  case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
622  case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
623  case ISD::FP_ROUND:           return visitFP_ROUND(N);
624  case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
625  case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
626  case ISD::FNEG:               return visitFNEG(N);
627  case ISD::FABS:               return visitFABS(N);
628  case ISD::BRCOND:             return visitBRCOND(N);
629  case ISD::BRCONDTWOWAY:       return visitBRCONDTWOWAY(N);
630  case ISD::BR_CC:              return visitBR_CC(N);
631  case ISD::BRTWOWAY_CC:        return visitBRTWOWAY_CC(N);
632  case ISD::LOAD:               return visitLOAD(N);
633  case ISD::STORE:              return visitSTORE(N);
634  }
635  return SDOperand();
636}
637
638SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
639  std::vector<SDOperand> Ops;
640  bool Changed = false;
641
642  // If the token factor has two operands and one is the entry token, replace
643  // the token factor with the other operand.
644  if (N->getNumOperands() == 2) {
645    if (N->getOperand(0).getOpcode() == ISD::EntryToken)
646      return N->getOperand(1);
647    if (N->getOperand(1).getOpcode() == ISD::EntryToken)
648      return N->getOperand(0);
649  }
650
651  // fold (tokenfactor (tokenfactor)) -> tokenfactor
652  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
653    SDOperand Op = N->getOperand(i);
654    if (Op.getOpcode() == ISD::TokenFactor && Op.hasOneUse()) {
655      Changed = true;
656      for (unsigned j = 0, e = Op.getNumOperands(); j != e; ++j)
657        Ops.push_back(Op.getOperand(j));
658    } else {
659      Ops.push_back(Op);
660    }
661  }
662  if (Changed)
663    return DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
664  return SDOperand();
665}
666
667SDOperand DAGCombiner::visitADD(SDNode *N) {
668  SDOperand N0 = N->getOperand(0);
669  SDOperand N1 = N->getOperand(1);
670  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
671  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
672  MVT::ValueType VT = N0.getValueType();
673
674  // fold (add c1, c2) -> c1+c2
675  if (N0C && N1C)
676    return DAG.getConstant(N0C->getValue() + N1C->getValue(), VT);
677  // canonicalize constant to RHS
678  if (N0C && !N1C)
679    return DAG.getNode(ISD::ADD, VT, N1, N0);
680  // fold (add x, 0) -> x
681  if (N1C && N1C->isNullValue())
682    return N0;
683  // fold (add (add x, c1), c2) -> (add x, c1+c2)
684  if (N1C && N0.getOpcode() == ISD::ADD) {
685    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
686    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
687    if (N00C)
688      return DAG.getNode(ISD::ADD, VT, N0.getOperand(1),
689                         DAG.getConstant(N1C->getValue()+N00C->getValue(), VT));
690    if (N01C)
691      return DAG.getNode(ISD::ADD, VT, N0.getOperand(0),
692                         DAG.getConstant(N1C->getValue()+N01C->getValue(), VT));
693  }
694  // fold ((0-A) + B) -> B-A
695  if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
696      cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
697    return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
698  // fold (A + (0-B)) -> A-B
699  if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
700      cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
701    return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
702  // fold (A+(B-A)) -> B
703  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
704    return N1.getOperand(0);
705  return SDOperand();
706}
707
708SDOperand DAGCombiner::visitSUB(SDNode *N) {
709  SDOperand N0 = N->getOperand(0);
710  SDOperand N1 = N->getOperand(1);
711  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
712  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
713
714  // fold (sub x, x) -> 0
715  if (N0 == N1)
716    return DAG.getConstant(0, N->getValueType(0));
717
718  // fold (sub c1, c2) -> c1-c2
719  if (N0C && N1C)
720    return DAG.getConstant(N0C->getValue() - N1C->getValue(),
721                           N->getValueType(0));
722  // fold (sub x, c) -> (add x, -c)
723  if (N1C)
724    return DAG.getNode(ISD::ADD, N0.getValueType(), N0,
725                       DAG.getConstant(-N1C->getValue(), N0.getValueType()));
726
727  // fold (A+B)-A -> B
728  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
729    return N0.getOperand(1);
730  // fold (A+B)-B -> A
731  if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
732    return N0.getOperand(0);
733  return SDOperand();
734}
735
736SDOperand DAGCombiner::visitMUL(SDNode *N) {
737  SDOperand N0 = N->getOperand(0);
738  SDOperand N1 = N->getOperand(1);
739  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
740  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
741  MVT::ValueType VT = N0.getValueType();
742
743  // fold (mul c1, c2) -> c1*c2
744  if (N0C && N1C)
745    return DAG.getConstant(N0C->getValue() * N1C->getValue(), VT);
746  // canonicalize constant to RHS
747  if (N0C && !N1C)
748    return DAG.getNode(ISD::MUL, VT, N1, N0);
749  // fold (mul x, 0) -> 0
750  if (N1C && N1C->isNullValue())
751    return N1;
752  // fold (mul x, -1) -> 0-x
753  if (N1C && N1C->isAllOnesValue())
754    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
755  // fold (mul x, (1 << c)) -> x << c
756  if (N1C && isPowerOf2_64(N1C->getValue()))
757    return DAG.getNode(ISD::SHL, VT, N0,
758                       DAG.getConstant(Log2_64(N1C->getValue()),
759                                       TLI.getShiftAmountTy()));
760  // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
761  if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
762    // FIXME: If the input is something that is easily negated (e.g. a
763    // single-use add), we should put the negate there.
764    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
765                       DAG.getNode(ISD::SHL, VT, N0,
766                            DAG.getConstant(Log2_64(-N1C->getSignExtended()),
767                                            TLI.getShiftAmountTy())));
768  }
769
770
771  // fold (mul (mul x, c1), c2) -> (mul x, c1*c2)
772  if (N1C && N0.getOpcode() == ISD::MUL) {
773    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
774    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
775    if (N00C)
776      return DAG.getNode(ISD::MUL, VT, N0.getOperand(1),
777                         DAG.getConstant(N1C->getValue()*N00C->getValue(), VT));
778    if (N01C)
779      return DAG.getNode(ISD::MUL, VT, N0.getOperand(0),
780                         DAG.getConstant(N1C->getValue()*N01C->getValue(), VT));
781  }
782  return SDOperand();
783}
784
785SDOperand DAGCombiner::visitSDIV(SDNode *N) {
786  SDOperand N0 = N->getOperand(0);
787  SDOperand N1 = N->getOperand(1);
788  MVT::ValueType VT = N->getValueType(0);
789  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
790  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
791
792  // fold (sdiv c1, c2) -> c1/c2
793  if (N0C && N1C && !N1C->isNullValue())
794    return DAG.getConstant(N0C->getSignExtended() / N1C->getSignExtended(),
795                           N->getValueType(0));
796  // fold (sdiv X, 1) -> X
797  if (N1C && N1C->getSignExtended() == 1LL)
798    return N0;
799  // fold (sdiv X, -1) -> 0-X
800  if (N1C && N1C->isAllOnesValue())
801    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
802  // If we know the sign bits of both operands are zero, strength reduce to a
803  // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
804  uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
805  if (MaskedValueIsZero(N1, SignBit, TLI) &&
806      MaskedValueIsZero(N0, SignBit, TLI))
807    return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
808  // fold (sdiv X, pow2) -> (add (sra X, log(pow2)), (srl X, sizeof(X)-1))
809  if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
810      (isPowerOf2_64(N1C->getSignExtended()) ||
811       isPowerOf2_64(-N1C->getSignExtended()))) {
812    // If dividing by powers of two is cheap, then don't perform the following
813    // fold.
814    if (TLI.isPow2DivCheap())
815      return SDOperand();
816    int64_t pow2 = N1C->getSignExtended();
817    int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
818    SDOperand SRL = DAG.getNode(ISD::SRL, VT, N0,
819                                DAG.getConstant(MVT::getSizeInBits(VT)-1,
820                                                TLI.getShiftAmountTy()));
821    WorkList.push_back(SRL.Val);
822    SDOperand SGN = DAG.getNode(ISD::ADD, VT, N0, SRL);
823    WorkList.push_back(SGN.Val);
824    SDOperand SRA = DAG.getNode(ISD::SRA, VT, SGN,
825                                DAG.getConstant(Log2_64(abs2),
826                                                TLI.getShiftAmountTy()));
827    // If we're dividing by a positive value, we're done.  Otherwise, we must
828    // negate the result.
829    if (pow2 > 0)
830      return SRA;
831    WorkList.push_back(SRA.Val);
832    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
833  }
834  // if integer divide is expensive and we satisfy the requirements, emit an
835  // alternate sequence.
836  if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
837      !TLI.isIntDivCheap()) {
838    SDOperand Op = BuildSDIV(N);
839    if (Op.Val) return Op;
840  }
841  return SDOperand();
842}
843
844SDOperand DAGCombiner::visitUDIV(SDNode *N) {
845  SDOperand N0 = N->getOperand(0);
846  SDOperand N1 = N->getOperand(1);
847  MVT::ValueType VT = N->getValueType(0);
848  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
849  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
850
851  // fold (udiv c1, c2) -> c1/c2
852  if (N0C && N1C && !N1C->isNullValue())
853    return DAG.getConstant(N0C->getValue() / N1C->getValue(),
854                           N->getValueType(0));
855  // fold (udiv x, (1 << c)) -> x >>u c
856  if (N1C && isPowerOf2_64(N1C->getValue()))
857    return DAG.getNode(ISD::SRL, N->getValueType(0), N0,
858                       DAG.getConstant(Log2_64(N1C->getValue()),
859                                       TLI.getShiftAmountTy()));
860  // fold (udiv x, c) -> alternate
861  if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
862    SDOperand Op = BuildUDIV(N);
863    if (Op.Val) return Op;
864  }
865
866  return SDOperand();
867}
868
869SDOperand DAGCombiner::visitSREM(SDNode *N) {
870  SDOperand N0 = N->getOperand(0);
871  SDOperand N1 = N->getOperand(1);
872  MVT::ValueType VT = N->getValueType(0);
873  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
874  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
875
876  // fold (srem c1, c2) -> c1%c2
877  if (N0C && N1C && !N1C->isNullValue())
878    return DAG.getConstant(N0C->getSignExtended() % N1C->getSignExtended(),
879                           N->getValueType(0));
880  // If we know the sign bits of both operands are zero, strength reduce to a
881  // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
882  uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
883  if (MaskedValueIsZero(N1, SignBit, TLI) &&
884      MaskedValueIsZero(N0, SignBit, TLI))
885    return DAG.getNode(ISD::UREM, N1.getValueType(), N0, N1);
886  return SDOperand();
887}
888
889SDOperand DAGCombiner::visitUREM(SDNode *N) {
890  SDOperand N0 = N->getOperand(0);
891  SDOperand N1 = N->getOperand(1);
892  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
893  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
894
895  // fold (urem c1, c2) -> c1%c2
896  if (N0C && N1C && !N1C->isNullValue())
897    return DAG.getConstant(N0C->getValue() % N1C->getValue(),
898                           N->getValueType(0));
899  // fold (urem x, pow2) -> (and x, pow2-1)
900  if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
901    return DAG.getNode(ISD::AND, N0.getValueType(), N0,
902                       DAG.getConstant(N1C->getValue()-1, N1.getValueType()));
903  return SDOperand();
904}
905
906SDOperand DAGCombiner::visitMULHS(SDNode *N) {
907  SDOperand N0 = N->getOperand(0);
908  SDOperand N1 = N->getOperand(1);
909  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
910
911  // fold (mulhs x, 0) -> 0
912  if (N1C && N1C->isNullValue())
913    return N1;
914  // fold (mulhs x, 1) -> (sra x, size(x)-1)
915  if (N1C && N1C->getValue() == 1)
916    return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
917                       DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
918                                       TLI.getShiftAmountTy()));
919  return SDOperand();
920}
921
922SDOperand DAGCombiner::visitMULHU(SDNode *N) {
923  SDOperand N0 = N->getOperand(0);
924  SDOperand N1 = N->getOperand(1);
925  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
926
927  // fold (mulhu x, 0) -> 0
928  if (N1C && N1C->isNullValue())
929    return N1;
930  // fold (mulhu x, 1) -> 0
931  if (N1C && N1C->getValue() == 1)
932    return DAG.getConstant(0, N0.getValueType());
933  return SDOperand();
934}
935
936SDOperand DAGCombiner::visitAND(SDNode *N) {
937  SDOperand N0 = N->getOperand(0);
938  SDOperand N1 = N->getOperand(1);
939  SDOperand LL, LR, RL, RR, CC0, CC1;
940  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
941  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
942  MVT::ValueType VT = N1.getValueType();
943  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
944
945  // fold (and c1, c2) -> c1&c2
946  if (N0C && N1C)
947    return DAG.getConstant(N0C->getValue() & N1C->getValue(), VT);
948  // canonicalize constant to RHS
949  if (N0C && !N1C)
950    return DAG.getNode(ISD::AND, VT, N1, N0);
951  // fold (and x, -1) -> x
952  if (N1C && N1C->isAllOnesValue())
953    return N0;
954  // if (and x, c) is known to be zero, return 0
955  if (N1C && MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits),TLI))
956    return DAG.getConstant(0, VT);
957  // fold (and x, c) -> x iff (x & ~c) == 0
958  if (N1C && MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits)),
959                               TLI))
960    return N0;
961  // fold (and (and x, c1), c2) -> (and x, c1^c2)
962  if (N1C && N0.getOpcode() == ISD::AND) {
963    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
964    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
965    if (N00C)
966      return DAG.getNode(ISD::AND, VT, N0.getOperand(1),
967                         DAG.getConstant(N1C->getValue()&N00C->getValue(), VT));
968    if (N01C)
969      return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
970                         DAG.getConstant(N1C->getValue()&N01C->getValue(), VT));
971  }
972  // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
973  if (N1C && N0.getOpcode() == ISD::SIGN_EXTEND_INREG) {
974    unsigned ExtendBits =
975        MVT::getSizeInBits(cast<VTSDNode>(N0.getOperand(1))->getVT());
976    if (ExtendBits == 64 || ((N1C->getValue() & (~0ULL << ExtendBits)) == 0))
977      return DAG.getNode(ISD::AND, VT, N0.getOperand(0), N1);
978  }
979  // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
980  if (N1C && N0.getOpcode() == ISD::OR)
981    if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
982      if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
983        return N1;
984  // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
985  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
986    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
987    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
988
989    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
990        MVT::isInteger(LL.getValueType())) {
991      // fold (X == 0) & (Y == 0) -> (X|Y == 0)
992      if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
993        SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
994        WorkList.push_back(ORNode.Val);
995        return DAG.getSetCC(VT, ORNode, LR, Op1);
996      }
997      // fold (X == -1) & (Y == -1) -> (X&Y == -1)
998      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
999        SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1000        WorkList.push_back(ANDNode.Val);
1001        return DAG.getSetCC(VT, ANDNode, LR, Op1);
1002      }
1003      // fold (X >  -1) & (Y >  -1) -> (X|Y > -1)
1004      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1005        SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1006        WorkList.push_back(ORNode.Val);
1007        return DAG.getSetCC(VT, ORNode, LR, Op1);
1008      }
1009    }
1010    // canonicalize equivalent to ll == rl
1011    if (LL == RR && LR == RL) {
1012      Op1 = ISD::getSetCCSwappedOperands(Op1);
1013      std::swap(RL, RR);
1014    }
1015    if (LL == RL && LR == RR) {
1016      bool isInteger = MVT::isInteger(LL.getValueType());
1017      ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1018      if (Result != ISD::SETCC_INVALID)
1019        return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1020    }
1021  }
1022  // fold (and (zext x), (zext y)) -> (zext (and x, y))
1023  if (N0.getOpcode() == ISD::ZERO_EXTEND &&
1024      N1.getOpcode() == ISD::ZERO_EXTEND &&
1025      N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1026    SDOperand ANDNode = DAG.getNode(ISD::AND, N0.getOperand(0).getValueType(),
1027                                    N0.getOperand(0), N1.getOperand(0));
1028    WorkList.push_back(ANDNode.Val);
1029    return DAG.getNode(ISD::ZERO_EXTEND, VT, ANDNode);
1030  }
1031  // fold (and (shl/srl x), (shl/srl y)) -> (shl/srl (and x, y))
1032  if (((N0.getOpcode() == ISD::SHL && N1.getOpcode() == ISD::SHL) ||
1033       (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SRL)) &&
1034      N0.getOperand(1) == N1.getOperand(1)) {
1035    SDOperand ANDNode = DAG.getNode(ISD::AND, N0.getOperand(0).getValueType(),
1036                                    N0.getOperand(0), N1.getOperand(0));
1037    WorkList.push_back(ANDNode.Val);
1038    return DAG.getNode(N0.getOpcode(), VT, ANDNode, N0.getOperand(1));
1039  }
1040  // fold (and (sra)) -> (and (srl)) when possible.
1041  if (N0.getOpcode() == ISD::SRA && N0.Val->hasOneUse()) {
1042    if (ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1043      // If the RHS of the AND has zeros where the sign bits of the SRA will
1044      // land, turn the SRA into an SRL.
1045      if (MaskedValueIsZero(N1, (~0ULL << (OpSizeInBits-N01C->getValue())) &
1046                            (~0ULL>>(64-OpSizeInBits)), TLI)) {
1047        WorkList.push_back(N);
1048        CombineTo(N0.Val, DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
1049                                      N0.getOperand(1)));
1050        return SDOperand();
1051      }
1052    }
1053  }
1054  // fold (zext_inreg (extload x)) -> (zextload x)
1055  if (N0.getOpcode() == ISD::EXTLOAD) {
1056    MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1057    // If we zero all the possible extended bits, then we can turn this into
1058    // a zextload if we are running before legalize or the operation is legal.
1059    if (MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT), TLI) &&
1060        (!AfterLegalize || TLI.isOperationLegal(ISD::ZEXTLOAD, EVT))) {
1061      SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1062                                         N0.getOperand(1), N0.getOperand(2),
1063                                         EVT);
1064      WorkList.push_back(N);
1065      CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1066      return SDOperand();
1067    }
1068  }
1069  // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1070  if (N0.getOpcode() == ISD::SEXTLOAD && N0.hasOneUse()) {
1071    MVT::ValueType EVT = cast<VTSDNode>(N0.getOperand(3))->getVT();
1072    // If we zero all the possible extended bits, then we can turn this into
1073    // a zextload if we are running before legalize or the operation is legal.
1074    if (MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT), TLI) &&
1075        (!AfterLegalize || TLI.isOperationLegal(ISD::ZEXTLOAD, EVT))) {
1076      SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1077                                         N0.getOperand(1), N0.getOperand(2),
1078                                         EVT);
1079      WorkList.push_back(N);
1080      CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1081      return SDOperand();
1082    }
1083  }
1084  return SDOperand();
1085}
1086
1087SDOperand DAGCombiner::visitOR(SDNode *N) {
1088  SDOperand N0 = N->getOperand(0);
1089  SDOperand N1 = N->getOperand(1);
1090  SDOperand LL, LR, RL, RR, CC0, CC1;
1091  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1092  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1093  MVT::ValueType VT = N1.getValueType();
1094  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1095
1096  // fold (or c1, c2) -> c1|c2
1097  if (N0C && N1C)
1098    return DAG.getConstant(N0C->getValue() | N1C->getValue(),
1099                           N->getValueType(0));
1100  // canonicalize constant to RHS
1101  if (N0C && !N1C)
1102    return DAG.getNode(ISD::OR, VT, N1, N0);
1103  // fold (or x, 0) -> x
1104  if (N1C && N1C->isNullValue())
1105    return N0;
1106  // fold (or x, -1) -> -1
1107  if (N1C && N1C->isAllOnesValue())
1108    return N1;
1109  // fold (or x, c) -> c iff (x & ~c) == 0
1110  if (N1C && MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits)),
1111                               TLI))
1112    return N1;
1113  // fold (or (or x, c1), c2) -> (or x, c1|c2)
1114  if (N1C && N0.getOpcode() == ISD::OR) {
1115    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
1116    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1117    if (N00C)
1118      return DAG.getNode(ISD::OR, VT, N0.getOperand(1),
1119                         DAG.getConstant(N1C->getValue()|N00C->getValue(), VT));
1120    if (N01C)
1121      return DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1122                         DAG.getConstant(N1C->getValue()|N01C->getValue(), VT));
1123  } else if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1124             isa<ConstantSDNode>(N0.getOperand(1))) {
1125    // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1126    ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1127    return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1128                                                 N1),
1129                       DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1130  }
1131
1132
1133  // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1134  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1135    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1136    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1137
1138    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1139        MVT::isInteger(LL.getValueType())) {
1140      // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1141      // fold (X <  0) | (Y <  0) -> (X|Y < 0)
1142      if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1143          (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1144        SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1145        WorkList.push_back(ORNode.Val);
1146        return DAG.getSetCC(VT, ORNode, LR, Op1);
1147      }
1148      // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1149      // fold (X >  -1) | (Y >  -1) -> (X&Y >  -1)
1150      if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1151          (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1152        SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1153        WorkList.push_back(ANDNode.Val);
1154        return DAG.getSetCC(VT, ANDNode, LR, Op1);
1155      }
1156    }
1157    // canonicalize equivalent to ll == rl
1158    if (LL == RR && LR == RL) {
1159      Op1 = ISD::getSetCCSwappedOperands(Op1);
1160      std::swap(RL, RR);
1161    }
1162    if (LL == RL && LR == RR) {
1163      bool isInteger = MVT::isInteger(LL.getValueType());
1164      ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1165      if (Result != ISD::SETCC_INVALID)
1166        return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1167    }
1168  }
1169  // fold (or (zext x), (zext y)) -> (zext (or x, y))
1170  if (N0.getOpcode() == ISD::ZERO_EXTEND &&
1171      N1.getOpcode() == ISD::ZERO_EXTEND &&
1172      N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1173    SDOperand ORNode = DAG.getNode(ISD::OR, N0.getOperand(0).getValueType(),
1174                                   N0.getOperand(0), N1.getOperand(0));
1175    WorkList.push_back(ORNode.Val);
1176    return DAG.getNode(ISD::ZERO_EXTEND, VT, ORNode);
1177  }
1178  return SDOperand();
1179}
1180
1181SDOperand DAGCombiner::visitXOR(SDNode *N) {
1182  SDOperand N0 = N->getOperand(0);
1183  SDOperand N1 = N->getOperand(1);
1184  SDOperand LHS, RHS, CC;
1185  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1186  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1187  MVT::ValueType VT = N0.getValueType();
1188
1189  // fold (xor c1, c2) -> c1^c2
1190  if (N0C && N1C)
1191    return DAG.getConstant(N0C->getValue() ^ N1C->getValue(), VT);
1192  // canonicalize constant to RHS
1193  if (N0C && !N1C)
1194    return DAG.getNode(ISD::XOR, VT, N1, N0);
1195  // fold (xor x, 0) -> x
1196  if (N1C && N1C->isNullValue())
1197    return N0;
1198  // fold !(x cc y) -> (x !cc y)
1199  if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
1200    bool isInt = MVT::isInteger(LHS.getValueType());
1201    ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
1202                                               isInt);
1203    if (N0.getOpcode() == ISD::SETCC)
1204      return DAG.getSetCC(VT, LHS, RHS, NotCC);
1205    if (N0.getOpcode() == ISD::SELECT_CC)
1206      return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
1207    assert(0 && "Unhandled SetCC Equivalent!");
1208    abort();
1209  }
1210  // fold !(x or y) -> (!x and !y) iff x or y are setcc
1211  if (N1C && N1C->getValue() == 1 &&
1212      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1213    SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1214    if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
1215      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1216      LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
1217      RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
1218      WorkList.push_back(LHS.Val); WorkList.push_back(RHS.Val);
1219      return DAG.getNode(NewOpcode, VT, LHS, RHS);
1220    }
1221  }
1222  // fold !(x or y) -> (!x and !y) iff x or y are constants
1223  if (N1C && N1C->isAllOnesValue() &&
1224      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1225    SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1226    if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
1227      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1228      LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
1229      RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
1230      WorkList.push_back(LHS.Val); WorkList.push_back(RHS.Val);
1231      return DAG.getNode(NewOpcode, VT, LHS, RHS);
1232    }
1233  }
1234  // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
1235  if (N1C && N0.getOpcode() == ISD::XOR) {
1236    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
1237    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1238    if (N00C)
1239      return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
1240                         DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
1241    if (N01C)
1242      return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
1243                         DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
1244  }
1245  // fold (xor x, x) -> 0
1246  if (N0 == N1)
1247    return DAG.getConstant(0, VT);
1248  // fold (xor (zext x), (zext y)) -> (zext (xor x, y))
1249  if (N0.getOpcode() == ISD::ZERO_EXTEND &&
1250      N1.getOpcode() == ISD::ZERO_EXTEND &&
1251      N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1252    SDOperand XORNode = DAG.getNode(ISD::XOR, N0.getOperand(0).getValueType(),
1253                                   N0.getOperand(0), N1.getOperand(0));
1254    WorkList.push_back(XORNode.Val);
1255    return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
1256  }
1257  return SDOperand();
1258}
1259
1260SDOperand DAGCombiner::visitSHL(SDNode *N) {
1261  SDOperand N0 = N->getOperand(0);
1262  SDOperand N1 = N->getOperand(1);
1263  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1264  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1265  MVT::ValueType VT = N0.getValueType();
1266  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1267
1268  // fold (shl c1, c2) -> c1<<c2
1269  if (N0C && N1C)
1270    return DAG.getConstant(N0C->getValue() << N1C->getValue(), VT);
1271  // fold (shl 0, x) -> 0
1272  if (N0C && N0C->isNullValue())
1273    return N0;
1274  // fold (shl x, c >= size(x)) -> undef
1275  if (N1C && N1C->getValue() >= OpSizeInBits)
1276    return DAG.getNode(ISD::UNDEF, VT);
1277  // fold (shl x, 0) -> x
1278  if (N1C && N1C->isNullValue())
1279    return N0;
1280  // if (shl x, c) is known to be zero, return 0
1281  if (N1C && MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits),TLI))
1282    return DAG.getConstant(0, VT);
1283  // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
1284  if (N1C && N0.getOpcode() == ISD::SHL &&
1285      N0.getOperand(1).getOpcode() == ISD::Constant) {
1286    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1287    uint64_t c2 = N1C->getValue();
1288    if (c1 + c2 > OpSizeInBits)
1289      return DAG.getConstant(0, VT);
1290    return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
1291                       DAG.getConstant(c1 + c2, N1.getValueType()));
1292  }
1293  // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
1294  //                               (srl (and x, -1 << c1), c1-c2)
1295  if (N1C && N0.getOpcode() == ISD::SRL &&
1296      N0.getOperand(1).getOpcode() == ISD::Constant) {
1297    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1298    uint64_t c2 = N1C->getValue();
1299    SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1300                                 DAG.getConstant(~0ULL << c1, VT));
1301    if (c2 > c1)
1302      return DAG.getNode(ISD::SHL, VT, Mask,
1303                         DAG.getConstant(c2-c1, N1.getValueType()));
1304    else
1305      return DAG.getNode(ISD::SRL, VT, Mask,
1306                         DAG.getConstant(c1-c2, N1.getValueType()));
1307  }
1308  // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
1309  if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
1310    return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1311                       DAG.getConstant(~0ULL << N1C->getValue(), VT));
1312  return SDOperand();
1313}
1314
1315SDOperand DAGCombiner::visitSRA(SDNode *N) {
1316  SDOperand N0 = N->getOperand(0);
1317  SDOperand N1 = N->getOperand(1);
1318  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1319  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1320  MVT::ValueType VT = N0.getValueType();
1321  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1322
1323  // fold (sra c1, c2) -> c1>>c2
1324  if (N0C && N1C)
1325    return DAG.getConstant(N0C->getSignExtended() >> N1C->getValue(), VT);
1326  // fold (sra 0, x) -> 0
1327  if (N0C && N0C->isNullValue())
1328    return N0;
1329  // fold (sra -1, x) -> -1
1330  if (N0C && N0C->isAllOnesValue())
1331    return N0;
1332  // fold (sra x, c >= size(x)) -> undef
1333  if (N1C && N1C->getValue() >= OpSizeInBits)
1334    return DAG.getNode(ISD::UNDEF, VT);
1335  // fold (sra x, 0) -> x
1336  if (N1C && N1C->isNullValue())
1337    return N0;
1338  // If the sign bit is known to be zero, switch this to a SRL.
1339  if (MaskedValueIsZero(N0, (1ULL << (OpSizeInBits-1)), TLI))
1340    return DAG.getNode(ISD::SRL, VT, N0, N1);
1341  return SDOperand();
1342}
1343
1344SDOperand DAGCombiner::visitSRL(SDNode *N) {
1345  SDOperand N0 = N->getOperand(0);
1346  SDOperand N1 = N->getOperand(1);
1347  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1348  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1349  MVT::ValueType VT = N0.getValueType();
1350  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1351
1352  // fold (srl c1, c2) -> c1 >>u c2
1353  if (N0C && N1C)
1354    return DAG.getConstant(N0C->getValue() >> N1C->getValue(), VT);
1355  // fold (srl 0, x) -> 0
1356  if (N0C && N0C->isNullValue())
1357    return N0;
1358  // fold (srl x, c >= size(x)) -> undef
1359  if (N1C && N1C->getValue() >= OpSizeInBits)
1360    return DAG.getNode(ISD::UNDEF, VT);
1361  // fold (srl x, 0) -> x
1362  if (N1C && N1C->isNullValue())
1363    return N0;
1364  // if (srl x, c) is known to be zero, return 0
1365  if (N1C && MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits),TLI))
1366    return DAG.getConstant(0, VT);
1367  // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
1368  if (N1C && N0.getOpcode() == ISD::SRL &&
1369      N0.getOperand(1).getOpcode() == ISD::Constant) {
1370    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1371    uint64_t c2 = N1C->getValue();
1372    if (c1 + c2 > OpSizeInBits)
1373      return DAG.getConstant(0, VT);
1374    return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
1375                       DAG.getConstant(c1 + c2, N1.getValueType()));
1376  }
1377  return SDOperand();
1378}
1379
1380SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
1381  SDOperand N0 = N->getOperand(0);
1382  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1383
1384  // fold (ctlz c1) -> c2
1385  if (N0C)
1386    return DAG.getConstant(CountLeadingZeros_64(N0C->getValue()),
1387                           N0.getValueType());
1388  return SDOperand();
1389}
1390
1391SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
1392  SDOperand N0 = N->getOperand(0);
1393  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1394
1395  // fold (cttz c1) -> c2
1396  if (N0C)
1397    return DAG.getConstant(CountTrailingZeros_64(N0C->getValue()),
1398                           N0.getValueType());
1399  return SDOperand();
1400}
1401
1402SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
1403  SDOperand N0 = N->getOperand(0);
1404  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1405
1406  // fold (ctpop c1) -> c2
1407  if (N0C)
1408    return DAG.getConstant(CountPopulation_64(N0C->getValue()),
1409                           N0.getValueType());
1410  return SDOperand();
1411}
1412
1413SDOperand DAGCombiner::visitSELECT(SDNode *N) {
1414  SDOperand N0 = N->getOperand(0);
1415  SDOperand N1 = N->getOperand(1);
1416  SDOperand N2 = N->getOperand(2);
1417  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1418  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1419  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
1420  MVT::ValueType VT = N->getValueType(0);
1421
1422  // fold select C, X, X -> X
1423  if (N1 == N2)
1424    return N1;
1425  // fold select true, X, Y -> X
1426  if (N0C && !N0C->isNullValue())
1427    return N1;
1428  // fold select false, X, Y -> Y
1429  if (N0C && N0C->isNullValue())
1430    return N2;
1431  // fold select C, 1, X -> C | X
1432  if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
1433    return DAG.getNode(ISD::OR, VT, N0, N2);
1434  // fold select C, 0, X -> ~C & X
1435  // FIXME: this should check for C type == X type, not i1?
1436  if (MVT::i1 == VT && N1C && N1C->isNullValue()) {
1437    SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
1438    WorkList.push_back(XORNode.Val);
1439    return DAG.getNode(ISD::AND, VT, XORNode, N2);
1440  }
1441  // fold select C, X, 1 -> ~C | X
1442  if (MVT::i1 == VT && N2C && N2C->getValue() == 1) {
1443    SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
1444    WorkList.push_back(XORNode.Val);
1445    return DAG.getNode(ISD::OR, VT, XORNode, N1);
1446  }
1447  // fold select C, X, 0 -> C & X
1448  // FIXME: this should check for C type == X type, not i1?
1449  if (MVT::i1 == VT && N2C && N2C->isNullValue())
1450    return DAG.getNode(ISD::AND, VT, N0, N1);
1451  // fold  X ? X : Y --> X ? 1 : Y --> X | Y
1452  if (MVT::i1 == VT && N0 == N1)
1453    return DAG.getNode(ISD::OR, VT, N0, N2);
1454  // fold X ? Y : X --> X ? Y : 0 --> X & Y
1455  if (MVT::i1 == VT && N0 == N2)
1456    return DAG.getNode(ISD::AND, VT, N0, N1);
1457
1458  // If we can fold this based on the true/false value, do so.
1459  if (SimplifySelectOps(N, N1, N2))
1460    return SDOperand();
1461
1462  // fold selects based on a setcc into other things, such as min/max/abs
1463  if (N0.getOpcode() == ISD::SETCC)
1464    return SimplifySelect(N0, N1, N2);
1465  return SDOperand();
1466}
1467
1468SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
1469  SDOperand N0 = N->getOperand(0);
1470  SDOperand N1 = N->getOperand(1);
1471  SDOperand N2 = N->getOperand(2);
1472  SDOperand N3 = N->getOperand(3);
1473  SDOperand N4 = N->getOperand(4);
1474  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1475  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1476  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
1477  ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
1478
1479  // Determine if the condition we're dealing with is constant
1480  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
1481  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
1482
1483  // fold select_cc lhs, rhs, x, x, cc -> x
1484  if (N2 == N3)
1485    return N2;
1486
1487  // If we can fold this based on the true/false value, do so.
1488  if (SimplifySelectOps(N, N2, N3))
1489    return SDOperand();
1490
1491  // fold select_cc into other things, such as min/max/abs
1492  return SimplifySelectCC(N0, N1, N2, N3, CC);
1493}
1494
1495SDOperand DAGCombiner::visitSETCC(SDNode *N) {
1496  return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
1497                       cast<CondCodeSDNode>(N->getOperand(2))->get());
1498}
1499
1500SDOperand DAGCombiner::visitADD_PARTS(SDNode *N) {
1501  SDOperand LHSLo = N->getOperand(0);
1502  SDOperand RHSLo = N->getOperand(2);
1503  MVT::ValueType VT = LHSLo.getValueType();
1504
1505  // fold (a_Hi, 0) + (b_Hi, b_Lo) -> (b_Hi + a_Hi, b_Lo)
1506  if (MaskedValueIsZero(LHSLo, (1ULL << MVT::getSizeInBits(VT))-1, TLI)) {
1507    SDOperand Hi = DAG.getNode(ISD::ADD, VT, N->getOperand(1),
1508                               N->getOperand(3));
1509    WorkList.push_back(Hi.Val);
1510    CombineTo(N, RHSLo, Hi);
1511    return SDOperand();
1512  }
1513  // fold (a_Hi, a_Lo) + (b_Hi, 0) -> (a_Hi + b_Hi, a_Lo)
1514  if (MaskedValueIsZero(RHSLo, (1ULL << MVT::getSizeInBits(VT))-1, TLI)) {
1515    SDOperand Hi = DAG.getNode(ISD::ADD, VT, N->getOperand(1),
1516                               N->getOperand(3));
1517    WorkList.push_back(Hi.Val);
1518    CombineTo(N, LHSLo, Hi);
1519    return SDOperand();
1520  }
1521  return SDOperand();
1522}
1523
1524SDOperand DAGCombiner::visitSUB_PARTS(SDNode *N) {
1525  SDOperand LHSLo = N->getOperand(0);
1526  SDOperand RHSLo = N->getOperand(2);
1527  MVT::ValueType VT = LHSLo.getValueType();
1528
1529  // fold (a_Hi, a_Lo) - (b_Hi, 0) -> (a_Hi - b_Hi, a_Lo)
1530  if (MaskedValueIsZero(RHSLo, (1ULL << MVT::getSizeInBits(VT))-1, TLI)) {
1531    SDOperand Hi = DAG.getNode(ISD::SUB, VT, N->getOperand(1),
1532                               N->getOperand(3));
1533    WorkList.push_back(Hi.Val);
1534    CombineTo(N, LHSLo, Hi);
1535    return SDOperand();
1536  }
1537  return SDOperand();
1538}
1539
1540SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
1541  SDOperand N0 = N->getOperand(0);
1542  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1543  MVT::ValueType VT = N->getValueType(0);
1544
1545  // fold (sext c1) -> c1
1546  if (N0C)
1547    return DAG.getConstant(N0C->getSignExtended(), VT);
1548  // fold (sext (sext x)) -> (sext x)
1549  if (N0.getOpcode() == ISD::SIGN_EXTEND)
1550    return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
1551  // fold (sext (truncate x)) -> (sextinreg x) iff x size == sext size.
1552  if (N0.getOpcode() == ISD::TRUNCATE && N0.getOperand(0).getValueType() == VT&&
1553      (!AfterLegalize ||
1554       TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, N0.getValueType())))
1555    return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
1556                       DAG.getValueType(N0.getValueType()));
1557  // fold (sext (load x)) -> (sext (truncate (sextload x)))
1558  if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse() &&
1559      (!AfterLegalize||TLI.isOperationLegal(ISD::SEXTLOAD, N0.getValueType()))){
1560    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1561                                       N0.getOperand(1), N0.getOperand(2),
1562                                       N0.getValueType());
1563    CombineTo(N, ExtLoad);
1564    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1565              ExtLoad.getValue(1));
1566    return SDOperand();
1567  }
1568
1569  // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
1570  // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
1571  if ((N0.getOpcode() == ISD::SEXTLOAD || N0.getOpcode() == ISD::EXTLOAD) &&
1572      N0.hasOneUse()) {
1573    SDOperand ExtLoad = DAG.getNode(ISD::SEXTLOAD, VT, N0.getOperand(0),
1574                                    N0.getOperand(1), N0.getOperand(2),
1575                                    N0.getOperand(3));
1576    CombineTo(N, ExtLoad);
1577    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1578              ExtLoad.getValue(1));
1579    return SDOperand();
1580  }
1581
1582  return SDOperand();
1583}
1584
1585SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
1586  SDOperand N0 = N->getOperand(0);
1587  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1588  MVT::ValueType VT = N->getValueType(0);
1589
1590  // fold (zext c1) -> c1
1591  if (N0C)
1592    return DAG.getConstant(N0C->getValue(), VT);
1593  // fold (zext (zext x)) -> (zext x)
1594  if (N0.getOpcode() == ISD::ZERO_EXTEND)
1595    return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
1596  // fold (zext (truncate x)) -> (zextinreg x) iff x size == zext size.
1597  if (N0.getOpcode() == ISD::TRUNCATE && N0.getOperand(0).getValueType() == VT&&
1598      (!AfterLegalize || TLI.isOperationLegal(ISD::AND, N0.getValueType())))
1599    return DAG.getZeroExtendInReg(N0.getOperand(0), N0.getValueType());
1600  // fold (zext (load x)) -> (zext (truncate (zextload x)))
1601  if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse() &&
1602      (!AfterLegalize||TLI.isOperationLegal(ISD::ZEXTLOAD, N0.getValueType()))){
1603    SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1604                                       N0.getOperand(1), N0.getOperand(2),
1605                                       N0.getValueType());
1606    CombineTo(N, ExtLoad);
1607    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1608              ExtLoad.getValue(1));
1609    return SDOperand();
1610  }
1611
1612  // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
1613  // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
1614  if ((N0.getOpcode() == ISD::ZEXTLOAD || N0.getOpcode() == ISD::EXTLOAD) &&
1615      N0.hasOneUse()) {
1616    SDOperand ExtLoad = DAG.getNode(ISD::ZEXTLOAD, VT, N0.getOperand(0),
1617                                    N0.getOperand(1), N0.getOperand(2),
1618                                    N0.getOperand(3));
1619    CombineTo(N, ExtLoad);
1620    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
1621              ExtLoad.getValue(1));
1622    return SDOperand();
1623  }
1624  return SDOperand();
1625}
1626
1627SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
1628  SDOperand N0 = N->getOperand(0);
1629  SDOperand N1 = N->getOperand(1);
1630  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1631  MVT::ValueType VT = N->getValueType(0);
1632  MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
1633  unsigned EVTBits = MVT::getSizeInBits(EVT);
1634
1635  // fold (sext_in_reg c1) -> c1
1636  if (N0C) {
1637    SDOperand Truncate = DAG.getConstant(N0C->getValue(), EVT);
1638    return DAG.getNode(ISD::SIGN_EXTEND, VT, Truncate);
1639  }
1640  // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt1
1641  if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1642      cast<VTSDNode>(N0.getOperand(1))->getVT() <= EVT) {
1643    return N0;
1644  }
1645  // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
1646  if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1647      EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
1648    return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
1649  }
1650  // fold (sext_in_reg (assert_sext x)) -> (assert_sext x)
1651  if (N0.getOpcode() == ISD::AssertSext &&
1652      cast<VTSDNode>(N0.getOperand(1))->getVT() <= EVT) {
1653    return N0;
1654  }
1655  // fold (sext_in_reg (sextload x)) -> (sextload x)
1656  if (N0.getOpcode() == ISD::SEXTLOAD &&
1657      cast<VTSDNode>(N0.getOperand(3))->getVT() <= EVT) {
1658    return N0;
1659  }
1660  // fold (sext_in_reg (setcc x)) -> setcc x iff (setcc x) == 0 or -1
1661  if (N0.getOpcode() == ISD::SETCC &&
1662      TLI.getSetCCResultContents() ==
1663        TargetLowering::ZeroOrNegativeOneSetCCResult)
1664    return N0;
1665  // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is zero
1666  if (MaskedValueIsZero(N0, 1ULL << (EVTBits-1), TLI))
1667    return DAG.getNode(ISD::AND, N0.getValueType(), N0,
1668                       DAG.getConstant(~0ULL >> (64-EVTBits), VT));
1669  // fold (sext_in_reg (srl x)) -> sra x
1670  if (N0.getOpcode() == ISD::SRL &&
1671      N0.getOperand(1).getOpcode() == ISD::Constant &&
1672      cast<ConstantSDNode>(N0.getOperand(1))->getValue() == EVTBits) {
1673    return DAG.getNode(ISD::SRA, N0.getValueType(), N0.getOperand(0),
1674                       N0.getOperand(1));
1675  }
1676  // fold (sext_inreg (extload x)) -> (sextload x)
1677  if (N0.getOpcode() == ISD::EXTLOAD &&
1678      EVT == cast<VTSDNode>(N0.getOperand(3))->getVT() &&
1679      (!AfterLegalize || TLI.isOperationLegal(ISD::SEXTLOAD, EVT))) {
1680    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1681                                       N0.getOperand(1), N0.getOperand(2),
1682                                       EVT);
1683    CombineTo(N, ExtLoad);
1684    CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1685    return SDOperand();
1686  }
1687  // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
1688  if (N0.getOpcode() == ISD::ZEXTLOAD && N0.hasOneUse() &&
1689      EVT == cast<VTSDNode>(N0.getOperand(3))->getVT() &&
1690      (!AfterLegalize || TLI.isOperationLegal(ISD::SEXTLOAD, EVT))) {
1691    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N0.getOperand(0),
1692                                       N0.getOperand(1), N0.getOperand(2),
1693                                       EVT);
1694    CombineTo(N, ExtLoad);
1695    CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1696    return SDOperand();
1697  }
1698  return SDOperand();
1699}
1700
1701SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
1702  SDOperand N0 = N->getOperand(0);
1703  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1704  MVT::ValueType VT = N->getValueType(0);
1705
1706  // noop truncate
1707  if (N0.getValueType() == N->getValueType(0))
1708    return N0;
1709  // fold (truncate c1) -> c1
1710  if (N0C)
1711    return DAG.getConstant(N0C->getValue(), VT);
1712  // fold (truncate (truncate x)) -> (truncate x)
1713  if (N0.getOpcode() == ISD::TRUNCATE)
1714    return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
1715  // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
1716  if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND){
1717    if (N0.getValueType() < VT)
1718      // if the source is smaller than the dest, we still need an extend
1719      return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
1720    else if (N0.getValueType() > VT)
1721      // if the source is larger than the dest, than we just need the truncate
1722      return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
1723    else
1724      // if the source and dest are the same type, we can drop both the extend
1725      // and the truncate
1726      return N0.getOperand(0);
1727  }
1728  // fold (truncate (load x)) -> (smaller load x)
1729  if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse()) {
1730    assert(MVT::getSizeInBits(N0.getValueType()) > MVT::getSizeInBits(VT) &&
1731           "Cannot truncate to larger type!");
1732    MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1733    // For big endian targets, we need to add an offset to the pointer to load
1734    // the correct bytes.  For little endian systems, we merely need to read
1735    // fewer bytes from the same pointer.
1736    uint64_t PtrOff =
1737      (MVT::getSizeInBits(N0.getValueType()) - MVT::getSizeInBits(VT)) / 8;
1738    SDOperand NewPtr = TLI.isLittleEndian() ? N0.getOperand(1) :
1739      DAG.getNode(ISD::ADD, PtrType, N0.getOperand(1),
1740                  DAG.getConstant(PtrOff, PtrType));
1741    WorkList.push_back(NewPtr.Val);
1742    SDOperand Load = DAG.getLoad(VT, N0.getOperand(0), NewPtr,N0.getOperand(2));
1743    WorkList.push_back(N);
1744    CombineTo(N0.Val, Load, Load.getValue(1));
1745    return SDOperand();
1746  }
1747  return SDOperand();
1748}
1749
1750SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
1751  SDOperand N0 = N->getOperand(0);
1752  MVT::ValueType VT = N->getValueType(0);
1753
1754  // If the input is a constant, let getNode() fold it.
1755  if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
1756    SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
1757    if (Res.Val != N) return Res;
1758  }
1759
1760  if (N0.getOpcode() == ISD::BIT_CONVERT)  // conv(conv(x,t1),t2) -> conv(x,t2)
1761    return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
1762
1763  // fold (conv (load x)) -> (load (conv*)x)
1764  if (N0.getOpcode() == ISD::LOAD && N0.hasOneUse()) {
1765    SDOperand Load = DAG.getLoad(VT, N0.getOperand(0), N0.getOperand(1),
1766                                 N0.getOperand(2));
1767    WorkList.push_back(N);
1768    CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
1769              Load.getValue(1));
1770    return Load;
1771  }
1772
1773  return SDOperand();
1774}
1775
1776SDOperand DAGCombiner::visitFADD(SDNode *N) {
1777  SDOperand N0 = N->getOperand(0);
1778  SDOperand N1 = N->getOperand(1);
1779  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
1780  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
1781  MVT::ValueType VT = N->getValueType(0);
1782
1783  // fold (fadd c1, c2) -> c1+c2
1784  if (N0CFP && N1CFP)
1785    return DAG.getConstantFP(N0CFP->getValue() + N1CFP->getValue(), VT);
1786  // canonicalize constant to RHS
1787  if (N0CFP && !N1CFP)
1788    return DAG.getNode(ISD::FADD, VT, N1, N0);
1789  // fold (A + (-B)) -> A-B
1790  if (N1.getOpcode() == ISD::FNEG)
1791    return DAG.getNode(ISD::FSUB, VT, N0, N1.getOperand(0));
1792  // fold ((-A) + B) -> B-A
1793  if (N0.getOpcode() == ISD::FNEG)
1794    return DAG.getNode(ISD::FSUB, VT, N1, N0.getOperand(0));
1795  return SDOperand();
1796}
1797
1798SDOperand DAGCombiner::visitFSUB(SDNode *N) {
1799  SDOperand N0 = N->getOperand(0);
1800  SDOperand N1 = N->getOperand(1);
1801  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
1802  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
1803  MVT::ValueType VT = N->getValueType(0);
1804
1805  // fold (fsub c1, c2) -> c1-c2
1806  if (N0CFP && N1CFP)
1807    return DAG.getConstantFP(N0CFP->getValue() - N1CFP->getValue(), VT);
1808  // fold (A-(-B)) -> A+B
1809  if (N1.getOpcode() == ISD::FNEG)
1810    return DAG.getNode(ISD::FADD, N0.getValueType(), N0, N1.getOperand(0));
1811  return SDOperand();
1812}
1813
1814SDOperand DAGCombiner::visitFMUL(SDNode *N) {
1815  SDOperand N0 = N->getOperand(0);
1816  SDOperand N1 = N->getOperand(1);
1817  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
1818  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
1819  MVT::ValueType VT = N->getValueType(0);
1820
1821  // fold (fmul c1, c2) -> c1*c2
1822  if (N0CFP && N1CFP)
1823    return DAG.getConstantFP(N0CFP->getValue() * N1CFP->getValue(), VT);
1824  // canonicalize constant to RHS
1825  if (N0CFP && !N1CFP)
1826    return DAG.getNode(ISD::FMUL, VT, N1, N0);
1827  // fold (fmul X, 2.0) -> (fadd X, X)
1828  if (N1CFP && N1CFP->isExactlyValue(+2.0))
1829    return DAG.getNode(ISD::FADD, VT, N0, N0);
1830  return SDOperand();
1831}
1832
1833SDOperand DAGCombiner::visitFDIV(SDNode *N) {
1834  SDOperand N0 = N->getOperand(0);
1835  SDOperand N1 = N->getOperand(1);
1836  MVT::ValueType VT = N->getValueType(0);
1837
1838  if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0))
1839    if (ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1)) {
1840      // fold floating point (fdiv c1, c2)
1841      return DAG.getConstantFP(N0CFP->getValue() / N1CFP->getValue(), VT);
1842    }
1843  return SDOperand();
1844}
1845
1846SDOperand DAGCombiner::visitFREM(SDNode *N) {
1847  SDOperand N0 = N->getOperand(0);
1848  SDOperand N1 = N->getOperand(1);
1849  MVT::ValueType VT = N->getValueType(0);
1850
1851  if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0))
1852    if (ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1)) {
1853      // fold floating point (frem c1, c2) -> fmod(c1, c2)
1854      return DAG.getConstantFP(fmod(N0CFP->getValue(),N1CFP->getValue()), VT);
1855    }
1856  return SDOperand();
1857}
1858
1859
1860SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
1861  SDOperand N0 = N->getOperand(0);
1862  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1863
1864  // fold (sint_to_fp c1) -> c1fp
1865  if (N0C)
1866    return DAG.getConstantFP(N0C->getSignExtended(), N->getValueType(0));
1867  return SDOperand();
1868}
1869
1870SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
1871  SDOperand N0 = N->getOperand(0);
1872  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1873
1874  // fold (uint_to_fp c1) -> c1fp
1875  if (N0C)
1876    return DAG.getConstantFP(N0C->getValue(), N->getValueType(0));
1877  return SDOperand();
1878}
1879
1880SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
1881  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
1882
1883  // fold (fp_to_sint c1fp) -> c1
1884  if (N0CFP)
1885    return DAG.getConstant((int64_t)N0CFP->getValue(), N->getValueType(0));
1886  return SDOperand();
1887}
1888
1889SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
1890  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
1891
1892  // fold (fp_to_uint c1fp) -> c1
1893  if (N0CFP)
1894    return DAG.getConstant((uint64_t)N0CFP->getValue(), N->getValueType(0));
1895  return SDOperand();
1896}
1897
1898SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
1899  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
1900
1901  // fold (fp_round c1fp) -> c1fp
1902  if (N0CFP)
1903    return DAG.getConstantFP(N0CFP->getValue(), N->getValueType(0));
1904  return SDOperand();
1905}
1906
1907SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
1908  SDOperand N0 = N->getOperand(0);
1909  MVT::ValueType VT = N->getValueType(0);
1910  MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1911  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
1912
1913  // fold (fp_round_inreg c1fp) -> c1fp
1914  if (N0CFP) {
1915    SDOperand Round = DAG.getConstantFP(N0CFP->getValue(), EVT);
1916    return DAG.getNode(ISD::FP_EXTEND, VT, Round);
1917  }
1918  return SDOperand();
1919}
1920
1921SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
1922  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
1923
1924  // fold (fp_extend c1fp) -> c1fp
1925  if (N0CFP)
1926    return DAG.getConstantFP(N0CFP->getValue(), N->getValueType(0));
1927  return SDOperand();
1928}
1929
1930SDOperand DAGCombiner::visitFNEG(SDNode *N) {
1931  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
1932  // fold (neg c1) -> -c1
1933  if (N0CFP)
1934    return DAG.getConstantFP(-N0CFP->getValue(), N->getValueType(0));
1935  // fold (neg (sub x, y)) -> (sub y, x)
1936  if (N->getOperand(0).getOpcode() == ISD::SUB)
1937    return DAG.getNode(ISD::SUB, N->getValueType(0), N->getOperand(1),
1938                       N->getOperand(0));
1939  // fold (neg (neg x)) -> x
1940  if (N->getOperand(0).getOpcode() == ISD::FNEG)
1941    return N->getOperand(0).getOperand(0);
1942  return SDOperand();
1943}
1944
1945SDOperand DAGCombiner::visitFABS(SDNode *N) {
1946  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
1947  // fold (fabs c1) -> fabs(c1)
1948  if (N0CFP)
1949    return DAG.getConstantFP(fabs(N0CFP->getValue()), N->getValueType(0));
1950  // fold (fabs (fabs x)) -> (fabs x)
1951  if (N->getOperand(0).getOpcode() == ISD::FABS)
1952    return N->getOperand(0);
1953  // fold (fabs (fneg x)) -> (fabs x)
1954  if (N->getOperand(0).getOpcode() == ISD::FNEG)
1955    return DAG.getNode(ISD::FABS, N->getValueType(0),
1956                       N->getOperand(0).getOperand(0));
1957  return SDOperand();
1958}
1959
1960SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
1961  SDOperand Chain = N->getOperand(0);
1962  SDOperand N1 = N->getOperand(1);
1963  SDOperand N2 = N->getOperand(2);
1964  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1965
1966  // never taken branch, fold to chain
1967  if (N1C && N1C->isNullValue())
1968    return Chain;
1969  // unconditional branch
1970  if (N1C && N1C->getValue() == 1)
1971    return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
1972  return SDOperand();
1973}
1974
1975SDOperand DAGCombiner::visitBRCONDTWOWAY(SDNode *N) {
1976  SDOperand Chain = N->getOperand(0);
1977  SDOperand N1 = N->getOperand(1);
1978  SDOperand N2 = N->getOperand(2);
1979  SDOperand N3 = N->getOperand(3);
1980  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1981
1982  // unconditional branch to true mbb
1983  if (N1C && N1C->getValue() == 1)
1984    return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
1985  // unconditional branch to false mbb
1986  if (N1C && N1C->isNullValue())
1987    return DAG.getNode(ISD::BR, MVT::Other, Chain, N3);
1988  return SDOperand();
1989}
1990
1991// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
1992//
1993SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
1994  CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
1995  SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
1996
1997  // Use SimplifySetCC  to simplify SETCC's.
1998  SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
1999  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
2000
2001  // fold br_cc true, dest -> br dest (unconditional branch)
2002  if (SCCC && SCCC->getValue())
2003    return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
2004                       N->getOperand(4));
2005  // fold br_cc false, dest -> unconditional fall through
2006  if (SCCC && SCCC->isNullValue())
2007    return N->getOperand(0);
2008  // fold to a simpler setcc
2009  if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
2010    return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
2011                       Simp.getOperand(2), Simp.getOperand(0),
2012                       Simp.getOperand(1), N->getOperand(4));
2013  return SDOperand();
2014}
2015
2016SDOperand DAGCombiner::visitBRTWOWAY_CC(SDNode *N) {
2017  SDOperand Chain = N->getOperand(0);
2018  SDOperand CCN = N->getOperand(1);
2019  SDOperand LHS = N->getOperand(2);
2020  SDOperand RHS = N->getOperand(3);
2021  SDOperand N4 = N->getOperand(4);
2022  SDOperand N5 = N->getOperand(5);
2023
2024  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), LHS, RHS,
2025                                cast<CondCodeSDNode>(CCN)->get(), false);
2026  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
2027
2028  // fold select_cc lhs, rhs, x, x, cc -> x
2029  if (N4 == N5)
2030    return DAG.getNode(ISD::BR, MVT::Other, Chain, N4);
2031  // fold select_cc true, x, y -> x
2032  if (SCCC && SCCC->getValue())
2033    return DAG.getNode(ISD::BR, MVT::Other, Chain, N4);
2034  // fold select_cc false, x, y -> y
2035  if (SCCC && SCCC->isNullValue())
2036    return DAG.getNode(ISD::BR, MVT::Other, Chain, N5);
2037  // fold to a simpler setcc
2038  if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2039    return DAG.getBR2Way_CC(Chain, SCC.getOperand(2), SCC.getOperand(0),
2040                            SCC.getOperand(1), N4, N5);
2041  return SDOperand();
2042}
2043
2044SDOperand DAGCombiner::visitLOAD(SDNode *N) {
2045  SDOperand Chain    = N->getOperand(0);
2046  SDOperand Ptr      = N->getOperand(1);
2047  SDOperand SrcValue = N->getOperand(2);
2048
2049  // If this load is directly stored, replace the load value with the stored
2050  // value.
2051  // TODO: Handle store large -> read small portion.
2052  // TODO: Handle TRUNCSTORE/EXTLOAD
2053  if (Chain.getOpcode() == ISD::STORE && Chain.getOperand(2) == Ptr &&
2054      Chain.getOperand(1).getValueType() == N->getValueType(0))
2055    return CombineTo(N, Chain.getOperand(1), Chain);
2056
2057  return SDOperand();
2058}
2059
2060SDOperand DAGCombiner::visitSTORE(SDNode *N) {
2061  SDOperand Chain    = N->getOperand(0);
2062  SDOperand Value    = N->getOperand(1);
2063  SDOperand Ptr      = N->getOperand(2);
2064  SDOperand SrcValue = N->getOperand(3);
2065
2066  // If this is a store that kills a previous store, remove the previous store.
2067  if (Chain.getOpcode() == ISD::STORE && Chain.getOperand(2) == Ptr &&
2068      Chain.Val->hasOneUse() /* Avoid introducing DAG cycles */ &&
2069      // Make sure that these stores are the same value type:
2070      // FIXME: we really care that the second store is >= size of the first.
2071      Value.getValueType() == Chain.getOperand(1).getValueType()) {
2072    // Create a new store of Value that replaces both stores.
2073    SDNode *PrevStore = Chain.Val;
2074    if (PrevStore->getOperand(1) == Value) // Same value multiply stored.
2075      return Chain;
2076    SDOperand NewStore = DAG.getNode(ISD::STORE, MVT::Other,
2077                                     PrevStore->getOperand(0), Value, Ptr,
2078                                     SrcValue);
2079    CombineTo(N, NewStore);                 // Nuke this store.
2080    CombineTo(PrevStore, NewStore);  // Nuke the previous store.
2081    return SDOperand(N, 0);
2082  }
2083
2084  // If this is a store of a bit convert, store the input value.
2085  if (Value.getOpcode() == ISD::BIT_CONVERT)
2086    return DAG.getNode(ISD::STORE, MVT::Other, Chain, Value.getOperand(0),
2087                       Ptr, SrcValue);
2088
2089  return SDOperand();
2090}
2091
2092SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
2093  assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
2094
2095  SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
2096                                 cast<CondCodeSDNode>(N0.getOperand(2))->get());
2097  // If we got a simplified select_cc node back from SimplifySelectCC, then
2098  // break it down into a new SETCC node, and a new SELECT node, and then return
2099  // the SELECT node, since we were called with a SELECT node.
2100  if (SCC.Val) {
2101    // Check to see if we got a select_cc back (to turn into setcc/select).
2102    // Otherwise, just return whatever node we got back, like fabs.
2103    if (SCC.getOpcode() == ISD::SELECT_CC) {
2104      SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
2105                                    SCC.getOperand(0), SCC.getOperand(1),
2106                                    SCC.getOperand(4));
2107      WorkList.push_back(SETCC.Val);
2108      return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
2109                         SCC.getOperand(3), SETCC);
2110    }
2111    return SCC;
2112  }
2113  return SDOperand();
2114}
2115
2116/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
2117/// are the two values being selected between, see if we can simplify the
2118/// select.
2119///
2120bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
2121                                    SDOperand RHS) {
2122
2123  // If this is a select from two identical things, try to pull the operation
2124  // through the select.
2125  if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
2126#if 0
2127    std::cerr << "SELECT: ["; LHS.Val->dump();
2128    std::cerr << "] ["; RHS.Val->dump();
2129    std::cerr << "]\n";
2130#endif
2131
2132    // If this is a load and the token chain is identical, replace the select
2133    // of two loads with a load through a select of the address to load from.
2134    // This triggers in things like "select bool X, 10.0, 123.0" after the FP
2135    // constants have been dropped into the constant pool.
2136    if ((LHS.getOpcode() == ISD::LOAD ||
2137         LHS.getOpcode() == ISD::EXTLOAD ||
2138         LHS.getOpcode() == ISD::ZEXTLOAD ||
2139         LHS.getOpcode() == ISD::SEXTLOAD) &&
2140        // Token chains must be identical.
2141        LHS.getOperand(0) == RHS.getOperand(0) &&
2142        // If this is an EXTLOAD, the VT's must match.
2143        (LHS.getOpcode() == ISD::LOAD ||
2144         LHS.getOperand(3) == RHS.getOperand(3))) {
2145      // FIXME: this conflates two src values, discarding one.  This is not
2146      // the right thing to do, but nothing uses srcvalues now.  When they do,
2147      // turn SrcValue into a list of locations.
2148      SDOperand Addr;
2149      if (TheSelect->getOpcode() == ISD::SELECT)
2150        Addr = DAG.getNode(ISD::SELECT, LHS.getOperand(1).getValueType(),
2151                           TheSelect->getOperand(0), LHS.getOperand(1),
2152                           RHS.getOperand(1));
2153      else
2154        Addr = DAG.getNode(ISD::SELECT_CC, LHS.getOperand(1).getValueType(),
2155                           TheSelect->getOperand(0),
2156                           TheSelect->getOperand(1),
2157                           LHS.getOperand(1), RHS.getOperand(1),
2158                           TheSelect->getOperand(4));
2159
2160      SDOperand Load;
2161      if (LHS.getOpcode() == ISD::LOAD)
2162        Load = DAG.getLoad(TheSelect->getValueType(0), LHS.getOperand(0),
2163                           Addr, LHS.getOperand(2));
2164      else
2165        Load = DAG.getExtLoad(LHS.getOpcode(), TheSelect->getValueType(0),
2166                              LHS.getOperand(0), Addr, LHS.getOperand(2),
2167                              cast<VTSDNode>(LHS.getOperand(3))->getVT());
2168      // Users of the select now use the result of the load.
2169      CombineTo(TheSelect, Load);
2170
2171      // Users of the old loads now use the new load's chain.  We know the
2172      // old-load value is dead now.
2173      CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
2174      CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
2175      return true;
2176    }
2177  }
2178
2179  return false;
2180}
2181
2182SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
2183                                        SDOperand N2, SDOperand N3,
2184                                        ISD::CondCode CC) {
2185
2186  MVT::ValueType VT = N2.getValueType();
2187  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
2188  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2189  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2190  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
2191
2192  // Determine if the condition we're dealing with is constant
2193  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
2194  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
2195
2196  // fold select_cc true, x, y -> x
2197  if (SCCC && SCCC->getValue())
2198    return N2;
2199  // fold select_cc false, x, y -> y
2200  if (SCCC && SCCC->getValue() == 0)
2201    return N3;
2202
2203  // Check to see if we can simplify the select into an fabs node
2204  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
2205    // Allow either -0.0 or 0.0
2206    if (CFP->getValue() == 0.0) {
2207      // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
2208      if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
2209          N0 == N2 && N3.getOpcode() == ISD::FNEG &&
2210          N2 == N3.getOperand(0))
2211        return DAG.getNode(ISD::FABS, VT, N0);
2212
2213      // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
2214      if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
2215          N0 == N3 && N2.getOpcode() == ISD::FNEG &&
2216          N2.getOperand(0) == N3)
2217        return DAG.getNode(ISD::FABS, VT, N3);
2218    }
2219  }
2220
2221  // Check to see if we can perform the "gzip trick", transforming
2222  // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
2223  if (N1C && N1C->isNullValue() && N3C && N3C->isNullValue() &&
2224      MVT::isInteger(N0.getValueType()) &&
2225      MVT::isInteger(N2.getValueType()) && CC == ISD::SETLT) {
2226    MVT::ValueType XType = N0.getValueType();
2227    MVT::ValueType AType = N2.getValueType();
2228    if (XType >= AType) {
2229      // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
2230      // single-bit constant.
2231      if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
2232        unsigned ShCtV = Log2_64(N2C->getValue());
2233        ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
2234        SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
2235        SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
2236        WorkList.push_back(Shift.Val);
2237        if (XType > AType) {
2238          Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
2239          WorkList.push_back(Shift.Val);
2240        }
2241        return DAG.getNode(ISD::AND, AType, Shift, N2);
2242      }
2243      SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
2244                                    DAG.getConstant(MVT::getSizeInBits(XType)-1,
2245                                                    TLI.getShiftAmountTy()));
2246      WorkList.push_back(Shift.Val);
2247      if (XType > AType) {
2248        Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
2249        WorkList.push_back(Shift.Val);
2250      }
2251      return DAG.getNode(ISD::AND, AType, Shift, N2);
2252    }
2253  }
2254
2255  // fold select C, 16, 0 -> shl C, 4
2256  if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
2257      TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
2258    // Get a SetCC of the condition
2259    // FIXME: Should probably make sure that setcc is legal if we ever have a
2260    // target where it isn't.
2261    SDOperand Temp, SCC = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
2262    WorkList.push_back(SCC.Val);
2263    // cast from setcc result type to select result type
2264    if (AfterLegalize)
2265      Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
2266    else
2267      Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
2268    WorkList.push_back(Temp.Val);
2269    // shl setcc result by log2 n2c
2270    return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
2271                       DAG.getConstant(Log2_64(N2C->getValue()),
2272                                       TLI.getShiftAmountTy()));
2273  }
2274
2275  // Check to see if this is the equivalent of setcc
2276  // FIXME: Turn all of these into setcc if setcc if setcc is legal
2277  // otherwise, go ahead with the folds.
2278  if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
2279    MVT::ValueType XType = N0.getValueType();
2280    if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
2281      SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
2282      if (Res.getValueType() != VT)
2283        Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
2284      return Res;
2285    }
2286
2287    // seteq X, 0 -> srl (ctlz X, log2(size(X)))
2288    if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
2289        TLI.isOperationLegal(ISD::CTLZ, XType)) {
2290      SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
2291      return DAG.getNode(ISD::SRL, XType, Ctlz,
2292                         DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
2293                                         TLI.getShiftAmountTy()));
2294    }
2295    // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
2296    if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
2297      SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
2298                                    N0);
2299      SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
2300                                    DAG.getConstant(~0ULL, XType));
2301      return DAG.getNode(ISD::SRL, XType,
2302                         DAG.getNode(ISD::AND, XType, NegN0, NotN0),
2303                         DAG.getConstant(MVT::getSizeInBits(XType)-1,
2304                                         TLI.getShiftAmountTy()));
2305    }
2306    // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
2307    if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
2308      SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
2309                                   DAG.getConstant(MVT::getSizeInBits(XType)-1,
2310                                                   TLI.getShiftAmountTy()));
2311      return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
2312    }
2313  }
2314
2315  // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
2316  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
2317  if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
2318      N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) {
2319    if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0))) {
2320      MVT::ValueType XType = N0.getValueType();
2321      if (SubC->isNullValue() && MVT::isInteger(XType)) {
2322        SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
2323                                    DAG.getConstant(MVT::getSizeInBits(XType)-1,
2324                                                    TLI.getShiftAmountTy()));
2325        SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
2326        WorkList.push_back(Shift.Val);
2327        WorkList.push_back(Add.Val);
2328        return DAG.getNode(ISD::XOR, XType, Add, Shift);
2329      }
2330    }
2331  }
2332
2333  return SDOperand();
2334}
2335
2336SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
2337                                     SDOperand N1, ISD::CondCode Cond,
2338                                     bool foldBooleans) {
2339  // These setcc operations always fold.
2340  switch (Cond) {
2341  default: break;
2342  case ISD::SETFALSE:
2343  case ISD::SETFALSE2: return DAG.getConstant(0, VT);
2344  case ISD::SETTRUE:
2345  case ISD::SETTRUE2:  return DAG.getConstant(1, VT);
2346  }
2347
2348  if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
2349    uint64_t C1 = N1C->getValue();
2350    if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val)) {
2351      uint64_t C0 = N0C->getValue();
2352
2353      // Sign extend the operands if required
2354      if (ISD::isSignedIntSetCC(Cond)) {
2355        C0 = N0C->getSignExtended();
2356        C1 = N1C->getSignExtended();
2357      }
2358
2359      switch (Cond) {
2360      default: assert(0 && "Unknown integer setcc!");
2361      case ISD::SETEQ:  return DAG.getConstant(C0 == C1, VT);
2362      case ISD::SETNE:  return DAG.getConstant(C0 != C1, VT);
2363      case ISD::SETULT: return DAG.getConstant(C0 <  C1, VT);
2364      case ISD::SETUGT: return DAG.getConstant(C0 >  C1, VT);
2365      case ISD::SETULE: return DAG.getConstant(C0 <= C1, VT);
2366      case ISD::SETUGE: return DAG.getConstant(C0 >= C1, VT);
2367      case ISD::SETLT:  return DAG.getConstant((int64_t)C0 <  (int64_t)C1, VT);
2368      case ISD::SETGT:  return DAG.getConstant((int64_t)C0 >  (int64_t)C1, VT);
2369      case ISD::SETLE:  return DAG.getConstant((int64_t)C0 <= (int64_t)C1, VT);
2370      case ISD::SETGE:  return DAG.getConstant((int64_t)C0 >= (int64_t)C1, VT);
2371      }
2372    } else {
2373      // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
2374      if (N0.getOpcode() == ISD::ZERO_EXTEND) {
2375        unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
2376
2377        // If the comparison constant has bits in the upper part, the
2378        // zero-extended value could never match.
2379        if (C1 & (~0ULL << InSize)) {
2380          unsigned VSize = MVT::getSizeInBits(N0.getValueType());
2381          switch (Cond) {
2382          case ISD::SETUGT:
2383          case ISD::SETUGE:
2384          case ISD::SETEQ: return DAG.getConstant(0, VT);
2385          case ISD::SETULT:
2386          case ISD::SETULE:
2387          case ISD::SETNE: return DAG.getConstant(1, VT);
2388          case ISD::SETGT:
2389          case ISD::SETGE:
2390            // True if the sign bit of C1 is set.
2391            return DAG.getConstant((C1 & (1ULL << VSize)) != 0, VT);
2392          case ISD::SETLT:
2393          case ISD::SETLE:
2394            // True if the sign bit of C1 isn't set.
2395            return DAG.getConstant((C1 & (1ULL << VSize)) == 0, VT);
2396          default:
2397            break;
2398          }
2399        }
2400
2401        // Otherwise, we can perform the comparison with the low bits.
2402        switch (Cond) {
2403        case ISD::SETEQ:
2404        case ISD::SETNE:
2405        case ISD::SETUGT:
2406        case ISD::SETUGE:
2407        case ISD::SETULT:
2408        case ISD::SETULE:
2409          return DAG.getSetCC(VT, N0.getOperand(0),
2410                          DAG.getConstant(C1, N0.getOperand(0).getValueType()),
2411                          Cond);
2412        default:
2413          break;   // todo, be more careful with signed comparisons
2414        }
2415      } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2416                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2417        MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
2418        unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
2419        MVT::ValueType ExtDstTy = N0.getValueType();
2420        unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
2421
2422        // If the extended part has any inconsistent bits, it cannot ever
2423        // compare equal.  In other words, they have to be all ones or all
2424        // zeros.
2425        uint64_t ExtBits =
2426          (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
2427        if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
2428          return DAG.getConstant(Cond == ISD::SETNE, VT);
2429
2430        SDOperand ZextOp;
2431        MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
2432        if (Op0Ty == ExtSrcTy) {
2433          ZextOp = N0.getOperand(0);
2434        } else {
2435          int64_t Imm = ~0ULL >> (64-ExtSrcTyBits);
2436          ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
2437                               DAG.getConstant(Imm, Op0Ty));
2438        }
2439        WorkList.push_back(ZextOp.Val);
2440        // Otherwise, make this a use of a zext.
2441        return DAG.getSetCC(VT, ZextOp,
2442                            DAG.getConstant(C1 & (~0ULL>>(64-ExtSrcTyBits)),
2443                                            ExtDstTy),
2444                            Cond);
2445      }
2446
2447      uint64_t MinVal, MaxVal;
2448      unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
2449      if (ISD::isSignedIntSetCC(Cond)) {
2450        MinVal = 1ULL << (OperandBitSize-1);
2451        if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
2452          MaxVal = ~0ULL >> (65-OperandBitSize);
2453        else
2454          MaxVal = 0;
2455      } else {
2456        MinVal = 0;
2457        MaxVal = ~0ULL >> (64-OperandBitSize);
2458      }
2459
2460      // Canonicalize GE/LE comparisons to use GT/LT comparisons.
2461      if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
2462        if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
2463        --C1;                                          // X >= C0 --> X > (C0-1)
2464        return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
2465                        (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
2466      }
2467
2468      if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
2469        if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
2470        ++C1;                                          // X <= C0 --> X < (C0+1)
2471        return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
2472                        (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
2473      }
2474
2475      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
2476        return DAG.getConstant(0, VT);      // X < MIN --> false
2477
2478      // Canonicalize setgt X, Min --> setne X, Min
2479      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
2480        return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
2481      // Canonicalize setlt X, Max --> setne X, Max
2482      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
2483        return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
2484
2485      // If we have setult X, 1, turn it into seteq X, 0
2486      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
2487        return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
2488                        ISD::SETEQ);
2489      // If we have setugt X, Max-1, turn it into seteq X, Max
2490      else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
2491        return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
2492                        ISD::SETEQ);
2493
2494      // If we have "setcc X, C0", check to see if we can shrink the immediate
2495      // by changing cc.
2496
2497      // SETUGT X, SINTMAX  -> SETLT X, 0
2498      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
2499          C1 == (~0ULL >> (65-OperandBitSize)))
2500        return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
2501                            ISD::SETLT);
2502
2503      // FIXME: Implement the rest of these.
2504
2505      // Fold bit comparisons when we can.
2506      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2507          VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
2508        if (ConstantSDNode *AndRHS =
2509                    dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2510          if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
2511            // Perform the xform if the AND RHS is a single bit.
2512            if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
2513              return DAG.getNode(ISD::SRL, VT, N0,
2514                             DAG.getConstant(Log2_64(AndRHS->getValue()),
2515                                                   TLI.getShiftAmountTy()));
2516            }
2517          } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
2518            // (X & 8) == 8  -->  (X & 8) >> 3
2519            // Perform the xform if C1 is a single bit.
2520            if ((C1 & (C1-1)) == 0) {
2521              return DAG.getNode(ISD::SRL, VT, N0,
2522                             DAG.getConstant(Log2_64(C1),TLI.getShiftAmountTy()));
2523            }
2524          }
2525        }
2526    }
2527  } else if (isa<ConstantSDNode>(N0.Val)) {
2528      // Ensure that the constant occurs on the RHS.
2529    return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
2530  }
2531
2532  if (ConstantFPSDNode *N0C = dyn_cast<ConstantFPSDNode>(N0.Val))
2533    if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
2534      double C0 = N0C->getValue(), C1 = N1C->getValue();
2535
2536      switch (Cond) {
2537      default: break; // FIXME: Implement the rest of these!
2538      case ISD::SETEQ:  return DAG.getConstant(C0 == C1, VT);
2539      case ISD::SETNE:  return DAG.getConstant(C0 != C1, VT);
2540      case ISD::SETLT:  return DAG.getConstant(C0 < C1, VT);
2541      case ISD::SETGT:  return DAG.getConstant(C0 > C1, VT);
2542      case ISD::SETLE:  return DAG.getConstant(C0 <= C1, VT);
2543      case ISD::SETGE:  return DAG.getConstant(C0 >= C1, VT);
2544      }
2545    } else {
2546      // Ensure that the constant occurs on the RHS.
2547      return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
2548    }
2549
2550  if (N0 == N1) {
2551    // We can always fold X == Y for integer setcc's.
2552    if (MVT::isInteger(N0.getValueType()))
2553      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
2554    unsigned UOF = ISD::getUnorderedFlavor(Cond);
2555    if (UOF == 2)   // FP operators that are undefined on NaNs.
2556      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
2557    if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
2558      return DAG.getConstant(UOF, VT);
2559    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
2560    // if it is not already.
2561    ISD::CondCode NewCond = UOF == 0 ? ISD::SETUO : ISD::SETO;
2562    if (NewCond != Cond)
2563      return DAG.getSetCC(VT, N0, N1, NewCond);
2564  }
2565
2566  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2567      MVT::isInteger(N0.getValueType())) {
2568    if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2569        N0.getOpcode() == ISD::XOR) {
2570      // Simplify (X+Y) == (X+Z) -->  Y == Z
2571      if (N0.getOpcode() == N1.getOpcode()) {
2572        if (N0.getOperand(0) == N1.getOperand(0))
2573          return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
2574        if (N0.getOperand(1) == N1.getOperand(1))
2575          return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
2576        if (isCommutativeBinOp(N0.getOpcode())) {
2577          // If X op Y == Y op X, try other combinations.
2578          if (N0.getOperand(0) == N1.getOperand(1))
2579            return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
2580          if (N0.getOperand(1) == N1.getOperand(0))
2581            return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
2582        }
2583      }
2584
2585      // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.  Common for condcodes.
2586      if (N0.getOpcode() == ISD::XOR)
2587        if (ConstantSDNode *XORC = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2588          if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2589            // If we know that all of the inverted bits are zero, don't bother
2590            // performing the inversion.
2591            if (MaskedValueIsZero(N0.getOperand(0), ~XORC->getValue(), TLI))
2592              return DAG.getSetCC(VT, N0.getOperand(0),
2593                              DAG.getConstant(XORC->getValue()^RHSC->getValue(),
2594                                              N0.getValueType()), Cond);
2595          }
2596
2597      // Simplify (X+Z) == X -->  Z == 0
2598      if (N0.getOperand(0) == N1)
2599        return DAG.getSetCC(VT, N0.getOperand(1),
2600                        DAG.getConstant(0, N0.getValueType()), Cond);
2601      if (N0.getOperand(1) == N1) {
2602        if (isCommutativeBinOp(N0.getOpcode()))
2603          return DAG.getSetCC(VT, N0.getOperand(0),
2604                          DAG.getConstant(0, N0.getValueType()), Cond);
2605        else {
2606          assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2607          // (Z-X) == X  --> Z == X<<1
2608          SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
2609                                     N1,
2610                                     DAG.getConstant(1,TLI.getShiftAmountTy()));
2611          WorkList.push_back(SH.Val);
2612          return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
2613        }
2614      }
2615    }
2616
2617    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2618        N1.getOpcode() == ISD::XOR) {
2619      // Simplify  X == (X+Z) -->  Z == 0
2620      if (N1.getOperand(0) == N0) {
2621        return DAG.getSetCC(VT, N1.getOperand(1),
2622                        DAG.getConstant(0, N1.getValueType()), Cond);
2623      } else if (N1.getOperand(1) == N0) {
2624        if (isCommutativeBinOp(N1.getOpcode())) {
2625          return DAG.getSetCC(VT, N1.getOperand(0),
2626                          DAG.getConstant(0, N1.getValueType()), Cond);
2627        } else {
2628          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2629          // X == (Z-X)  --> X<<1 == Z
2630          SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0,
2631                                     DAG.getConstant(1,TLI.getShiftAmountTy()));
2632          WorkList.push_back(SH.Val);
2633          return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
2634        }
2635      }
2636    }
2637  }
2638
2639  // Fold away ALL boolean setcc's.
2640  SDOperand Temp;
2641  if (N0.getValueType() == MVT::i1 && foldBooleans) {
2642    switch (Cond) {
2643    default: assert(0 && "Unknown integer setcc!");
2644    case ISD::SETEQ:  // X == Y  -> (X^Y)^1
2645      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
2646      N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
2647      WorkList.push_back(Temp.Val);
2648      break;
2649    case ISD::SETNE:  // X != Y   -->  (X^Y)
2650      N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
2651      break;
2652    case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
2653    case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
2654      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
2655      N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
2656      WorkList.push_back(Temp.Val);
2657      break;
2658    case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
2659    case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
2660      Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
2661      N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
2662      WorkList.push_back(Temp.Val);
2663      break;
2664    case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
2665    case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
2666      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
2667      N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
2668      WorkList.push_back(Temp.Val);
2669      break;
2670    case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
2671    case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
2672      Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
2673      N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
2674      break;
2675    }
2676    if (VT != MVT::i1) {
2677      WorkList.push_back(N0.Val);
2678      // FIXME: If running after legalize, we probably can't do this.
2679      N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2680    }
2681    return N0;
2682  }
2683
2684  // Could not fold it.
2685  return SDOperand();
2686}
2687
2688/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
2689/// return a DAG expression to select that will generate the same value by
2690/// multiplying by a magic number.  See:
2691/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2692SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
2693  MVT::ValueType VT = N->getValueType(0);
2694
2695  // Check to see if we can do this.
2696  if (!TLI.isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
2697    return SDOperand();       // BuildSDIV only operates on i32 or i64
2698  if (!TLI.isOperationLegal(ISD::MULHS, VT))
2699    return SDOperand();       // Make sure the target supports MULHS.
2700
2701  int64_t d = cast<ConstantSDNode>(N->getOperand(1))->getSignExtended();
2702  ms magics = (VT == MVT::i32) ? magic32(d) : magic64(d);
2703
2704  // Multiply the numerator (operand 0) by the magic value
2705  SDOperand Q = DAG.getNode(ISD::MULHS, VT, N->getOperand(0),
2706                            DAG.getConstant(magics.m, VT));
2707  // If d > 0 and m < 0, add the numerator
2708  if (d > 0 && magics.m < 0) {
2709    Q = DAG.getNode(ISD::ADD, VT, Q, N->getOperand(0));
2710    WorkList.push_back(Q.Val);
2711  }
2712  // If d < 0 and m > 0, subtract the numerator.
2713  if (d < 0 && magics.m > 0) {
2714    Q = DAG.getNode(ISD::SUB, VT, Q, N->getOperand(0));
2715    WorkList.push_back(Q.Val);
2716  }
2717  // Shift right algebraic if shift value is nonzero
2718  if (magics.s > 0) {
2719    Q = DAG.getNode(ISD::SRA, VT, Q,
2720                    DAG.getConstant(magics.s, TLI.getShiftAmountTy()));
2721    WorkList.push_back(Q.Val);
2722  }
2723  // Extract the sign bit and add it to the quotient
2724  SDOperand T =
2725    DAG.getNode(ISD::SRL, VT, Q, DAG.getConstant(MVT::getSizeInBits(VT)-1,
2726                                                 TLI.getShiftAmountTy()));
2727  WorkList.push_back(T.Val);
2728  return DAG.getNode(ISD::ADD, VT, Q, T);
2729}
2730
2731/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
2732/// return a DAG expression to select that will generate the same value by
2733/// multiplying by a magic number.  See:
2734/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2735SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
2736  MVT::ValueType VT = N->getValueType(0);
2737
2738  // Check to see if we can do this.
2739  if (!TLI.isTypeLegal(VT) || (VT != MVT::i32 && VT != MVT::i64))
2740    return SDOperand();       // BuildUDIV only operates on i32 or i64
2741  if (!TLI.isOperationLegal(ISD::MULHU, VT))
2742    return SDOperand();       // Make sure the target supports MULHU.
2743
2744  uint64_t d = cast<ConstantSDNode>(N->getOperand(1))->getValue();
2745  mu magics = (VT == MVT::i32) ? magicu32(d) : magicu64(d);
2746
2747  // Multiply the numerator (operand 0) by the magic value
2748  SDOperand Q = DAG.getNode(ISD::MULHU, VT, N->getOperand(0),
2749                            DAG.getConstant(magics.m, VT));
2750  WorkList.push_back(Q.Val);
2751
2752  if (magics.a == 0) {
2753    return DAG.getNode(ISD::SRL, VT, Q,
2754                       DAG.getConstant(magics.s, TLI.getShiftAmountTy()));
2755  } else {
2756    SDOperand NPQ = DAG.getNode(ISD::SUB, VT, N->getOperand(0), Q);
2757    WorkList.push_back(NPQ.Val);
2758    NPQ = DAG.getNode(ISD::SRL, VT, NPQ,
2759                      DAG.getConstant(1, TLI.getShiftAmountTy()));
2760    WorkList.push_back(NPQ.Val);
2761    NPQ = DAG.getNode(ISD::ADD, VT, NPQ, Q);
2762    WorkList.push_back(NPQ.Val);
2763    return DAG.getNode(ISD::SRL, VT, NPQ,
2764                       DAG.getConstant(magics.s-1, TLI.getShiftAmountTy()));
2765  }
2766}
2767
2768// SelectionDAG::Combine - This is the entry point for the file.
2769//
2770void SelectionDAG::Combine(bool RunningAfterLegalize) {
2771  /// run - This is the main entry point to this class.
2772  ///
2773  DAGCombiner(*this).Run(RunningAfterLegalize);
2774}
2775