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