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