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