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