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