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