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