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