DAGCombiner.cpp revision 99257956e5562c6d206fa64bced563657519262d
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      TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
4124    if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4125      ShLeftAmt = N01->getZExtValue();
4126      N0 = N0.getOperand(0);
4127    }
4128  }
4129
4130  // Do not generate loads of non-round integer types since these can
4131  // be expensive (and would be wrong if the type is not byte sized).
4132  if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() &&
4133      cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() >= EVTBits &&
4134      // Do not change the width of a volatile load.
4135      !cast<LoadSDNode>(N0)->isVolatile()) {
4136    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4137    EVT PtrType = N0.getOperand(1).getValueType();
4138
4139    // For big endian targets, we need to adjust the offset to the pointer to
4140    // load the correct bytes.
4141    if (TLI.isBigEndian()) {
4142      unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
4143      unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
4144      ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
4145    }
4146
4147    uint64_t PtrOff =  ShAmt / 8;
4148    unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
4149    SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
4150                                 PtrType, LN0->getBasePtr(),
4151                                 DAG.getConstant(PtrOff, PtrType));
4152    AddToWorkList(NewPtr.getNode());
4153
4154    SDValue Load = (ExtType == ISD::NON_EXTLOAD)
4155      ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
4156                    LN0->getPointerInfo().getWithOffset(PtrOff),
4157                    LN0->isVolatile(), LN0->isNonTemporal(), NewAlign)
4158      : DAG.getExtLoad(ExtType, VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
4159                       LN0->getPointerInfo().getWithOffset(PtrOff),
4160                       ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
4161                       NewAlign);
4162
4163    // Replace the old load's chain with the new load's chain.
4164    WorkListRemover DeadNodes(*this);
4165    DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
4166                                  &DeadNodes);
4167
4168    // Shift the result left, if we've swallowed a left shift.
4169    SDValue Result = Load;
4170    if (ShLeftAmt != 0) {
4171      EVT ShImmTy = getShiftAmountTy();
4172      if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
4173        ShImmTy = VT;
4174      Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
4175                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
4176    }
4177
4178    // Return the new loaded value.
4179    return Result;
4180  }
4181
4182  return SDValue();
4183}
4184
4185SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
4186  SDValue N0 = N->getOperand(0);
4187  SDValue N1 = N->getOperand(1);
4188  EVT VT = N->getValueType(0);
4189  EVT EVT = cast<VTSDNode>(N1)->getVT();
4190  unsigned VTBits = VT.getScalarType().getSizeInBits();
4191  unsigned EVTBits = EVT.getScalarType().getSizeInBits();
4192
4193  // fold (sext_in_reg c1) -> c1
4194  if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
4195    return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
4196
4197  // If the input is already sign extended, just drop the extension.
4198  if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
4199    return N0;
4200
4201  // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
4202  if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4203      EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
4204    return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4205                       N0.getOperand(0), N1);
4206  }
4207
4208  // fold (sext_in_reg (sext x)) -> (sext x)
4209  // fold (sext_in_reg (aext x)) -> (sext x)
4210  // if x is small enough.
4211  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
4212    SDValue N00 = N0.getOperand(0);
4213    if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
4214        (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
4215      return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
4216  }
4217
4218  // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
4219  if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
4220    return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
4221
4222  // fold operands of sext_in_reg based on knowledge that the top bits are not
4223  // demanded.
4224  if (SimplifyDemandedBits(SDValue(N, 0)))
4225    return SDValue(N, 0);
4226
4227  // fold (sext_in_reg (load x)) -> (smaller sextload x)
4228  // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
4229  SDValue NarrowLoad = ReduceLoadWidth(N);
4230  if (NarrowLoad.getNode())
4231    return NarrowLoad;
4232
4233  // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
4234  // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
4235  // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
4236  if (N0.getOpcode() == ISD::SRL) {
4237    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
4238      if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
4239        // We can turn this into an SRA iff the input to the SRL is already sign
4240        // extended enough.
4241        unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
4242        if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
4243          return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
4244                             N0.getOperand(0), N0.getOperand(1));
4245      }
4246  }
4247
4248  // fold (sext_inreg (extload x)) -> (sextload x)
4249  if (ISD::isEXTLoad(N0.getNode()) &&
4250      ISD::isUNINDEXEDLoad(N0.getNode()) &&
4251      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4252      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4253       TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4254    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4255    SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
4256                                     LN0->getChain(),
4257                                     LN0->getBasePtr(), LN0->getPointerInfo(),
4258                                     EVT,
4259                                     LN0->isVolatile(), LN0->isNonTemporal(),
4260                                     LN0->getAlignment());
4261    CombineTo(N, ExtLoad);
4262    CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4263    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4264  }
4265  // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
4266  if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4267      N0.hasOneUse() &&
4268      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4269      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4270       TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4271    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4272    SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, N->getDebugLoc(),
4273                                     LN0->getChain(),
4274                                     LN0->getBasePtr(), LN0->getPointerInfo(),
4275                                     EVT,
4276                                     LN0->isVolatile(), LN0->isNonTemporal(),
4277                                     LN0->getAlignment());
4278    CombineTo(N, ExtLoad);
4279    CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4280    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4281  }
4282  return SDValue();
4283}
4284
4285SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4286  SDValue N0 = N->getOperand(0);
4287  EVT VT = N->getValueType(0);
4288
4289  // noop truncate
4290  if (N0.getValueType() == N->getValueType(0))
4291    return N0;
4292  // fold (truncate c1) -> c1
4293  if (isa<ConstantSDNode>(N0))
4294    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4295  // fold (truncate (truncate x)) -> (truncate x)
4296  if (N0.getOpcode() == ISD::TRUNCATE)
4297    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4298  // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4299  if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4300      N0.getOpcode() == ISD::SIGN_EXTEND ||
4301      N0.getOpcode() == ISD::ANY_EXTEND) {
4302    if (N0.getOperand(0).getValueType().bitsLT(VT))
4303      // if the source is smaller than the dest, we still need an extend
4304      return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4305                         N0.getOperand(0));
4306    else if (N0.getOperand(0).getValueType().bitsGT(VT))
4307      // if the source is larger than the dest, than we just need the truncate
4308      return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4309    else
4310      // if the source and dest are the same type, we can drop both the extend
4311      // and the truncate.
4312      return N0.getOperand(0);
4313  }
4314
4315  // See if we can simplify the input to this truncate through knowledge that
4316  // only the low bits are being used.  For example "trunc (or (shl x, 8), y)"
4317  // -> trunc y
4318  SDValue Shorter =
4319    GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4320                                             VT.getSizeInBits()));
4321  if (Shorter.getNode())
4322    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4323
4324  // fold (truncate (load x)) -> (smaller load x)
4325  // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4326  if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
4327    SDValue Reduced = ReduceLoadWidth(N);
4328    if (Reduced.getNode())
4329      return Reduced;
4330  }
4331
4332  // Simplify the operands using demanded-bits information.
4333  if (!VT.isVector() &&
4334      SimplifyDemandedBits(SDValue(N, 0)))
4335    return SDValue(N, 0);
4336
4337  return SDValue();
4338}
4339
4340static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4341  SDValue Elt = N->getOperand(i);
4342  if (Elt.getOpcode() != ISD::MERGE_VALUES)
4343    return Elt.getNode();
4344  return Elt.getOperand(Elt.getResNo()).getNode();
4345}
4346
4347/// CombineConsecutiveLoads - build_pair (load, load) -> load
4348/// if load locations are consecutive.
4349SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4350  assert(N->getOpcode() == ISD::BUILD_PAIR);
4351
4352  LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4353  LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4354  if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
4355      LD1->getPointerInfo().getAddrSpace() !=
4356         LD2->getPointerInfo().getAddrSpace())
4357    return SDValue();
4358  EVT LD1VT = LD1->getValueType(0);
4359
4360  if (ISD::isNON_EXTLoad(LD2) &&
4361      LD2->hasOneUse() &&
4362      // If both are volatile this would reduce the number of volatile loads.
4363      // If one is volatile it might be ok, but play conservative and bail out.
4364      !LD1->isVolatile() &&
4365      !LD2->isVolatile() &&
4366      DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4367    unsigned Align = LD1->getAlignment();
4368    unsigned NewAlign = TLI.getTargetData()->
4369      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4370
4371    if (NewAlign <= Align &&
4372        (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4373      return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4374                         LD1->getBasePtr(), LD1->getPointerInfo(),
4375                         false, false, Align);
4376  }
4377
4378  return SDValue();
4379}
4380
4381SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
4382  SDValue N0 = N->getOperand(0);
4383  EVT VT = N->getValueType(0);
4384
4385  // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4386  // Only do this before legalize, since afterward the target may be depending
4387  // on the bitconvert.
4388  // First check to see if this is all constant.
4389  if (!LegalTypes &&
4390      N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4391      VT.isVector()) {
4392    bool isSimple = true;
4393    for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4394      if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4395          N0.getOperand(i).getOpcode() != ISD::Constant &&
4396          N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
4397        isSimple = false;
4398        break;
4399      }
4400
4401    EVT DestEltVT = N->getValueType(0).getVectorElementType();
4402    assert(!DestEltVT.isVector() &&
4403           "Element type of vector ValueType must not be vector!");
4404    if (isSimple)
4405      return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
4406  }
4407
4408  // If the input is a constant, let getNode fold it.
4409  if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
4410    SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
4411    if (Res.getNode() != N) {
4412      if (!LegalOperations ||
4413          TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
4414        return Res;
4415
4416      // Folding it resulted in an illegal node, and it's too late to
4417      // do that. Clean up the old node and forego the transformation.
4418      // Ideally this won't happen very often, because instcombine
4419      // and the earlier dagcombine runs (where illegal nodes are
4420      // permitted) should have folded most of them already.
4421      DAG.DeleteNode(Res.getNode());
4422    }
4423  }
4424
4425  // (conv (conv x, t1), t2) -> (conv x, t2)
4426  if (N0.getOpcode() == ISD::BIT_CONVERT)
4427    return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
4428                       N0.getOperand(0));
4429
4430  // fold (conv (load x)) -> (load (conv*)x)
4431  // If the resultant load doesn't need a higher alignment than the original!
4432  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
4433      // Do not change the width of a volatile load.
4434      !cast<LoadSDNode>(N0)->isVolatile() &&
4435      (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
4436    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4437    unsigned Align = TLI.getTargetData()->
4438      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4439    unsigned OrigAlign = LN0->getAlignment();
4440
4441    if (Align <= OrigAlign) {
4442      SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
4443                                 LN0->getBasePtr(), LN0->getPointerInfo(),
4444                                 LN0->isVolatile(), LN0->isNonTemporal(),
4445                                 OrigAlign);
4446      AddToWorkList(N);
4447      CombineTo(N0.getNode(),
4448                DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4449                            N0.getValueType(), Load),
4450                Load.getValue(1));
4451      return Load;
4452    }
4453  }
4454
4455  // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
4456  // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
4457  // This often reduces constant pool loads.
4458  if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
4459      N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
4460    SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
4461                                  N0.getOperand(0));
4462    AddToWorkList(NewConv.getNode());
4463
4464    APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4465    if (N0.getOpcode() == ISD::FNEG)
4466      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
4467                         NewConv, DAG.getConstant(SignBit, VT));
4468    assert(N0.getOpcode() == ISD::FABS);
4469    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4470                       NewConv, DAG.getConstant(~SignBit, VT));
4471  }
4472
4473  // fold (bitconvert (fcopysign cst, x)) ->
4474  //         (or (and (bitconvert x), sign), (and cst, (not sign)))
4475  // Note that we don't handle (copysign x, cst) because this can always be
4476  // folded to an fneg or fabs.
4477  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
4478      isa<ConstantFPSDNode>(N0.getOperand(0)) &&
4479      VT.isInteger() && !VT.isVector()) {
4480    unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
4481    EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
4482    if (isTypeLegal(IntXVT)) {
4483      SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4484                              IntXVT, N0.getOperand(1));
4485      AddToWorkList(X.getNode());
4486
4487      // If X has a different width than the result/lhs, sext it or truncate it.
4488      unsigned VTWidth = VT.getSizeInBits();
4489      if (OrigXWidth < VTWidth) {
4490        X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
4491        AddToWorkList(X.getNode());
4492      } else if (OrigXWidth > VTWidth) {
4493        // To get the sign bit in the right place, we have to shift it right
4494        // before truncating.
4495        X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
4496                        X.getValueType(), X,
4497                        DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
4498        AddToWorkList(X.getNode());
4499        X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4500        AddToWorkList(X.getNode());
4501      }
4502
4503      APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4504      X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
4505                      X, DAG.getConstant(SignBit, VT));
4506      AddToWorkList(X.getNode());
4507
4508      SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4509                                VT, N0.getOperand(0));
4510      Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
4511                        Cst, DAG.getConstant(~SignBit, VT));
4512      AddToWorkList(Cst.getNode());
4513
4514      return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
4515    }
4516  }
4517
4518  // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
4519  if (N0.getOpcode() == ISD::BUILD_PAIR) {
4520    SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
4521    if (CombineLD.getNode())
4522      return CombineLD;
4523  }
4524
4525  return SDValue();
4526}
4527
4528SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
4529  EVT VT = N->getValueType(0);
4530  return CombineConsecutiveLoads(N, VT);
4531}
4532
4533/// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
4534/// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
4535/// destination element value type.
4536SDValue DAGCombiner::
4537ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
4538  EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
4539
4540  // If this is already the right type, we're done.
4541  if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
4542
4543  unsigned SrcBitSize = SrcEltVT.getSizeInBits();
4544  unsigned DstBitSize = DstEltVT.getSizeInBits();
4545
4546  // If this is a conversion of N elements of one type to N elements of another
4547  // type, convert each element.  This handles FP<->INT cases.
4548  if (SrcBitSize == DstBitSize) {
4549    EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4550                              BV->getValueType(0).getVectorNumElements());
4551
4552    // Due to the FP element handling below calling this routine recursively,
4553    // we can end up with a scalar-to-vector node here.
4554    if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
4555      return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4556                         DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
4557                                     DstEltVT, BV->getOperand(0)));
4558
4559    SmallVector<SDValue, 8> Ops;
4560    for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4561      SDValue Op = BV->getOperand(i);
4562      // If the vector element type is not legal, the BUILD_VECTOR operands
4563      // are promoted and implicitly truncated.  Make that explicit here.
4564      if (Op.getValueType() != SrcEltVT)
4565        Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4566      Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
4567                                DstEltVT, Op));
4568      AddToWorkList(Ops.back().getNode());
4569    }
4570    return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4571                       &Ops[0], Ops.size());
4572  }
4573
4574  // Otherwise, we're growing or shrinking the elements.  To avoid having to
4575  // handle annoying details of growing/shrinking FP values, we convert them to
4576  // int first.
4577  if (SrcEltVT.isFloatingPoint()) {
4578    // Convert the input float vector to a int vector where the elements are the
4579    // same sizes.
4580    assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4581    EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4582    BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
4583    SrcEltVT = IntVT;
4584  }
4585
4586  // Now we know the input is an integer vector.  If the output is a FP type,
4587  // convert to integer first, then to FP of the right size.
4588  if (DstEltVT.isFloatingPoint()) {
4589    assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4590    EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4591    SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
4592
4593    // Next, convert to FP elements of the same size.
4594    return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
4595  }
4596
4597  // Okay, we know the src/dst types are both integers of differing types.
4598  // Handling growing first.
4599  assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4600  if (SrcBitSize < DstBitSize) {
4601    unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4602
4603    SmallVector<SDValue, 8> Ops;
4604    for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4605         i += NumInputsPerOutput) {
4606      bool isLE = TLI.isLittleEndian();
4607      APInt NewBits = APInt(DstBitSize, 0);
4608      bool EltIsUndef = true;
4609      for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4610        // Shift the previously computed bits over.
4611        NewBits <<= SrcBitSize;
4612        SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4613        if (Op.getOpcode() == ISD::UNDEF) continue;
4614        EltIsUndef = false;
4615
4616        NewBits |= APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).
4617                   zextOrTrunc(SrcBitSize).zext(DstBitSize);
4618      }
4619
4620      if (EltIsUndef)
4621        Ops.push_back(DAG.getUNDEF(DstEltVT));
4622      else
4623        Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4624    }
4625
4626    EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4627    return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4628                       &Ops[0], Ops.size());
4629  }
4630
4631  // Finally, this must be the case where we are shrinking elements: each input
4632  // turns into multiple outputs.
4633  bool isS2V = ISD::isScalarToVector(BV);
4634  unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4635  EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4636                            NumOutputsPerInput*BV->getNumOperands());
4637  SmallVector<SDValue, 8> Ops;
4638
4639  for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4640    if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4641      for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4642        Ops.push_back(DAG.getUNDEF(DstEltVT));
4643      continue;
4644    }
4645
4646    APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))->
4647                        getAPIntValue()).zextOrTrunc(SrcBitSize);
4648
4649    for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4650      APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
4651      Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4652      if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
4653        // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4654        return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4655                           Ops[0]);
4656      OpVal = OpVal.lshr(DstBitSize);
4657    }
4658
4659    // For big endian targets, swap the order of the pieces of each element.
4660    if (TLI.isBigEndian())
4661      std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4662  }
4663
4664  return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4665                     &Ops[0], Ops.size());
4666}
4667
4668SDValue DAGCombiner::visitFADD(SDNode *N) {
4669  SDValue N0 = N->getOperand(0);
4670  SDValue N1 = N->getOperand(1);
4671  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4672  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4673  EVT VT = N->getValueType(0);
4674
4675  // fold vector ops
4676  if (VT.isVector()) {
4677    SDValue FoldedVOp = SimplifyVBinOp(N);
4678    if (FoldedVOp.getNode()) return FoldedVOp;
4679  }
4680
4681  // fold (fadd c1, c2) -> (fadd c1, c2)
4682  if (N0CFP && N1CFP && VT != MVT::ppcf128)
4683    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4684  // canonicalize constant to RHS
4685  if (N0CFP && !N1CFP)
4686    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4687  // fold (fadd A, 0) -> A
4688  if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4689    return N0;
4690  // fold (fadd A, (fneg B)) -> (fsub A, B)
4691  if (isNegatibleForFree(N1, LegalOperations) == 2)
4692    return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4693                       GetNegatedExpression(N1, DAG, LegalOperations));
4694  // fold (fadd (fneg A), B) -> (fsub B, A)
4695  if (isNegatibleForFree(N0, LegalOperations) == 2)
4696    return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4697                       GetNegatedExpression(N0, DAG, LegalOperations));
4698
4699  // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4700  if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4701      N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4702    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4703                       DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4704                                   N0.getOperand(1), N1));
4705
4706  return SDValue();
4707}
4708
4709SDValue DAGCombiner::visitFSUB(SDNode *N) {
4710  SDValue N0 = N->getOperand(0);
4711  SDValue N1 = N->getOperand(1);
4712  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4713  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4714  EVT VT = N->getValueType(0);
4715
4716  // fold vector ops
4717  if (VT.isVector()) {
4718    SDValue FoldedVOp = SimplifyVBinOp(N);
4719    if (FoldedVOp.getNode()) return FoldedVOp;
4720  }
4721
4722  // fold (fsub c1, c2) -> c1-c2
4723  if (N0CFP && N1CFP && VT != MVT::ppcf128)
4724    return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4725  // fold (fsub A, 0) -> A
4726  if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4727    return N0;
4728  // fold (fsub 0, B) -> -B
4729  if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4730    if (isNegatibleForFree(N1, LegalOperations))
4731      return GetNegatedExpression(N1, DAG, LegalOperations);
4732    if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4733      return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4734  }
4735  // fold (fsub A, (fneg B)) -> (fadd A, B)
4736  if (isNegatibleForFree(N1, LegalOperations))
4737    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4738                       GetNegatedExpression(N1, DAG, LegalOperations));
4739
4740  return SDValue();
4741}
4742
4743SDValue DAGCombiner::visitFMUL(SDNode *N) {
4744  SDValue N0 = N->getOperand(0);
4745  SDValue N1 = N->getOperand(1);
4746  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4747  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4748  EVT VT = N->getValueType(0);
4749
4750  // fold vector ops
4751  if (VT.isVector()) {
4752    SDValue FoldedVOp = SimplifyVBinOp(N);
4753    if (FoldedVOp.getNode()) return FoldedVOp;
4754  }
4755
4756  // fold (fmul c1, c2) -> c1*c2
4757  if (N0CFP && N1CFP && VT != MVT::ppcf128)
4758    return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4759  // canonicalize constant to RHS
4760  if (N0CFP && !N1CFP)
4761    return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4762  // fold (fmul A, 0) -> 0
4763  if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4764    return N1;
4765  // fold (fmul A, 0) -> 0, vector edition.
4766  if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4767    return N1;
4768  // fold (fmul X, 2.0) -> (fadd X, X)
4769  if (N1CFP && N1CFP->isExactlyValue(+2.0))
4770    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4771  // fold (fmul X, -1.0) -> (fneg X)
4772  if (N1CFP && N1CFP->isExactlyValue(-1.0))
4773    if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4774      return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4775
4776  // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4777  if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4778    if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4779      // Both can be negated for free, check to see if at least one is cheaper
4780      // negated.
4781      if (LHSNeg == 2 || RHSNeg == 2)
4782        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4783                           GetNegatedExpression(N0, DAG, LegalOperations),
4784                           GetNegatedExpression(N1, DAG, LegalOperations));
4785    }
4786  }
4787
4788  // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4789  if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4790      N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4791    return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4792                       DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4793                                   N0.getOperand(1), N1));
4794
4795  return SDValue();
4796}
4797
4798SDValue DAGCombiner::visitFDIV(SDNode *N) {
4799  SDValue N0 = N->getOperand(0);
4800  SDValue N1 = N->getOperand(1);
4801  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4802  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4803  EVT VT = N->getValueType(0);
4804
4805  // fold vector ops
4806  if (VT.isVector()) {
4807    SDValue FoldedVOp = SimplifyVBinOp(N);
4808    if (FoldedVOp.getNode()) return FoldedVOp;
4809  }
4810
4811  // fold (fdiv c1, c2) -> c1/c2
4812  if (N0CFP && N1CFP && VT != MVT::ppcf128)
4813    return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4814
4815
4816  // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4817  if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4818    if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4819      // Both can be negated for free, check to see if at least one is cheaper
4820      // negated.
4821      if (LHSNeg == 2 || RHSNeg == 2)
4822        return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4823                           GetNegatedExpression(N0, DAG, LegalOperations),
4824                           GetNegatedExpression(N1, DAG, LegalOperations));
4825    }
4826  }
4827
4828  return SDValue();
4829}
4830
4831SDValue DAGCombiner::visitFREM(SDNode *N) {
4832  SDValue N0 = N->getOperand(0);
4833  SDValue N1 = N->getOperand(1);
4834  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4835  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4836  EVT VT = N->getValueType(0);
4837
4838  // fold (frem c1, c2) -> fmod(c1,c2)
4839  if (N0CFP && N1CFP && VT != MVT::ppcf128)
4840    return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
4841
4842  return SDValue();
4843}
4844
4845SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
4846  SDValue N0 = N->getOperand(0);
4847  SDValue N1 = N->getOperand(1);
4848  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4849  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4850  EVT VT = N->getValueType(0);
4851
4852  if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
4853    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
4854
4855  if (N1CFP) {
4856    const APFloat& V = N1CFP->getValueAPF();
4857    // copysign(x, c1) -> fabs(x)       iff ispos(c1)
4858    // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
4859    if (!V.isNegative()) {
4860      if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
4861        return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4862    } else {
4863      if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4864        return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
4865                           DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
4866    }
4867  }
4868
4869  // copysign(fabs(x), y) -> copysign(x, y)
4870  // copysign(fneg(x), y) -> copysign(x, y)
4871  // copysign(copysign(x,z), y) -> copysign(x, y)
4872  if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
4873      N0.getOpcode() == ISD::FCOPYSIGN)
4874    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4875                       N0.getOperand(0), N1);
4876
4877  // copysign(x, abs(y)) -> abs(x)
4878  if (N1.getOpcode() == ISD::FABS)
4879    return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4880
4881  // copysign(x, copysign(y,z)) -> copysign(x, z)
4882  if (N1.getOpcode() == ISD::FCOPYSIGN)
4883    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4884                       N0, N1.getOperand(1));
4885
4886  // copysign(x, fp_extend(y)) -> copysign(x, y)
4887  // copysign(x, fp_round(y)) -> copysign(x, y)
4888  if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
4889    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4890                       N0, N1.getOperand(0));
4891
4892  return SDValue();
4893}
4894
4895SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
4896  SDValue N0 = N->getOperand(0);
4897  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4898  EVT VT = N->getValueType(0);
4899  EVT OpVT = N0.getValueType();
4900
4901  // fold (sint_to_fp c1) -> c1fp
4902  if (N0C && OpVT != MVT::ppcf128)
4903    return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4904
4905  // If the input is a legal type, and SINT_TO_FP is not legal on this target,
4906  // but UINT_TO_FP is legal on this target, try to convert.
4907  if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
4908      TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
4909    // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
4910    if (DAG.SignBitIsZero(N0))
4911      return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4912  }
4913
4914  return SDValue();
4915}
4916
4917SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
4918  SDValue N0 = N->getOperand(0);
4919  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4920  EVT VT = N->getValueType(0);
4921  EVT OpVT = N0.getValueType();
4922
4923  // fold (uint_to_fp c1) -> c1fp
4924  if (N0C && OpVT != MVT::ppcf128)
4925    return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4926
4927  // If the input is a legal type, and UINT_TO_FP is not legal on this target,
4928  // but SINT_TO_FP is legal on this target, try to convert.
4929  if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
4930      TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
4931    // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
4932    if (DAG.SignBitIsZero(N0))
4933      return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4934  }
4935
4936  return SDValue();
4937}
4938
4939SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
4940  SDValue N0 = N->getOperand(0);
4941  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4942  EVT VT = N->getValueType(0);
4943
4944  // fold (fp_to_sint c1fp) -> c1
4945  if (N0CFP)
4946    return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
4947
4948  return SDValue();
4949}
4950
4951SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
4952  SDValue N0 = N->getOperand(0);
4953  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4954  EVT VT = N->getValueType(0);
4955
4956  // fold (fp_to_uint c1fp) -> c1
4957  if (N0CFP && VT != MVT::ppcf128)
4958    return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
4959
4960  return SDValue();
4961}
4962
4963SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
4964  SDValue N0 = N->getOperand(0);
4965  SDValue N1 = N->getOperand(1);
4966  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4967  EVT VT = N->getValueType(0);
4968
4969  // fold (fp_round c1fp) -> c1fp
4970  if (N0CFP && N0.getValueType() != MVT::ppcf128)
4971    return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
4972
4973  // fold (fp_round (fp_extend x)) -> x
4974  if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4975    return N0.getOperand(0);
4976
4977  // fold (fp_round (fp_round x)) -> (fp_round x)
4978  if (N0.getOpcode() == ISD::FP_ROUND) {
4979    // This is a value preserving truncation if both round's are.
4980    bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4981                   N0.getNode()->getConstantOperandVal(1) == 1;
4982    return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
4983                       DAG.getIntPtrConstant(IsTrunc));
4984  }
4985
4986  // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4987  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4988    SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
4989                              N0.getOperand(0), N1);
4990    AddToWorkList(Tmp.getNode());
4991    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4992                       Tmp, N0.getOperand(1));
4993  }
4994
4995  return SDValue();
4996}
4997
4998SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4999  SDValue N0 = N->getOperand(0);
5000  EVT VT = N->getValueType(0);
5001  EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5002  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5003
5004  // fold (fp_round_inreg c1fp) -> c1fp
5005  if (N0CFP && isTypeLegal(EVT)) {
5006    SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
5007    return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
5008  }
5009
5010  return SDValue();
5011}
5012
5013SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
5014  SDValue N0 = N->getOperand(0);
5015  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5016  EVT VT = N->getValueType(0);
5017
5018  // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
5019  if (N->hasOneUse() &&
5020      N->use_begin()->getOpcode() == ISD::FP_ROUND)
5021    return SDValue();
5022
5023  // fold (fp_extend c1fp) -> c1fp
5024  if (N0CFP && VT != MVT::ppcf128)
5025    return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
5026
5027  // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
5028  // value of X.
5029  if (N0.getOpcode() == ISD::FP_ROUND
5030      && N0.getNode()->getConstantOperandVal(1) == 1) {
5031    SDValue In = N0.getOperand(0);
5032    if (In.getValueType() == VT) return In;
5033    if (VT.bitsLT(In.getValueType()))
5034      return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
5035                         In, N0.getOperand(1));
5036    return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
5037  }
5038
5039  // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
5040  if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
5041      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5042       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5043    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5044    SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, N->getDebugLoc(),
5045                                     LN0->getChain(),
5046                                     LN0->getBasePtr(), LN0->getPointerInfo(),
5047                                     N0.getValueType(),
5048                                     LN0->isVolatile(), LN0->isNonTemporal(),
5049                                     LN0->getAlignment());
5050    CombineTo(N, ExtLoad);
5051    CombineTo(N0.getNode(),
5052              DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
5053                          N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
5054              ExtLoad.getValue(1));
5055    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5056  }
5057
5058  return SDValue();
5059}
5060
5061SDValue DAGCombiner::visitFNEG(SDNode *N) {
5062  SDValue N0 = N->getOperand(0);
5063  EVT VT = N->getValueType(0);
5064
5065  if (isNegatibleForFree(N0, LegalOperations))
5066    return GetNegatedExpression(N0, DAG, LegalOperations);
5067
5068  // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
5069  // constant pool values.
5070  if (N0.getOpcode() == ISD::BIT_CONVERT &&
5071      !VT.isVector() &&
5072      N0.getNode()->hasOneUse() &&
5073      N0.getOperand(0).getValueType().isInteger()) {
5074    SDValue Int = N0.getOperand(0);
5075    EVT IntVT = Int.getValueType();
5076    if (IntVT.isInteger() && !IntVT.isVector()) {
5077      Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
5078              DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5079      AddToWorkList(Int.getNode());
5080      return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
5081                         VT, Int);
5082    }
5083  }
5084
5085  return SDValue();
5086}
5087
5088SDValue DAGCombiner::visitFABS(SDNode *N) {
5089  SDValue N0 = N->getOperand(0);
5090  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5091  EVT VT = N->getValueType(0);
5092
5093  // fold (fabs c1) -> fabs(c1)
5094  if (N0CFP && VT != MVT::ppcf128)
5095    return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5096  // fold (fabs (fabs x)) -> (fabs x)
5097  if (N0.getOpcode() == ISD::FABS)
5098    return N->getOperand(0);
5099  // fold (fabs (fneg x)) -> (fabs x)
5100  // fold (fabs (fcopysign x, y)) -> (fabs x)
5101  if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
5102    return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
5103
5104  // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
5105  // constant pool values.
5106  if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
5107      N0.getOperand(0).getValueType().isInteger() &&
5108      !N0.getOperand(0).getValueType().isVector()) {
5109    SDValue Int = N0.getOperand(0);
5110    EVT IntVT = Int.getValueType();
5111    if (IntVT.isInteger() && !IntVT.isVector()) {
5112      Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
5113             DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5114      AddToWorkList(Int.getNode());
5115      return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
5116                         N->getValueType(0), Int);
5117    }
5118  }
5119
5120  return SDValue();
5121}
5122
5123SDValue DAGCombiner::visitBRCOND(SDNode *N) {
5124  SDValue Chain = N->getOperand(0);
5125  SDValue N1 = N->getOperand(1);
5126  SDValue N2 = N->getOperand(2);
5127
5128  // If N is a constant we could fold this into a fallthrough or unconditional
5129  // branch. However that doesn't happen very often in normal code, because
5130  // Instcombine/SimplifyCFG should have handled the available opportunities.
5131  // If we did this folding here, it would be necessary to update the
5132  // MachineBasicBlock CFG, which is awkward.
5133
5134  // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
5135  // on the target.
5136  if (N1.getOpcode() == ISD::SETCC &&
5137      TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
5138    return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5139                       Chain, N1.getOperand(2),
5140                       N1.getOperand(0), N1.getOperand(1), N2);
5141  }
5142
5143  if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
5144      ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
5145       (N1.getOperand(0).hasOneUse() &&
5146        N1.getOperand(0).getOpcode() == ISD::SRL))) {
5147    SDNode *Trunc = 0;
5148    if (N1.getOpcode() == ISD::TRUNCATE) {
5149      // Look pass the truncate.
5150      Trunc = N1.getNode();
5151      N1 = N1.getOperand(0);
5152    }
5153
5154    // Match this pattern so that we can generate simpler code:
5155    //
5156    //   %a = ...
5157    //   %b = and i32 %a, 2
5158    //   %c = srl i32 %b, 1
5159    //   brcond i32 %c ...
5160    //
5161    // into
5162    //
5163    //   %a = ...
5164    //   %b = and i32 %a, 2
5165    //   %c = setcc eq %b, 0
5166    //   brcond %c ...
5167    //
5168    // This applies only when the AND constant value has one bit set and the
5169    // SRL constant is equal to the log2 of the AND constant. The back-end is
5170    // smart enough to convert the result into a TEST/JMP sequence.
5171    SDValue Op0 = N1.getOperand(0);
5172    SDValue Op1 = N1.getOperand(1);
5173
5174    if (Op0.getOpcode() == ISD::AND &&
5175        Op1.getOpcode() == ISD::Constant) {
5176      SDValue AndOp1 = Op0.getOperand(1);
5177
5178      if (AndOp1.getOpcode() == ISD::Constant) {
5179        const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
5180
5181        if (AndConst.isPowerOf2() &&
5182            cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
5183          SDValue SetCC =
5184            DAG.getSetCC(N->getDebugLoc(),
5185                         TLI.getSetCCResultType(Op0.getValueType()),
5186                         Op0, DAG.getConstant(0, Op0.getValueType()),
5187                         ISD::SETNE);
5188
5189          SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5190                                          MVT::Other, Chain, SetCC, N2);
5191          // Don't add the new BRCond into the worklist or else SimplifySelectCC
5192          // will convert it back to (X & C1) >> C2.
5193          CombineTo(N, NewBRCond, false);
5194          // Truncate is dead.
5195          if (Trunc) {
5196            removeFromWorkList(Trunc);
5197            DAG.DeleteNode(Trunc);
5198          }
5199          // Replace the uses of SRL with SETCC
5200          WorkListRemover DeadNodes(*this);
5201          DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5202          removeFromWorkList(N1.getNode());
5203          DAG.DeleteNode(N1.getNode());
5204          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5205        }
5206      }
5207    }
5208
5209    if (Trunc)
5210      // Restore N1 if the above transformation doesn't match.
5211      N1 = N->getOperand(1);
5212  }
5213
5214  // Transform br(xor(x, y)) -> br(x != y)
5215  // Transform br(xor(xor(x,y), 1)) -> br (x == y)
5216  if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
5217    SDNode *TheXor = N1.getNode();
5218    SDValue Op0 = TheXor->getOperand(0);
5219    SDValue Op1 = TheXor->getOperand(1);
5220    if (Op0.getOpcode() == Op1.getOpcode()) {
5221      // Avoid missing important xor optimizations.
5222      SDValue Tmp = visitXOR(TheXor);
5223      if (Tmp.getNode() && Tmp.getNode() != TheXor) {
5224        DEBUG(dbgs() << "\nReplacing.8 ";
5225              TheXor->dump(&DAG);
5226              dbgs() << "\nWith: ";
5227              Tmp.getNode()->dump(&DAG);
5228              dbgs() << '\n');
5229        WorkListRemover DeadNodes(*this);
5230        DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
5231        removeFromWorkList(TheXor);
5232        DAG.DeleteNode(TheXor);
5233        return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5234                           MVT::Other, Chain, Tmp, N2);
5235      }
5236    }
5237
5238    if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
5239      bool Equal = false;
5240      if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
5241        if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
5242            Op0.getOpcode() == ISD::XOR) {
5243          TheXor = Op0.getNode();
5244          Equal = true;
5245        }
5246
5247      EVT SetCCVT = N1.getValueType();
5248      if (LegalTypes)
5249        SetCCVT = TLI.getSetCCResultType(SetCCVT);
5250      SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
5251                                   SetCCVT,
5252                                   Op0, Op1,
5253                                   Equal ? ISD::SETEQ : ISD::SETNE);
5254      // Replace the uses of XOR with SETCC
5255      WorkListRemover DeadNodes(*this);
5256      DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5257      removeFromWorkList(N1.getNode());
5258      DAG.DeleteNode(N1.getNode());
5259      return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5260                         MVT::Other, Chain, SetCC, N2);
5261    }
5262  }
5263
5264  return SDValue();
5265}
5266
5267// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
5268//
5269SDValue DAGCombiner::visitBR_CC(SDNode *N) {
5270  CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
5271  SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
5272
5273  // If N is a constant we could fold this into a fallthrough or unconditional
5274  // branch. However that doesn't happen very often in normal code, because
5275  // Instcombine/SimplifyCFG should have handled the available opportunities.
5276  // If we did this folding here, it would be necessary to update the
5277  // MachineBasicBlock CFG, which is awkward.
5278
5279  // Use SimplifySetCC to simplify SETCC's.
5280  SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
5281                               CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
5282                               false);
5283  if (Simp.getNode()) AddToWorkList(Simp.getNode());
5284
5285  // fold to a simpler setcc
5286  if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
5287    return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5288                       N->getOperand(0), Simp.getOperand(2),
5289                       Simp.getOperand(0), Simp.getOperand(1),
5290                       N->getOperand(4));
5291
5292  return SDValue();
5293}
5294
5295/// CombineToPreIndexedLoadStore - Try turning a load / store into a
5296/// pre-indexed load / store when the base pointer is an add or subtract
5297/// and it has other uses besides the load / store. After the
5298/// transformation, the new indexed load / store has effectively folded
5299/// the add / subtract in and all of its other uses are redirected to the
5300/// new load / store.
5301bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
5302  if (!LegalOperations)
5303    return false;
5304
5305  bool isLoad = true;
5306  SDValue Ptr;
5307  EVT VT;
5308  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
5309    if (LD->isIndexed())
5310      return false;
5311    VT = LD->getMemoryVT();
5312    if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5313        !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5314      return false;
5315    Ptr = LD->getBasePtr();
5316  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
5317    if (ST->isIndexed())
5318      return false;
5319    VT = ST->getMemoryVT();
5320    if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5321        !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5322      return false;
5323    Ptr = ST->getBasePtr();
5324    isLoad = false;
5325  } else {
5326    return false;
5327  }
5328
5329  // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5330  // out.  There is no reason to make this a preinc/predec.
5331  if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5332      Ptr.getNode()->hasOneUse())
5333    return false;
5334
5335  // Ask the target to do addressing mode selection.
5336  SDValue BasePtr;
5337  SDValue Offset;
5338  ISD::MemIndexedMode AM = ISD::UNINDEXED;
5339  if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5340    return false;
5341  // Don't create a indexed load / store with zero offset.
5342  if (isa<ConstantSDNode>(Offset) &&
5343      cast<ConstantSDNode>(Offset)->isNullValue())
5344    return false;
5345
5346  // Try turning it into a pre-indexed load / store except when:
5347  // 1) The new base ptr is a frame index.
5348  // 2) If N is a store and the new base ptr is either the same as or is a
5349  //    predecessor of the value being stored.
5350  // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5351  //    that would create a cycle.
5352  // 4) All uses are load / store ops that use it as old base ptr.
5353
5354  // Check #1.  Preinc'ing a frame index would require copying the stack pointer
5355  // (plus the implicit offset) to a register to preinc anyway.
5356  if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5357    return false;
5358
5359  // Check #2.
5360  if (!isLoad) {
5361    SDValue Val = cast<StoreSDNode>(N)->getValue();
5362    if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5363      return false;
5364  }
5365
5366  // Now check for #3 and #4.
5367  bool RealUse = false;
5368  for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5369         E = Ptr.getNode()->use_end(); I != E; ++I) {
5370    SDNode *Use = *I;
5371    if (Use == N)
5372      continue;
5373    if (Use->isPredecessorOf(N))
5374      return false;
5375
5376    if (!((Use->getOpcode() == ISD::LOAD &&
5377           cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
5378          (Use->getOpcode() == ISD::STORE &&
5379           cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
5380      RealUse = true;
5381  }
5382
5383  if (!RealUse)
5384    return false;
5385
5386  SDValue Result;
5387  if (isLoad)
5388    Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5389                                BasePtr, Offset, AM);
5390  else
5391    Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5392                                 BasePtr, Offset, AM);
5393  ++PreIndexedNodes;
5394  ++NodesCombined;
5395  DEBUG(dbgs() << "\nReplacing.4 ";
5396        N->dump(&DAG);
5397        dbgs() << "\nWith: ";
5398        Result.getNode()->dump(&DAG);
5399        dbgs() << '\n');
5400  WorkListRemover DeadNodes(*this);
5401  if (isLoad) {
5402    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5403                                  &DeadNodes);
5404    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5405                                  &DeadNodes);
5406  } else {
5407    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5408                                  &DeadNodes);
5409  }
5410
5411  // Finally, since the node is now dead, remove it from the graph.
5412  DAG.DeleteNode(N);
5413
5414  // Replace the uses of Ptr with uses of the updated base value.
5415  DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
5416                                &DeadNodes);
5417  removeFromWorkList(Ptr.getNode());
5418  DAG.DeleteNode(Ptr.getNode());
5419
5420  return true;
5421}
5422
5423/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
5424/// add / sub of the base pointer node into a post-indexed load / store.
5425/// The transformation folded the add / subtract into the new indexed
5426/// load / store effectively and all of its uses are redirected to the
5427/// new load / store.
5428bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
5429  if (!LegalOperations)
5430    return false;
5431
5432  bool isLoad = true;
5433  SDValue Ptr;
5434  EVT VT;
5435  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
5436    if (LD->isIndexed())
5437      return false;
5438    VT = LD->getMemoryVT();
5439    if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
5440        !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
5441      return false;
5442    Ptr = LD->getBasePtr();
5443  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
5444    if (ST->isIndexed())
5445      return false;
5446    VT = ST->getMemoryVT();
5447    if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
5448        !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
5449      return false;
5450    Ptr = ST->getBasePtr();
5451    isLoad = false;
5452  } else {
5453    return false;
5454  }
5455
5456  if (Ptr.getNode()->hasOneUse())
5457    return false;
5458
5459  for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5460         E = Ptr.getNode()->use_end(); I != E; ++I) {
5461    SDNode *Op = *I;
5462    if (Op == N ||
5463        (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
5464      continue;
5465
5466    SDValue BasePtr;
5467    SDValue Offset;
5468    ISD::MemIndexedMode AM = ISD::UNINDEXED;
5469    if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
5470      // Don't create a indexed load / store with zero offset.
5471      if (isa<ConstantSDNode>(Offset) &&
5472          cast<ConstantSDNode>(Offset)->isNullValue())
5473        continue;
5474
5475      // Try turning it into a post-indexed load / store except when
5476      // 1) All uses are load / store ops that use it as base ptr.
5477      // 2) Op must be independent of N, i.e. Op is neither a predecessor
5478      //    nor a successor of N. Otherwise, if Op is folded that would
5479      //    create a cycle.
5480
5481      if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5482        continue;
5483
5484      // Check for #1.
5485      bool TryNext = false;
5486      for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
5487             EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
5488        SDNode *Use = *II;
5489        if (Use == Ptr.getNode())
5490          continue;
5491
5492        // If all the uses are load / store addresses, then don't do the
5493        // transformation.
5494        if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
5495          bool RealUse = false;
5496          for (SDNode::use_iterator III = Use->use_begin(),
5497                 EEE = Use->use_end(); III != EEE; ++III) {
5498            SDNode *UseUse = *III;
5499            if (!((UseUse->getOpcode() == ISD::LOAD &&
5500                   cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
5501                  (UseUse->getOpcode() == ISD::STORE &&
5502                   cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
5503              RealUse = true;
5504          }
5505
5506          if (!RealUse) {
5507            TryNext = true;
5508            break;
5509          }
5510        }
5511      }
5512
5513      if (TryNext)
5514        continue;
5515
5516      // Check for #2
5517      if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
5518        SDValue Result = isLoad
5519          ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5520                               BasePtr, Offset, AM)
5521          : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5522                                BasePtr, Offset, AM);
5523        ++PostIndexedNodes;
5524        ++NodesCombined;
5525        DEBUG(dbgs() << "\nReplacing.5 ";
5526              N->dump(&DAG);
5527              dbgs() << "\nWith: ";
5528              Result.getNode()->dump(&DAG);
5529              dbgs() << '\n');
5530        WorkListRemover DeadNodes(*this);
5531        if (isLoad) {
5532          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5533                                        &DeadNodes);
5534          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5535                                        &DeadNodes);
5536        } else {
5537          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5538                                        &DeadNodes);
5539        }
5540
5541        // Finally, since the node is now dead, remove it from the graph.
5542        DAG.DeleteNode(N);
5543
5544        // Replace the uses of Use with uses of the updated base value.
5545        DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
5546                                      Result.getValue(isLoad ? 1 : 0),
5547                                      &DeadNodes);
5548        removeFromWorkList(Op);
5549        DAG.DeleteNode(Op);
5550        return true;
5551      }
5552    }
5553  }
5554
5555  return false;
5556}
5557
5558SDValue DAGCombiner::visitLOAD(SDNode *N) {
5559  LoadSDNode *LD  = cast<LoadSDNode>(N);
5560  SDValue Chain = LD->getChain();
5561  SDValue Ptr   = LD->getBasePtr();
5562
5563  // If load is not volatile and there are no uses of the loaded value (and
5564  // the updated indexed value in case of indexed loads), change uses of the
5565  // chain value into uses of the chain input (i.e. delete the dead load).
5566  if (!LD->isVolatile()) {
5567    if (N->getValueType(1) == MVT::Other) {
5568      // Unindexed loads.
5569      if (N->hasNUsesOfValue(0, 0)) {
5570        // It's not safe to use the two value CombineTo variant here. e.g.
5571        // v1, chain2 = load chain1, loc
5572        // v2, chain3 = load chain2, loc
5573        // v3         = add v2, c
5574        // Now we replace use of chain2 with chain1.  This makes the second load
5575        // isomorphic to the one we are deleting, and thus makes this load live.
5576        DEBUG(dbgs() << "\nReplacing.6 ";
5577              N->dump(&DAG);
5578              dbgs() << "\nWith chain: ";
5579              Chain.getNode()->dump(&DAG);
5580              dbgs() << "\n");
5581        WorkListRemover DeadNodes(*this);
5582        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
5583
5584        if (N->use_empty()) {
5585          removeFromWorkList(N);
5586          DAG.DeleteNode(N);
5587        }
5588
5589        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5590      }
5591    } else {
5592      // Indexed loads.
5593      assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
5594      if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
5595        SDValue Undef = DAG.getUNDEF(N->getValueType(0));
5596        DEBUG(dbgs() << "\nReplacing.7 ";
5597              N->dump(&DAG);
5598              dbgs() << "\nWith: ";
5599              Undef.getNode()->dump(&DAG);
5600              dbgs() << " and 2 other values\n");
5601        WorkListRemover DeadNodes(*this);
5602        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
5603        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5604                                      DAG.getUNDEF(N->getValueType(1)),
5605                                      &DeadNodes);
5606        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5607        removeFromWorkList(N);
5608        DAG.DeleteNode(N);
5609        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5610      }
5611    }
5612  }
5613
5614  // If this load is directly stored, replace the load value with the stored
5615  // value.
5616  // TODO: Handle store large -> read small portion.
5617  // TODO: Handle TRUNCSTORE/LOADEXT
5618  if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
5619      !LD->isVolatile()) {
5620    if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5621      StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5622      if (PrevST->getBasePtr() == Ptr &&
5623          PrevST->getValue().getValueType() == N->getValueType(0))
5624      return CombineTo(N, Chain.getOperand(1), Chain);
5625    }
5626  }
5627
5628  // Try to infer better alignment information than the load already has.
5629  if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
5630    if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5631      if (Align > LD->getAlignment())
5632        return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
5633                              N->getDebugLoc(),
5634                              Chain, Ptr, LD->getPointerInfo(),
5635                              LD->getMemoryVT(),
5636                              LD->isVolatile(), LD->isNonTemporal(), Align);
5637    }
5638  }
5639
5640  if (CombinerAA) {
5641    // Walk up chain skipping non-aliasing memory nodes.
5642    SDValue BetterChain = FindBetterChain(N, Chain);
5643
5644    // If there is a better chain.
5645    if (Chain != BetterChain) {
5646      SDValue ReplLoad;
5647
5648      // Replace the chain to void dependency.
5649      if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5650        ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5651                               BetterChain, Ptr, LD->getPointerInfo(),
5652                               LD->isVolatile(), LD->isNonTemporal(),
5653                               LD->getAlignment());
5654      } else {
5655        ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
5656                                  LD->getDebugLoc(),
5657                                  BetterChain, Ptr, LD->getPointerInfo(),
5658                                  LD->getMemoryVT(),
5659                                  LD->isVolatile(),
5660                                  LD->isNonTemporal(),
5661                                  LD->getAlignment());
5662      }
5663
5664      // Create token factor to keep old chain connected.
5665      SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5666                                  MVT::Other, Chain, ReplLoad.getValue(1));
5667
5668      // Make sure the new and old chains are cleaned up.
5669      AddToWorkList(Token.getNode());
5670
5671      // Replace uses with load result and token factor. Don't add users
5672      // to work list.
5673      return CombineTo(N, ReplLoad.getValue(0), Token, false);
5674    }
5675  }
5676
5677  // Try transforming N to an indexed load.
5678  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5679    return SDValue(N, 0);
5680
5681  return SDValue();
5682}
5683
5684/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
5685/// load is having specific bytes cleared out.  If so, return the byte size
5686/// being masked out and the shift amount.
5687static std::pair<unsigned, unsigned>
5688CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
5689  std::pair<unsigned, unsigned> Result(0, 0);
5690
5691  // Check for the structure we're looking for.
5692  if (V->getOpcode() != ISD::AND ||
5693      !isa<ConstantSDNode>(V->getOperand(1)) ||
5694      !ISD::isNormalLoad(V->getOperand(0).getNode()))
5695    return Result;
5696
5697  // Check the chain and pointer.
5698  LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
5699  if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
5700
5701  // The store should be chained directly to the load or be an operand of a
5702  // tokenfactor.
5703  if (LD == Chain.getNode())
5704    ; // ok.
5705  else if (Chain->getOpcode() != ISD::TokenFactor)
5706    return Result; // Fail.
5707  else {
5708    bool isOk = false;
5709    for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
5710      if (Chain->getOperand(i).getNode() == LD) {
5711        isOk = true;
5712        break;
5713      }
5714    if (!isOk) return Result;
5715  }
5716
5717  // This only handles simple types.
5718  if (V.getValueType() != MVT::i16 &&
5719      V.getValueType() != MVT::i32 &&
5720      V.getValueType() != MVT::i64)
5721    return Result;
5722
5723  // Check the constant mask.  Invert it so that the bits being masked out are
5724  // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
5725  // follow the sign bit for uniformity.
5726  uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
5727  unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
5728  if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
5729  unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
5730  if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
5731  if (NotMaskLZ == 64) return Result;  // All zero mask.
5732
5733  // See if we have a continuous run of bits.  If so, we have 0*1+0*
5734  if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
5735    return Result;
5736
5737  // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
5738  if (V.getValueType() != MVT::i64 && NotMaskLZ)
5739    NotMaskLZ -= 64-V.getValueSizeInBits();
5740
5741  unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
5742  switch (MaskedBytes) {
5743  case 1:
5744  case 2:
5745  case 4: break;
5746  default: return Result; // All one mask, or 5-byte mask.
5747  }
5748
5749  // Verify that the first bit starts at a multiple of mask so that the access
5750  // is aligned the same as the access width.
5751  if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
5752
5753  Result.first = MaskedBytes;
5754  Result.second = NotMaskTZ/8;
5755  return Result;
5756}
5757
5758
5759/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
5760/// provides a value as specified by MaskInfo.  If so, replace the specified
5761/// store with a narrower store of truncated IVal.
5762static SDNode *
5763ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
5764                                SDValue IVal, StoreSDNode *St,
5765                                DAGCombiner *DC) {
5766  unsigned NumBytes = MaskInfo.first;
5767  unsigned ByteShift = MaskInfo.second;
5768  SelectionDAG &DAG = DC->getDAG();
5769
5770  // Check to see if IVal is all zeros in the part being masked in by the 'or'
5771  // that uses this.  If not, this is not a replacement.
5772  APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
5773                                  ByteShift*8, (ByteShift+NumBytes)*8);
5774  if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
5775
5776  // Check that it is legal on the target to do this.  It is legal if the new
5777  // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
5778  // legalization.
5779  MVT VT = MVT::getIntegerVT(NumBytes*8);
5780  if (!DC->isTypeLegal(VT))
5781    return 0;
5782
5783  // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
5784  // shifted by ByteShift and truncated down to NumBytes.
5785  if (ByteShift)
5786    IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
5787                       DAG.getConstant(ByteShift*8, DC->getShiftAmountTy()));
5788
5789  // Figure out the offset for the store and the alignment of the access.
5790  unsigned StOffset;
5791  unsigned NewAlign = St->getAlignment();
5792
5793  if (DAG.getTargetLoweringInfo().isLittleEndian())
5794    StOffset = ByteShift;
5795  else
5796    StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
5797
5798  SDValue Ptr = St->getBasePtr();
5799  if (StOffset) {
5800    Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
5801                      Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
5802    NewAlign = MinAlign(NewAlign, StOffset);
5803  }
5804
5805  // Truncate down to the new size.
5806  IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
5807
5808  ++OpsNarrowed;
5809  return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
5810                      St->getPointerInfo().getWithOffset(StOffset),
5811                      false, false, NewAlign).getNode();
5812}
5813
5814
5815/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
5816/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
5817/// of the loaded bits, try narrowing the load and store if it would end up
5818/// being a win for performance or code size.
5819SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
5820  StoreSDNode *ST  = cast<StoreSDNode>(N);
5821  if (ST->isVolatile())
5822    return SDValue();
5823
5824  SDValue Chain = ST->getChain();
5825  SDValue Value = ST->getValue();
5826  SDValue Ptr   = ST->getBasePtr();
5827  EVT VT = Value.getValueType();
5828
5829  if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
5830    return SDValue();
5831
5832  unsigned Opc = Value.getOpcode();
5833
5834  // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
5835  // is a byte mask indicating a consecutive number of bytes, check to see if
5836  // Y is known to provide just those bytes.  If so, we try to replace the
5837  // load + replace + store sequence with a single (narrower) store, which makes
5838  // the load dead.
5839  if (Opc == ISD::OR) {
5840    std::pair<unsigned, unsigned> MaskedLoad;
5841    MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
5842    if (MaskedLoad.first)
5843      if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
5844                                                  Value.getOperand(1), ST,this))
5845        return SDValue(NewST, 0);
5846
5847    // Or is commutative, so try swapping X and Y.
5848    MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
5849    if (MaskedLoad.first)
5850      if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
5851                                                  Value.getOperand(0), ST,this))
5852        return SDValue(NewST, 0);
5853  }
5854
5855  if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
5856      Value.getOperand(1).getOpcode() != ISD::Constant)
5857    return SDValue();
5858
5859  SDValue N0 = Value.getOperand(0);
5860  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5861      Chain == SDValue(N0.getNode(), 1)) {
5862    LoadSDNode *LD = cast<LoadSDNode>(N0);
5863    if (LD->getBasePtr() != Ptr ||
5864        LD->getPointerInfo().getAddrSpace() !=
5865        ST->getPointerInfo().getAddrSpace())
5866      return SDValue();
5867
5868    // Find the type to narrow it the load / op / store to.
5869    SDValue N1 = Value.getOperand(1);
5870    unsigned BitWidth = N1.getValueSizeInBits();
5871    APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
5872    if (Opc == ISD::AND)
5873      Imm ^= APInt::getAllOnesValue(BitWidth);
5874    if (Imm == 0 || Imm.isAllOnesValue())
5875      return SDValue();
5876    unsigned ShAmt = Imm.countTrailingZeros();
5877    unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
5878    unsigned NewBW = NextPowerOf2(MSB - ShAmt);
5879    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5880    while (NewBW < BitWidth &&
5881           !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
5882             TLI.isNarrowingProfitable(VT, NewVT))) {
5883      NewBW = NextPowerOf2(NewBW);
5884      NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5885    }
5886    if (NewBW >= BitWidth)
5887      return SDValue();
5888
5889    // If the lsb changed does not start at the type bitwidth boundary,
5890    // start at the previous one.
5891    if (ShAmt % NewBW)
5892      ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
5893    APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
5894    if ((Imm & Mask) == Imm) {
5895      APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
5896      if (Opc == ISD::AND)
5897        NewImm ^= APInt::getAllOnesValue(NewBW);
5898      uint64_t PtrOff = ShAmt / 8;
5899      // For big endian targets, we need to adjust the offset to the pointer to
5900      // load the correct bytes.
5901      if (TLI.isBigEndian())
5902        PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
5903
5904      unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
5905      const Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
5906      if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
5907        return SDValue();
5908
5909      SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
5910                                   Ptr.getValueType(), Ptr,
5911                                   DAG.getConstant(PtrOff, Ptr.getValueType()));
5912      SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
5913                                  LD->getChain(), NewPtr,
5914                                  LD->getPointerInfo().getWithOffset(PtrOff),
5915                                  LD->isVolatile(), LD->isNonTemporal(),
5916                                  NewAlign);
5917      SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
5918                                   DAG.getConstant(NewImm, NewVT));
5919      SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
5920                                   NewVal, NewPtr,
5921                                   ST->getPointerInfo().getWithOffset(PtrOff),
5922                                   false, false, NewAlign);
5923
5924      AddToWorkList(NewPtr.getNode());
5925      AddToWorkList(NewLD.getNode());
5926      AddToWorkList(NewVal.getNode());
5927      WorkListRemover DeadNodes(*this);
5928      DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
5929                                    &DeadNodes);
5930      ++OpsNarrowed;
5931      return NewST;
5932    }
5933  }
5934
5935  return SDValue();
5936}
5937
5938SDValue DAGCombiner::visitSTORE(SDNode *N) {
5939  StoreSDNode *ST  = cast<StoreSDNode>(N);
5940  SDValue Chain = ST->getChain();
5941  SDValue Value = ST->getValue();
5942  SDValue Ptr   = ST->getBasePtr();
5943
5944  // If this is a store of a bit convert, store the input value if the
5945  // resultant store does not need a higher alignment than the original.
5946  if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
5947      ST->isUnindexed()) {
5948    unsigned OrigAlign = ST->getAlignment();
5949    EVT SVT = Value.getOperand(0).getValueType();
5950    unsigned Align = TLI.getTargetData()->
5951      getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
5952    if (Align <= OrigAlign &&
5953        ((!LegalOperations && !ST->isVolatile()) ||
5954         TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
5955      return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5956                          Ptr, ST->getPointerInfo(), ST->isVolatile(),
5957                          ST->isNonTemporal(), OrigAlign);
5958  }
5959
5960  // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
5961  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
5962    // NOTE: If the original store is volatile, this transform must not increase
5963    // the number of stores.  For example, on x86-32 an f64 can be stored in one
5964    // processor operation but an i64 (which is not legal) requires two.  So the
5965    // transform should not be done in this case.
5966    if (Value.getOpcode() != ISD::TargetConstantFP) {
5967      SDValue Tmp;
5968      switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
5969      default: llvm_unreachable("Unknown FP type");
5970      case MVT::f80:    // We don't do this for these yet.
5971      case MVT::f128:
5972      case MVT::ppcf128:
5973        break;
5974      case MVT::f32:
5975        if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
5976            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5977          Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
5978                              bitcastToAPInt().getZExtValue(), MVT::i32);
5979          return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5980                              Ptr, ST->getPointerInfo(), ST->isVolatile(),
5981                              ST->isNonTemporal(), ST->getAlignment());
5982        }
5983        break;
5984      case MVT::f64:
5985        if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
5986             !ST->isVolatile()) ||
5987            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
5988          Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
5989                                getZExtValue(), MVT::i64);
5990          return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5991                              Ptr, ST->getPointerInfo(), ST->isVolatile(),
5992                              ST->isNonTemporal(), ST->getAlignment());
5993        } else if (!ST->isVolatile() &&
5994                   TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5995          // Many FP stores are not made apparent until after legalize, e.g. for
5996          // argument passing.  Since this is so common, custom legalize the
5997          // 64-bit integer store into two 32-bit stores.
5998          uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
5999          SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
6000          SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
6001          if (TLI.isBigEndian()) std::swap(Lo, Hi);
6002
6003          unsigned Alignment = ST->getAlignment();
6004          bool isVolatile = ST->isVolatile();
6005          bool isNonTemporal = ST->isNonTemporal();
6006
6007          SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
6008                                     Ptr, ST->getPointerInfo(),
6009                                     isVolatile, isNonTemporal,
6010                                     ST->getAlignment());
6011          Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
6012                            DAG.getConstant(4, Ptr.getValueType()));
6013          Alignment = MinAlign(Alignment, 4U);
6014          SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
6015                                     Ptr, ST->getPointerInfo().getWithOffset(4),
6016                                     isVolatile, isNonTemporal,
6017                                     Alignment);
6018          return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6019                             St0, St1);
6020        }
6021
6022        break;
6023      }
6024    }
6025  }
6026
6027  // Try to infer better alignment information than the store already has.
6028  if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
6029    if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6030      if (Align > ST->getAlignment())
6031        return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
6032                                 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6033                                 ST->isVolatile(), ST->isNonTemporal(), Align);
6034    }
6035  }
6036
6037  if (CombinerAA) {
6038    // Walk up chain skipping non-aliasing memory nodes.
6039    SDValue BetterChain = FindBetterChain(N, Chain);
6040
6041    // If there is a better chain.
6042    if (Chain != BetterChain) {
6043      SDValue ReplStore;
6044
6045      // Replace the chain to avoid dependency.
6046      if (ST->isTruncatingStore()) {
6047        ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6048                                      ST->getPointerInfo(),
6049                                      ST->getMemoryVT(), ST->isVolatile(),
6050                                      ST->isNonTemporal(), ST->getAlignment());
6051      } else {
6052        ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6053                                 ST->getPointerInfo(),
6054                                 ST->isVolatile(), ST->isNonTemporal(),
6055                                 ST->getAlignment());
6056      }
6057
6058      // Create token to keep both nodes around.
6059      SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6060                                  MVT::Other, Chain, ReplStore);
6061
6062      // Make sure the new and old chains are cleaned up.
6063      AddToWorkList(Token.getNode());
6064
6065      // Don't add users to work list.
6066      return CombineTo(N, Token, false);
6067    }
6068  }
6069
6070  // Try transforming N to an indexed store.
6071  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6072    return SDValue(N, 0);
6073
6074  // FIXME: is there such a thing as a truncating indexed store?
6075  if (ST->isTruncatingStore() && ST->isUnindexed() &&
6076      Value.getValueType().isInteger()) {
6077    // See if we can simplify the input to this truncstore with knowledge that
6078    // only the low bits are being used.  For example:
6079    // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
6080    SDValue Shorter =
6081      GetDemandedBits(Value,
6082                      APInt::getLowBitsSet(Value.getValueSizeInBits(),
6083                                           ST->getMemoryVT().getSizeInBits()));
6084    AddToWorkList(Value.getNode());
6085    if (Shorter.getNode())
6086      return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
6087                               Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6088                               ST->isVolatile(), ST->isNonTemporal(),
6089                               ST->getAlignment());
6090
6091    // Otherwise, see if we can simplify the operation with
6092    // SimplifyDemandedBits, which only works if the value has a single use.
6093    if (SimplifyDemandedBits(Value,
6094                             APInt::getLowBitsSet(
6095                               Value.getValueType().getScalarType().getSizeInBits(),
6096                               ST->getMemoryVT().getScalarType().getSizeInBits())))
6097      return SDValue(N, 0);
6098  }
6099
6100  // If this is a load followed by a store to the same location, then the store
6101  // is dead/noop.
6102  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
6103    if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
6104        ST->isUnindexed() && !ST->isVolatile() &&
6105        // There can't be any side effects between the load and store, such as
6106        // a call or store.
6107        Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
6108      // The store is dead, remove it.
6109      return Chain;
6110    }
6111  }
6112
6113  // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
6114  // truncating store.  We can do this even if this is already a truncstore.
6115  if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
6116      && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
6117      TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
6118                            ST->getMemoryVT())) {
6119    return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6120                             Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6121                             ST->isVolatile(), ST->isNonTemporal(),
6122                             ST->getAlignment());
6123  }
6124
6125  return ReduceLoadOpStoreWidth(N);
6126}
6127
6128SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
6129  SDValue InVec = N->getOperand(0);
6130  SDValue InVal = N->getOperand(1);
6131  SDValue EltNo = N->getOperand(2);
6132
6133  // If the inserted element is an UNDEF, just use the input vector.
6134  if (InVal.getOpcode() == ISD::UNDEF)
6135    return InVec;
6136
6137  // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
6138  // vector with the inserted element.
6139  if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
6140    unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6141    SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
6142                                InVec.getNode()->op_end());
6143    if (Elt < Ops.size())
6144      Ops[Elt] = InVal;
6145    return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6146                       InVec.getValueType(), &Ops[0], Ops.size());
6147  }
6148  // If the invec is an UNDEF and if EltNo is a constant, create a new
6149  // BUILD_VECTOR with undef elements and the inserted element.
6150  if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
6151      isa<ConstantSDNode>(EltNo)) {
6152    EVT VT = InVec.getValueType();
6153    EVT EltVT = VT.getVectorElementType();
6154    unsigned NElts = VT.getVectorNumElements();
6155    SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
6156
6157    unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6158    if (Elt < Ops.size())
6159      Ops[Elt] = InVal;
6160    return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6161                       InVec.getValueType(), &Ops[0], Ops.size());
6162  }
6163  return SDValue();
6164}
6165
6166SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
6167  // (vextract (scalar_to_vector val, 0) -> val
6168  SDValue InVec = N->getOperand(0);
6169
6170 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6171   // Check if the result type doesn't match the inserted element type. A
6172   // SCALAR_TO_VECTOR may truncate the inserted element and the
6173   // EXTRACT_VECTOR_ELT may widen the extracted vector.
6174   SDValue InOp = InVec.getOperand(0);
6175   EVT NVT = N->getValueType(0);
6176   if (InOp.getValueType() != NVT) {
6177     assert(InOp.getValueType().isInteger() && NVT.isInteger());
6178     return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
6179   }
6180   return InOp;
6181 }
6182
6183  // Perform only after legalization to ensure build_vector / vector_shuffle
6184  // optimizations have already been done.
6185  if (!LegalOperations) return SDValue();
6186
6187  // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
6188  // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
6189  // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
6190  SDValue EltNo = N->getOperand(1);
6191
6192  if (isa<ConstantSDNode>(EltNo)) {
6193    int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6194    bool NewLoad = false;
6195    bool BCNumEltsChanged = false;
6196    EVT VT = InVec.getValueType();
6197    EVT ExtVT = VT.getVectorElementType();
6198    EVT LVT = ExtVT;
6199
6200    if (InVec.getOpcode() == ISD::BIT_CONVERT) {
6201      EVT BCVT = InVec.getOperand(0).getValueType();
6202      if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
6203        return SDValue();
6204      if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
6205        BCNumEltsChanged = true;
6206      InVec = InVec.getOperand(0);
6207      ExtVT = BCVT.getVectorElementType();
6208      NewLoad = true;
6209    }
6210
6211    LoadSDNode *LN0 = NULL;
6212    const ShuffleVectorSDNode *SVN = NULL;
6213    if (ISD::isNormalLoad(InVec.getNode())) {
6214      LN0 = cast<LoadSDNode>(InVec);
6215    } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6216               InVec.getOperand(0).getValueType() == ExtVT &&
6217               ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
6218      LN0 = cast<LoadSDNode>(InVec.getOperand(0));
6219    } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
6220      // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
6221      // =>
6222      // (load $addr+1*size)
6223
6224      // If the bit convert changed the number of elements, it is unsafe
6225      // to examine the mask.
6226      if (BCNumEltsChanged)
6227        return SDValue();
6228
6229      // Select the input vector, guarding against out of range extract vector.
6230      unsigned NumElems = VT.getVectorNumElements();
6231      int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
6232      InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
6233
6234      if (InVec.getOpcode() == ISD::BIT_CONVERT)
6235        InVec = InVec.getOperand(0);
6236      if (ISD::isNormalLoad(InVec.getNode())) {
6237        LN0 = cast<LoadSDNode>(InVec);
6238        Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
6239      }
6240    }
6241
6242    if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
6243      return SDValue();
6244
6245    unsigned Align = LN0->getAlignment();
6246    if (NewLoad) {
6247      // Check the resultant load doesn't need a higher alignment than the
6248      // original load.
6249      unsigned NewAlign =
6250        TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
6251
6252      if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
6253        return SDValue();
6254
6255      Align = NewAlign;
6256    }
6257
6258    SDValue NewPtr = LN0->getBasePtr();
6259    unsigned PtrOff = 0;
6260    // If Idx was -1 above, Elt is going to be -1, so just use undef as our
6261    // new pointer.
6262    if (Elt == -1) {
6263      NewPtr = DAG.getUNDEF(NewPtr.getValueType());
6264    } else if (Elt) {
6265      PtrOff = LVT.getSizeInBits() * Elt / 8;
6266      EVT PtrType = NewPtr.getValueType();
6267      if (TLI.isBigEndian())
6268        PtrOff = VT.getSizeInBits() / 8 - PtrOff;
6269      NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
6270                           DAG.getConstant(PtrOff, PtrType));
6271    }
6272
6273    return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
6274                       LN0->getPointerInfo().getWithOffset(PtrOff),
6275                       LN0->isVolatile(), LN0->isNonTemporal(), Align);
6276  }
6277
6278  return SDValue();
6279}
6280
6281SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
6282  unsigned NumInScalars = N->getNumOperands();
6283  EVT VT = N->getValueType(0);
6284
6285  // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
6286  // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
6287  // at most two distinct vectors, turn this into a shuffle node.
6288  SDValue VecIn1, VecIn2;
6289  for (unsigned i = 0; i != NumInScalars; ++i) {
6290    // Ignore undef inputs.
6291    if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6292
6293    // If this input is something other than a EXTRACT_VECTOR_ELT with a
6294    // constant index, bail out.
6295    if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6296        !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
6297      VecIn1 = VecIn2 = SDValue(0, 0);
6298      break;
6299    }
6300
6301    // If the input vector type disagrees with the result of the build_vector,
6302    // we can't make a shuffle.
6303    SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
6304    if (ExtractedFromVec.getValueType() != VT) {
6305      VecIn1 = VecIn2 = SDValue(0, 0);
6306      break;
6307    }
6308
6309    // Otherwise, remember this.  We allow up to two distinct input vectors.
6310    if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
6311      continue;
6312
6313    if (VecIn1.getNode() == 0) {
6314      VecIn1 = ExtractedFromVec;
6315    } else if (VecIn2.getNode() == 0) {
6316      VecIn2 = ExtractedFromVec;
6317    } else {
6318      // Too many inputs.
6319      VecIn1 = VecIn2 = SDValue(0, 0);
6320      break;
6321    }
6322  }
6323
6324  // If everything is good, we can make a shuffle operation.
6325  if (VecIn1.getNode()) {
6326    SmallVector<int, 8> Mask;
6327    for (unsigned i = 0; i != NumInScalars; ++i) {
6328      if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
6329        Mask.push_back(-1);
6330        continue;
6331      }
6332
6333      // If extracting from the first vector, just use the index directly.
6334      SDValue Extract = N->getOperand(i);
6335      SDValue ExtVal = Extract.getOperand(1);
6336      if (Extract.getOperand(0) == VecIn1) {
6337        unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6338        if (ExtIndex > VT.getVectorNumElements())
6339          return SDValue();
6340
6341        Mask.push_back(ExtIndex);
6342        continue;
6343      }
6344
6345      // Otherwise, use InIdx + VecSize
6346      unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6347      Mask.push_back(Idx+NumInScalars);
6348    }
6349
6350    // Add count and size info.
6351    if (!isTypeLegal(VT))
6352      return SDValue();
6353
6354    // Return the new VECTOR_SHUFFLE node.
6355    SDValue Ops[2];
6356    Ops[0] = VecIn1;
6357    Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6358    return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
6359  }
6360
6361  return SDValue();
6362}
6363
6364SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
6365  // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
6366  // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
6367  // inputs come from at most two distinct vectors, turn this into a shuffle
6368  // node.
6369
6370  // If we only have one input vector, we don't need to do any concatenation.
6371  if (N->getNumOperands() == 1)
6372    return N->getOperand(0);
6373
6374  return SDValue();
6375}
6376
6377SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
6378  EVT VT = N->getValueType(0);
6379  unsigned NumElts = VT.getVectorNumElements();
6380
6381  SDValue N0 = N->getOperand(0);
6382
6383  assert(N0.getValueType().getVectorNumElements() == NumElts &&
6384        "Vector shuffle must be normalized in DAG");
6385
6386  // FIXME: implement canonicalizations from DAG.getVectorShuffle()
6387
6388  // If it is a splat, check if the argument vector is another splat or a
6389  // build_vector with all scalar elements the same.
6390  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
6391  if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
6392    SDNode *V = N0.getNode();
6393
6394    // If this is a bit convert that changes the element type of the vector but
6395    // not the number of vector elements, look through it.  Be careful not to
6396    // look though conversions that change things like v4f32 to v2f64.
6397    if (V->getOpcode() == ISD::BIT_CONVERT) {
6398      SDValue ConvInput = V->getOperand(0);
6399      if (ConvInput.getValueType().isVector() &&
6400          ConvInput.getValueType().getVectorNumElements() == NumElts)
6401        V = ConvInput.getNode();
6402    }
6403
6404    if (V->getOpcode() == ISD::BUILD_VECTOR) {
6405      assert(V->getNumOperands() == NumElts &&
6406             "BUILD_VECTOR has wrong number of operands");
6407      SDValue Base;
6408      bool AllSame = true;
6409      for (unsigned i = 0; i != NumElts; ++i) {
6410        if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
6411          Base = V->getOperand(i);
6412          break;
6413        }
6414      }
6415      // Splat of <u, u, u, u>, return <u, u, u, u>
6416      if (!Base.getNode())
6417        return N0;
6418      for (unsigned i = 0; i != NumElts; ++i) {
6419        if (V->getOperand(i) != Base) {
6420          AllSame = false;
6421          break;
6422        }
6423      }
6424      // Splat of <x, x, x, x>, return <x, x, x, x>
6425      if (AllSame)
6426        return N0;
6427    }
6428  }
6429  return SDValue();
6430}
6431
6432SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
6433  if (!TLI.getShouldFoldAtomicFences())
6434    return SDValue();
6435
6436  SDValue atomic = N->getOperand(0);
6437  switch (atomic.getOpcode()) {
6438    case ISD::ATOMIC_CMP_SWAP:
6439    case ISD::ATOMIC_SWAP:
6440    case ISD::ATOMIC_LOAD_ADD:
6441    case ISD::ATOMIC_LOAD_SUB:
6442    case ISD::ATOMIC_LOAD_AND:
6443    case ISD::ATOMIC_LOAD_OR:
6444    case ISD::ATOMIC_LOAD_XOR:
6445    case ISD::ATOMIC_LOAD_NAND:
6446    case ISD::ATOMIC_LOAD_MIN:
6447    case ISD::ATOMIC_LOAD_MAX:
6448    case ISD::ATOMIC_LOAD_UMIN:
6449    case ISD::ATOMIC_LOAD_UMAX:
6450      break;
6451    default:
6452      return SDValue();
6453  }
6454
6455  SDValue fence = atomic.getOperand(0);
6456  if (fence.getOpcode() != ISD::MEMBARRIER)
6457    return SDValue();
6458
6459  switch (atomic.getOpcode()) {
6460    case ISD::ATOMIC_CMP_SWAP:
6461      return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6462                                    fence.getOperand(0),
6463                                    atomic.getOperand(1), atomic.getOperand(2),
6464                                    atomic.getOperand(3)), atomic.getResNo());
6465    case ISD::ATOMIC_SWAP:
6466    case ISD::ATOMIC_LOAD_ADD:
6467    case ISD::ATOMIC_LOAD_SUB:
6468    case ISD::ATOMIC_LOAD_AND:
6469    case ISD::ATOMIC_LOAD_OR:
6470    case ISD::ATOMIC_LOAD_XOR:
6471    case ISD::ATOMIC_LOAD_NAND:
6472    case ISD::ATOMIC_LOAD_MIN:
6473    case ISD::ATOMIC_LOAD_MAX:
6474    case ISD::ATOMIC_LOAD_UMIN:
6475    case ISD::ATOMIC_LOAD_UMAX:
6476      return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6477                                    fence.getOperand(0),
6478                                    atomic.getOperand(1), atomic.getOperand(2)),
6479                     atomic.getResNo());
6480    default:
6481      return SDValue();
6482  }
6483}
6484
6485/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
6486/// an AND to a vector_shuffle with the destination vector and a zero vector.
6487/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
6488///      vector_shuffle V, Zero, <0, 4, 2, 4>
6489SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
6490  EVT VT = N->getValueType(0);
6491  DebugLoc dl = N->getDebugLoc();
6492  SDValue LHS = N->getOperand(0);
6493  SDValue RHS = N->getOperand(1);
6494  if (N->getOpcode() == ISD::AND) {
6495    if (RHS.getOpcode() == ISD::BIT_CONVERT)
6496      RHS = RHS.getOperand(0);
6497    if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
6498      SmallVector<int, 8> Indices;
6499      unsigned NumElts = RHS.getNumOperands();
6500      for (unsigned i = 0; i != NumElts; ++i) {
6501        SDValue Elt = RHS.getOperand(i);
6502        if (!isa<ConstantSDNode>(Elt))
6503          return SDValue();
6504        else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
6505          Indices.push_back(i);
6506        else if (cast<ConstantSDNode>(Elt)->isNullValue())
6507          Indices.push_back(NumElts);
6508        else
6509          return SDValue();
6510      }
6511
6512      // Let's see if the target supports this vector_shuffle.
6513      EVT RVT = RHS.getValueType();
6514      if (!TLI.isVectorClearMaskLegal(Indices, RVT))
6515        return SDValue();
6516
6517      // Return the new VECTOR_SHUFFLE node.
6518      EVT EltVT = RVT.getVectorElementType();
6519      SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
6520                                     DAG.getConstant(0, EltVT));
6521      SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6522                                 RVT, &ZeroOps[0], ZeroOps.size());
6523      LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS);
6524      SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
6525      return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf);
6526    }
6527  }
6528
6529  return SDValue();
6530}
6531
6532/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
6533SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
6534  // After legalize, the target may be depending on adds and other
6535  // binary ops to provide legal ways to construct constants or other
6536  // things. Simplifying them may result in a loss of legality.
6537  if (LegalOperations) return SDValue();
6538
6539  EVT VT = N->getValueType(0);
6540  assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
6541
6542  EVT EltType = VT.getVectorElementType();
6543  SDValue LHS = N->getOperand(0);
6544  SDValue RHS = N->getOperand(1);
6545  SDValue Shuffle = XformToShuffleWithZero(N);
6546  if (Shuffle.getNode()) return Shuffle;
6547
6548  // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
6549  // this operation.
6550  if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
6551      RHS.getOpcode() == ISD::BUILD_VECTOR) {
6552    SmallVector<SDValue, 8> Ops;
6553    for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
6554      SDValue LHSOp = LHS.getOperand(i);
6555      SDValue RHSOp = RHS.getOperand(i);
6556      // If these two elements can't be folded, bail out.
6557      if ((LHSOp.getOpcode() != ISD::UNDEF &&
6558           LHSOp.getOpcode() != ISD::Constant &&
6559           LHSOp.getOpcode() != ISD::ConstantFP) ||
6560          (RHSOp.getOpcode() != ISD::UNDEF &&
6561           RHSOp.getOpcode() != ISD::Constant &&
6562           RHSOp.getOpcode() != ISD::ConstantFP))
6563        break;
6564
6565      // Can't fold divide by zero.
6566      if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
6567          N->getOpcode() == ISD::FDIV) {
6568        if ((RHSOp.getOpcode() == ISD::Constant &&
6569             cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
6570            (RHSOp.getOpcode() == ISD::ConstantFP &&
6571             cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
6572          break;
6573      }
6574
6575      // If the vector element type is not legal, the BUILD_VECTOR operands
6576      // are promoted and implicitly truncated.  Make that explicit here.
6577      if (LHSOp.getValueType() != EltType)
6578        LHSOp = DAG.getNode(ISD::TRUNCATE, LHS.getDebugLoc(), EltType, LHSOp);
6579      if (RHSOp.getValueType() != EltType)
6580        RHSOp = DAG.getNode(ISD::TRUNCATE, RHS.getDebugLoc(), EltType, RHSOp);
6581
6582      SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), EltType,
6583                                   LHSOp, RHSOp);
6584      if (FoldOp.getOpcode() != ISD::UNDEF &&
6585          FoldOp.getOpcode() != ISD::Constant &&
6586          FoldOp.getOpcode() != ISD::ConstantFP)
6587        break;
6588      Ops.push_back(FoldOp);
6589      AddToWorkList(FoldOp.getNode());
6590    }
6591
6592    if (Ops.size() == LHS.getNumOperands()) {
6593      EVT VT = LHS.getValueType();
6594      return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
6595                         &Ops[0], Ops.size());
6596    }
6597  }
6598
6599  return SDValue();
6600}
6601
6602SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
6603                                    SDValue N1, SDValue N2){
6604  assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
6605
6606  SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
6607                                 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6608
6609  // If we got a simplified select_cc node back from SimplifySelectCC, then
6610  // break it down into a new SETCC node, and a new SELECT node, and then return
6611  // the SELECT node, since we were called with a SELECT node.
6612  if (SCC.getNode()) {
6613    // Check to see if we got a select_cc back (to turn into setcc/select).
6614    // Otherwise, just return whatever node we got back, like fabs.
6615    if (SCC.getOpcode() == ISD::SELECT_CC) {
6616      SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
6617                                  N0.getValueType(),
6618                                  SCC.getOperand(0), SCC.getOperand(1),
6619                                  SCC.getOperand(4));
6620      AddToWorkList(SETCC.getNode());
6621      return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
6622                         SCC.getOperand(2), SCC.getOperand(3), SETCC);
6623    }
6624
6625    return SCC;
6626  }
6627  return SDValue();
6628}
6629
6630/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
6631/// are the two values being selected between, see if we can simplify the
6632/// select.  Callers of this should assume that TheSelect is deleted if this
6633/// returns true.  As such, they should return the appropriate thing (e.g. the
6634/// node) back to the top-level of the DAG combiner loop to avoid it being
6635/// looked at.
6636bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
6637                                    SDValue RHS) {
6638
6639  // If this is a select from two identical things, try to pull the operation
6640  // through the select.
6641  if (LHS.getOpcode() != RHS.getOpcode() ||
6642      !LHS.hasOneUse() || !RHS.hasOneUse())
6643    return false;
6644
6645  // If this is a load and the token chain is identical, replace the select
6646  // of two loads with a load through a select of the address to load from.
6647  // This triggers in things like "select bool X, 10.0, 123.0" after the FP
6648  // constants have been dropped into the constant pool.
6649  if (LHS.getOpcode() == ISD::LOAD) {
6650    LoadSDNode *LLD = cast<LoadSDNode>(LHS);
6651    LoadSDNode *RLD = cast<LoadSDNode>(RHS);
6652
6653    // Token chains must be identical.
6654    if (LHS.getOperand(0) != RHS.getOperand(0) ||
6655        // Do not let this transformation reduce the number of volatile loads.
6656        LLD->isVolatile() || RLD->isVolatile() ||
6657        // If this is an EXTLOAD, the VT's must match.
6658        LLD->getMemoryVT() != RLD->getMemoryVT() ||
6659        // FIXME: this discards src value information.  This is
6660        // over-conservative. It would be beneficial to be able to remember
6661        // both potential memory locations.  Since we are discarding
6662        // src value info, don't do the transformation if the memory
6663        // locations are not in the default address space.
6664        LLD->getPointerInfo().getAddrSpace() != 0 ||
6665        RLD->getPointerInfo().getAddrSpace() != 0)
6666      return false;
6667
6668    // Check that the select condition doesn't reach either load.  If so,
6669    // folding this will induce a cycle into the DAG.  If not, this is safe to
6670    // xform, so create a select of the addresses.
6671    SDValue Addr;
6672    if (TheSelect->getOpcode() == ISD::SELECT) {
6673      SDNode *CondNode = TheSelect->getOperand(0).getNode();
6674      if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
6675          (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
6676        return false;
6677      Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
6678                         LLD->getBasePtr().getValueType(),
6679                         TheSelect->getOperand(0), LLD->getBasePtr(),
6680                         RLD->getBasePtr());
6681    } else {  // Otherwise SELECT_CC
6682      SDNode *CondLHS = TheSelect->getOperand(0).getNode();
6683      SDNode *CondRHS = TheSelect->getOperand(1).getNode();
6684
6685      if ((LLD->hasAnyUseOfValue(1) &&
6686           (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
6687          (LLD->hasAnyUseOfValue(1) &&
6688           (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))))
6689        return false;
6690
6691      Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
6692                         LLD->getBasePtr().getValueType(),
6693                         TheSelect->getOperand(0),
6694                         TheSelect->getOperand(1),
6695                         LLD->getBasePtr(), RLD->getBasePtr(),
6696                         TheSelect->getOperand(4));
6697    }
6698
6699    SDValue Load;
6700    if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
6701      Load = DAG.getLoad(TheSelect->getValueType(0),
6702                         TheSelect->getDebugLoc(),
6703                         // FIXME: Discards pointer info.
6704                         LLD->getChain(), Addr, MachinePointerInfo(),
6705                         LLD->isVolatile(), LLD->isNonTemporal(),
6706                         LLD->getAlignment());
6707    } else {
6708      Load = DAG.getExtLoad(LLD->getExtensionType(),
6709                            TheSelect->getValueType(0),
6710                            TheSelect->getDebugLoc(),
6711                            // FIXME: Discards pointer info.
6712                            LLD->getChain(), Addr, MachinePointerInfo(),
6713                            LLD->getMemoryVT(), LLD->isVolatile(),
6714                            LLD->isNonTemporal(), LLD->getAlignment());
6715    }
6716
6717    // Users of the select now use the result of the load.
6718    CombineTo(TheSelect, Load);
6719
6720    // Users of the old loads now use the new load's chain.  We know the
6721    // old-load value is dead now.
6722    CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
6723    CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
6724    return true;
6725  }
6726
6727  return false;
6728}
6729
6730/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
6731/// where 'cond' is the comparison specified by CC.
6732SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
6733                                      SDValue N2, SDValue N3,
6734                                      ISD::CondCode CC, bool NotExtCompare) {
6735  // (x ? y : y) -> y.
6736  if (N2 == N3) return N2;
6737
6738  EVT VT = N2.getValueType();
6739  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
6740  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
6741  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
6742
6743  // Determine if the condition we're dealing with is constant
6744  SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
6745                              N0, N1, CC, DL, false);
6746  if (SCC.getNode()) AddToWorkList(SCC.getNode());
6747  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
6748
6749  // fold select_cc true, x, y -> x
6750  if (SCCC && !SCCC->isNullValue())
6751    return N2;
6752  // fold select_cc false, x, y -> y
6753  if (SCCC && SCCC->isNullValue())
6754    return N3;
6755
6756  // Check to see if we can simplify the select into an fabs node
6757  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
6758    // Allow either -0.0 or 0.0
6759    if (CFP->getValueAPF().isZero()) {
6760      // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
6761      if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
6762          N0 == N2 && N3.getOpcode() == ISD::FNEG &&
6763          N2 == N3.getOperand(0))
6764        return DAG.getNode(ISD::FABS, DL, VT, N0);
6765
6766      // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
6767      if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
6768          N0 == N3 && N2.getOpcode() == ISD::FNEG &&
6769          N2.getOperand(0) == N3)
6770        return DAG.getNode(ISD::FABS, DL, VT, N3);
6771    }
6772  }
6773
6774  // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
6775  // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
6776  // in it.  This is a win when the constant is not otherwise available because
6777  // it replaces two constant pool loads with one.  We only do this if the FP
6778  // type is known to be legal, because if it isn't, then we are before legalize
6779  // types an we want the other legalization to happen first (e.g. to avoid
6780  // messing with soft float) and if the ConstantFP is not legal, because if
6781  // it is legal, we may not need to store the FP constant in a constant pool.
6782  if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
6783    if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
6784      if (TLI.isTypeLegal(N2.getValueType()) &&
6785          (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
6786           TargetLowering::Legal) &&
6787          // If both constants have multiple uses, then we won't need to do an
6788          // extra load, they are likely around in registers for other users.
6789          (TV->hasOneUse() || FV->hasOneUse())) {
6790        Constant *Elts[] = {
6791          const_cast<ConstantFP*>(FV->getConstantFPValue()),
6792          const_cast<ConstantFP*>(TV->getConstantFPValue())
6793        };
6794        const Type *FPTy = Elts[0]->getType();
6795        const TargetData &TD = *TLI.getTargetData();
6796
6797        // Create a ConstantArray of the two constants.
6798        Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
6799        SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
6800                                            TD.getPrefTypeAlignment(FPTy));
6801        unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
6802
6803        // Get the offsets to the 0 and 1 element of the array so that we can
6804        // select between them.
6805        SDValue Zero = DAG.getIntPtrConstant(0);
6806        unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
6807        SDValue One = DAG.getIntPtrConstant(EltSize);
6808
6809        SDValue Cond = DAG.getSetCC(DL,
6810                                    TLI.getSetCCResultType(N0.getValueType()),
6811                                    N0, N1, CC);
6812        SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
6813                                        Cond, One, Zero);
6814        CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
6815                            CstOffset);
6816        return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
6817                           MachinePointerInfo::getConstantPool(), false,
6818                           false, Alignment);
6819
6820      }
6821    }
6822
6823  // Check to see if we can perform the "gzip trick", transforming
6824  // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
6825  if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
6826      N0.getValueType().isInteger() &&
6827      N2.getValueType().isInteger() &&
6828      (N1C->isNullValue() ||                         // (a < 0) ? b : 0
6829       (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
6830    EVT XType = N0.getValueType();
6831    EVT AType = N2.getValueType();
6832    if (XType.bitsGE(AType)) {
6833      // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
6834      // single-bit constant.
6835      if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
6836        unsigned ShCtV = N2C->getAPIntValue().logBase2();
6837        ShCtV = XType.getSizeInBits()-ShCtV-1;
6838        SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
6839        SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
6840                                    XType, N0, ShCt);
6841        AddToWorkList(Shift.getNode());
6842
6843        if (XType.bitsGT(AType)) {
6844          Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6845          AddToWorkList(Shift.getNode());
6846        }
6847
6848        return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6849      }
6850
6851      SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
6852                                  XType, N0,
6853                                  DAG.getConstant(XType.getSizeInBits()-1,
6854                                                  getShiftAmountTy()));
6855      AddToWorkList(Shift.getNode());
6856
6857      if (XType.bitsGT(AType)) {
6858        Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6859        AddToWorkList(Shift.getNode());
6860      }
6861
6862      return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6863    }
6864  }
6865
6866  // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
6867  // where y is has a single bit set.
6868  // A plaintext description would be, we can turn the SELECT_CC into an AND
6869  // when the condition can be materialized as an all-ones register.  Any
6870  // single bit-test can be materialized as an all-ones register with
6871  // shift-left and shift-right-arith.
6872  if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
6873      N0->getValueType(0) == VT &&
6874      N1C && N1C->isNullValue() &&
6875      N2C && N2C->isNullValue()) {
6876    SDValue AndLHS = N0->getOperand(0);
6877    ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6878    if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
6879      // Shift the tested bit over the sign bit.
6880      APInt AndMask = ConstAndRHS->getAPIntValue();
6881      SDValue ShlAmt =
6882        DAG.getConstant(AndMask.countLeadingZeros(), getShiftAmountTy());
6883      SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
6884
6885      // Now arithmetic right shift it all the way over, so the result is either
6886      // all-ones, or zero.
6887      SDValue ShrAmt =
6888        DAG.getConstant(AndMask.getBitWidth()-1, getShiftAmountTy());
6889      SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
6890
6891      return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
6892    }
6893  }
6894
6895  // fold select C, 16, 0 -> shl C, 4
6896  if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
6897      TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
6898
6899    // If the caller doesn't want us to simplify this into a zext of a compare,
6900    // don't do it.
6901    if (NotExtCompare && N2C->getAPIntValue() == 1)
6902      return SDValue();
6903
6904    // Get a SetCC of the condition
6905    // FIXME: Should probably make sure that setcc is legal if we ever have a
6906    // target where it isn't.
6907    SDValue Temp, SCC;
6908    // cast from setcc result type to select result type
6909    if (LegalTypes) {
6910      SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
6911                          N0, N1, CC);
6912      if (N2.getValueType().bitsLT(SCC.getValueType()))
6913        Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
6914      else
6915        Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6916                           N2.getValueType(), SCC);
6917    } else {
6918      SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
6919      Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6920                         N2.getValueType(), SCC);
6921    }
6922
6923    AddToWorkList(SCC.getNode());
6924    AddToWorkList(Temp.getNode());
6925
6926    if (N2C->getAPIntValue() == 1)
6927      return Temp;
6928
6929    // shl setcc result by log2 n2c
6930    return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
6931                       DAG.getConstant(N2C->getAPIntValue().logBase2(),
6932                                       getShiftAmountTy()));
6933  }
6934
6935  // Check to see if this is the equivalent of setcc
6936  // FIXME: Turn all of these into setcc if setcc if setcc is legal
6937  // otherwise, go ahead with the folds.
6938  if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
6939    EVT XType = N0.getValueType();
6940    if (!LegalOperations ||
6941        TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
6942      SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
6943      if (Res.getValueType() != VT)
6944        Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
6945      return Res;
6946    }
6947
6948    // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
6949    if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
6950        (!LegalOperations ||
6951         TLI.isOperationLegal(ISD::CTLZ, XType))) {
6952      SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
6953      return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
6954                         DAG.getConstant(Log2_32(XType.getSizeInBits()),
6955                                         getShiftAmountTy()));
6956    }
6957    // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
6958    if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
6959      SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
6960                                  XType, DAG.getConstant(0, XType), N0);
6961      SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
6962      return DAG.getNode(ISD::SRL, DL, XType,
6963                         DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
6964                         DAG.getConstant(XType.getSizeInBits()-1,
6965                                         getShiftAmountTy()));
6966    }
6967    // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
6968    if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
6969      SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
6970                                 DAG.getConstant(XType.getSizeInBits()-1,
6971                                                 getShiftAmountTy()));
6972      return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
6973    }
6974  }
6975
6976  // Check to see if this is an integer abs.
6977  // select_cc setg[te] X,  0,  X, -X ->
6978  // select_cc setgt    X, -1,  X, -X ->
6979  // select_cc setl[te] X,  0, -X,  X ->
6980  // select_cc setlt    X,  1, -X,  X ->
6981  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6982  if (N1C) {
6983    ConstantSDNode *SubC = NULL;
6984    if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
6985         (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
6986        N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
6987      SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
6988    else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
6989              (N1C->isOne() && CC == ISD::SETLT)) &&
6990             N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
6991      SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
6992
6993    EVT XType = N0.getValueType();
6994    if (SubC && SubC->isNullValue() && XType.isInteger()) {
6995      SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
6996                                  N0,
6997                                  DAG.getConstant(XType.getSizeInBits()-1,
6998                                                  getShiftAmountTy()));
6999      SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
7000                                XType, N0, Shift);
7001      AddToWorkList(Shift.getNode());
7002      AddToWorkList(Add.getNode());
7003      return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
7004    }
7005  }
7006
7007  return SDValue();
7008}
7009
7010/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
7011SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
7012                                   SDValue N1, ISD::CondCode Cond,
7013                                   DebugLoc DL, bool foldBooleans) {
7014  TargetLowering::DAGCombinerInfo
7015    DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
7016  return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
7017}
7018
7019/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
7020/// return a DAG expression to select that will generate the same value by
7021/// multiplying by a magic number.  See:
7022/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7023SDValue DAGCombiner::BuildSDIV(SDNode *N) {
7024  std::vector<SDNode*> Built;
7025  SDValue S = TLI.BuildSDIV(N, DAG, &Built);
7026
7027  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7028       ii != ee; ++ii)
7029    AddToWorkList(*ii);
7030  return S;
7031}
7032
7033/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
7034/// return a DAG expression to select that will generate the same value by
7035/// multiplying by a magic number.  See:
7036/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7037SDValue DAGCombiner::BuildUDIV(SDNode *N) {
7038  std::vector<SDNode*> Built;
7039  SDValue S = TLI.BuildUDIV(N, DAG, &Built);
7040
7041  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7042       ii != ee; ++ii)
7043    AddToWorkList(*ii);
7044  return S;
7045}
7046
7047/// FindBaseOffset - Return true if base is a frame index, which is known not
7048// to alias with anything but itself.  Provides base object and offset as results.
7049static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
7050                           const GlobalValue *&GV, void *&CV) {
7051  // Assume it is a primitive operation.
7052  Base = Ptr; Offset = 0; GV = 0; CV = 0;
7053
7054  // If it's an adding a simple constant then integrate the offset.
7055  if (Base.getOpcode() == ISD::ADD) {
7056    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
7057      Base = Base.getOperand(0);
7058      Offset += C->getZExtValue();
7059    }
7060  }
7061
7062  // Return the underlying GlobalValue, and update the Offset.  Return false
7063  // for GlobalAddressSDNode since the same GlobalAddress may be represented
7064  // by multiple nodes with different offsets.
7065  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
7066    GV = G->getGlobal();
7067    Offset += G->getOffset();
7068    return false;
7069  }
7070
7071  // Return the underlying Constant value, and update the Offset.  Return false
7072  // for ConstantSDNodes since the same constant pool entry may be represented
7073  // by multiple nodes with different offsets.
7074  if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
7075    CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
7076                                         : (void *)C->getConstVal();
7077    Offset += C->getOffset();
7078    return false;
7079  }
7080  // If it's any of the following then it can't alias with anything but itself.
7081  return isa<FrameIndexSDNode>(Base);
7082}
7083
7084/// isAlias - Return true if there is any possibility that the two addresses
7085/// overlap.
7086bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
7087                          const Value *SrcValue1, int SrcValueOffset1,
7088                          unsigned SrcValueAlign1,
7089                          const MDNode *TBAAInfo1,
7090                          SDValue Ptr2, int64_t Size2,
7091                          const Value *SrcValue2, int SrcValueOffset2,
7092                          unsigned SrcValueAlign2,
7093                          const MDNode *TBAAInfo2) const {
7094  // If they are the same then they must be aliases.
7095  if (Ptr1 == Ptr2) return true;
7096
7097  // Gather base node and offset information.
7098  SDValue Base1, Base2;
7099  int64_t Offset1, Offset2;
7100  const GlobalValue *GV1, *GV2;
7101  void *CV1, *CV2;
7102  bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
7103  bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
7104
7105  // If they have a same base address then check to see if they overlap.
7106  if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
7107    return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7108
7109  // It is possible for different frame indices to alias each other, mostly
7110  // when tail call optimization reuses return address slots for arguments.
7111  // To catch this case, look up the actual index of frame indices to compute
7112  // the real alias relationship.
7113  if (isFrameIndex1 && isFrameIndex2) {
7114    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7115    Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
7116    Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
7117    return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7118  }
7119
7120  // Otherwise, if we know what the bases are, and they aren't identical, then
7121  // we know they cannot alias.
7122  if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
7123    return false;
7124
7125  // If we know required SrcValue1 and SrcValue2 have relatively large alignment
7126  // compared to the size and offset of the access, we may be able to prove they
7127  // do not alias.  This check is conservative for now to catch cases created by
7128  // splitting vector types.
7129  if ((SrcValueAlign1 == SrcValueAlign2) &&
7130      (SrcValueOffset1 != SrcValueOffset2) &&
7131      (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
7132    int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
7133    int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
7134
7135    // There is no overlap between these relatively aligned accesses of similar
7136    // size, return no alias.
7137    if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
7138      return false;
7139  }
7140
7141  if (CombinerGlobalAA) {
7142    // Use alias analysis information.
7143    int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
7144    int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
7145    int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
7146    AliasAnalysis::AliasResult AAResult =
7147      AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
7148               AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
7149    if (AAResult == AliasAnalysis::NoAlias)
7150      return false;
7151  }
7152
7153  // Otherwise we have to assume they alias.
7154  return true;
7155}
7156
7157/// FindAliasInfo - Extracts the relevant alias information from the memory
7158/// node.  Returns true if the operand was a load.
7159bool DAGCombiner::FindAliasInfo(SDNode *N,
7160                        SDValue &Ptr, int64_t &Size,
7161                        const Value *&SrcValue,
7162                        int &SrcValueOffset,
7163                        unsigned &SrcValueAlign,
7164                        const MDNode *&TBAAInfo) const {
7165  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7166    Ptr = LD->getBasePtr();
7167    Size = LD->getMemoryVT().getSizeInBits() >> 3;
7168    SrcValue = LD->getSrcValue();
7169    SrcValueOffset = LD->getSrcValueOffset();
7170    SrcValueAlign = LD->getOriginalAlignment();
7171    TBAAInfo = LD->getTBAAInfo();
7172    return true;
7173  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7174    Ptr = ST->getBasePtr();
7175    Size = ST->getMemoryVT().getSizeInBits() >> 3;
7176    SrcValue = ST->getSrcValue();
7177    SrcValueOffset = ST->getSrcValueOffset();
7178    SrcValueAlign = ST->getOriginalAlignment();
7179    TBAAInfo = ST->getTBAAInfo();
7180  } else {
7181    llvm_unreachable("FindAliasInfo expected a memory operand");
7182  }
7183
7184  return false;
7185}
7186
7187/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
7188/// looking for aliasing nodes and adding them to the Aliases vector.
7189void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
7190                                   SmallVector<SDValue, 8> &Aliases) {
7191  SmallVector<SDValue, 8> Chains;     // List of chains to visit.
7192  SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
7193
7194  // Get alias information for node.
7195  SDValue Ptr;
7196  int64_t Size;
7197  const Value *SrcValue;
7198  int SrcValueOffset;
7199  unsigned SrcValueAlign;
7200  const MDNode *SrcTBAAInfo;
7201  bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
7202                              SrcValueAlign, SrcTBAAInfo);
7203
7204  // Starting off.
7205  Chains.push_back(OriginalChain);
7206  unsigned Depth = 0;
7207
7208  // Look at each chain and determine if it is an alias.  If so, add it to the
7209  // aliases list.  If not, then continue up the chain looking for the next
7210  // candidate.
7211  while (!Chains.empty()) {
7212    SDValue Chain = Chains.back();
7213    Chains.pop_back();
7214
7215    // For TokenFactor nodes, look at each operand and only continue up the
7216    // chain until we find two aliases.  If we've seen two aliases, assume we'll
7217    // find more and revert to original chain since the xform is unlikely to be
7218    // profitable.
7219    //
7220    // FIXME: The depth check could be made to return the last non-aliasing
7221    // chain we found before we hit a tokenfactor rather than the original
7222    // chain.
7223    if (Depth > 6 || Aliases.size() == 2) {
7224      Aliases.clear();
7225      Aliases.push_back(OriginalChain);
7226      break;
7227    }
7228
7229    // Don't bother if we've been before.
7230    if (!Visited.insert(Chain.getNode()))
7231      continue;
7232
7233    switch (Chain.getOpcode()) {
7234    case ISD::EntryToken:
7235      // Entry token is ideal chain operand, but handled in FindBetterChain.
7236      break;
7237
7238    case ISD::LOAD:
7239    case ISD::STORE: {
7240      // Get alias information for Chain.
7241      SDValue OpPtr;
7242      int64_t OpSize;
7243      const Value *OpSrcValue;
7244      int OpSrcValueOffset;
7245      unsigned OpSrcValueAlign;
7246      const MDNode *OpSrcTBAAInfo;
7247      bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
7248                                    OpSrcValue, OpSrcValueOffset,
7249                                    OpSrcValueAlign,
7250                                    OpSrcTBAAInfo);
7251
7252      // If chain is alias then stop here.
7253      if (!(IsLoad && IsOpLoad) &&
7254          isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
7255                  SrcTBAAInfo,
7256                  OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
7257                  OpSrcValueAlign, OpSrcTBAAInfo)) {
7258        Aliases.push_back(Chain);
7259      } else {
7260        // Look further up the chain.
7261        Chains.push_back(Chain.getOperand(0));
7262        ++Depth;
7263      }
7264      break;
7265    }
7266
7267    case ISD::TokenFactor:
7268      // We have to check each of the operands of the token factor for "small"
7269      // token factors, so we queue them up.  Adding the operands to the queue
7270      // (stack) in reverse order maintains the original order and increases the
7271      // likelihood that getNode will find a matching token factor (CSE.)
7272      if (Chain.getNumOperands() > 16) {
7273        Aliases.push_back(Chain);
7274        break;
7275      }
7276      for (unsigned n = Chain.getNumOperands(); n;)
7277        Chains.push_back(Chain.getOperand(--n));
7278      ++Depth;
7279      break;
7280
7281    default:
7282      // For all other instructions we will just have to take what we can get.
7283      Aliases.push_back(Chain);
7284      break;
7285    }
7286  }
7287}
7288
7289/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
7290/// for a better chain (aliasing node.)
7291SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
7292  SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
7293
7294  // Accumulate all the aliases to this node.
7295  GatherAllAliases(N, OldChain, Aliases);
7296
7297  if (Aliases.size() == 0) {
7298    // If no operands then chain to entry token.
7299    return DAG.getEntryNode();
7300  } else if (Aliases.size() == 1) {
7301    // If a single operand then chain to it.  We don't need to revisit it.
7302    return Aliases[0];
7303  }
7304
7305  // Construct a custom tailored token factor.
7306  return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7307                     &Aliases[0], Aliases.size());
7308}
7309
7310// SelectionDAG::Combine - This is the entry point for the file.
7311//
7312void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
7313                           CodeGenOpt::Level OptLevel) {
7314  /// run - This is the main entry point to this class.
7315  ///
7316  DAGCombiner(*this, AA, OptLevel).Run(Level);
7317}
7318