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