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