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