Added DAG combiner transformation to generate pre-indexed loads.
[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 was developed by Nate Begeman and is distributed under the
6 // University of Illinois Open Source 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 // FIXME: Missing folds
14 // sdiv, udiv, srem, urem (X, const) where X is an integer can be expanded into
15 //  a sequence of multiplies, shifts, and adds.  This should be controlled by
16 //  some kind of hint from the target that int div is expensive.
17 // various folds of mulh[s,u] by constants such as -1, powers of 2, etc.
18 //
19 // FIXME: select C, pow2, pow2 -> something smart
20 // FIXME: trunc(select X, Y, Z) -> select X, trunc(Y), trunc(Z)
21 // FIXME: Dead stores -> nuke
22 // FIXME: shr X, (and Y,31) -> shr X, Y   (TRICKY!)
23 // FIXME: mul (x, const) -> shifts + adds
24 // FIXME: undef values
25 // FIXME: divide by zero is currently left unfolded.  do we want to turn this
26 //        into an undef?
27 // FIXME: select ne (select cc, 1, 0), 0, true, false -> select cc, true, false
28 // 
29 //===----------------------------------------------------------------------===//
30
31 #define DEBUG_TYPE "dagcombine"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Analysis/AliasAnalysis.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/CommandLine.h"
40 #include <algorithm>
41 #include <cmath>
42 #include <iostream>
43 #include <algorithm>
44 using namespace llvm;
45
46 namespace {
47   static Statistic<> NodesCombined ("dagcombiner", 
48                                     "Number of dag nodes combined");
49             
50   static cl::opt<bool>
51     CombinerAA("combiner-alias-analysis", cl::Hidden,
52                cl::desc("Turn on alias analysis during testing"));
53
54   static cl::opt<bool>
55     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
56                cl::desc("Include global information in alias analysis"));
57
58 //------------------------------ DAGCombiner ---------------------------------//
59
60   class VISIBILITY_HIDDEN DAGCombiner {
61     SelectionDAG &DAG;
62     TargetLowering &TLI;
63     bool AfterLegalize;
64
65     // Worklist of all of the nodes that need to be simplified.
66     std::vector<SDNode*> WorkList;
67
68     // AA - Used for DAG load/store alias analysis.
69     AliasAnalysis &AA;
70
71     /// AddUsersToWorkList - When an instruction is simplified, add all users of
72     /// the instruction to the work lists because they might get more simplified
73     /// now.
74     ///
75     void AddUsersToWorkList(SDNode *N) {
76       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
77            UI != UE; ++UI)
78         AddToWorkList(*UI);
79     }
80
81     /// removeFromWorkList - remove all instances of N from the worklist.
82     ///
83     void removeFromWorkList(SDNode *N) {
84       WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
85                      WorkList.end());
86     }
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     SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
97                         bool AddTo = true) {
98       assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
99       ++NodesCombined;
100       DEBUG(std::cerr << "\nReplacing.1 "; N->dump();
101             std::cerr << "\nWith: "; To[0].Val->dump(&DAG);
102             std::cerr << " and " << NumTo-1 << " other values\n");
103       std::vector<SDNode*> NowDead;
104       DAG.ReplaceAllUsesWith(N, To, &NowDead);
105       
106       if (AddTo) {
107         // Push the new nodes and any users onto the worklist
108         for (unsigned i = 0, e = NumTo; i != e; ++i) {
109           AddToWorkList(To[i].Val);
110           AddUsersToWorkList(To[i].Val);
111         }
112       }
113       
114       // Nodes can be reintroduced into the worklist.  Make sure we do not
115       // process a node that has been replaced.
116       removeFromWorkList(N);
117       for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
118         removeFromWorkList(NowDead[i]);
119       
120       // Finally, since the node is now dead, remove it from the graph.
121       DAG.DeleteNode(N);
122       return SDOperand(N, 0);
123     }
124     
125     SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
126       return CombineTo(N, &Res, 1, AddTo);
127     }
128     
129     SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
130                         bool AddTo = true) {
131       SDOperand To[] = { Res0, Res1 };
132       return CombineTo(N, To, 2, AddTo);
133     }
134   private:    
135     
136     /// SimplifyDemandedBits - Check the specified integer node value to see if
137     /// it can be simplified or if things it uses can be simplified by bit
138     /// propagation.  If so, return true.
139     bool SimplifyDemandedBits(SDOperand Op) {
140       TargetLowering::TargetLoweringOpt TLO(DAG);
141       uint64_t KnownZero, KnownOne;
142       uint64_t Demanded = MVT::getIntVTBitMask(Op.getValueType());
143       if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
144         return false;
145
146       // Revisit the node.
147       AddToWorkList(Op.Val);
148       
149       // Replace the old value with the new one.
150       ++NodesCombined;
151       DEBUG(std::cerr << "\nReplacing.2 "; TLO.Old.Val->dump();
152             std::cerr << "\nWith: "; TLO.New.Val->dump(&DAG);
153             std::cerr << '\n');
154
155       std::vector<SDNode*> NowDead;
156       DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, NowDead);
157       
158       // Push the new node and any (possibly new) users onto the worklist.
159       AddToWorkList(TLO.New.Val);
160       AddUsersToWorkList(TLO.New.Val);
161       
162       // Nodes can end up on the worklist more than once.  Make sure we do
163       // not process a node that has been replaced.
164       for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
165         removeFromWorkList(NowDead[i]);
166       
167       // Finally, if the node is now dead, remove it from the graph.  The node
168       // may not be dead if the replacement process recursively simplified to
169       // something else needing this node.
170       if (TLO.Old.Val->use_empty()) {
171         removeFromWorkList(TLO.Old.Val);
172         DAG.DeleteNode(TLO.Old.Val);
173       }
174       return true;
175     }
176
177     bool CombineToIndexedLoadStore(SDNode *N) {
178       SDOperand Ptr;
179       bool isLoad = true;
180       if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
181         Ptr = LD->getBasePtr();
182       } else
183         return false;
184
185       if (AfterLegalize &&
186           (Ptr.getOpcode() == ISD::ADD || Ptr.getOpcode() == ISD::SUB) &&
187           Ptr.Val->use_size() > 1) {
188         SDOperand BasePtr;
189         SDOperand Offset;
190         ISD::MemOpAddrMode AM = ISD::UNINDEXED;
191         if (TLI.getLegalPreIndexedAddressBase(N, BasePtr, Offset, AM, DAG)) {
192           // Try turning it into a pre-indexed load / store except when
193           // 1) Another use of base ptr is a predecessor of N. If ptr is folded
194           //    that would create a cycle.
195           // 2) All uses are load / store ops that use it as base ptr and offset
196           //    is just an addressing mode immediate.
197           // 3) If the would-be new base may not to be dead at N. FIXME: The
198           //    proper check is too expensive (in turns of compile time) to 
199           //    check. Just make sure other uses of the new base are not also
200           //    themselves use of loads / stores.
201
202           bool OffIsAMImm = Offset.getOpcode() == ISD::Constant &&
203             TLI.isLegalAddressImmediate(cast<ConstantSDNode>(Offset)->getValue());
204
205           // Check for #3.
206           if (OffIsAMImm && BasePtr.Val->use_size() > 1) {
207             for (SDNode::use_iterator I = BasePtr.Val->use_begin(),
208                    E = BasePtr.Val->use_end(); I != E; ++I) {
209               SDNode *Use = *I;
210               if (Use == Ptr.Val)
211                 continue;
212               if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB) {
213                 for (SDNode::use_iterator II = Use->use_begin(),
214                        EE = Use->use_end(); II != EE; ++II) {
215                   SDNode *UseUse = *II;
216                   if (UseUse->getOpcode() == ISD::LOAD &&
217                       cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use)
218                     return false;
219                   else if (UseUse->getOpcode() == ISD::STORE &&
220                            cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)
221                     return false;
222                 }
223               }
224             }
225           }
226
227           // Now check for #1 and #2.
228           unsigned NumRealUses = 0;
229           for (SDNode::use_iterator I = Ptr.Val->use_begin(),
230                  E = Ptr.Val->use_end(); I != E; ++I) {
231             SDNode *Use = *I;
232             if (Use == N)
233               continue;
234             if (Use->isPredecessor(N))
235               return false;
236
237             if (!OffIsAMImm)
238               NumRealUses++;
239             // FIXME: Do we need a target hook here
240             else if (Use->getOpcode() == ISD::LOAD) {
241               if (cast<LoadSDNode>(Use)->getBasePtr().Val != Ptr.Val)
242                 NumRealUses++;
243             } else if (Use->getOpcode() == ISD::STORE) {
244               if (cast<StoreSDNode>(Use)->getBasePtr().Val != Ptr.Val)
245                 NumRealUses++;
246             } else
247               NumRealUses++;
248           }
249           if (NumRealUses == 0)
250             return false;
251
252           SDOperand Result =
253             DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
254           ++NodesCombined;
255           DEBUG(std::cerr << "\nReplacing.4 "; N->dump();
256                 std::cerr << "\nWith: "; Result.Val->dump(&DAG);
257                 std::cerr << '\n');
258           std::vector<SDNode*> NowDead;
259           DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
260                                         NowDead);
261           DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
262                                         NowDead);
263
264           // Nodes can end up on the worklist more than once.  Make sure we do
265           // not process a node that has been replaced.
266           for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
267             removeFromWorkList(NowDead[i]);
268           // Finally, since the node is now dead, remove it from the graph.
269           DAG.DeleteNode(N);
270
271           // Replace the uses of Ptr with uses of the updated base value.
272           DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(1), NowDead);
273           removeFromWorkList(Ptr.Val);
274           for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
275             removeFromWorkList(NowDead[i]);
276           DAG.DeleteNode(Ptr.Val);
277
278           return true;
279         }
280       }
281
282       return false;
283     }
284
285     /// visit - call the node-specific routine that knows how to fold each
286     /// particular type of node.
287     SDOperand visit(SDNode *N);
288
289     // Visitation implementation - Implement dag node combining for different
290     // node types.  The semantics are as follows:
291     // Return Value:
292     //   SDOperand.Val == 0   - No change was made
293     //   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
294     //   otherwise            - N should be replaced by the returned Operand.
295     //
296     SDOperand visitTokenFactor(SDNode *N);
297     SDOperand visitADD(SDNode *N);
298     SDOperand visitSUB(SDNode *N);
299     SDOperand visitMUL(SDNode *N);
300     SDOperand visitSDIV(SDNode *N);
301     SDOperand visitUDIV(SDNode *N);
302     SDOperand visitSREM(SDNode *N);
303     SDOperand visitUREM(SDNode *N);
304     SDOperand visitMULHU(SDNode *N);
305     SDOperand visitMULHS(SDNode *N);
306     SDOperand visitAND(SDNode *N);
307     SDOperand visitOR(SDNode *N);
308     SDOperand visitXOR(SDNode *N);
309     SDOperand visitVBinOp(SDNode *N, ISD::NodeType IntOp, ISD::NodeType FPOp);
310     SDOperand visitSHL(SDNode *N);
311     SDOperand visitSRA(SDNode *N);
312     SDOperand visitSRL(SDNode *N);
313     SDOperand visitCTLZ(SDNode *N);
314     SDOperand visitCTTZ(SDNode *N);
315     SDOperand visitCTPOP(SDNode *N);
316     SDOperand visitSELECT(SDNode *N);
317     SDOperand visitSELECT_CC(SDNode *N);
318     SDOperand visitSETCC(SDNode *N);
319     SDOperand visitSIGN_EXTEND(SDNode *N);
320     SDOperand visitZERO_EXTEND(SDNode *N);
321     SDOperand visitANY_EXTEND(SDNode *N);
322     SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
323     SDOperand visitTRUNCATE(SDNode *N);
324     SDOperand visitBIT_CONVERT(SDNode *N);
325     SDOperand visitVBIT_CONVERT(SDNode *N);
326     SDOperand visitFADD(SDNode *N);
327     SDOperand visitFSUB(SDNode *N);
328     SDOperand visitFMUL(SDNode *N);
329     SDOperand visitFDIV(SDNode *N);
330     SDOperand visitFREM(SDNode *N);
331     SDOperand visitFCOPYSIGN(SDNode *N);
332     SDOperand visitSINT_TO_FP(SDNode *N);
333     SDOperand visitUINT_TO_FP(SDNode *N);
334     SDOperand visitFP_TO_SINT(SDNode *N);
335     SDOperand visitFP_TO_UINT(SDNode *N);
336     SDOperand visitFP_ROUND(SDNode *N);
337     SDOperand visitFP_ROUND_INREG(SDNode *N);
338     SDOperand visitFP_EXTEND(SDNode *N);
339     SDOperand visitFNEG(SDNode *N);
340     SDOperand visitFABS(SDNode *N);
341     SDOperand visitBRCOND(SDNode *N);
342     SDOperand visitBR_CC(SDNode *N);
343     SDOperand visitLOAD(SDNode *N);
344     SDOperand visitSTORE(SDNode *N);
345     SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
346     SDOperand visitVINSERT_VECTOR_ELT(SDNode *N);
347     SDOperand visitVBUILD_VECTOR(SDNode *N);
348     SDOperand visitVECTOR_SHUFFLE(SDNode *N);
349     SDOperand visitVVECTOR_SHUFFLE(SDNode *N);
350
351     SDOperand XformToShuffleWithZero(SDNode *N);
352     SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
353     
354     bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
355     SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
356     SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
357     SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2, 
358                                SDOperand N3, ISD::CondCode CC);
359     SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
360                             ISD::CondCode Cond, bool foldBooleans = true);
361     SDOperand ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(SDNode *, MVT::ValueType);
362     SDOperand BuildSDIV(SDNode *N);
363     SDOperand BuildUDIV(SDNode *N);
364     SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
365     
366     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
367     /// looking for aliasing nodes and adding them to the Aliases vector.
368     void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
369                           SmallVector<SDOperand, 8> &Aliases);
370
371     /// isAlias - Return true if there is any possibility that the two addresses
372     /// overlap.
373     bool isAlias(SDOperand Ptr1, int64_t Size1,
374                  const Value *SrcValue1, int SrcValueOffset1,
375                  SDOperand Ptr2, int64_t Size2,
376                  const Value *SrcValue2, int SrcValueOffset1);
377                  
378     /// FindAliasInfo - Extracts the relevant alias information from the memory
379     /// node.  Returns true if the operand was a load.
380     bool FindAliasInfo(SDNode *N,
381                        SDOperand &Ptr, int64_t &Size,
382                        const Value *&SrcValue, int &SrcValueOffset);
383                        
384     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
385     /// looking for a better chain (aliasing node.)
386     SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
387     
388 public:
389     DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
390       : DAG(D),
391         TLI(D.getTargetLoweringInfo()),
392         AfterLegalize(false),
393         AA(A) {}
394     
395     /// Run - runs the dag combiner on all nodes in the work list
396     void Run(bool RunningAfterLegalize); 
397   };
398 }
399
400 //===----------------------------------------------------------------------===//
401 //  TargetLowering::DAGCombinerInfo implementation
402 //===----------------------------------------------------------------------===//
403
404 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
405   ((DAGCombiner*)DC)->AddToWorkList(N);
406 }
407
408 SDOperand TargetLowering::DAGCombinerInfo::
409 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
410   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
411 }
412
413 SDOperand TargetLowering::DAGCombinerInfo::
414 CombineTo(SDNode *N, SDOperand Res) {
415   return ((DAGCombiner*)DC)->CombineTo(N, Res);
416 }
417
418
419 SDOperand TargetLowering::DAGCombinerInfo::
420 CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
421   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
422 }
423
424
425
426
427 //===----------------------------------------------------------------------===//
428
429
430 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
431 // that selects between the values 1 and 0, making it equivalent to a setcc.
432 // Also, set the incoming LHS, RHS, and CC references to the appropriate 
433 // nodes based on the type of node we are checking.  This simplifies life a
434 // bit for the callers.
435 static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
436                               SDOperand &CC) {
437   if (N.getOpcode() == ISD::SETCC) {
438     LHS = N.getOperand(0);
439     RHS = N.getOperand(1);
440     CC  = N.getOperand(2);
441     return true;
442   }
443   if (N.getOpcode() == ISD::SELECT_CC && 
444       N.getOperand(2).getOpcode() == ISD::Constant &&
445       N.getOperand(3).getOpcode() == ISD::Constant &&
446       cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
447       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
448     LHS = N.getOperand(0);
449     RHS = N.getOperand(1);
450     CC  = N.getOperand(4);
451     return true;
452   }
453   return false;
454 }
455
456 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
457 // one use.  If this is true, it allows the users to invert the operation for
458 // free when it is profitable to do so.
459 static bool isOneUseSetCC(SDOperand N) {
460   SDOperand N0, N1, N2;
461   if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
462     return true;
463   return false;
464 }
465
466 SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
467   MVT::ValueType VT = N0.getValueType();
468   // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
469   // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
470   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
471     if (isa<ConstantSDNode>(N1)) {
472       SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
473       AddToWorkList(OpNode.Val);
474       return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
475     } else if (N0.hasOneUse()) {
476       SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
477       AddToWorkList(OpNode.Val);
478       return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
479     }
480   }
481   // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
482   // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
483   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
484     if (isa<ConstantSDNode>(N0)) {
485       SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
486       AddToWorkList(OpNode.Val);
487       return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
488     } else if (N1.hasOneUse()) {
489       SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
490       AddToWorkList(OpNode.Val);
491       return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
492     }
493   }
494   return SDOperand();
495 }
496
497 void DAGCombiner::Run(bool RunningAfterLegalize) {
498   // set the instance variable, so that the various visit routines may use it.
499   AfterLegalize = RunningAfterLegalize;
500
501   // Add all the dag nodes to the worklist.
502   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
503        E = DAG.allnodes_end(); I != E; ++I)
504     WorkList.push_back(I);
505   
506   // Create a dummy node (which is not added to allnodes), that adds a reference
507   // to the root node, preventing it from being deleted, and tracking any
508   // changes of the root.
509   HandleSDNode Dummy(DAG.getRoot());
510   
511   // The root of the dag may dangle to deleted nodes until the dag combiner is
512   // done.  Set it to null to avoid confusion.
513   DAG.setRoot(SDOperand());
514   
515   /// DagCombineInfo - Expose the DAG combiner to the target combiner impls.
516   TargetLowering::DAGCombinerInfo 
517     DagCombineInfo(DAG, !RunningAfterLegalize, this);
518
519   // while the worklist isn't empty, inspect the node on the end of it and
520   // try and combine it.
521   while (!WorkList.empty()) {
522     SDNode *N = WorkList.back();
523     WorkList.pop_back();
524     
525     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
526     // N is deleted from the DAG, since they too may now be dead or may have a
527     // reduced number of uses, allowing other xforms.
528     if (N->use_empty() && N != &Dummy) {
529       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
530         AddToWorkList(N->getOperand(i).Val);
531       
532       DAG.DeleteNode(N);
533       continue;
534     }
535     
536     SDOperand RV = visit(N);
537     
538     // If nothing happened, try a target-specific DAG combine.
539     if (RV.Val == 0) {
540       assert(N->getOpcode() != ISD::DELETED_NODE &&
541              "Node was deleted but visit returned NULL!");
542       if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
543           TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode()))
544         RV = TLI.PerformDAGCombine(N, DagCombineInfo);
545     }
546     
547     if (RV.Val) {
548       ++NodesCombined;
549       // If we get back the same node we passed in, rather than a new node or
550       // zero, we know that the node must have defined multiple values and
551       // CombineTo was used.  Since CombineTo takes care of the worklist 
552       // mechanics for us, we have no work to do in this case.
553       if (RV.Val != N) {
554         assert(N->getOpcode() != ISD::DELETED_NODE &&
555                RV.Val->getOpcode() != ISD::DELETED_NODE &&
556                "Node was deleted but visit returned new node!");
557
558         DEBUG(std::cerr << "\nReplacing.3 "; N->dump();
559               std::cerr << "\nWith: "; RV.Val->dump(&DAG);
560               std::cerr << '\n');
561         std::vector<SDNode*> NowDead;
562         if (N->getNumValues() == RV.Val->getNumValues())
563           DAG.ReplaceAllUsesWith(N, RV.Val, &NowDead);
564         else {
565           assert(N->getValueType(0) == RV.getValueType() && "Type mismatch");
566           SDOperand OpV = RV;
567           DAG.ReplaceAllUsesWith(N, &OpV, &NowDead);
568         }
569           
570         // Push the new node and any users onto the worklist
571         AddToWorkList(RV.Val);
572         AddUsersToWorkList(RV.Val);
573           
574         // Nodes can be reintroduced into the worklist.  Make sure we do not
575         // process a node that has been replaced.
576         removeFromWorkList(N);
577         for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
578           removeFromWorkList(NowDead[i]);
579         
580         // Finally, since the node is now dead, remove it from the graph.
581         DAG.DeleteNode(N);
582       }
583     }
584   }
585   
586   // If the root changed (e.g. it was a dead load, update the root).
587   DAG.setRoot(Dummy.getValue());
588 }
589
590 SDOperand DAGCombiner::visit(SDNode *N) {
591   switch(N->getOpcode()) {
592   default: break;
593   case ISD::TokenFactor:        return visitTokenFactor(N);
594   case ISD::ADD:                return visitADD(N);
595   case ISD::SUB:                return visitSUB(N);
596   case ISD::MUL:                return visitMUL(N);
597   case ISD::SDIV:               return visitSDIV(N);
598   case ISD::UDIV:               return visitUDIV(N);
599   case ISD::SREM:               return visitSREM(N);
600   case ISD::UREM:               return visitUREM(N);
601   case ISD::MULHU:              return visitMULHU(N);
602   case ISD::MULHS:              return visitMULHS(N);
603   case ISD::AND:                return visitAND(N);
604   case ISD::OR:                 return visitOR(N);
605   case ISD::XOR:                return visitXOR(N);
606   case ISD::SHL:                return visitSHL(N);
607   case ISD::SRA:                return visitSRA(N);
608   case ISD::SRL:                return visitSRL(N);
609   case ISD::CTLZ:               return visitCTLZ(N);
610   case ISD::CTTZ:               return visitCTTZ(N);
611   case ISD::CTPOP:              return visitCTPOP(N);
612   case ISD::SELECT:             return visitSELECT(N);
613   case ISD::SELECT_CC:          return visitSELECT_CC(N);
614   case ISD::SETCC:              return visitSETCC(N);
615   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
616   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
617   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
618   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
619   case ISD::TRUNCATE:           return visitTRUNCATE(N);
620   case ISD::BIT_CONVERT:        return visitBIT_CONVERT(N);
621   case ISD::VBIT_CONVERT:       return visitVBIT_CONVERT(N);
622   case ISD::FADD:               return visitFADD(N);
623   case ISD::FSUB:               return visitFSUB(N);
624   case ISD::FMUL:               return visitFMUL(N);
625   case ISD::FDIV:               return visitFDIV(N);
626   case ISD::FREM:               return visitFREM(N);
627   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
628   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
629   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
630   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
631   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
632   case ISD::FP_ROUND:           return visitFP_ROUND(N);
633   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
634   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
635   case ISD::FNEG:               return visitFNEG(N);
636   case ISD::FABS:               return visitFABS(N);
637   case ISD::BRCOND:             return visitBRCOND(N);
638   case ISD::BR_CC:              return visitBR_CC(N);
639   case ISD::LOAD:               return visitLOAD(N);
640   case ISD::STORE:              return visitSTORE(N);
641   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
642   case ISD::VINSERT_VECTOR_ELT: return visitVINSERT_VECTOR_ELT(N);
643   case ISD::VBUILD_VECTOR:      return visitVBUILD_VECTOR(N);
644   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
645   case ISD::VVECTOR_SHUFFLE:    return visitVVECTOR_SHUFFLE(N);
646   case ISD::VADD:               return visitVBinOp(N, ISD::ADD , ISD::FADD);
647   case ISD::VSUB:               return visitVBinOp(N, ISD::SUB , ISD::FSUB);
648   case ISD::VMUL:               return visitVBinOp(N, ISD::MUL , ISD::FMUL);
649   case ISD::VSDIV:              return visitVBinOp(N, ISD::SDIV, ISD::FDIV);
650   case ISD::VUDIV:              return visitVBinOp(N, ISD::UDIV, ISD::UDIV);
651   case ISD::VAND:               return visitVBinOp(N, ISD::AND , ISD::AND);
652   case ISD::VOR:                return visitVBinOp(N, ISD::OR  , ISD::OR);
653   case ISD::VXOR:               return visitVBinOp(N, ISD::XOR , ISD::XOR);
654   }
655   return SDOperand();
656 }
657
658 /// getInputChainForNode - Given a node, return its input chain if it has one,
659 /// otherwise return a null sd operand.
660 static SDOperand getInputChainForNode(SDNode *N) {
661   if (unsigned NumOps = N->getNumOperands()) {
662     if (N->getOperand(0).getValueType() == MVT::Other)
663       return N->getOperand(0);
664     else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
665       return N->getOperand(NumOps-1);
666     for (unsigned i = 1; i < NumOps-1; ++i)
667       if (N->getOperand(i).getValueType() == MVT::Other)
668         return N->getOperand(i);
669   }
670   return SDOperand(0, 0);
671 }
672
673 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
674   // If N has two operands, where one has an input chain equal to the other,
675   // the 'other' chain is redundant.
676   if (N->getNumOperands() == 2) {
677     if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
678       return N->getOperand(0);
679     if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
680       return N->getOperand(1);
681   }
682   
683   
684   SmallVector<SDNode *, 8> TFs;   // List of token factors to visit.
685   SmallVector<SDOperand, 8> Ops;  // Ops for replacing token factor.
686   bool Changed = false;           // If we should replace this token factor.
687   
688   // Start out with this token factor.
689   TFs.push_back(N);
690   
691   // Iterate through token factors.  The TFs grows when new token factors are
692   // encountered.
693   for (unsigned i = 0; i < TFs.size(); ++i) {
694     SDNode *TF = TFs[i];
695     
696     // Check each of the operands.
697     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
698       SDOperand Op = TF->getOperand(i);
699       
700       switch (Op.getOpcode()) {
701       case ISD::EntryToken:
702         // Entry tokens don't need to be added to the list. They are
703         // rededundant.
704         Changed = true;
705         break;
706         
707       case ISD::TokenFactor:
708         if ((CombinerAA || Op.hasOneUse()) &&
709             std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
710           // Queue up for processing.
711           TFs.push_back(Op.Val);
712           // Clean up in case the token factor is removed.
713           AddToWorkList(Op.Val);
714           Changed = true;
715           break;
716         }
717         // Fall thru
718         
719       default:
720         // Only add if not there prior.
721         if (std::find(Ops.begin(), Ops.end(), Op) == Ops.end())
722           Ops.push_back(Op);
723         break;
724       }
725     }
726   }
727
728   SDOperand Result;
729
730   // If we've change things around then replace token factor.
731   if (Changed) {
732     if (Ops.size() == 0) {
733       // The entry token is the only possible outcome.
734       Result = DAG.getEntryNode();
735     } else {
736       // New and improved token factor.
737       Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
738     }
739     
740     // Don't add users to work list.
741     return CombineTo(N, Result, false);
742   }
743   
744   return Result;
745 }
746
747 SDOperand DAGCombiner::visitADD(SDNode *N) {
748   SDOperand N0 = N->getOperand(0);
749   SDOperand N1 = N->getOperand(1);
750   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
751   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
752   MVT::ValueType VT = N0.getValueType();
753   
754   // fold (add c1, c2) -> c1+c2
755   if (N0C && N1C)
756     return DAG.getNode(ISD::ADD, VT, N0, N1);
757   // canonicalize constant to RHS
758   if (N0C && !N1C)
759     return DAG.getNode(ISD::ADD, VT, N1, N0);
760   // fold (add x, 0) -> x
761   if (N1C && N1C->isNullValue())
762     return N0;
763   // fold ((c1-A)+c2) -> (c1+c2)-A
764   if (N1C && N0.getOpcode() == ISD::SUB)
765     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
766       return DAG.getNode(ISD::SUB, VT,
767                          DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
768                          N0.getOperand(1));
769   // reassociate add
770   SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
771   if (RADD.Val != 0)
772     return RADD;
773   // fold ((0-A) + B) -> B-A
774   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
775       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
776     return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
777   // fold (A + (0-B)) -> A-B
778   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
779       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
780     return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
781   // fold (A+(B-A)) -> B
782   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
783     return N1.getOperand(0);
784
785   if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
786     return SDOperand(N, 0);
787   
788   // fold (a+b) -> (a|b) iff a and b share no bits.
789   if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
790     uint64_t LHSZero, LHSOne;
791     uint64_t RHSZero, RHSOne;
792     uint64_t Mask = MVT::getIntVTBitMask(VT);
793     TLI.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
794     if (LHSZero) {
795       TLI.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
796       
797       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
798       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
799       if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
800           (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
801         return DAG.getNode(ISD::OR, VT, N0, N1);
802     }
803   }
804   
805   return SDOperand();
806 }
807
808 SDOperand DAGCombiner::visitSUB(SDNode *N) {
809   SDOperand N0 = N->getOperand(0);
810   SDOperand N1 = N->getOperand(1);
811   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
812   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
813   MVT::ValueType VT = N0.getValueType();
814   
815   // fold (sub x, x) -> 0
816   if (N0 == N1)
817     return DAG.getConstant(0, N->getValueType(0));
818   // fold (sub c1, c2) -> c1-c2
819   if (N0C && N1C)
820     return DAG.getNode(ISD::SUB, VT, N0, N1);
821   // fold (sub x, c) -> (add x, -c)
822   if (N1C)
823     return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
824   // fold (A+B)-A -> B
825   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
826     return N0.getOperand(1);
827   // fold (A+B)-B -> A
828   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
829     return N0.getOperand(0);
830   return SDOperand();
831 }
832
833 SDOperand DAGCombiner::visitMUL(SDNode *N) {
834   SDOperand N0 = N->getOperand(0);
835   SDOperand N1 = N->getOperand(1);
836   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
837   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
838   MVT::ValueType VT = N0.getValueType();
839   
840   // fold (mul c1, c2) -> c1*c2
841   if (N0C && N1C)
842     return DAG.getNode(ISD::MUL, VT, N0, N1);
843   // canonicalize constant to RHS
844   if (N0C && !N1C)
845     return DAG.getNode(ISD::MUL, VT, N1, N0);
846   // fold (mul x, 0) -> 0
847   if (N1C && N1C->isNullValue())
848     return N1;
849   // fold (mul x, -1) -> 0-x
850   if (N1C && N1C->isAllOnesValue())
851     return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
852   // fold (mul x, (1 << c)) -> x << c
853   if (N1C && isPowerOf2_64(N1C->getValue()))
854     return DAG.getNode(ISD::SHL, VT, N0,
855                        DAG.getConstant(Log2_64(N1C->getValue()),
856                                        TLI.getShiftAmountTy()));
857   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
858   if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
859     // FIXME: If the input is something that is easily negated (e.g. a 
860     // single-use add), we should put the negate there.
861     return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
862                        DAG.getNode(ISD::SHL, VT, N0,
863                             DAG.getConstant(Log2_64(-N1C->getSignExtended()),
864                                             TLI.getShiftAmountTy())));
865   }
866
867   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
868   if (N1C && N0.getOpcode() == ISD::SHL && 
869       isa<ConstantSDNode>(N0.getOperand(1))) {
870     SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
871     AddToWorkList(C3.Val);
872     return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
873   }
874   
875   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
876   // use.
877   {
878     SDOperand Sh(0,0), Y(0,0);
879     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
880     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
881         N0.Val->hasOneUse()) {
882       Sh = N0; Y = N1;
883     } else if (N1.getOpcode() == ISD::SHL && 
884                isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
885       Sh = N1; Y = N0;
886     }
887     if (Sh.Val) {
888       SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
889       return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
890     }
891   }
892   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
893   if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() && 
894       isa<ConstantSDNode>(N0.getOperand(1))) {
895     return DAG.getNode(ISD::ADD, VT, 
896                        DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
897                        DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
898   }
899   
900   // reassociate mul
901   SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
902   if (RMUL.Val != 0)
903     return RMUL;
904   return SDOperand();
905 }
906
907 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
908   SDOperand N0 = N->getOperand(0);
909   SDOperand N1 = N->getOperand(1);
910   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
911   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
912   MVT::ValueType VT = N->getValueType(0);
913
914   // fold (sdiv c1, c2) -> c1/c2
915   if (N0C && N1C && !N1C->isNullValue())
916     return DAG.getNode(ISD::SDIV, VT, N0, N1);
917   // fold (sdiv X, 1) -> X
918   if (N1C && N1C->getSignExtended() == 1LL)
919     return N0;
920   // fold (sdiv X, -1) -> 0-X
921   if (N1C && N1C->isAllOnesValue())
922     return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
923   // If we know the sign bits of both operands are zero, strength reduce to a
924   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
925   uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
926   if (TLI.MaskedValueIsZero(N1, SignBit) &&
927       TLI.MaskedValueIsZero(N0, SignBit))
928     return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
929   // fold (sdiv X, pow2) -> simple ops after legalize
930   if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
931       (isPowerOf2_64(N1C->getSignExtended()) || 
932        isPowerOf2_64(-N1C->getSignExtended()))) {
933     // If dividing by powers of two is cheap, then don't perform the following
934     // fold.
935     if (TLI.isPow2DivCheap())
936       return SDOperand();
937     int64_t pow2 = N1C->getSignExtended();
938     int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
939     unsigned lg2 = Log2_64(abs2);
940     // Splat the sign bit into the register
941     SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
942                                 DAG.getConstant(MVT::getSizeInBits(VT)-1,
943                                                 TLI.getShiftAmountTy()));
944     AddToWorkList(SGN.Val);
945     // Add (N0 < 0) ? abs2 - 1 : 0;
946     SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
947                                 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
948                                                 TLI.getShiftAmountTy()));
949     SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
950     AddToWorkList(SRL.Val);
951     AddToWorkList(ADD.Val);    // Divide by pow2
952     SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
953                                 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
954     // If we're dividing by a positive value, we're done.  Otherwise, we must
955     // negate the result.
956     if (pow2 > 0)
957       return SRA;
958     AddToWorkList(SRA.Val);
959     return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
960   }
961   // if integer divide is expensive and we satisfy the requirements, emit an
962   // alternate sequence.
963   if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) && 
964       !TLI.isIntDivCheap()) {
965     SDOperand Op = BuildSDIV(N);
966     if (Op.Val) return Op;
967   }
968   return SDOperand();
969 }
970
971 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
972   SDOperand N0 = N->getOperand(0);
973   SDOperand N1 = N->getOperand(1);
974   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
975   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
976   MVT::ValueType VT = N->getValueType(0);
977   
978   // fold (udiv c1, c2) -> c1/c2
979   if (N0C && N1C && !N1C->isNullValue())
980     return DAG.getNode(ISD::UDIV, VT, N0, N1);
981   // fold (udiv x, (1 << c)) -> x >>u c
982   if (N1C && isPowerOf2_64(N1C->getValue()))
983     return DAG.getNode(ISD::SRL, VT, N0, 
984                        DAG.getConstant(Log2_64(N1C->getValue()),
985                                        TLI.getShiftAmountTy()));
986   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
987   if (N1.getOpcode() == ISD::SHL) {
988     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
989       if (isPowerOf2_64(SHC->getValue())) {
990         MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
991         SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
992                                     DAG.getConstant(Log2_64(SHC->getValue()),
993                                                     ADDVT));
994         AddToWorkList(Add.Val);
995         return DAG.getNode(ISD::SRL, VT, N0, Add);
996       }
997     }
998   }
999   // fold (udiv x, c) -> alternate
1000   if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
1001     SDOperand Op = BuildUDIV(N);
1002     if (Op.Val) return Op;
1003   }
1004   return SDOperand();
1005 }
1006
1007 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1008   SDOperand N0 = N->getOperand(0);
1009   SDOperand N1 = N->getOperand(1);
1010   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1011   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1012   MVT::ValueType VT = N->getValueType(0);
1013   
1014   // fold (srem c1, c2) -> c1%c2
1015   if (N0C && N1C && !N1C->isNullValue())
1016     return DAG.getNode(ISD::SREM, VT, N0, N1);
1017   // If we know the sign bits of both operands are zero, strength reduce to a
1018   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1019   uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1020   if (TLI.MaskedValueIsZero(N1, SignBit) &&
1021       TLI.MaskedValueIsZero(N0, SignBit))
1022     return DAG.getNode(ISD::UREM, VT, N0, N1);
1023   
1024   // Unconditionally lower X%C -> X-X/C*C.  This allows the X/C logic to hack on
1025   // the remainder operation.
1026   if (N1C && !N1C->isNullValue()) {
1027     SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1028     SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
1029     SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1030     AddToWorkList(Div.Val);
1031     AddToWorkList(Mul.Val);
1032     return Sub;
1033   }
1034   
1035   return SDOperand();
1036 }
1037
1038 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1039   SDOperand N0 = N->getOperand(0);
1040   SDOperand N1 = N->getOperand(1);
1041   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1042   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1043   MVT::ValueType VT = N->getValueType(0);
1044   
1045   // fold (urem c1, c2) -> c1%c2
1046   if (N0C && N1C && !N1C->isNullValue())
1047     return DAG.getNode(ISD::UREM, VT, N0, N1);
1048   // fold (urem x, pow2) -> (and x, pow2-1)
1049   if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
1050     return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
1051   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1052   if (N1.getOpcode() == ISD::SHL) {
1053     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1054       if (isPowerOf2_64(SHC->getValue())) {
1055         SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
1056         AddToWorkList(Add.Val);
1057         return DAG.getNode(ISD::AND, VT, N0, Add);
1058       }
1059     }
1060   }
1061   
1062   // Unconditionally lower X%C -> X-X/C*C.  This allows the X/C logic to hack on
1063   // the remainder operation.
1064   if (N1C && !N1C->isNullValue()) {
1065     SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1066     SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
1067     SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1068     AddToWorkList(Div.Val);
1069     AddToWorkList(Mul.Val);
1070     return Sub;
1071   }
1072   
1073   return SDOperand();
1074 }
1075
1076 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1077   SDOperand N0 = N->getOperand(0);
1078   SDOperand N1 = N->getOperand(1);
1079   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1080   
1081   // fold (mulhs x, 0) -> 0
1082   if (N1C && N1C->isNullValue())
1083     return N1;
1084   // fold (mulhs x, 1) -> (sra x, size(x)-1)
1085   if (N1C && N1C->getValue() == 1)
1086     return DAG.getNode(ISD::SRA, N0.getValueType(), N0, 
1087                        DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1088                                        TLI.getShiftAmountTy()));
1089   return SDOperand();
1090 }
1091
1092 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1093   SDOperand N0 = N->getOperand(0);
1094   SDOperand N1 = N->getOperand(1);
1095   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1096   
1097   // fold (mulhu x, 0) -> 0
1098   if (N1C && N1C->isNullValue())
1099     return N1;
1100   // fold (mulhu x, 1) -> 0
1101   if (N1C && N1C->getValue() == 1)
1102     return DAG.getConstant(0, N0.getValueType());
1103   return SDOperand();
1104 }
1105
1106 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1107 /// two operands of the same opcode, try to simplify it.
1108 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1109   SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1110   MVT::ValueType VT = N0.getValueType();
1111   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1112   
1113   // For each of OP in AND/OR/XOR:
1114   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1115   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1116   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1117   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1118   if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1119        N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1120       N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1121     SDOperand ORNode = DAG.getNode(N->getOpcode(), 
1122                                    N0.getOperand(0).getValueType(),
1123                                    N0.getOperand(0), N1.getOperand(0));
1124     AddToWorkList(ORNode.Val);
1125     return DAG.getNode(N0.getOpcode(), VT, ORNode);
1126   }
1127   
1128   // For each of OP in SHL/SRL/SRA/AND...
1129   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1130   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
1131   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1132   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1133        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1134       N0.getOperand(1) == N1.getOperand(1)) {
1135     SDOperand ORNode = DAG.getNode(N->getOpcode(),
1136                                    N0.getOperand(0).getValueType(),
1137                                    N0.getOperand(0), N1.getOperand(0));
1138     AddToWorkList(ORNode.Val);
1139     return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1140   }
1141   
1142   return SDOperand();
1143 }
1144
1145 SDOperand DAGCombiner::visitAND(SDNode *N) {
1146   SDOperand N0 = N->getOperand(0);
1147   SDOperand N1 = N->getOperand(1);
1148   SDOperand LL, LR, RL, RR, CC0, CC1;
1149   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1150   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1151   MVT::ValueType VT = N1.getValueType();
1152   
1153   // fold (and c1, c2) -> c1&c2
1154   if (N0C && N1C)
1155     return DAG.getNode(ISD::AND, VT, N0, N1);
1156   // canonicalize constant to RHS
1157   if (N0C && !N1C)
1158     return DAG.getNode(ISD::AND, VT, N1, N0);
1159   // fold (and x, -1) -> x
1160   if (N1C && N1C->isAllOnesValue())
1161     return N0;
1162   // if (and x, c) is known to be zero, return 0
1163   if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1164     return DAG.getConstant(0, VT);
1165   // reassociate and
1166   SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1167   if (RAND.Val != 0)
1168     return RAND;
1169   // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1170   if (N1C && N0.getOpcode() == ISD::OR)
1171     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1172       if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
1173         return N1;
1174   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1175   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1176     unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
1177     if (TLI.MaskedValueIsZero(N0.getOperand(0),
1178                               ~N1C->getValue() & InMask)) {
1179       SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1180                                    N0.getOperand(0));
1181       
1182       // Replace uses of the AND with uses of the Zero extend node.
1183       CombineTo(N, Zext);
1184       
1185       // We actually want to replace all uses of the any_extend with the
1186       // zero_extend, to avoid duplicating things.  This will later cause this
1187       // AND to be folded.
1188       CombineTo(N0.Val, Zext);
1189       return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1190     }
1191   }
1192   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1193   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1194     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1195     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1196     
1197     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1198         MVT::isInteger(LL.getValueType())) {
1199       // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1200       if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
1201         SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1202         AddToWorkList(ORNode.Val);
1203         return DAG.getSetCC(VT, ORNode, LR, Op1);
1204       }
1205       // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1206       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1207         SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1208         AddToWorkList(ANDNode.Val);
1209         return DAG.getSetCC(VT, ANDNode, LR, Op1);
1210       }
1211       // fold (X >  -1) & (Y >  -1) -> (X|Y > -1)
1212       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1213         SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1214         AddToWorkList(ORNode.Val);
1215         return DAG.getSetCC(VT, ORNode, LR, Op1);
1216       }
1217     }
1218     // canonicalize equivalent to ll == rl
1219     if (LL == RR && LR == RL) {
1220       Op1 = ISD::getSetCCSwappedOperands(Op1);
1221       std::swap(RL, RR);
1222     }
1223     if (LL == RL && LR == RR) {
1224       bool isInteger = MVT::isInteger(LL.getValueType());
1225       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1226       if (Result != ISD::SETCC_INVALID)
1227         return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1228     }
1229   }
1230
1231   // Simplify: and (op x...), (op y...)  -> (op (and x, y))
1232   if (N0.getOpcode() == N1.getOpcode()) {
1233     SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1234     if (Tmp.Val) return Tmp;
1235   }
1236   
1237   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1238   // fold (and (sra)) -> (and (srl)) when possible.
1239   if (!MVT::isVector(VT) &&
1240       SimplifyDemandedBits(SDOperand(N, 0)))
1241     return SDOperand(N, 0);
1242   // fold (zext_inreg (extload x)) -> (zextload x)
1243   if (ISD::isEXTLoad(N0.Val)) {
1244     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1245     MVT::ValueType EVT = LN0->getLoadedVT();
1246     // If we zero all the possible extended bits, then we can turn this into
1247     // a zextload if we are running before legalize or the operation is legal.
1248     if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1249         (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1250       SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1251                                          LN0->getBasePtr(), LN0->getSrcValue(),
1252                                          LN0->getSrcValueOffset(), EVT);
1253       AddToWorkList(N);
1254       CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1255       return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1256     }
1257   }
1258   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1259   if (ISD::isSEXTLoad(N0.Val) && N0.hasOneUse()) {
1260     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1261     MVT::ValueType EVT = LN0->getLoadedVT();
1262     // If we zero all the possible extended bits, then we can turn this into
1263     // a zextload if we are running before legalize or the operation is legal.
1264     if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1265         (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1266       SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1267                                          LN0->getBasePtr(), LN0->getSrcValue(),
1268                                          LN0->getSrcValueOffset(), EVT);
1269       AddToWorkList(N);
1270       CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1271       return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1272     }
1273   }
1274   
1275   // fold (and (load x), 255) -> (zextload x, i8)
1276   // fold (and (extload x, i16), 255) -> (zextload x, i8)
1277   if (N1C && N0.getOpcode() == ISD::LOAD) {
1278     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1279     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1280         N0.hasOneUse()) {
1281       MVT::ValueType EVT, LoadedVT;
1282       if (N1C->getValue() == 255)
1283         EVT = MVT::i8;
1284       else if (N1C->getValue() == 65535)
1285         EVT = MVT::i16;
1286       else if (N1C->getValue() == ~0U)
1287         EVT = MVT::i32;
1288       else
1289         EVT = MVT::Other;
1290     
1291       LoadedVT = LN0->getLoadedVT();
1292       if (EVT != MVT::Other && LoadedVT > EVT &&
1293           (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1294         MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1295         // For big endian targets, we need to add an offset to the pointer to
1296         // load the correct bytes.  For little endian systems, we merely need to
1297         // read fewer bytes from the same pointer.
1298         unsigned PtrOff =
1299           (MVT::getSizeInBits(LoadedVT) - MVT::getSizeInBits(EVT)) / 8;
1300         SDOperand NewPtr = LN0->getBasePtr();
1301         if (!TLI.isLittleEndian())
1302           NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1303                                DAG.getConstant(PtrOff, PtrType));
1304         AddToWorkList(NewPtr.Val);
1305         SDOperand Load =
1306           DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1307                          LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT);
1308         AddToWorkList(N);
1309         CombineTo(N0.Val, Load, Load.getValue(1));
1310         return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1311       }
1312     }
1313   }
1314   
1315   return SDOperand();
1316 }
1317
1318 SDOperand DAGCombiner::visitOR(SDNode *N) {
1319   SDOperand N0 = N->getOperand(0);
1320   SDOperand N1 = N->getOperand(1);
1321   SDOperand LL, LR, RL, RR, CC0, CC1;
1322   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1323   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1324   MVT::ValueType VT = N1.getValueType();
1325   unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1326   
1327   // fold (or c1, c2) -> c1|c2
1328   if (N0C && N1C)
1329     return DAG.getNode(ISD::OR, VT, N0, N1);
1330   // canonicalize constant to RHS
1331   if (N0C && !N1C)
1332     return DAG.getNode(ISD::OR, VT, N1, N0);
1333   // fold (or x, 0) -> x
1334   if (N1C && N1C->isNullValue())
1335     return N0;
1336   // fold (or x, -1) -> -1
1337   if (N1C && N1C->isAllOnesValue())
1338     return N1;
1339   // fold (or x, c) -> c iff (x & ~c) == 0
1340   if (N1C && 
1341       TLI.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
1342     return N1;
1343   // reassociate or
1344   SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1345   if (ROR.Val != 0)
1346     return ROR;
1347   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1348   if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1349              isa<ConstantSDNode>(N0.getOperand(1))) {
1350     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1351     return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1352                                                  N1),
1353                        DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1354   }
1355   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1356   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1357     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1358     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1359     
1360     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1361         MVT::isInteger(LL.getValueType())) {
1362       // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1363       // fold (X <  0) | (Y <  0) -> (X|Y < 0)
1364       if (cast<ConstantSDNode>(LR)->getValue() == 0 && 
1365           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1366         SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1367         AddToWorkList(ORNode.Val);
1368         return DAG.getSetCC(VT, ORNode, LR, Op1);
1369       }
1370       // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1371       // fold (X >  -1) | (Y >  -1) -> (X&Y >  -1)
1372       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 
1373           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1374         SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1375         AddToWorkList(ANDNode.Val);
1376         return DAG.getSetCC(VT, ANDNode, LR, Op1);
1377       }
1378     }
1379     // canonicalize equivalent to ll == rl
1380     if (LL == RR && LR == RL) {
1381       Op1 = ISD::getSetCCSwappedOperands(Op1);
1382       std::swap(RL, RR);
1383     }
1384     if (LL == RL && LR == RR) {
1385       bool isInteger = MVT::isInteger(LL.getValueType());
1386       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1387       if (Result != ISD::SETCC_INVALID)
1388         return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1389     }
1390   }
1391   
1392   // Simplify: or (op x...), (op y...)  -> (op (or x, y))
1393   if (N0.getOpcode() == N1.getOpcode()) {
1394     SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1395     if (Tmp.Val) return Tmp;
1396   }
1397   
1398   // (X & C1) | (Y & C2)  -> (X|Y) & C3  if possible.
1399   if (N0.getOpcode() == ISD::AND &&
1400       N1.getOpcode() == ISD::AND &&
1401       N0.getOperand(1).getOpcode() == ISD::Constant &&
1402       N1.getOperand(1).getOpcode() == ISD::Constant &&
1403       // Don't increase # computations.
1404       (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1405     // We can only do this xform if we know that bits from X that are set in C2
1406     // but not in C1 are already zero.  Likewise for Y.
1407     uint64_t LHSMask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1408     uint64_t RHSMask = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
1409     
1410     if (TLI.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1411         TLI.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1412       SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1413       return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1414     }
1415   }
1416   
1417   
1418   // See if this is some rotate idiom.
1419   if (SDNode *Rot = MatchRotate(N0, N1))
1420     return SDOperand(Rot, 0);
1421
1422   return SDOperand();
1423 }
1424
1425
1426 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1427 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1428   if (Op.getOpcode() == ISD::AND) {
1429     if (isa<ConstantSDNode>(Op.getOperand(1))) {
1430       Mask = Op.getOperand(1);
1431       Op = Op.getOperand(0);
1432     } else {
1433       return false;
1434     }
1435   }
1436   
1437   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1438     Shift = Op;
1439     return true;
1440   }
1441   return false;  
1442 }
1443
1444
1445 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
1446 // idioms for rotate, and if the target supports rotation instructions, generate
1447 // a rot[lr].
1448 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1449   // Must be a legal type.  Expanded an promoted things won't work with rotates.
1450   MVT::ValueType VT = LHS.getValueType();
1451   if (!TLI.isTypeLegal(VT)) return 0;
1452
1453   // The target must have at least one rotate flavor.
1454   bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1455   bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1456   if (!HasROTL && !HasROTR) return 0;
1457   
1458   // Match "(X shl/srl V1) & V2" where V2 may not be present.
1459   SDOperand LHSShift;   // The shift.
1460   SDOperand LHSMask;    // AND value if any.
1461   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1462     return 0; // Not part of a rotate.
1463
1464   SDOperand RHSShift;   // The shift.
1465   SDOperand RHSMask;    // AND value if any.
1466   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1467     return 0; // Not part of a rotate.
1468   
1469   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1470     return 0;   // Not shifting the same value.
1471
1472   if (LHSShift.getOpcode() == RHSShift.getOpcode())
1473     return 0;   // Shifts must disagree.
1474     
1475   // Canonicalize shl to left side in a shl/srl pair.
1476   if (RHSShift.getOpcode() == ISD::SHL) {
1477     std::swap(LHS, RHS);
1478     std::swap(LHSShift, RHSShift);
1479     std::swap(LHSMask , RHSMask );
1480   }
1481
1482   unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1483
1484   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1485   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1486   if (LHSShift.getOperand(1).getOpcode() == ISD::Constant &&
1487       RHSShift.getOperand(1).getOpcode() == ISD::Constant) {
1488     uint64_t LShVal = cast<ConstantSDNode>(LHSShift.getOperand(1))->getValue();
1489     uint64_t RShVal = cast<ConstantSDNode>(RHSShift.getOperand(1))->getValue();
1490     if ((LShVal + RShVal) != OpSizeInBits)
1491       return 0;
1492
1493     SDOperand Rot;
1494     if (HasROTL)
1495       Rot = DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1496                         LHSShift.getOperand(1));
1497     else
1498       Rot = DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1499                         RHSShift.getOperand(1));
1500     
1501     // If there is an AND of either shifted operand, apply it to the result.
1502     if (LHSMask.Val || RHSMask.Val) {
1503       uint64_t Mask = MVT::getIntVTBitMask(VT);
1504       
1505       if (LHSMask.Val) {
1506         uint64_t RHSBits = (1ULL << LShVal)-1;
1507         Mask &= cast<ConstantSDNode>(LHSMask)->getValue() | RHSBits;
1508       }
1509       if (RHSMask.Val) {
1510         uint64_t LHSBits = ~((1ULL << (OpSizeInBits-RShVal))-1);
1511         Mask &= cast<ConstantSDNode>(RHSMask)->getValue() | LHSBits;
1512       }
1513         
1514       Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
1515     }
1516     
1517     return Rot.Val;
1518   }
1519   
1520   // If there is a mask here, and we have a variable shift, we can't be sure
1521   // that we're masking out the right stuff.
1522   if (LHSMask.Val || RHSMask.Val)
1523     return 0;
1524   
1525   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
1526   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
1527   if (RHSShift.getOperand(1).getOpcode() == ISD::SUB &&
1528       LHSShift.getOperand(1) == RHSShift.getOperand(1).getOperand(1)) {
1529     if (ConstantSDNode *SUBC = 
1530           dyn_cast<ConstantSDNode>(RHSShift.getOperand(1).getOperand(0))) {
1531       if (SUBC->getValue() == OpSizeInBits)
1532         if (HasROTL)
1533           return DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1534                              LHSShift.getOperand(1)).Val;
1535         else
1536           return DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1537                              LHSShift.getOperand(1)).Val;
1538     }
1539   }
1540   
1541   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
1542   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
1543   if (LHSShift.getOperand(1).getOpcode() == ISD::SUB &&
1544       RHSShift.getOperand(1) == LHSShift.getOperand(1).getOperand(1)) {
1545     if (ConstantSDNode *SUBC = 
1546           dyn_cast<ConstantSDNode>(LHSShift.getOperand(1).getOperand(0))) {
1547       if (SUBC->getValue() == OpSizeInBits)
1548         if (HasROTL)
1549           return DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1550                              LHSShift.getOperand(1)).Val;
1551         else
1552           return DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0), 
1553                              RHSShift.getOperand(1)).Val;
1554     }
1555   }
1556   
1557   return 0;
1558 }
1559
1560
1561 SDOperand DAGCombiner::visitXOR(SDNode *N) {
1562   SDOperand N0 = N->getOperand(0);
1563   SDOperand N1 = N->getOperand(1);
1564   SDOperand LHS, RHS, CC;
1565   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1566   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1567   MVT::ValueType VT = N0.getValueType();
1568   
1569   // fold (xor c1, c2) -> c1^c2
1570   if (N0C && N1C)
1571     return DAG.getNode(ISD::XOR, VT, N0, N1);
1572   // canonicalize constant to RHS
1573   if (N0C && !N1C)
1574     return DAG.getNode(ISD::XOR, VT, N1, N0);
1575   // fold (xor x, 0) -> x
1576   if (N1C && N1C->isNullValue())
1577     return N0;
1578   // reassociate xor
1579   SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
1580   if (RXOR.Val != 0)
1581     return RXOR;
1582   // fold !(x cc y) -> (x !cc y)
1583   if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
1584     bool isInt = MVT::isInteger(LHS.getValueType());
1585     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
1586                                                isInt);
1587     if (N0.getOpcode() == ISD::SETCC)
1588       return DAG.getSetCC(VT, LHS, RHS, NotCC);
1589     if (N0.getOpcode() == ISD::SELECT_CC)
1590       return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
1591     assert(0 && "Unhandled SetCC Equivalent!");
1592     abort();
1593   }
1594   // fold !(x or y) -> (!x and !y) iff x or y are setcc
1595   if (N1C && N1C->getValue() == 1 && 
1596       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1597     SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1598     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
1599       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1600       LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
1601       RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
1602       AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1603       return DAG.getNode(NewOpcode, VT, LHS, RHS);
1604     }
1605   }
1606   // fold !(x or y) -> (!x and !y) iff x or y are constants
1607   if (N1C && N1C->isAllOnesValue() && 
1608       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1609     SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1610     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
1611       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1612       LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
1613       RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
1614       AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1615       return DAG.getNode(NewOpcode, VT, LHS, RHS);
1616     }
1617   }
1618   // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
1619   if (N1C && N0.getOpcode() == ISD::XOR) {
1620     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
1621     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1622     if (N00C)
1623       return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
1624                          DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
1625     if (N01C)
1626       return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
1627                          DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
1628   }
1629   // fold (xor x, x) -> 0
1630   if (N0 == N1) {
1631     if (!MVT::isVector(VT)) {
1632       return DAG.getConstant(0, VT);
1633     } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1634       // Produce a vector of zeros.
1635       SDOperand El = DAG.getConstant(0, MVT::getVectorBaseType(VT));
1636       std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
1637       return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1638     }
1639   }
1640   
1641   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
1642   if (N0.getOpcode() == N1.getOpcode()) {
1643     SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1644     if (Tmp.Val) return Tmp;
1645   }
1646   
1647   // Simplify the expression using non-local knowledge.
1648   if (!MVT::isVector(VT) &&
1649       SimplifyDemandedBits(SDOperand(N, 0)))
1650     return SDOperand(N, 0);
1651   
1652   return SDOperand();
1653 }
1654
1655 SDOperand DAGCombiner::visitSHL(SDNode *N) {
1656   SDOperand N0 = N->getOperand(0);
1657   SDOperand N1 = N->getOperand(1);
1658   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1659   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1660   MVT::ValueType VT = N0.getValueType();
1661   unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1662   
1663   // fold (shl c1, c2) -> c1<<c2
1664   if (N0C && N1C)
1665     return DAG.getNode(ISD::SHL, VT, N0, N1);
1666   // fold (shl 0, x) -> 0
1667   if (N0C && N0C->isNullValue())
1668     return N0;
1669   // fold (shl x, c >= size(x)) -> undef
1670   if (N1C && N1C->getValue() >= OpSizeInBits)
1671     return DAG.getNode(ISD::UNDEF, VT);
1672   // fold (shl x, 0) -> x
1673   if (N1C && N1C->isNullValue())
1674     return N0;
1675   // if (shl x, c) is known to be zero, return 0
1676   if (TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1677     return DAG.getConstant(0, VT);
1678   if (SimplifyDemandedBits(SDOperand(N, 0)))
1679     return SDOperand(N, 0);
1680   // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
1681   if (N1C && N0.getOpcode() == ISD::SHL && 
1682       N0.getOperand(1).getOpcode() == ISD::Constant) {
1683     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1684     uint64_t c2 = N1C->getValue();
1685     if (c1 + c2 > OpSizeInBits)
1686       return DAG.getConstant(0, VT);
1687     return DAG.getNode(ISD::SHL, VT, N0.getOperand(0), 
1688                        DAG.getConstant(c1 + c2, N1.getValueType()));
1689   }
1690   // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
1691   //                               (srl (and x, -1 << c1), c1-c2)
1692   if (N1C && N0.getOpcode() == ISD::SRL && 
1693       N0.getOperand(1).getOpcode() == ISD::Constant) {
1694     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1695     uint64_t c2 = N1C->getValue();
1696     SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1697                                  DAG.getConstant(~0ULL << c1, VT));
1698     if (c2 > c1)
1699       return DAG.getNode(ISD::SHL, VT, Mask, 
1700                          DAG.getConstant(c2-c1, N1.getValueType()));
1701     else
1702       return DAG.getNode(ISD::SRL, VT, Mask, 
1703                          DAG.getConstant(c1-c2, N1.getValueType()));
1704   }
1705   // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
1706   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
1707     return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1708                        DAG.getConstant(~0ULL << N1C->getValue(), VT));
1709   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1<<c2)
1710   if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() && 
1711       isa<ConstantSDNode>(N0.getOperand(1))) {
1712     return DAG.getNode(ISD::ADD, VT, 
1713                        DAG.getNode(ISD::SHL, VT, N0.getOperand(0), N1),
1714                        DAG.getNode(ISD::SHL, VT, N0.getOperand(1), N1));
1715   }
1716   return SDOperand();
1717 }
1718
1719 SDOperand DAGCombiner::visitSRA(SDNode *N) {
1720   SDOperand N0 = N->getOperand(0);
1721   SDOperand N1 = N->getOperand(1);
1722   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1723   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1724   MVT::ValueType VT = N0.getValueType();
1725   
1726   // fold (sra c1, c2) -> c1>>c2
1727   if (N0C && N1C)
1728     return DAG.getNode(ISD::SRA, VT, N0, N1);
1729   // fold (sra 0, x) -> 0
1730   if (N0C && N0C->isNullValue())
1731     return N0;
1732   // fold (sra -1, x) -> -1
1733   if (N0C && N0C->isAllOnesValue())
1734     return N0;
1735   // fold (sra x, c >= size(x)) -> undef
1736   if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
1737     return DAG.getNode(ISD::UNDEF, VT);
1738   // fold (sra x, 0) -> x
1739   if (N1C && N1C->isNullValue())
1740     return N0;
1741   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
1742   // sext_inreg.
1743   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
1744     unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
1745     MVT::ValueType EVT;
1746     switch (LowBits) {
1747     default: EVT = MVT::Other; break;
1748     case  1: EVT = MVT::i1;    break;
1749     case  8: EVT = MVT::i8;    break;
1750     case 16: EVT = MVT::i16;   break;
1751     case 32: EVT = MVT::i32;   break;
1752     }
1753     if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
1754       return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
1755                          DAG.getValueType(EVT));
1756   }
1757   
1758   // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
1759   if (N1C && N0.getOpcode() == ISD::SRA) {
1760     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1761       unsigned Sum = N1C->getValue() + C1->getValue();
1762       if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
1763       return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
1764                          DAG.getConstant(Sum, N1C->getValueType(0)));
1765     }
1766   }
1767   
1768   // Simplify, based on bits shifted out of the LHS. 
1769   if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
1770     return SDOperand(N, 0);
1771   
1772   
1773   // If the sign bit is known to be zero, switch this to a SRL.
1774   if (TLI.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
1775     return DAG.getNode(ISD::SRL, VT, N0, N1);
1776   return SDOperand();
1777 }
1778
1779 SDOperand DAGCombiner::visitSRL(SDNode *N) {
1780   SDOperand N0 = N->getOperand(0);
1781   SDOperand N1 = N->getOperand(1);
1782   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1783   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1784   MVT::ValueType VT = N0.getValueType();
1785   unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1786   
1787   // fold (srl c1, c2) -> c1 >>u c2
1788   if (N0C && N1C)
1789     return DAG.getNode(ISD::SRL, VT, N0, N1);
1790   // fold (srl 0, x) -> 0
1791   if (N0C && N0C->isNullValue())
1792     return N0;
1793   // fold (srl x, c >= size(x)) -> undef
1794   if (N1C && N1C->getValue() >= OpSizeInBits)
1795     return DAG.getNode(ISD::UNDEF, VT);
1796   // fold (srl x, 0) -> x
1797   if (N1C && N1C->isNullValue())
1798     return N0;
1799   // if (srl x, c) is known to be zero, return 0
1800   if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
1801     return DAG.getConstant(0, VT);
1802   // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
1803   if (N1C && N0.getOpcode() == ISD::SRL && 
1804       N0.getOperand(1).getOpcode() == ISD::Constant) {
1805     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1806     uint64_t c2 = N1C->getValue();
1807     if (c1 + c2 > OpSizeInBits)
1808       return DAG.getConstant(0, VT);
1809     return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), 
1810                        DAG.getConstant(c1 + c2, N1.getValueType()));
1811   }
1812   
1813   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
1814   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1815     // Shifting in all undef bits?
1816     MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
1817     if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
1818       return DAG.getNode(ISD::UNDEF, VT);
1819
1820     SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
1821     AddToWorkList(SmallShift.Val);
1822     return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
1823   }
1824   
1825   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
1826   // bit, which is unmodified by sra.
1827   if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
1828     if (N0.getOpcode() == ISD::SRA)
1829       return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
1830   }
1831   
1832   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
1833   if (N1C && N0.getOpcode() == ISD::CTLZ && 
1834       N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
1835     uint64_t KnownZero, KnownOne, Mask = MVT::getIntVTBitMask(VT);
1836     TLI.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
1837     
1838     // If any of the input bits are KnownOne, then the input couldn't be all
1839     // zeros, thus the result of the srl will always be zero.
1840     if (KnownOne) return DAG.getConstant(0, VT);
1841     
1842     // If all of the bits input the to ctlz node are known to be zero, then
1843     // the result of the ctlz is "32" and the result of the shift is one.
1844     uint64_t UnknownBits = ~KnownZero & Mask;
1845     if (UnknownBits == 0) return DAG.getConstant(1, VT);
1846     
1847     // Otherwise, check to see if there is exactly one bit input to the ctlz.
1848     if ((UnknownBits & (UnknownBits-1)) == 0) {
1849       // Okay, we know that only that the single bit specified by UnknownBits
1850       // could be set on input to the CTLZ node.  If this bit is set, the SRL
1851       // will return 0, if it is clear, it returns 1.  Change the CTLZ/SRL pair
1852       // to an SRL,XOR pair, which is likely to simplify more.
1853       unsigned ShAmt = CountTrailingZeros_64(UnknownBits);
1854       SDOperand Op = N0.getOperand(0);
1855       if (ShAmt) {
1856         Op = DAG.getNode(ISD::SRL, VT, Op,
1857                          DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
1858         AddToWorkList(Op.Val);
1859       }
1860       return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
1861     }
1862   }
1863   
1864   return SDOperand();
1865 }
1866
1867 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
1868   SDOperand N0 = N->getOperand(0);
1869   MVT::ValueType VT = N->getValueType(0);
1870
1871   // fold (ctlz c1) -> c2
1872   if (isa<ConstantSDNode>(N0))
1873     return DAG.getNode(ISD::CTLZ, VT, N0);
1874   return SDOperand();
1875 }
1876
1877 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
1878   SDOperand N0 = N->getOperand(0);
1879   MVT::ValueType VT = N->getValueType(0);
1880   
1881   // fold (cttz c1) -> c2
1882   if (isa<ConstantSDNode>(N0))
1883     return DAG.getNode(ISD::CTTZ, VT, N0);
1884   return SDOperand();
1885 }
1886
1887 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
1888   SDOperand N0 = N->getOperand(0);
1889   MVT::ValueType VT = N->getValueType(0);
1890   
1891   // fold (ctpop c1) -> c2
1892   if (isa<ConstantSDNode>(N0))
1893     return DAG.getNode(ISD::CTPOP, VT, N0);
1894   return SDOperand();
1895 }
1896
1897 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
1898   SDOperand N0 = N->getOperand(0);
1899   SDOperand N1 = N->getOperand(1);
1900   SDOperand N2 = N->getOperand(2);
1901   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1902   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1903   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
1904   MVT::ValueType VT = N->getValueType(0);
1905
1906   // fold select C, X, X -> X
1907   if (N1 == N2)
1908     return N1;
1909   // fold select true, X, Y -> X
1910   if (N0C && !N0C->isNullValue())
1911     return N1;
1912   // fold select false, X, Y -> Y
1913   if (N0C && N0C->isNullValue())
1914     return N2;
1915   // fold select C, 1, X -> C | X
1916   if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
1917     return DAG.getNode(ISD::OR, VT, N0, N2);
1918   // fold select C, 0, X -> ~C & X
1919   // FIXME: this should check for C type == X type, not i1?
1920   if (MVT::i1 == VT && N1C && N1C->isNullValue()) {
1921     SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
1922     AddToWorkList(XORNode.Val);
1923     return DAG.getNode(ISD::AND, VT, XORNode, N2);
1924   }
1925   // fold select C, X, 1 -> ~C | X
1926   if (MVT::i1 == VT && N2C && N2C->getValue() == 1) {
1927     SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
1928     AddToWorkList(XORNode.Val);
1929     return DAG.getNode(ISD::OR, VT, XORNode, N1);
1930   }
1931   // fold select C, X, 0 -> C & X
1932   // FIXME: this should check for C type == X type, not i1?
1933   if (MVT::i1 == VT && N2C && N2C->isNullValue())
1934     return DAG.getNode(ISD::AND, VT, N0, N1);
1935   // fold  X ? X : Y --> X ? 1 : Y --> X | Y
1936   if (MVT::i1 == VT && N0 == N1)
1937     return DAG.getNode(ISD::OR, VT, N0, N2);
1938   // fold X ? Y : X --> X ? Y : 0 --> X & Y
1939   if (MVT::i1 == VT && N0 == N2)
1940     return DAG.getNode(ISD::AND, VT, N0, N1);
1941   
1942   // If we can fold this based on the true/false value, do so.
1943   if (SimplifySelectOps(N, N1, N2))
1944     return SDOperand(N, 0);  // Don't revisit N.
1945   
1946   // fold selects based on a setcc into other things, such as min/max/abs
1947   if (N0.getOpcode() == ISD::SETCC)
1948     // FIXME:
1949     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
1950     // having to say they don't support SELECT_CC on every type the DAG knows
1951     // about, since there is no way to mark an opcode illegal at all value types
1952     if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
1953       return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
1954                          N1, N2, N0.getOperand(2));
1955     else
1956       return SimplifySelect(N0, N1, N2);
1957   return SDOperand();
1958 }
1959
1960 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
1961   SDOperand N0 = N->getOperand(0);
1962   SDOperand N1 = N->getOperand(1);
1963   SDOperand N2 = N->getOperand(2);
1964   SDOperand N3 = N->getOperand(3);
1965   SDOperand N4 = N->getOperand(4);
1966   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
1967   
1968   // fold select_cc lhs, rhs, x, x, cc -> x
1969   if (N2 == N3)
1970     return N2;
1971   
1972   // Determine if the condition we're dealing with is constant
1973   SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
1974   if (SCC.Val) AddToWorkList(SCC.Val);
1975
1976   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
1977     if (SCCC->getValue())
1978       return N2;    // cond always true -> true val
1979     else
1980       return N3;    // cond always false -> false val
1981   }
1982   
1983   // Fold to a simpler select_cc
1984   if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
1985     return DAG.getNode(ISD::SELECT_CC, N2.getValueType(), 
1986                        SCC.getOperand(0), SCC.getOperand(1), N2, N3, 
1987                        SCC.getOperand(2));
1988   
1989   // If we can fold this based on the true/false value, do so.
1990   if (SimplifySelectOps(N, N2, N3))
1991     return SDOperand(N, 0);  // Don't revisit N.
1992   
1993   // fold select_cc into other things, such as min/max/abs
1994   return SimplifySelectCC(N0, N1, N2, N3, CC);
1995 }
1996
1997 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
1998   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
1999                        cast<CondCodeSDNode>(N->getOperand(2))->get());
2000 }
2001
2002 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2003   SDOperand N0 = N->getOperand(0);
2004   MVT::ValueType VT = N->getValueType(0);
2005
2006   // fold (sext c1) -> c1
2007   if (isa<ConstantSDNode>(N0))
2008     return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2009   
2010   // fold (sext (sext x)) -> (sext x)
2011   // fold (sext (aext x)) -> (sext x)
2012   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2013     return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2014   
2015   // fold (sext (truncate x)) -> (sextinreg x).
2016   if (N0.getOpcode() == ISD::TRUNCATE && 
2017       (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2018                                               N0.getValueType()))) {
2019     SDOperand Op = N0.getOperand(0);
2020     if (Op.getValueType() < VT) {
2021       Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2022     } else if (Op.getValueType() > VT) {
2023       Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2024     }
2025     return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2026                        DAG.getValueType(N0.getValueType()));
2027   }
2028   
2029   // fold (sext (load x)) -> (sext (truncate (sextload x)))
2030   if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2031       (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
2032     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2033     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2034                                        LN0->getBasePtr(), LN0->getSrcValue(),
2035                                        LN0->getSrcValueOffset(),
2036                                        N0.getValueType());
2037     CombineTo(N, ExtLoad);
2038     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2039               ExtLoad.getValue(1));
2040     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2041   }
2042
2043   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2044   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2045   if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) && N0.hasOneUse()) {
2046     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2047     MVT::ValueType EVT = LN0->getLoadedVT();
2048     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2049                                        LN0->getBasePtr(), LN0->getSrcValue(),
2050                                        LN0->getSrcValueOffset(), EVT);
2051     CombineTo(N, ExtLoad);
2052     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2053               ExtLoad.getValue(1));
2054     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2055   }
2056   
2057   return SDOperand();
2058 }
2059
2060 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2061   SDOperand N0 = N->getOperand(0);
2062   MVT::ValueType VT = N->getValueType(0);
2063
2064   // fold (zext c1) -> c1
2065   if (isa<ConstantSDNode>(N0))
2066     return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2067   // fold (zext (zext x)) -> (zext x)
2068   // fold (zext (aext x)) -> (zext x)
2069   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2070     return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2071
2072   // fold (zext (truncate x)) -> (and x, mask)
2073   if (N0.getOpcode() == ISD::TRUNCATE &&
2074       (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2075     SDOperand Op = N0.getOperand(0);
2076     if (Op.getValueType() < VT) {
2077       Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2078     } else if (Op.getValueType() > VT) {
2079       Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2080     }
2081     return DAG.getZeroExtendInReg(Op, N0.getValueType());
2082   }
2083   
2084   // fold (zext (and (trunc x), cst)) -> (and x, cst).
2085   if (N0.getOpcode() == ISD::AND &&
2086       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2087       N0.getOperand(1).getOpcode() == ISD::Constant) {
2088     SDOperand X = N0.getOperand(0).getOperand(0);
2089     if (X.getValueType() < VT) {
2090       X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2091     } else if (X.getValueType() > VT) {
2092       X = DAG.getNode(ISD::TRUNCATE, VT, X);
2093     }
2094     uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2095     return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2096   }
2097   
2098   // fold (zext (load x)) -> (zext (truncate (zextload x)))
2099   if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2100       (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2101     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2102     SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2103                                        LN0->getBasePtr(), LN0->getSrcValue(),
2104                                        LN0->getSrcValueOffset(),
2105                                        N0.getValueType());
2106     CombineTo(N, ExtLoad);
2107     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2108               ExtLoad.getValue(1));
2109     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2110   }
2111
2112   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2113   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2114   if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) && N0.hasOneUse()) {
2115     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2116     MVT::ValueType EVT = LN0->getLoadedVT();
2117     SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2118                                        LN0->getBasePtr(), LN0->getSrcValue(),
2119                                        LN0->getSrcValueOffset(), EVT);
2120     CombineTo(N, ExtLoad);
2121     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2122               ExtLoad.getValue(1));
2123     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2124   }
2125   return SDOperand();
2126 }
2127
2128 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
2129   SDOperand N0 = N->getOperand(0);
2130   MVT::ValueType VT = N->getValueType(0);
2131   
2132   // fold (aext c1) -> c1
2133   if (isa<ConstantSDNode>(N0))
2134     return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
2135   // fold (aext (aext x)) -> (aext x)
2136   // fold (aext (zext x)) -> (zext x)
2137   // fold (aext (sext x)) -> (sext x)
2138   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
2139       N0.getOpcode() == ISD::ZERO_EXTEND ||
2140       N0.getOpcode() == ISD::SIGN_EXTEND)
2141     return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2142   
2143   // fold (aext (truncate x))
2144   if (N0.getOpcode() == ISD::TRUNCATE) {
2145     SDOperand TruncOp = N0.getOperand(0);
2146     if (TruncOp.getValueType() == VT)
2147       return TruncOp; // x iff x size == zext size.
2148     if (TruncOp.getValueType() > VT)
2149       return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
2150     return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
2151   }
2152   
2153   // fold (aext (and (trunc x), cst)) -> (and x, cst).
2154   if (N0.getOpcode() == ISD::AND &&
2155       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2156       N0.getOperand(1).getOpcode() == ISD::Constant) {
2157     SDOperand X = N0.getOperand(0).getOperand(0);
2158     if (X.getValueType() < VT) {
2159       X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2160     } else if (X.getValueType() > VT) {
2161       X = DAG.getNode(ISD::TRUNCATE, VT, X);
2162     }
2163     uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2164     return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2165   }
2166   
2167   // fold (aext (load x)) -> (aext (truncate (extload x)))
2168   if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2169       (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2170     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2171     SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2172                                        LN0->getBasePtr(), LN0->getSrcValue(),
2173                                        LN0->getSrcValueOffset(),
2174                                        N0.getValueType());
2175     CombineTo(N, ExtLoad);
2176     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2177               ExtLoad.getValue(1));
2178     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2179   }
2180   
2181   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
2182   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
2183   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
2184   if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.Val) &&
2185       N0.hasOneUse()) {
2186     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2187     MVT::ValueType EVT = LN0->getLoadedVT();
2188     SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
2189                                        LN0->getChain(), LN0->getBasePtr(),
2190                                        LN0->getSrcValue(),
2191                                        LN0->getSrcValueOffset(), EVT);
2192     CombineTo(N, ExtLoad);
2193     CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2194               ExtLoad.getValue(1));
2195     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2196   }
2197   return SDOperand();
2198 }
2199
2200
2201 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
2202   SDOperand N0 = N->getOperand(0);
2203   SDOperand N1 = N->getOperand(1);
2204   MVT::ValueType VT = N->getValueType(0);
2205   MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
2206   unsigned EVTBits = MVT::getSizeInBits(EVT);
2207   
2208   // fold (sext_in_reg c1) -> c1
2209   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
2210     return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
2211   
2212   // If the input is already sign extended, just drop the extension.
2213   if (TLI.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
2214     return N0;
2215   
2216   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
2217   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2218       EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
2219     return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
2220   }
2221
2222   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is zero
2223   if (TLI.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
2224     return DAG.getZeroExtendInReg(N0, EVT);
2225   
2226   // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
2227   // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
2228   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
2229   if (N0.getOpcode() == ISD::SRL) {
2230     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2231       if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
2232         // We can turn this into an SRA iff the input to the SRL is already sign
2233         // extended enough.
2234         unsigned InSignBits = TLI.ComputeNumSignBits(N0.getOperand(0));
2235         if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
2236           return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
2237       }
2238   }
2239   
2240   // fold (sext_inreg (extload x)) -> (sextload x)
2241   if (ISD::isEXTLoad(N0.Val) && 
2242       EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2243       (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2244     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2245     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2246                                        LN0->getBasePtr(), LN0->getSrcValue(),
2247                                        LN0->getSrcValueOffset(), EVT);
2248     CombineTo(N, ExtLoad);
2249     CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2250     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2251   }
2252   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
2253   if (ISD::isZEXTLoad(N0.Val) && N0.hasOneUse() &&
2254       EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2255       (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2256     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2257     SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2258                                        LN0->getBasePtr(), LN0->getSrcValue(),
2259                                        LN0->getSrcValueOffset(), EVT);
2260     CombineTo(N, ExtLoad);
2261     CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2262     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2263   }
2264   return SDOperand();
2265 }
2266
2267 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
2268   SDOperand N0 = N->getOperand(0);
2269   MVT::ValueType VT = N->getValueType(0);
2270
2271   // noop truncate
2272   if (N0.getValueType() == N->getValueType(0))
2273     return N0;
2274   // fold (truncate c1) -> c1
2275   if (isa<ConstantSDNode>(N0))
2276     return DAG.getNode(ISD::TRUNCATE, VT, N0);
2277   // fold (truncate (truncate x)) -> (truncate x)
2278   if (N0.getOpcode() == ISD::TRUNCATE)
2279     return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
2280   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
2281   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
2282       N0.getOpcode() == ISD::ANY_EXTEND) {
2283     if (N0.getValueType() < VT)
2284       // if the source is smaller than the dest, we still need an extend
2285       return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2286     else if (N0.getValueType() > VT)
2287       // if the source is larger than the dest, than we just need the truncate
2288       return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
2289     else
2290       // if the source and dest are the same type, we can drop both the extend
2291       // and the truncate
2292       return N0.getOperand(0);
2293   }
2294   // fold (truncate (load x)) -> (smaller load x)
2295   if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse()) {
2296     assert(MVT::getSizeInBits(N0.getValueType()) > MVT::getSizeInBits(VT) &&
2297            "Cannot truncate to larger type!");
2298     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2299     MVT::ValueType PtrType = N0.getOperand(1).getValueType();
2300     // For big endian targets, we need to add an offset to the pointer to load
2301     // the correct bytes.  For little endian systems, we merely need to read
2302     // fewer bytes from the same pointer.
2303     uint64_t PtrOff = 
2304       (MVT::getSizeInBits(N0.getValueType()) - MVT::getSizeInBits(VT)) / 8;
2305     SDOperand NewPtr = TLI.isLittleEndian() ? LN0->getBasePtr() : 
2306       DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
2307                   DAG.getConstant(PtrOff, PtrType));
2308     AddToWorkList(NewPtr.Val);
2309     SDOperand Load = DAG.getLoad(VT, LN0->getChain(), NewPtr,
2310                                  LN0->getSrcValue(), LN0->getSrcValueOffset());
2311     AddToWorkList(N);
2312     CombineTo(N0.Val, Load, Load.getValue(1));
2313     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2314   }
2315   return SDOperand();
2316 }
2317
2318 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
2319   SDOperand N0 = N->getOperand(0);
2320   MVT::ValueType VT = N->getValueType(0);
2321
2322   // If the input is a constant, let getNode() fold it.
2323   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
2324     SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
2325     if (Res.Val != N) return Res;
2326   }
2327   
2328   if (N0.getOpcode() == ISD::BIT_CONVERT)  // conv(conv(x,t1),t2) -> conv(x,t2)
2329     return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
2330
2331   // fold (conv (load x)) -> (load (conv*)x)
2332   // FIXME: These xforms need to know that the resultant load doesn't need a 
2333   // higher alignment than the original!
2334   if (0 && ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse()) {
2335     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2336     SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
2337                                  LN0->getSrcValue(), LN0->getSrcValueOffset());
2338     AddToWorkList(N);
2339     CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
2340               Load.getValue(1));
2341     return Load;
2342   }
2343   
2344   return SDOperand();
2345 }
2346
2347 SDOperand DAGCombiner::visitVBIT_CONVERT(SDNode *N) {
2348   SDOperand N0 = N->getOperand(0);
2349   MVT::ValueType VT = N->getValueType(0);
2350
2351   // If the input is a VBUILD_VECTOR with all constant elements, fold this now.
2352   // First check to see if this is all constant.
2353   if (N0.getOpcode() == ISD::VBUILD_VECTOR && N0.Val->hasOneUse() &&
2354       VT == MVT::Vector) {
2355     bool isSimple = true;
2356     for (unsigned i = 0, e = N0.getNumOperands()-2; i != e; ++i)
2357       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
2358           N0.getOperand(i).getOpcode() != ISD::Constant &&
2359           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
2360         isSimple = false; 
2361         break;
2362       }
2363         
2364     MVT::ValueType DestEltVT = cast<VTSDNode>(N->getOperand(2))->getVT();
2365     if (isSimple && !MVT::isVector(DestEltVT)) {
2366       return ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(N0.Val, DestEltVT);
2367     }
2368   }
2369   
2370   return SDOperand();
2371 }
2372
2373 /// ConstantFoldVBIT_CONVERTofVBUILD_VECTOR - We know that BV is a vbuild_vector
2374 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the 
2375 /// destination element value type.
2376 SDOperand DAGCombiner::
2377 ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
2378   MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
2379   
2380   // If this is already the right type, we're done.
2381   if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
2382   
2383   unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
2384   unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
2385   
2386   // If this is a conversion of N elements of one type to N elements of another
2387   // type, convert each element.  This handles FP<->INT cases.
2388   if (SrcBitSize == DstBitSize) {
2389     SmallVector<SDOperand, 8> Ops;
2390     for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) {
2391       Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
2392       AddToWorkList(Ops.back().Val);
2393     }
2394     Ops.push_back(*(BV->op_end()-2)); // Add num elements.
2395     Ops.push_back(DAG.getValueType(DstEltVT));
2396     return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2397   }
2398   
2399   // Otherwise, we're growing or shrinking the elements.  To avoid having to
2400   // handle annoying details of growing/shrinking FP values, we convert them to
2401   // int first.
2402   if (MVT::isFloatingPoint(SrcEltVT)) {
2403     // Convert the input float vector to a int vector where the elements are the
2404     // same sizes.
2405     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
2406     MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2407     BV = ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(BV, IntVT).Val;
2408     SrcEltVT = IntVT;
2409   }
2410   
2411   // Now we know the input is an integer vector.  If the output is a FP type,
2412   // convert to integer first, then to FP of the right size.
2413   if (MVT::isFloatingPoint(DstEltVT)) {
2414     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
2415     MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2416     SDNode *Tmp = ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(BV, TmpVT).Val;
2417     
2418     // Next, convert to FP elements of the same size.
2419     return ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(Tmp, DstEltVT);
2420   }
2421   
2422   // Okay, we know the src/dst types are both integers of differing types.
2423   // Handling growing first.
2424   assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
2425   if (SrcBitSize < DstBitSize) {
2426     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
2427     
2428     SmallVector<SDOperand, 8> Ops;
2429     for (unsigned i = 0, e = BV->getNumOperands()-2; i != e;
2430          i += NumInputsPerOutput) {
2431       bool isLE = TLI.isLittleEndian();
2432       uint64_t NewBits = 0;
2433       bool EltIsUndef = true;
2434       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
2435         // Shift the previously computed bits over.
2436         NewBits <<= SrcBitSize;
2437         SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
2438         if (Op.getOpcode() == ISD::UNDEF) continue;
2439         EltIsUndef = false;
2440         
2441         NewBits |= cast<ConstantSDNode>(Op)->getValue();
2442       }
2443       
2444       if (EltIsUndef)
2445         Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2446       else
2447         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
2448     }
2449
2450     Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements.
2451     Ops.push_back(DAG.getValueType(DstEltVT));            // Add element size.
2452     return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2453   }
2454   
2455   // Finally, this must be the case where we are shrinking elements: each input
2456   // turns into multiple outputs.
2457   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
2458   SmallVector<SDOperand, 8> Ops;
2459   for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) {
2460     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
2461       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
2462         Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2463       continue;
2464     }
2465     uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
2466
2467     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
2468       unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
2469       OpVal >>= DstBitSize;
2470       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
2471     }
2472
2473     // For big endian targets, swap the order of the pieces of each element.
2474     if (!TLI.isLittleEndian())
2475       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
2476   }
2477   Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements.
2478   Ops.push_back(DAG.getValueType(DstEltVT));            // Add element size.
2479   return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2480 }
2481
2482
2483
2484 SDOperand DAGCombiner::visitFADD(SDNode *N) {
2485   SDOperand N0 = N->getOperand(0);
2486   SDOperand N1 = N->getOperand(1);
2487   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2488   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2489   MVT::ValueType VT = N->getValueType(0);
2490   
2491   // fold (fadd c1, c2) -> c1+c2
2492   if (N0CFP && N1CFP)
2493     return DAG.getNode(ISD::FADD, VT, N0, N1);
2494   // canonicalize constant to RHS
2495   if (N0CFP && !N1CFP)
2496     return DAG.getNode(ISD::FADD, VT, N1, N0);
2497   // fold (A + (-B)) -> A-B
2498   if (N1.getOpcode() == ISD::FNEG)
2499     return DAG.getNode(ISD::FSUB, VT, N0, N1.getOperand(0));
2500   // fold ((-A) + B) -> B-A
2501   if (N0.getOpcode() == ISD::FNEG)
2502     return DAG.getNode(ISD::FSUB, VT, N1, N0.getOperand(0));
2503   return SDOperand();
2504 }
2505
2506 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
2507   SDOperand N0 = N->getOperand(0);
2508   SDOperand N1 = N->getOperand(1);
2509   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2510   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2511   MVT::ValueType VT = N->getValueType(0);
2512   
2513   // fold (fsub c1, c2) -> c1-c2
2514   if (N0CFP && N1CFP)
2515     return DAG.getNode(ISD::FSUB, VT, N0, N1);
2516   // fold (A-(-B)) -> A+B
2517   if (N1.getOpcode() == ISD::FNEG)
2518     return DAG.getNode(ISD::FADD, VT, N0, N1.getOperand(0));
2519   return SDOperand();
2520 }
2521
2522 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
2523   SDOperand N0 = N->getOperand(0);
2524   SDOperand N1 = N->getOperand(1);
2525   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2526   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2527   MVT::ValueType VT = N->getValueType(0);
2528
2529   // fold (fmul c1, c2) -> c1*c2
2530   if (N0CFP && N1CFP)
2531     return DAG.getNode(ISD::FMUL, VT, N0, N1);
2532   // canonicalize constant to RHS
2533   if (N0CFP && !N1CFP)
2534     return DAG.getNode(ISD::FMUL, VT, N1, N0);
2535   // fold (fmul X, 2.0) -> (fadd X, X)
2536   if (N1CFP && N1CFP->isExactlyValue(+2.0))
2537     return DAG.getNode(ISD::FADD, VT, N0, N0);
2538   return SDOperand();
2539 }
2540
2541 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
2542   SDOperand N0 = N->getOperand(0);
2543   SDOperand N1 = N->getOperand(1);
2544   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2545   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2546   MVT::ValueType VT = N->getValueType(0);
2547
2548   // fold (fdiv c1, c2) -> c1/c2
2549   if (N0CFP && N1CFP)
2550     return DAG.getNode(ISD::FDIV, VT, N0, N1);
2551   return SDOperand();
2552 }
2553
2554 SDOperand DAGCombiner::visitFREM(SDNode *N) {
2555   SDOperand N0 = N->getOperand(0);
2556   SDOperand N1 = N->getOperand(1);
2557   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2558   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2559   MVT::ValueType VT = N->getValueType(0);
2560
2561   // fold (frem c1, c2) -> fmod(c1,c2)
2562   if (N0CFP && N1CFP)
2563     return DAG.getNode(ISD::FREM, VT, N0, N1);
2564   return SDOperand();
2565 }
2566
2567 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
2568   SDOperand N0 = N->getOperand(0);
2569   SDOperand N1 = N->getOperand(1);
2570   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2571   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2572   MVT::ValueType VT = N->getValueType(0);
2573
2574   if (N0CFP && N1CFP)  // Constant fold
2575     return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
2576   
2577   if (N1CFP) {
2578     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
2579     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
2580     union {
2581       double d;
2582       int64_t i;
2583     } u;
2584     u.d = N1CFP->getValue();
2585     if (u.i >= 0)
2586       return DAG.getNode(ISD::FABS, VT, N0);
2587     else
2588       return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
2589   }
2590   
2591   // copysign(fabs(x), y) -> copysign(x, y)
2592   // copysign(fneg(x), y) -> copysign(x, y)
2593   // copysign(copysign(x,z), y) -> copysign(x, y)
2594   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
2595       N0.getOpcode() == ISD::FCOPYSIGN)
2596     return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
2597
2598   // copysign(x, abs(y)) -> abs(x)
2599   if (N1.getOpcode() == ISD::FABS)
2600     return DAG.getNode(ISD::FABS, VT, N0);
2601   
2602   // copysign(x, copysign(y,z)) -> copysign(x, z)
2603   if (N1.getOpcode() == ISD::FCOPYSIGN)
2604     return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
2605   
2606   // copysign(x, fp_extend(y)) -> copysign(x, y)
2607   // copysign(x, fp_round(y)) -> copysign(x, y)
2608   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
2609     return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
2610   
2611   return SDOperand();
2612 }
2613
2614
2615
2616 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
2617   SDOperand N0 = N->getOperand(0);
2618   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2619   MVT::ValueType VT = N->getValueType(0);
2620   
2621   // fold (sint_to_fp c1) -> c1fp
2622   if (N0C)
2623     return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
2624   return SDOperand();
2625 }
2626
2627 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
2628   SDOperand N0 = N->getOperand(0);
2629   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2630   MVT::ValueType VT = N->getValueType(0);
2631
2632   // fold (uint_to_fp c1) -> c1fp
2633   if (N0C)
2634     return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
2635   return SDOperand();
2636 }
2637
2638 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
2639   SDOperand N0 = N->getOperand(0);
2640   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2641   MVT::ValueType VT = N->getValueType(0);
2642   
2643   // fold (fp_to_sint c1fp) -> c1
2644   if (N0CFP)
2645     return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
2646   return SDOperand();
2647 }
2648
2649 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
2650   SDOperand N0 = N->getOperand(0);
2651   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2652   MVT::ValueType VT = N->getValueType(0);
2653   
2654   // fold (fp_to_uint c1fp) -> c1
2655   if (N0CFP)
2656     return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
2657   return SDOperand();
2658 }
2659
2660 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
2661   SDOperand N0 = N->getOperand(0);
2662   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2663   MVT::ValueType VT = N->getValueType(0);
2664   
2665   // fold (fp_round c1fp) -> c1fp
2666   if (N0CFP)
2667     return DAG.getNode(ISD::FP_ROUND, VT, N0);
2668   
2669   // fold (fp_round (fp_extend x)) -> x
2670   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
2671     return N0.getOperand(0);
2672   
2673   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
2674   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
2675     SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0));
2676     AddToWorkList(Tmp.Val);
2677     return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
2678   }
2679   
2680   return SDOperand();
2681 }
2682
2683 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
2684   SDOperand N0 = N->getOperand(0);
2685   MVT::ValueType VT = N->getValueType(0);
2686   MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2687   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2688   
2689   // fold (fp_round_inreg c1fp) -> c1fp
2690   if (N0CFP) {
2691     SDOperand Round = DAG.getConstantFP(N0CFP->getValue(), EVT);
2692     return DAG.getNode(ISD::FP_EXTEND, VT, Round);
2693   }
2694   return SDOperand();
2695 }
2696
2697 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
2698   SDOperand N0 = N->getOperand(0);
2699   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2700   MVT::ValueType VT = N->getValueType(0);
2701   
2702   // fold (fp_extend c1fp) -> c1fp
2703   if (N0CFP)
2704     return DAG.getNode(ISD::FP_EXTEND, VT, N0);
2705   
2706   // fold (fpext (load x)) -> (fpext (fpround (extload x)))
2707   if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2708       (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2709     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2710     SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2711                                        LN0->getBasePtr(), LN0->getSrcValue(),
2712                                        LN0->getSrcValueOffset(),
2713                                        N0.getValueType());
2714     CombineTo(N, ExtLoad);
2715     CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad),
2716               ExtLoad.getValue(1));
2717     return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2718   }
2719   
2720   
2721   return SDOperand();
2722 }
2723
2724 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
2725   SDOperand N0 = N->getOperand(0);
2726   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2727   MVT::ValueType VT = N->getValueType(0);
2728
2729   // fold (fneg c1) -> -c1
2730   if (N0CFP)
2731     return DAG.getNode(ISD::FNEG, VT, N0);
2732   // fold (fneg (sub x, y)) -> (sub y, x)
2733   if (N0.getOpcode() == ISD::SUB)
2734     return DAG.getNode(ISD::SUB, VT, N0.getOperand(1), N0.getOperand(0));
2735   // fold (fneg (fneg x)) -> x
2736   if (N0.getOpcode() == ISD::FNEG)
2737     return N0.getOperand(0);
2738   return SDOperand();
2739 }
2740
2741 SDOperand DAGCombiner::visitFABS(SDNode *N) {
2742   SDOperand N0 = N->getOperand(0);
2743   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2744   MVT::ValueType VT = N->getValueType(0);
2745   
2746   // fold (fabs c1) -> fabs(c1)
2747   if (N0CFP)
2748     return DAG.getNode(ISD::FABS, VT, N0);
2749   // fold (fabs (fabs x)) -> (fabs x)
2750   if (N0.getOpcode() == ISD::FABS)
2751     return N->getOperand(0);
2752   // fold (fabs (fneg x)) -> (fabs x)
2753   // fold (fabs (fcopysign x, y)) -> (fabs x)
2754   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
2755     return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
2756   
2757   return SDOperand();
2758 }
2759
2760 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
2761   SDOperand Chain = N->getOperand(0);
2762   SDOperand N1 = N->getOperand(1);
2763   SDOperand N2 = N->getOperand(2);
2764   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2765   
2766   // never taken branch, fold to chain
2767   if (N1C && N1C->isNullValue())
2768     return Chain;
2769   // unconditional branch
2770   if (N1C && N1C->getValue() == 1)
2771     return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
2772   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
2773   // on the target.
2774   if (N1.getOpcode() == ISD::SETCC && 
2775       TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
2776     return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
2777                        N1.getOperand(0), N1.getOperand(1), N2);
2778   }
2779   return SDOperand();
2780 }
2781
2782 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
2783 //
2784 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
2785   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
2786   SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
2787   
2788   // Use SimplifySetCC  to simplify SETCC's.
2789   SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
2790   if (Simp.Val) AddToWorkList(Simp.Val);
2791
2792   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
2793
2794   // fold br_cc true, dest -> br dest (unconditional branch)
2795   if (SCCC && SCCC->getValue())
2796     return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
2797                        N->getOperand(4));
2798   // fold br_cc false, dest -> unconditional fall through
2799   if (SCCC && SCCC->isNullValue())
2800     return N->getOperand(0);
2801
2802   // fold to a simpler setcc
2803   if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
2804     return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0), 
2805                        Simp.getOperand(2), Simp.getOperand(0),
2806                        Simp.getOperand(1), N->getOperand(4));
2807   return SDOperand();
2808 }
2809
2810 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
2811   LoadSDNode *LD  = cast<LoadSDNode>(N);
2812   SDOperand Chain = LD->getChain();
2813   SDOperand Ptr   = LD->getBasePtr();
2814   
2815   // If there are no uses of the loaded value, change uses of the chain value
2816   // into uses of the chain input (i.e. delete the dead load).
2817   if (N->hasNUsesOfValue(0, 0))
2818     return CombineTo(N, DAG.getNode(ISD::UNDEF, N->getValueType(0)), Chain);
2819   
2820   // If this load is directly stored, replace the load value with the stored
2821   // value.
2822   // TODO: Handle store large -> read small portion.
2823   // TODO: Handle TRUNCSTORE/LOADEXT
2824   if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
2825     if (ISD::isNON_TRUNCStore(Chain.Val)) {
2826       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
2827       if (PrevST->getBasePtr() == Ptr &&
2828           PrevST->getValue().getValueType() == N->getValueType(0))
2829       return CombineTo(N, Chain.getOperand(1), Chain);
2830     }
2831   }
2832     
2833   if (CombinerAA) {
2834     // Walk up chain skipping non-aliasing memory nodes.
2835     SDOperand BetterChain = FindBetterChain(N, Chain);
2836     
2837     // If there is a better chain.
2838     if (Chain != BetterChain) {
2839       SDOperand ReplLoad;
2840
2841       // Replace the chain to void dependency.
2842       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
2843         ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
2844                               LD->getSrcValue(), LD->getSrcValueOffset());
2845       } else {
2846         ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
2847                                   LD->getValueType(0),
2848                                   BetterChain, Ptr, LD->getSrcValue(),
2849                                   LD->getSrcValueOffset(),
2850                                   LD->getLoadedVT());
2851       }
2852
2853       // Create token factor to keep old chain connected.
2854       SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
2855                                     Chain, ReplLoad.getValue(1));
2856       
2857       // Replace uses with load result and token factor. Don't add users
2858       // to work list.
2859       return CombineTo(N, ReplLoad.getValue(0), Token, false);
2860     }
2861   }
2862
2863   // Try transforming N to an indexed load.
2864   if (CombineToIndexedLoadStore(N))
2865     return SDOperand(N, 0);
2866
2867   return SDOperand();
2868 }
2869
2870 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
2871   StoreSDNode *ST  = cast<StoreSDNode>(N);
2872   SDOperand Chain = ST->getChain();
2873   SDOperand Value = ST->getValue();
2874   SDOperand Ptr   = ST->getBasePtr();
2875   
2876   // If this is a store of a bit convert, store the input value.
2877   // FIXME: This needs to know that the resultant store does not need a 
2878   // higher alignment than the original.
2879   if (0 && Value.getOpcode() == ISD::BIT_CONVERT) {
2880     return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
2881                         ST->getSrcValueOffset());
2882   }
2883   
2884   if (CombinerAA) { 
2885     // Walk up chain skipping non-aliasing memory nodes.
2886     SDOperand BetterChain = FindBetterChain(N, Chain);
2887     
2888     // If there is a better chain.
2889     if (Chain != BetterChain) {
2890       // Replace the chain to avoid dependency.
2891       SDOperand ReplStore;
2892       if (ST->isTruncatingStore()) {
2893         ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
2894           ST->getSrcValue(),ST->getSrcValueOffset(), ST->getStoredVT());
2895       } else {
2896         ReplStore = DAG.getStore(BetterChain, Value, Ptr,
2897           ST->getSrcValue(), ST->getSrcValueOffset());
2898       }
2899       
2900       // Create token to keep both nodes around.
2901       SDOperand Token =
2902         DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
2903         
2904       // Don't add users to work list.
2905       return CombineTo(N, Token, false);
2906     }
2907   }
2908   
2909   return SDOperand();
2910 }
2911
2912 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
2913   SDOperand InVec = N->getOperand(0);
2914   SDOperand InVal = N->getOperand(1);
2915   SDOperand EltNo = N->getOperand(2);
2916   
2917   // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
2918   // vector with the inserted element.
2919   if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
2920     unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
2921     SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
2922     if (Elt < Ops.size())
2923       Ops[Elt] = InVal;
2924     return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
2925                        &Ops[0], Ops.size());
2926   }
2927   
2928   return SDOperand();
2929 }
2930
2931 SDOperand DAGCombiner::visitVINSERT_VECTOR_ELT(SDNode *N) {
2932   SDOperand InVec = N->getOperand(0);
2933   SDOperand InVal = N->getOperand(1);
2934   SDOperand EltNo = N->getOperand(2);
2935   SDOperand NumElts = N->getOperand(3);
2936   SDOperand EltType = N->getOperand(4);
2937   
2938   // If the invec is a VBUILD_VECTOR and if EltNo is a constant, build a new
2939   // vector with the inserted element.
2940   if (InVec.getOpcode() == ISD::VBUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
2941     unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
2942     SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
2943     if (Elt < Ops.size()-2)
2944       Ops[Elt] = InVal;
2945     return DAG.getNode(ISD::VBUILD_VECTOR, InVec.getValueType(),
2946                        &Ops[0], Ops.size());
2947   }
2948   
2949   return SDOperand();
2950 }
2951
2952 SDOperand DAGCombiner::visitVBUILD_VECTOR(SDNode *N) {
2953   unsigned NumInScalars = N->getNumOperands()-2;
2954   SDOperand NumElts = N->getOperand(NumInScalars);
2955   SDOperand EltType = N->getOperand(NumInScalars+1);
2956
2957   // Check to see if this is a VBUILD_VECTOR of a bunch of VEXTRACT_VECTOR_ELT
2958   // operations.  If so, and if the EXTRACT_ELT vector inputs come from at most
2959   // two distinct vectors, turn this into a shuffle node.
2960   SDOperand VecIn1, VecIn2;
2961   for (unsigned i = 0; i != NumInScalars; ++i) {
2962     // Ignore undef inputs.
2963     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
2964     
2965     // If this input is something other than a VEXTRACT_VECTOR_ELT with a
2966     // constant index, bail out.
2967     if (N->getOperand(i).getOpcode() != ISD::VEXTRACT_VECTOR_ELT ||
2968         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
2969       VecIn1 = VecIn2 = SDOperand(0, 0);
2970       break;
2971     }
2972     
2973     // If the input vector type disagrees with the result of the vbuild_vector,
2974     // we can't make a shuffle.
2975     SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
2976     if (*(ExtractedFromVec.Val->op_end()-2) != NumElts ||
2977         *(ExtractedFromVec.Val->op_end()-1) != EltType) {
2978       VecIn1 = VecIn2 = SDOperand(0, 0);
2979       break;
2980     }
2981     
2982     // Otherwise, remember this.  We allow up to two distinct input vectors.
2983     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
2984       continue;
2985     
2986     if (VecIn1.Val == 0) {
2987       VecIn1 = ExtractedFromVec;
2988     } else if (VecIn2.Val == 0) {
2989       VecIn2 = ExtractedFromVec;
2990     } else {
2991       // Too many inputs.
2992       VecIn1 = VecIn2 = SDOperand(0, 0);
2993       break;
2994     }
2995   }
2996   
2997   // If everything is good, we can make a shuffle operation.
2998   if (VecIn1.Val) {
2999     SmallVector<SDOperand, 8> BuildVecIndices;
3000     for (unsigned i = 0; i != NumInScalars; ++i) {
3001       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
3002         BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3003         continue;
3004       }
3005       
3006       SDOperand Extract = N->getOperand(i);
3007       
3008       // If extracting from the first vector, just use the index directly.
3009       if (Extract.getOperand(0) == VecIn1) {
3010         BuildVecIndices.push_back(Extract.getOperand(1));
3011         continue;
3012       }
3013
3014       // Otherwise, use InIdx + VecSize
3015       unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
3016       BuildVecIndices.push_back(DAG.getConstant(Idx+NumInScalars, MVT::i32));
3017     }
3018     
3019     // Add count and size info.
3020     BuildVecIndices.push_back(NumElts);
3021     BuildVecIndices.push_back(DAG.getValueType(MVT::i32));
3022     
3023     // Return the new VVECTOR_SHUFFLE node.
3024     SDOperand Ops[5];
3025     Ops[0] = VecIn1;
3026     if (VecIn2.Val) {
3027       Ops[1] = VecIn2;
3028     } else {
3029        // Use an undef vbuild_vector as input for the second operand.
3030       std::vector<SDOperand> UnOps(NumInScalars,
3031                                    DAG.getNode(ISD::UNDEF, 
3032                                            cast<VTSDNode>(EltType)->getVT()));
3033       UnOps.push_back(NumElts);
3034       UnOps.push_back(EltType);
3035       Ops[1] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3036                            &UnOps[0], UnOps.size());
3037       AddToWorkList(Ops[1].Val);
3038     }
3039     Ops[2] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3040                          &BuildVecIndices[0], BuildVecIndices.size());
3041     Ops[3] = NumElts;
3042     Ops[4] = EltType;
3043     return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, Ops, 5);
3044   }
3045   
3046   return SDOperand();
3047 }
3048
3049 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
3050   SDOperand ShufMask = N->getOperand(2);
3051   unsigned NumElts = ShufMask.getNumOperands();
3052
3053   // If the shuffle mask is an identity operation on the LHS, return the LHS.
3054   bool isIdentity = true;
3055   for (unsigned i = 0; i != NumElts; ++i) {
3056     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3057         cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
3058       isIdentity = false;
3059       break;
3060     }
3061   }
3062   if (isIdentity) return N->getOperand(0);
3063
3064   // If the shuffle mask is an identity operation on the RHS, return the RHS.
3065   isIdentity = true;
3066   for (unsigned i = 0; i != NumElts; ++i) {
3067     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3068         cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
3069       isIdentity = false;
3070       break;
3071     }
3072   }
3073   if (isIdentity) return N->getOperand(1);
3074
3075   // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
3076   // needed at all.
3077   bool isUnary = true;
3078   bool isSplat = true;
3079   int VecNum = -1;
3080   unsigned BaseIdx = 0;
3081   for (unsigned i = 0; i != NumElts; ++i)
3082     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
3083       unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
3084       int V = (Idx < NumElts) ? 0 : 1;
3085       if (VecNum == -1) {
3086         VecNum = V;
3087         BaseIdx = Idx;
3088       } else {
3089         if (BaseIdx != Idx)
3090           isSplat = false;
3091         if (VecNum != V) {
3092           isUnary = false;
3093           break;
3094         }
3095       }
3096     }
3097
3098   SDOperand N0 = N->getOperand(0);
3099   SDOperand N1 = N->getOperand(1);
3100   // Normalize unary shuffle so the RHS is undef.
3101   if (isUnary && VecNum == 1)
3102     std::swap(N0, N1);
3103
3104   // If it is a splat, check if the argument vector is a build_vector with
3105   // all scalar elements the same.
3106   if (isSplat) {
3107     SDNode *V = N0.Val;
3108     if (V->getOpcode() == ISD::BIT_CONVERT)
3109       V = V->getOperand(0).Val;
3110     if (V->getOpcode() == ISD::BUILD_VECTOR) {
3111       unsigned NumElems = V->getNumOperands()-2;
3112       if (NumElems > BaseIdx) {
3113         SDOperand Base;
3114         bool AllSame = true;
3115         for (unsigned i = 0; i != NumElems; ++i) {
3116           if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
3117             Base = V->getOperand(i);
3118             break;
3119           }
3120         }
3121         // Splat of <u, u, u, u>, return <u, u, u, u>
3122         if (!Base.Val)
3123           return N0;
3124         for (unsigned i = 0; i != NumElems; ++i) {
3125           if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
3126               V->getOperand(i) != Base) {
3127             AllSame = false;
3128             break;
3129           }
3130         }
3131         // Splat of <x, x, x, x>, return <x, x, x, x>
3132         if (AllSame)
3133           return N0;
3134       }
3135     }
3136   }
3137
3138   // If it is a unary or the LHS and the RHS are the same node, turn the RHS
3139   // into an undef.
3140   if (isUnary || N0 == N1) {
3141     if (N0.getOpcode() == ISD::UNDEF)
3142       return DAG.getNode(ISD::UNDEF, N->getValueType(0));
3143     // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
3144     // first operand.
3145     SmallVector<SDOperand, 8> MappedOps;
3146     for (unsigned i = 0, e = ShufMask.getNumOperands(); i != e; ++i) {
3147       if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
3148           cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
3149         MappedOps.push_back(ShufMask.getOperand(i));
3150       } else {
3151         unsigned NewIdx = 
3152            cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
3153         MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
3154       }
3155     }
3156     ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
3157                            &MappedOps[0], MappedOps.size());
3158     AddToWorkList(ShufMask.Val);
3159     return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
3160                        N0, 
3161                        DAG.getNode(ISD::UNDEF, N->getValueType(0)),
3162                        ShufMask);
3163   }
3164  
3165   return SDOperand();
3166 }
3167
3168 SDOperand DAGCombiner::visitVVECTOR_SHUFFLE(SDNode *N) {
3169   SDOperand ShufMask = N->getOperand(2);
3170   unsigned NumElts = ShufMask.getNumOperands()-2;
3171   
3172   // If the shuffle mask is an identity operation on the LHS, return the LHS.
3173   bool isIdentity = true;
3174   for (unsigned i = 0; i != NumElts; ++i) {
3175     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3176         cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
3177       isIdentity = false;
3178       break;
3179     }
3180   }
3181   if (isIdentity) return N->getOperand(0);
3182   
3183   // If the shuffle mask is an identity operation on the RHS, return the RHS.
3184   isIdentity = true;
3185   for (unsigned i = 0; i != NumElts; ++i) {
3186     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3187         cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
3188       isIdentity = false;
3189       break;
3190     }
3191   }
3192   if (isIdentity) return N->getOperand(1);
3193
3194   // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
3195   // needed at all.
3196   bool isUnary = true;
3197   bool isSplat = true;
3198   int VecNum = -1;
3199   unsigned BaseIdx = 0;
3200   for (unsigned i = 0; i != NumElts; ++i)
3201     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
3202       unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
3203       int V = (Idx < NumElts) ? 0 : 1;
3204       if (VecNum == -1) {
3205         VecNum = V;
3206         BaseIdx = Idx;
3207       } else {
3208         if (BaseIdx != Idx)
3209           isSplat = false;
3210         if (VecNum != V) {
3211           isUnary = false;
3212           break;
3213         }
3214       }
3215     }
3216
3217   SDOperand N0 = N->getOperand(0);
3218   SDOperand N1 = N->getOperand(1);
3219   // Normalize unary shuffle so the RHS is undef.
3220   if (isUnary && VecNum == 1)
3221     std::swap(N0, N1);
3222
3223   // If it is a splat, check if the argument vector is a build_vector with
3224   // all scalar elements the same.
3225   if (isSplat) {
3226     SDNode *V = N0.Val;
3227
3228     // If this is a vbit convert that changes the element type of the vector but
3229     // not the number of vector elements, look through it.  Be careful not to
3230     // look though conversions that change things like v4f32 to v2f64.
3231     if (V->getOpcode() == ISD::VBIT_CONVERT) {
3232       SDOperand ConvInput = V->getOperand(0);
3233       if (ConvInput.getValueType() == MVT::Vector &&
3234           NumElts ==
3235           ConvInput.getConstantOperandVal(ConvInput.getNumOperands()-2))
3236         V = ConvInput.Val;
3237     }
3238
3239     if (V->getOpcode() == ISD::VBUILD_VECTOR) {
3240       unsigned NumElems = V->getNumOperands()-2;
3241       if (NumElems > BaseIdx) {
3242         SDOperand Base;
3243         bool AllSame = true;
3244         for (unsigned i = 0; i != NumElems; ++i) {
3245           if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
3246             Base = V->getOperand(i);
3247             break;
3248           }
3249         }
3250         // Splat of <u, u, u, u>, return <u, u, u, u>
3251         if (!Base.Val)
3252           return N0;
3253         for (unsigned i = 0; i != NumElems; ++i) {
3254           if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
3255               V->getOperand(i) != Base) {
3256             AllSame = false;
3257             break;
3258           }
3259         }
3260         // Splat of <x, x, x, x>, return <x, x, x, x>
3261         if (AllSame)
3262           return N0;
3263       }
3264     }
3265   }
3266
3267   // If it is a unary or the LHS and the RHS are the same node, turn the RHS
3268   // into an undef.
3269   if (isUnary || N0 == N1) {
3270     // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
3271     // first operand.
3272     SmallVector<SDOperand, 8> MappedOps;
3273     for (unsigned i = 0; i != NumElts; ++i) {
3274       if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
3275           cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
3276         MappedOps.push_back(ShufMask.getOperand(i));
3277       } else {
3278         unsigned NewIdx = 
3279           cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
3280         MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
3281       }
3282     }
3283     // Add the type/#elts values.
3284     MappedOps.push_back(ShufMask.getOperand(NumElts));
3285     MappedOps.push_back(ShufMask.getOperand(NumElts+1));
3286
3287     ShufMask = DAG.getNode(ISD::VBUILD_VECTOR, ShufMask.getValueType(),
3288                            &MappedOps[0], MappedOps.size());
3289     AddToWorkList(ShufMask.Val);
3290     
3291     // Build the undef vector.
3292     SDOperand UDVal = DAG.getNode(ISD::UNDEF, MappedOps[0].getValueType());
3293     for (unsigned i = 0; i != NumElts; ++i)
3294       MappedOps[i] = UDVal;
3295     MappedOps[NumElts  ] = *(N0.Val->op_end()-2);
3296     MappedOps[NumElts+1] = *(N0.Val->op_end()-1);
3297     UDVal = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3298                         &MappedOps[0], MappedOps.size());
3299     
3300     return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, 
3301                        N0, UDVal, ShufMask,
3302                        MappedOps[NumElts], MappedOps[NumElts+1]);
3303   }
3304   
3305   return SDOperand();
3306 }
3307
3308 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
3309 /// a VAND to a vector_shuffle with the destination vector and a zero vector.
3310 /// e.g. VAND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
3311 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
3312 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
3313   SDOperand LHS = N->getOperand(0);
3314   SDOperand RHS = N->getOperand(1);
3315   if (N->getOpcode() == ISD::VAND) {
3316     SDOperand DstVecSize = *(LHS.Val->op_end()-2);
3317     SDOperand DstVecEVT  = *(LHS.Val->op_end()-1);
3318     if (RHS.getOpcode() == ISD::VBIT_CONVERT)
3319       RHS = RHS.getOperand(0);
3320     if (RHS.getOpcode() == ISD::VBUILD_VECTOR) {
3321       std::vector<SDOperand> IdxOps;
3322       unsigned NumOps = RHS.getNumOperands();
3323       unsigned NumElts = NumOps-2;
3324       MVT::ValueType EVT = cast<VTSDNode>(RHS.getOperand(NumOps-1))->getVT();
3325       for (unsigned i = 0; i != NumElts; ++i) {
3326         SDOperand Elt = RHS.getOperand(i);
3327         if (!isa<ConstantSDNode>(Elt))
3328           return SDOperand();
3329         else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
3330           IdxOps.push_back(DAG.getConstant(i, EVT));
3331         else if (cast<ConstantSDNode>(Elt)->isNullValue())
3332           IdxOps.push_back(DAG.getConstant(NumElts, EVT));
3333         else
3334           return SDOperand();
3335       }
3336
3337       // Let's see if the target supports this vector_shuffle.
3338       if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
3339         return SDOperand();
3340
3341       // Return the new VVECTOR_SHUFFLE node.
3342       SDOperand NumEltsNode = DAG.getConstant(NumElts, MVT::i32);
3343       SDOperand EVTNode = DAG.getValueType(EVT);
3344       std::vector<SDOperand> Ops;
3345       LHS = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, LHS, NumEltsNode,
3346                         EVTNode);
3347       Ops.push_back(LHS);
3348       AddToWorkList(LHS.Val);
3349       std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
3350       ZeroOps.push_back(NumEltsNode);
3351       ZeroOps.push_back(EVTNode);
3352       Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3353                                 &ZeroOps[0], ZeroOps.size()));
3354       IdxOps.push_back(NumEltsNode);
3355       IdxOps.push_back(EVTNode);
3356       Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3357                                 &IdxOps[0], IdxOps.size()));
3358       Ops.push_back(NumEltsNode);
3359       Ops.push_back(EVTNode);
3360       SDOperand Result = DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
3361                                      &Ops[0], Ops.size());
3362       if (NumEltsNode != DstVecSize || EVTNode != DstVecEVT) {
3363         Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
3364                              DstVecSize, DstVecEVT);
3365       }
3366       return Result;
3367     }
3368   }
3369   return SDOperand();
3370 }
3371
3372 /// visitVBinOp - Visit a binary vector operation, like VADD.  IntOp indicates
3373 /// the scalar operation of the vop if it is operating on an integer vector
3374 /// (e.g. ADD) and FPOp indicates the FP version (e.g. FADD).
3375 SDOperand DAGCombiner::visitVBinOp(SDNode *N, ISD::NodeType IntOp, 
3376                                    ISD::NodeType FPOp) {
3377   MVT::ValueType EltType = cast<VTSDNode>(*(N->op_end()-1))->getVT();
3378   ISD::NodeType ScalarOp = MVT::isInteger(EltType) ? IntOp : FPOp;
3379   SDOperand LHS = N->getOperand(0);
3380   SDOperand RHS = N->getOperand(1);
3381   SDOperand Shuffle = XformToShuffleWithZero(N);
3382   if (Shuffle.Val) return Shuffle;
3383
3384   // If the LHS and RHS are VBUILD_VECTOR nodes, see if we can constant fold
3385   // this operation.
3386   if (LHS.getOpcode() == ISD::VBUILD_VECTOR && 
3387       RHS.getOpcode() == ISD::VBUILD_VECTOR) {
3388     SmallVector<SDOperand, 8> Ops;
3389     for (unsigned i = 0, e = LHS.getNumOperands()-2; i != e; ++i) {
3390       SDOperand LHSOp = LHS.getOperand(i);
3391       SDOperand RHSOp = RHS.getOperand(i);
3392       // If these two elements can't be folded, bail out.
3393       if ((LHSOp.getOpcode() != ISD::UNDEF &&
3394            LHSOp.getOpcode() != ISD::Constant &&
3395            LHSOp.getOpcode() != ISD::ConstantFP) ||
3396           (RHSOp.getOpcode() != ISD::UNDEF &&
3397            RHSOp.getOpcode() != ISD::Constant &&
3398            RHSOp.getOpcode() != ISD::ConstantFP))
3399         break;
3400       // Can't fold divide by zero.
3401       if (N->getOpcode() == ISD::VSDIV || N->getOpcode() == ISD::VUDIV) {
3402         if ((RHSOp.getOpcode() == ISD::Constant &&
3403              cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
3404             (RHSOp.getOpcode() == ISD::ConstantFP &&
3405              !cast<ConstantFPSDNode>(RHSOp.Val)->getValue()))
3406           break;
3407       }
3408       Ops.push_back(DAG.getNode(ScalarOp, EltType, LHSOp, RHSOp));
3409       AddToWorkList(Ops.back().Val);
3410       assert((Ops.back().getOpcode() == ISD::UNDEF ||
3411               Ops.back().getOpcode() == ISD::Constant ||
3412               Ops.back().getOpcode() == ISD::ConstantFP) &&
3413              "Scalar binop didn't fold!");
3414     }
3415     
3416     if (Ops.size() == LHS.getNumOperands()-2) {
3417       Ops.push_back(*(LHS.Val->op_end()-2));
3418       Ops.push_back(*(LHS.Val->op_end()-1));
3419       return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
3420     }
3421   }
3422   
3423   return SDOperand();
3424 }
3425
3426 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
3427   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
3428   
3429   SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
3430                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
3431   // If we got a simplified select_cc node back from SimplifySelectCC, then
3432   // break it down into a new SETCC node, and a new SELECT node, and then return
3433   // the SELECT node, since we were called with a SELECT node.
3434   if (SCC.Val) {
3435     // Check to see if we got a select_cc back (to turn into setcc/select).
3436     // Otherwise, just return whatever node we got back, like fabs.
3437     if (SCC.getOpcode() == ISD::SELECT_CC) {
3438       SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
3439                                     SCC.getOperand(0), SCC.getOperand(1), 
3440                                     SCC.getOperand(4));
3441       AddToWorkList(SETCC.Val);
3442       return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
3443                          SCC.getOperand(3), SETCC);
3444     }
3445     return SCC;
3446   }
3447   return SDOperand();
3448 }
3449
3450 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
3451 /// are the two values being selected between, see if we can simplify the
3452 /// select.  Callers of this should assume that TheSelect is deleted if this
3453 /// returns true.  As such, they should return the appropriate thing (e.g. the
3454 /// node) back to the top-level of the DAG combiner loop to avoid it being
3455 /// looked at.
3456 ///
3457 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS, 
3458                                     SDOperand RHS) {
3459   
3460   // If this is a select from two identical things, try to pull the operation
3461   // through the select.
3462   if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
3463     // If this is a load and the token chain is identical, replace the select
3464     // of two loads with a load through a select of the address to load from.
3465     // This triggers in things like "select bool X, 10.0, 123.0" after the FP
3466     // constants have been dropped into the constant pool.
3467     if (LHS.getOpcode() == ISD::LOAD &&
3468         // Token chains must be identical.
3469         LHS.getOperand(0) == RHS.getOperand(0)) {
3470       LoadSDNode *LLD = cast<LoadSDNode>(LHS);
3471       LoadSDNode *RLD = cast<LoadSDNode>(RHS);
3472
3473       // If this is an EXTLOAD, the VT's must match.
3474       if (LLD->getLoadedVT() == RLD->getLoadedVT()) {
3475         // FIXME: this conflates two src values, discarding one.  This is not
3476         // the right thing to do, but nothing uses srcvalues now.  When they do,
3477         // turn SrcValue into a list of locations.
3478         SDOperand Addr;
3479         if (TheSelect->getOpcode() == ISD::SELECT)
3480           Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
3481                              TheSelect->getOperand(0), LLD->getBasePtr(),
3482                              RLD->getBasePtr());
3483         else
3484           Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
3485                              TheSelect->getOperand(0),
3486                              TheSelect->getOperand(1), 
3487                              LLD->getBasePtr(), RLD->getBasePtr(),
3488                              TheSelect->getOperand(4));
3489       
3490         SDOperand Load;
3491         if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
3492           Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
3493                              Addr,LLD->getSrcValue(), LLD->getSrcValueOffset());
3494         else {
3495           Load = DAG.getExtLoad(LLD->getExtensionType(),
3496                                 TheSelect->getValueType(0),
3497                                 LLD->getChain(), Addr, LLD->getSrcValue(),
3498                                 LLD->getSrcValueOffset(),
3499                                 LLD->getLoadedVT());
3500         }
3501         // Users of the select now use the result of the load.
3502         CombineTo(TheSelect, Load);
3503       
3504         // Users of the old loads now use the new load's chain.  We know the
3505         // old-load value is dead now.
3506         CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
3507         CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
3508         return true;
3509       }
3510     }
3511   }
3512   
3513   return false;
3514 }
3515
3516 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1, 
3517                                         SDOperand N2, SDOperand N3,
3518                                         ISD::CondCode CC) {
3519   
3520   MVT::ValueType VT = N2.getValueType();
3521   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
3522   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
3523   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
3524
3525   // Determine if the condition we're dealing with is constant
3526   SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
3527   if (SCC.Val) AddToWorkList(SCC.Val);
3528   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
3529
3530   // fold select_cc true, x, y -> x
3531   if (SCCC && SCCC->getValue())
3532     return N2;
3533   // fold select_cc false, x, y -> y
3534   if (SCCC && SCCC->getValue() == 0)
3535     return N3;
3536   
3537   // Check to see if we can simplify the select into an fabs node
3538   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
3539     // Allow either -0.0 or 0.0
3540     if (CFP->getValue() == 0.0) {
3541       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
3542       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
3543           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
3544           N2 == N3.getOperand(0))
3545         return DAG.getNode(ISD::FABS, VT, N0);
3546       
3547       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
3548       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
3549           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
3550           N2.getOperand(0) == N3)
3551         return DAG.getNode(ISD::FABS, VT, N3);
3552     }
3553   }
3554   
3555   // Check to see if we can perform the "gzip trick", transforming
3556   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
3557   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
3558       MVT::isInteger(N0.getValueType()) && 
3559       MVT::isInteger(N2.getValueType()) && 
3560       (N1C->isNullValue() ||                    // (a < 0) ? b : 0
3561        (N1C->getValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
3562     MVT::ValueType XType = N0.getValueType();
3563     MVT::ValueType AType = N2.getValueType();
3564     if (XType >= AType) {
3565       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
3566       // single-bit constant.
3567       if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
3568         unsigned ShCtV = Log2_64(N2C->getValue());
3569         ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
3570         SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
3571         SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
3572         AddToWorkList(Shift.Val);
3573         if (XType > AType) {
3574           Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
3575           AddToWorkList(Shift.Val);
3576         }
3577         return DAG.getNode(ISD::AND, AType, Shift, N2);
3578       }
3579       SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
3580                                     DAG.getConstant(MVT::getSizeInBits(XType)-1,
3581                                                     TLI.getShiftAmountTy()));
3582       AddToWorkList(Shift.Val);
3583       if (XType > AType) {
3584         Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
3585         AddToWorkList(Shift.Val);
3586       }
3587       return DAG.getNode(ISD::AND, AType, Shift, N2);
3588     }
3589   }
3590   
3591   // fold select C, 16, 0 -> shl C, 4
3592   if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
3593       TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
3594     // Get a SetCC of the condition
3595     // FIXME: Should probably make sure that setcc is legal if we ever have a
3596     // target where it isn't.
3597     SDOperand Temp, SCC;
3598     // cast from setcc result type to select result type
3599     if (AfterLegalize) {
3600       SCC  = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
3601       Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
3602     } else {
3603       SCC  = DAG.getSetCC(MVT::i1, N0, N1, CC);
3604       Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
3605     }
3606     AddToWorkList(SCC.Val);
3607     AddToWorkList(Temp.Val);
3608     // shl setcc result by log2 n2c
3609     return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
3610                        DAG.getConstant(Log2_64(N2C->getValue()),
3611                                        TLI.getShiftAmountTy()));
3612   }
3613     
3614   // Check to see if this is the equivalent of setcc
3615   // FIXME: Turn all of these into setcc if setcc if setcc is legal
3616   // otherwise, go ahead with the folds.
3617   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
3618     MVT::ValueType XType = N0.getValueType();
3619     if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
3620       SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
3621       if (Res.getValueType() != VT)
3622         Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
3623       return Res;
3624     }
3625     
3626     // seteq X, 0 -> srl (ctlz X, log2(size(X)))
3627     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 
3628         TLI.isOperationLegal(ISD::CTLZ, XType)) {
3629       SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
3630       return DAG.getNode(ISD::SRL, XType, Ctlz, 
3631                          DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
3632                                          TLI.getShiftAmountTy()));
3633     }
3634     // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
3635     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 
3636       SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
3637                                     N0);
3638       SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0, 
3639                                     DAG.getConstant(~0ULL, XType));
3640       return DAG.getNode(ISD::SRL, XType, 
3641                          DAG.getNode(ISD::AND, XType, NegN0, NotN0),
3642                          DAG.getConstant(MVT::getSizeInBits(XType)-1,
3643                                          TLI.getShiftAmountTy()));
3644     }
3645     // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
3646     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
3647       SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
3648                                    DAG.getConstant(MVT::getSizeInBits(XType)-1,
3649                                                    TLI.getShiftAmountTy()));
3650       return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
3651     }
3652   }
3653   
3654   // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
3655   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
3656   if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
3657       N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) {
3658     if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0))) {
3659       MVT::ValueType XType = N0.getValueType();
3660       if (SubC->isNullValue() && MVT::isInteger(XType)) {
3661         SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
3662                                     DAG.getConstant(MVT::getSizeInBits(XType)-1,
3663                                                     TLI.getShiftAmountTy()));
3664         SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
3665         AddToWorkList(Shift.Val);
3666         AddToWorkList(Add.Val);
3667         return DAG.getNode(ISD::XOR, XType, Add, Shift);
3668       }
3669     }
3670   }
3671
3672   return SDOperand();
3673 }
3674
3675 SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
3676                                      SDOperand N1, ISD::CondCode Cond,
3677                                      bool foldBooleans) {
3678   // These setcc operations always fold.
3679   switch (Cond) {
3680   default: break;
3681   case ISD::SETFALSE:
3682   case ISD::SETFALSE2: return DAG.getConstant(0, VT);
3683   case ISD::SETTRUE:
3684   case ISD::SETTRUE2:  return DAG.getConstant(1, VT);
3685   }
3686
3687   if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
3688     uint64_t C1 = N1C->getValue();
3689     if (isa<ConstantSDNode>(N0.Val)) {
3690       return DAG.FoldSetCC(VT, N0, N1, Cond);
3691     } else {
3692       // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3693       // equality comparison, then we're just comparing whether X itself is
3694       // zero.
3695       if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
3696           N0.getOperand(0).getOpcode() == ISD::CTLZ &&
3697           N0.getOperand(1).getOpcode() == ISD::Constant) {
3698         unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
3699         if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3700             ShAmt == Log2_32(MVT::getSizeInBits(N0.getValueType()))) {
3701           if ((C1 == 0) == (Cond == ISD::SETEQ)) {
3702             // (srl (ctlz x), 5) == 0  -> X != 0
3703             // (srl (ctlz x), 5) != 1  -> X != 0
3704             Cond = ISD::SETNE;
3705           } else {
3706             // (srl (ctlz x), 5) != 0  -> X == 0
3707             // (srl (ctlz x), 5) == 1  -> X == 0
3708             Cond = ISD::SETEQ;
3709           }
3710           SDOperand Zero = DAG.getConstant(0, N0.getValueType());
3711           return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0),
3712                               Zero, Cond);
3713         }
3714       }
3715       
3716       // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3717       if (N0.getOpcode() == ISD::ZERO_EXTEND) {
3718         unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
3719
3720         // If the comparison constant has bits in the upper part, the
3721         // zero-extended value could never match.
3722         if (C1 & (~0ULL << InSize)) {
3723           unsigned VSize = MVT::getSizeInBits(N0.getValueType());
3724           switch (Cond) {
3725           case ISD::SETUGT:
3726           case ISD::SETUGE:
3727           case ISD::SETEQ: return DAG.getConstant(0, VT);
3728           case ISD::SETULT:
3729           case ISD::SETULE:
3730           case ISD::SETNE: return DAG.getConstant(1, VT);
3731           case ISD::SETGT:
3732           case ISD::SETGE:
3733             // True if the sign bit of C1 is set.
3734             return DAG.getConstant((C1 & (1ULL << VSize)) != 0, VT);
3735           case ISD::SETLT:
3736           case ISD::SETLE:
3737             // True if the sign bit of C1 isn't set.
3738             return DAG.getConstant((C1 & (1ULL << VSize)) == 0, VT);
3739           default:
3740             break;
3741           }
3742         }
3743
3744         // Otherwise, we can perform the comparison with the low bits.
3745         switch (Cond) {
3746         case ISD::SETEQ:
3747         case ISD::SETNE:
3748         case ISD::SETUGT:
3749         case ISD::SETUGE:
3750         case ISD::SETULT:
3751         case ISD::SETULE:
3752           return DAG.getSetCC(VT, N0.getOperand(0),
3753                           DAG.getConstant(C1, N0.getOperand(0).getValueType()),
3754                           Cond);
3755         default:
3756           break;   // todo, be more careful with signed comparisons
3757         }
3758       } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3759                  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3760         MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
3761         unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
3762         MVT::ValueType ExtDstTy = N0.getValueType();
3763         unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
3764
3765         // If the extended part has any inconsistent bits, it cannot ever
3766         // compare equal.  In other words, they have to be all ones or all
3767         // zeros.
3768         uint64_t ExtBits =
3769           (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
3770         if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
3771           return DAG.getConstant(Cond == ISD::SETNE, VT);
3772         
3773         SDOperand ZextOp;
3774         MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
3775         if (Op0Ty == ExtSrcTy) {
3776           ZextOp = N0.getOperand(0);
3777         } else {
3778           int64_t Imm = ~0ULL >> (64-ExtSrcTyBits);
3779           ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
3780                                DAG.getConstant(Imm, Op0Ty));
3781         }
3782         AddToWorkList(ZextOp.Val);
3783         // Otherwise, make this a use of a zext.
3784         return DAG.getSetCC(VT, ZextOp, 
3785                             DAG.getConstant(C1 & (~0ULL>>(64-ExtSrcTyBits)), 
3786                                             ExtDstTy),
3787                             Cond);
3788       } else if ((N1C->getValue() == 0 || N1C->getValue() == 1) &&
3789                  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3790         
3791         // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
3792         if (N0.getOpcode() == ISD::SETCC) {
3793           bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getValue() != 1);
3794           if (TrueWhenTrue)
3795             return N0;
3796           
3797           // Invert the condition.
3798           ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
3799           CC = ISD::getSetCCInverse(CC, 
3800                                MVT::isInteger(N0.getOperand(0).getValueType()));
3801           return DAG.getSetCC(VT, N0.getOperand(0), N0.getOperand(1), CC);
3802         }
3803         
3804         if ((N0.getOpcode() == ISD::XOR ||
3805              (N0.getOpcode() == ISD::AND && 
3806               N0.getOperand(0).getOpcode() == ISD::XOR &&
3807               N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
3808             isa<ConstantSDNode>(N0.getOperand(1)) &&
3809             cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
3810           // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
3811           // can only do this if the top bits are known zero.
3812           if (TLI.MaskedValueIsZero(N0, 
3813                                     MVT::getIntVTBitMask(N0.getValueType())-1)){
3814             // Okay, get the un-inverted input value.
3815             SDOperand Val;
3816             if (N0.getOpcode() == ISD::XOR)
3817               Val = N0.getOperand(0);
3818             else {
3819               assert(N0.getOpcode() == ISD::AND && 
3820                      N0.getOperand(0).getOpcode() == ISD::XOR);
3821               // ((X^1)&1)^1 -> X & 1
3822               Val = DAG.getNode(ISD::AND, N0.getValueType(),
3823                                 N0.getOperand(0).getOperand(0),
3824                                 N0.getOperand(1));
3825             }
3826             return DAG.getSetCC(VT, Val, N1,
3827                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3828           }
3829         }
3830       }
3831       
3832       uint64_t MinVal, MaxVal;
3833       unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
3834       if (ISD::isSignedIntSetCC(Cond)) {
3835         MinVal = 1ULL << (OperandBitSize-1);
3836         if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
3837           MaxVal = ~0ULL >> (65-OperandBitSize);
3838         else
3839           MaxVal = 0;
3840       } else {
3841         MinVal = 0;
3842         MaxVal = ~0ULL >> (64-OperandBitSize);
3843       }
3844
3845       // Canonicalize GE/LE comparisons to use GT/LT comparisons.
3846       if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
3847         if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
3848         --C1;                                          // X >= C0 --> X > (C0-1)
3849         return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
3850                         (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
3851       }
3852
3853       if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
3854         if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
3855         ++C1;                                          // X <= C0 --> X < (C0+1)
3856         return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
3857                         (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
3858       }
3859
3860       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
3861         return DAG.getConstant(0, VT);      // X < MIN --> false
3862
3863       // Canonicalize setgt X, Min --> setne X, Min
3864       if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
3865         return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
3866       // Canonicalize setlt X, Max --> setne X, Max
3867       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
3868         return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
3869
3870       // If we have setult X, 1, turn it into seteq X, 0
3871       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
3872         return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
3873                         ISD::SETEQ);
3874       // If we have setugt X, Max-1, turn it into seteq X, Max
3875       else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
3876         return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
3877                         ISD::SETEQ);
3878
3879       // If we have "setcc X, C0", check to see if we can shrink the immediate
3880       // by changing cc.
3881
3882       // SETUGT X, SINTMAX  -> SETLT X, 0
3883       if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
3884           C1 == (~0ULL >> (65-OperandBitSize)))
3885         return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
3886                             ISD::SETLT);
3887
3888       // FIXME: Implement the rest of these.
3889
3890       // Fold bit comparisons when we can.
3891       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3892           VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
3893         if (ConstantSDNode *AndRHS =
3894                     dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3895           if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
3896             // Perform the xform if the AND RHS is a single bit.
3897             if (isPowerOf2_64(AndRHS->getValue())) {
3898               return DAG.getNode(ISD::SRL, VT, N0,
3899                              DAG.getConstant(Log2_64(AndRHS->getValue()),
3900                                                    TLI.getShiftAmountTy()));
3901             }
3902           } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
3903             // (X & 8) == 8  -->  (X & 8) >> 3
3904             // Perform the xform if C1 is a single bit.
3905             if (isPowerOf2_64(C1)) {
3906               return DAG.getNode(ISD::SRL, VT, N0,
3907                           DAG.getConstant(Log2_64(C1),TLI.getShiftAmountTy()));
3908             }
3909           }
3910         }
3911     }
3912   } else if (isa<ConstantSDNode>(N0.Val)) {
3913       // Ensure that the constant occurs on the RHS.
3914     return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
3915   }
3916
3917   if (isa<ConstantFPSDNode>(N0.Val)) {
3918     // Constant fold or commute setcc.
3919     SDOperand O = DAG.FoldSetCC(VT, N0, N1, Cond);    
3920     if (O.Val) return O;
3921   }
3922
3923   if (N0 == N1) {
3924     // We can always fold X == X for integer setcc's.
3925     if (MVT::isInteger(N0.getValueType()))
3926       return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
3927     unsigned UOF = ISD::getUnorderedFlavor(Cond);
3928     if (UOF == 2)   // FP operators that are undefined on NaNs.
3929       return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
3930     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
3931       return DAG.getConstant(UOF, VT);
3932     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
3933     // if it is not already.
3934     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
3935     if (NewCond != Cond)
3936       return DAG.getSetCC(VT, N0, N1, NewCond);
3937   }
3938
3939   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3940       MVT::isInteger(N0.getValueType())) {
3941     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
3942         N0.getOpcode() == ISD::XOR) {
3943       // Simplify (X+Y) == (X+Z) -->  Y == Z
3944       if (N0.getOpcode() == N1.getOpcode()) {
3945         if (N0.getOperand(0) == N1.getOperand(0))
3946           return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
3947         if (N0.getOperand(1) == N1.getOperand(1))
3948           return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
3949         if (DAG.isCommutativeBinOp(N0.getOpcode())) {
3950           // If X op Y == Y op X, try other combinations.
3951           if (N0.getOperand(0) == N1.getOperand(1))
3952             return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
3953           if (N0.getOperand(1) == N1.getOperand(0))
3954             return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
3955         }
3956       }
3957       
3958       if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
3959         if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3960           // Turn (X+C1) == C2 --> X == C2-C1
3961           if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
3962             return DAG.getSetCC(VT, N0.getOperand(0),
3963                               DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
3964                                 N0.getValueType()), Cond);
3965           }
3966           
3967           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
3968           if (N0.getOpcode() == ISD::XOR)
3969             // If we know that all of the inverted bits are zero, don't bother
3970             // performing the inversion.
3971             if (TLI.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getValue()))
3972               return DAG.getSetCC(VT, N0.getOperand(0),
3973                               DAG.getConstant(LHSR->getValue()^RHSC->getValue(),
3974                                               N0.getValueType()), Cond);
3975         }
3976         
3977         // Turn (C1-X) == C2 --> X == C1-C2
3978         if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
3979           if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
3980             return DAG.getSetCC(VT, N0.getOperand(1),
3981                              DAG.getConstant(SUBC->getValue()-RHSC->getValue(),
3982                                              N0.getValueType()), Cond);
3983           }
3984         }          
3985       }
3986
3987       // Simplify (X+Z) == X -->  Z == 0
3988       if (N0.getOperand(0) == N1)
3989         return DAG.getSetCC(VT, N0.getOperand(1),
3990                         DAG.getConstant(0, N0.getValueType()), Cond);
3991       if (N0.getOperand(1) == N1) {
3992         if (DAG.isCommutativeBinOp(N0.getOpcode()))
3993           return DAG.getSetCC(VT, N0.getOperand(0),
3994                           DAG.getConstant(0, N0.getValueType()), Cond);
3995         else {
3996           assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
3997           // (Z-X) == X  --> Z == X<<1
3998           SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
3999                                      N1, 
4000                                      DAG.getConstant(1,TLI.getShiftAmountTy()));
4001           AddToWorkList(SH.Val);
4002           return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
4003         }
4004       }
4005     }
4006
4007     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
4008         N1.getOpcode() == ISD::XOR) {
4009       // Simplify  X == (X+Z) -->  Z == 0
4010       if (N1.getOperand(0) == N0) {
4011         return DAG.getSetCC(VT, N1.getOperand(1),
4012                         DAG.getConstant(0, N1.getValueType()), Cond);
4013       } else if (N1.getOperand(1) == N0) {
4014         if (DAG.isCommutativeBinOp(N1.getOpcode())) {
4015           return DAG.getSetCC(VT, N1.getOperand(0),
4016                           DAG.getConstant(0, N1.getValueType()), Cond);
4017         } else {
4018           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
4019           // X == (Z-X)  --> X<<1 == Z
4020           SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0, 
4021                                      DAG.getConstant(1,TLI.getShiftAmountTy()));
4022           AddToWorkList(SH.Val);
4023           return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
4024         }
4025       }
4026     }
4027   }
4028
4029   // Fold away ALL boolean setcc's.
4030   SDOperand Temp;
4031   if (N0.getValueType() == MVT::i1 && foldBooleans) {
4032     switch (Cond) {
4033     default: assert(0 && "Unknown integer setcc!");
4034     case ISD::SETEQ:  // X == Y  -> (X^Y)^1
4035       Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
4036       N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
4037       AddToWorkList(Temp.Val);
4038       break;
4039     case ISD::SETNE:  // X != Y   -->  (X^Y)
4040       N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
4041       break;
4042     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
4043     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
4044       Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
4045       N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
4046       AddToWorkList(Temp.Val);
4047       break;
4048     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
4049     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
4050       Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
4051       N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
4052       AddToWorkList(Temp.Val);
4053       break;
4054     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
4055     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
4056       Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
4057       N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
4058       AddToWorkList(Temp.Val);
4059       break;
4060     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
4061     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
4062       Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
4063       N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
4064       break;
4065     }
4066     if (VT != MVT::i1) {
4067       AddToWorkList(N0.Val);
4068       // FIXME: If running after legalize, we probably can't do this.
4069       N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
4070     }
4071     return N0;
4072   }
4073
4074   // Could not fold it.
4075   return SDOperand();
4076 }
4077
4078 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
4079 /// return a DAG expression to select that will generate the same value by
4080 /// multiplying by a magic number.  See:
4081 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4082 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
4083   std::vector<SDNode*> Built;
4084   SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
4085
4086   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4087        ii != ee; ++ii)
4088     AddToWorkList(*ii);
4089   return S;
4090 }
4091
4092 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
4093 /// return a DAG expression to select that will generate the same value by
4094 /// multiplying by a magic number.  See:
4095 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4096 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
4097   std::vector<SDNode*> Built;
4098   SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
4099
4100   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4101        ii != ee; ++ii)
4102     AddToWorkList(*ii);
4103   return S;
4104 }
4105
4106 /// FindBaseOffset - Return true if base is known not to alias with anything
4107 /// but itself.  Provides base object and offset as results.
4108 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
4109   // Assume it is a primitive operation.
4110   Base = Ptr; Offset = 0;
4111   
4112   // If it's an adding a simple constant then integrate the offset.
4113   if (Base.getOpcode() == ISD::ADD) {
4114     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
4115       Base = Base.getOperand(0);
4116       Offset += C->getValue();
4117     }
4118   }
4119   
4120   // If it's any of the following then it can't alias with anything but itself.
4121   return isa<FrameIndexSDNode>(Base) ||
4122          isa<ConstantPoolSDNode>(Base) ||
4123          isa<GlobalAddressSDNode>(Base);
4124 }
4125
4126 /// isAlias - Return true if there is any possibility that the two addresses
4127 /// overlap.
4128 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
4129                           const Value *SrcValue1, int SrcValueOffset1,
4130                           SDOperand Ptr2, int64_t Size2,
4131                           const Value *SrcValue2, int SrcValueOffset2)
4132 {
4133   // If they are the same then they must be aliases.
4134   if (Ptr1 == Ptr2) return true;
4135   
4136   // Gather base node and offset information.
4137   SDOperand Base1, Base2;
4138   int64_t Offset1, Offset2;
4139   bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
4140   bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
4141   
4142   // If they have a same base address then...
4143   if (Base1 == Base2) {
4144     // Check to see if the addresses overlap.
4145     return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
4146   }
4147   
4148   // If we know both bases then they can't alias.
4149   if (KnownBase1 && KnownBase2) return false;
4150
4151   if (CombinerGlobalAA) {
4152     // Use alias analysis information.
4153     int Overlap1 = Size1 + SrcValueOffset1 + Offset1;
4154     int Overlap2 = Size2 + SrcValueOffset2 + Offset2;
4155     AliasAnalysis::AliasResult AAResult = 
4156                              AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
4157     if (AAResult == AliasAnalysis::NoAlias)
4158       return false;
4159   }
4160
4161   // Otherwise we have to assume they alias.
4162   return true;
4163 }
4164
4165 /// FindAliasInfo - Extracts the relevant alias information from the memory
4166 /// node.  Returns true if the operand was a load.
4167 bool DAGCombiner::FindAliasInfo(SDNode *N,
4168                         SDOperand &Ptr, int64_t &Size,
4169                         const Value *&SrcValue, int &SrcValueOffset) {
4170   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4171     Ptr = LD->getBasePtr();
4172     Size = MVT::getSizeInBits(LD->getLoadedVT()) >> 3;
4173     SrcValue = LD->getSrcValue();
4174     SrcValueOffset = LD->getSrcValueOffset();
4175     return true;
4176   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4177     Ptr = ST->getBasePtr();
4178     Size = MVT::getSizeInBits(ST->getStoredVT()) >> 3;
4179     SrcValue = ST->getSrcValue();
4180     SrcValueOffset = ST->getSrcValueOffset();
4181   } else {
4182     assert(0 && "FindAliasInfo expected a memory operand");
4183   }
4184   
4185   return false;
4186 }
4187
4188 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
4189 /// looking for aliasing nodes and adding them to the Aliases vector.
4190 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
4191                                    SmallVector<SDOperand, 8> &Aliases) {
4192   SmallVector<SDOperand, 8> Chains;     // List of chains to visit.
4193   std::set<SDNode *> Visited;           // Visited node set.
4194   
4195   // Get alias information for node.
4196   SDOperand Ptr;
4197   int64_t Size;
4198   const Value *SrcValue;
4199   int SrcValueOffset;
4200   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
4201
4202   // Starting off.
4203   Chains.push_back(OriginalChain);
4204   
4205   // Look at each chain and determine if it is an alias.  If so, add it to the
4206   // aliases list.  If not, then continue up the chain looking for the next
4207   // candidate.  
4208   while (!Chains.empty()) {
4209     SDOperand Chain = Chains.back();
4210     Chains.pop_back();
4211     
4212      // Don't bother if we've been before.
4213     if (Visited.find(Chain.Val) != Visited.end()) continue;
4214     Visited.insert(Chain.Val);
4215   
4216     switch (Chain.getOpcode()) {
4217     case ISD::EntryToken:
4218       // Entry token is ideal chain operand, but handled in FindBetterChain.
4219       break;
4220       
4221     case ISD::LOAD:
4222     case ISD::STORE: {
4223       // Get alias information for Chain.
4224       SDOperand OpPtr;
4225       int64_t OpSize;
4226       const Value *OpSrcValue;
4227       int OpSrcValueOffset;
4228       bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
4229                                     OpSrcValue, OpSrcValueOffset);
4230       
4231       // If chain is alias then stop here.
4232       if (!(IsLoad && IsOpLoad) &&
4233           isAlias(Ptr, Size, SrcValue, SrcValueOffset,
4234                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
4235         Aliases.push_back(Chain);
4236       } else {
4237         // Look further up the chain.
4238         Chains.push_back(Chain.getOperand(0));      
4239         // Clean up old chain.
4240         AddToWorkList(Chain.Val);
4241       }
4242       break;
4243     }
4244     
4245     case ISD::TokenFactor:
4246       // We have to check each of the operands of the token factor, so we queue
4247       // then up.  Adding the  operands to the queue (stack) in reverse order
4248       // maintains the original order and increases the likelihood that getNode
4249       // will find a matching token factor (CSE.)
4250       for (unsigned n = Chain.getNumOperands(); n;)
4251         Chains.push_back(Chain.getOperand(--n));
4252       // Eliminate the token factor if we can.
4253       AddToWorkList(Chain.Val);
4254       break;
4255       
4256     default:
4257       // For all other instructions we will just have to take what we can get.
4258       Aliases.push_back(Chain);
4259       break;
4260     }
4261   }
4262 }
4263
4264 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
4265 /// for a better chain (aliasing node.)
4266 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
4267   SmallVector<SDOperand, 8> Aliases;  // Ops for replacing token factor.
4268   
4269   // Accumulate all the aliases to this node.
4270   GatherAllAliases(N, OldChain, Aliases);
4271   
4272   if (Aliases.size() == 0) {
4273     // If no operands then chain to entry token.
4274     return DAG.getEntryNode();
4275   } else if (Aliases.size() == 1) {
4276     // If a single operand then chain to it.  We don't need to revisit it.
4277     return Aliases[0];
4278   }
4279
4280   // Construct a custom tailored token factor.
4281   SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4282                                    &Aliases[0], Aliases.size());
4283
4284   // Make sure the old chain gets cleaned up.
4285   if (NewChain != OldChain) AddToWorkList(OldChain.Val);
4286   
4287   return NewChain;
4288 }
4289
4290 // SelectionDAG::Combine - This is the entry point for the file.
4291 //
4292 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
4293   /// run - This is the main entry point to this class.
4294   ///
4295   DAGCombiner(*this, AA).Run(RunningAfterLegalize);
4296 }