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