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