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