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