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