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