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