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