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