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