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