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