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