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