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