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