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