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