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