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