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