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