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