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