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