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