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