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