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