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