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