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