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