DAGCombiner.cpp revision 734c91d2506233d6e5d6531abcfbf6302bff3c8d
1//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by Nate Begeman and is distributed under the
6// University of Illinois Open Source 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// FIXME: Missing folds
14// sdiv, udiv, srem, urem (X, const) where X is an integer can be expanded into
15//  a sequence of multiplies, shifts, and adds.  This should be controlled by
16//  some kind of hint from the target that int div is expensive.
17// various folds of mulh[s,u] by constants such as -1, powers of 2, etc.
18//
19// FIXME: select C, pow2, pow2 -> something smart
20// FIXME: trunc(select X, Y, Z) -> select X, trunc(Y), trunc(Z)
21// FIXME: Dead stores -> nuke
22// FIXME: shr X, (and Y,31) -> shr X, Y   (TRICKY!)
23// FIXME: mul (x, const) -> shifts + adds
24// FIXME: undef values
25// FIXME: divide by zero is currently left unfolded.  do we want to turn this
26//        into an undef?
27// FIXME: select ne (select cc, 1, 0), 0, true, false -> select cc, true, false
28//
29//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "dagcombine"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/Analysis/AliasAnalysis.h"
34#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/MathExtras.h"
37#include "llvm/Target/TargetLowering.h"
38#include "llvm/Support/Compiler.h"
39#include "llvm/Support/CommandLine.h"
40#include <algorithm>
41#include <iostream>
42#include <algorithm>
43using namespace llvm;
44
45namespace {
46  static Statistic<> NodesCombined ("dagcombiner",
47				    "Number of dag nodes combined");
48
49  static Statistic<> PreIndexedNodes ("pre_indexed_ops",
50                                      "Number of pre-indexed nodes created");
51  static Statistic<> PostIndexedNodes ("post_indexed_ops",
52                                       "Number of post-indexed nodes created");
53
54  static cl::opt<bool>
55    CombinerAA("combiner-alias-analysis", cl::Hidden,
56               cl::desc("Turn on alias analysis during testing"));
57
58  static cl::opt<bool>
59    CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60               cl::desc("Include global information in alias analysis"));
61
62//------------------------------ DAGCombiner ---------------------------------//
63
64  class VISIBILITY_HIDDEN DAGCombiner {
65    SelectionDAG &DAG;
66    TargetLowering &TLI;
67    bool AfterLegalize;
68
69    // Worklist of all of the nodes that need to be simplified.
70    std::vector<SDNode*> WorkList;
71
72    // AA - Used for DAG load/store alias analysis.
73    AliasAnalysis &AA;
74
75    /// AddUsersToWorkList - When an instruction is simplified, add all users of
76    /// the instruction to the work lists because they might get more simplified
77    /// now.
78    ///
79    void AddUsersToWorkList(SDNode *N) {
80      for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
81           UI != UE; ++UI)
82        AddToWorkList(*UI);
83    }
84
85    /// removeFromWorkList - remove all instances of N from the worklist.
86    ///
87    void removeFromWorkList(SDNode *N) {
88      WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
89                     WorkList.end());
90    }
91
92  public:
93    /// AddToWorkList - Add to the work list making sure it's instance is at the
94    /// the back (next to be processed.)
95    void AddToWorkList(SDNode *N) {
96      removeFromWorkList(N);
97      WorkList.push_back(N);
98    }
99
100    SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
101                        bool AddTo = true) {
102      assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
103      ++NodesCombined;
104      DEBUG(std::cerr << "\nReplacing.1 "; N->dump();
105            std::cerr << "\nWith: "; To[0].Val->dump(&DAG);
106            std::cerr << " and " << NumTo-1 << " other values\n");
107      std::vector<SDNode*> NowDead;
108      DAG.ReplaceAllUsesWith(N, To, &NowDead);
109
110      if (AddTo) {
111        // Push the new nodes and any users onto the worklist
112        for (unsigned i = 0, e = NumTo; i != e; ++i) {
113          AddToWorkList(To[i].Val);
114          AddUsersToWorkList(To[i].Val);
115        }
116      }
117
118      // Nodes can be reintroduced into the worklist.  Make sure we do not
119      // process a node that has been replaced.
120      removeFromWorkList(N);
121      for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
122        removeFromWorkList(NowDead[i]);
123
124      // Finally, since the node is now dead, remove it from the graph.
125      DAG.DeleteNode(N);
126      return SDOperand(N, 0);
127    }
128
129    SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
130      return CombineTo(N, &Res, 1, AddTo);
131    }
132
133    SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
134                        bool AddTo = true) {
135      SDOperand To[] = { Res0, Res1 };
136      return CombineTo(N, To, 2, AddTo);
137    }
138  private:
139
140    /// SimplifyDemandedBits - Check the specified integer node value to see if
141    /// it can be simplified or if things it uses can be simplified by bit
142    /// propagation.  If so, return true.
143    bool SimplifyDemandedBits(SDOperand Op) {
144      TargetLowering::TargetLoweringOpt TLO(DAG);
145      uint64_t KnownZero, KnownOne;
146      uint64_t Demanded = MVT::getIntVTBitMask(Op.getValueType());
147      if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
148        return false;
149
150      // Revisit the node.
151      AddToWorkList(Op.Val);
152
153      // Replace the old value with the new one.
154      ++NodesCombined;
155      DEBUG(std::cerr << "\nReplacing.2 "; TLO.Old.Val->dump();
156            std::cerr << "\nWith: "; TLO.New.Val->dump(&DAG);
157            std::cerr << '\n');
158
159      std::vector<SDNode*> NowDead;
160      DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, NowDead);
161
162      // Push the new node and any (possibly new) users onto the worklist.
163      AddToWorkList(TLO.New.Val);
164      AddUsersToWorkList(TLO.New.Val);
165
166      // Nodes can end up on the worklist more than once.  Make sure we do
167      // not process a node that has been replaced.
168      for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
169        removeFromWorkList(NowDead[i]);
170
171      // Finally, if the node is now dead, remove it from the graph.  The node
172      // may not be dead if the replacement process recursively simplified to
173      // something else needing this node.
174      if (TLO.Old.Val->use_empty()) {
175        removeFromWorkList(TLO.Old.Val);
176        DAG.DeleteNode(TLO.Old.Val);
177      }
178      return true;
179    }
180
181    /// CombineToPreIndexedLoadStore - Try turning a load / store and a
182    /// pre-indexed load / store when the base pointer is a add or subtract
183    /// and it has other uses besides the load / store. After the
184    /// transformation, the new indexed load / store has effectively folded
185    /// the add / subtract in and all of its other uses are redirected to the
186    /// new load / store.
187    bool CombineToPreIndexedLoadStore(SDNode *N) {
188      if (!AfterLegalize)
189        return false;
190
191      bool isLoad = true;
192      SDOperand Ptr;
193      MVT::ValueType VT;
194      if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
195        VT = LD->getLoadedVT();
196        if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
197            !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
198          return false;
199        Ptr = LD->getBasePtr();
200      } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
201        VT = ST->getStoredVT();
202        if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
203            !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
204          return false;
205        Ptr = ST->getBasePtr();
206        isLoad = false;
207      } else
208        return false;
209
210      if ((Ptr.getOpcode() == ISD::ADD || Ptr.getOpcode() == ISD::SUB) &&
211          Ptr.Val->use_size() > 1) {
212        SDOperand BasePtr;
213        SDOperand Offset;
214        ISD::MemIndexedMode AM = ISD::UNINDEXED;
215        if (TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) {
216          // Try turning it into a pre-indexed load / store except when
217          // 1) If N is a store and the ptr is either the same as or is a
218          //    predecessor of the value being stored.
219          // 2) Another use of base ptr is a predecessor of N. If ptr is folded
220          //    that would create a cycle.
221          // 3) All uses are load / store ops that use it as base ptr.
222
223          // Checking #1.
224          if (!isLoad) {
225            SDOperand Val = cast<StoreSDNode>(N)->getValue();
226            if (Val == Ptr || Ptr.Val->isPredecessor(Val.Val))
227              return false;
228          }
229
230          // Now check for #2 and #3.
231          bool RealUse = false;
232          for (SDNode::use_iterator I = Ptr.Val->use_begin(),
233                 E = Ptr.Val->use_end(); I != E; ++I) {
234            SDNode *Use = *I;
235            if (Use == N)
236              continue;
237            if (Use->isPredecessor(N))
238              return false;
239
240            if (!((Use->getOpcode() == ISD::LOAD &&
241                   cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
242                  (Use->getOpcode() == ISD::STORE) &&
243                  cast<StoreSDNode>(Use)->getBasePtr() == Ptr))
244              RealUse = true;
245          }
246          if (!RealUse)
247            return false;
248
249          SDOperand Result = isLoad
250            ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
251            : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
252          ++PreIndexedNodes;
253          ++NodesCombined;
254          DEBUG(std::cerr << "\nReplacing.4 "; N->dump();
255                std::cerr << "\nWith: "; Result.Val->dump(&DAG);
256                std::cerr << '\n');
257          std::vector<SDNode*> NowDead;
258          if (isLoad) {
259            DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
260                                          NowDead);
261            DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
262                                          NowDead);
263          } else {
264            DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
265                                          NowDead);
266          }
267
268          // Nodes can end up on the worklist more than once.  Make sure we do
269          // not process a node that has been replaced.
270          for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
271            removeFromWorkList(NowDead[i]);
272          // Finally, since the node is now dead, remove it from the graph.
273          DAG.DeleteNode(N);
274
275          // Replace the uses of Ptr with uses of the updated base value.
276          DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
277                                        NowDead);
278          removeFromWorkList(Ptr.Val);
279          for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
280            removeFromWorkList(NowDead[i]);
281          DAG.DeleteNode(Ptr.Val);
282
283          return true;
284        }
285      }
286      return false;
287    }
288
289    /// CombineToPostIndexedLoadStore - Try combine a load / store with a
290    /// add / sub of the base pointer node into a post-indexed load / store.
291    /// The transformation folded the add / subtract into the new indexed
292    /// load / store effectively and all of its uses are redirected to the
293    /// new load / store.
294    bool CombineToPostIndexedLoadStore(SDNode *N) {
295      if (!AfterLegalize)
296        return false;
297
298      bool isLoad = true;
299      SDOperand Ptr;
300      MVT::ValueType VT;
301      if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
302        VT = LD->getLoadedVT();
303        if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
304            !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
305          return false;
306        Ptr = LD->getBasePtr();
307      } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
308        VT = ST->getStoredVT();
309        if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
310            !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
311          return false;
312        Ptr = ST->getBasePtr();
313        isLoad = false;
314      } else
315        return false;
316
317      if (Ptr.Val->use_size() > 1) {
318        for (SDNode::use_iterator I = Ptr.Val->use_begin(),
319               E = Ptr.Val->use_end(); I != E; ++I) {
320          SDNode *Op = *I;
321          if (Op == N ||
322              (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
323            continue;
324
325          SDOperand BasePtr;
326          SDOperand Offset;
327          ISD::MemIndexedMode AM = ISD::UNINDEXED;
328          if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
329            if (Ptr == Offset)
330              std::swap(BasePtr, Offset);
331            if (Ptr != BasePtr)
332              continue;
333
334            // Try turning it into a post-indexed load / store except when
335            // 1) All uses are load / store ops that use it as base ptr.
336            // 2) Op must be independent of N, i.e. Op is neither a predecessor
337            //    nor a successor of N. Otherwise, if Op is folded that would
338            //    create a cycle.
339
340            // Check for #1.
341            bool TryNext = false;
342            for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
343                   EE = BasePtr.Val->use_end(); II != EE; ++II) {
344              SDNode *Use = *II;
345              if (Use == Ptr.Val)
346                continue;
347
348              // If all the uses are load / store addresses, then don't do the
349              // transformation.
350              if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
351                bool RealUse = false;
352                for (SDNode::use_iterator III = Use->use_begin(),
353                       EEE = Use->use_end(); III != EEE; ++III) {
354                  SDNode *UseUse = *III;
355                  if (!((UseUse->getOpcode() == ISD::LOAD &&
356                         cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
357                        (UseUse->getOpcode() == ISD::STORE) &&
358                        cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use))
359                    RealUse = true;
360                }
361
362                if (!RealUse) {
363                  TryNext = true;
364                  break;
365                }
366              }
367            }
368            if (TryNext)
369              continue;
370
371            // Check for #2
372            if (!Op->isPredecessor(N) && !N->isPredecessor(Op)) {
373              SDOperand Result = isLoad
374                ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
375                : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
376              ++PostIndexedNodes;
377              ++NodesCombined;
378              DEBUG(std::cerr << "\nReplacing.5 "; N->dump();
379                    std::cerr << "\nWith: "; Result.Val->dump(&DAG);
380                    std::cerr << '\n');
381              std::vector<SDNode*> NowDead;
382              if (isLoad) {
383                DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
384                                              NowDead);
385                DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
386                                              NowDead);
387              } else {
388                DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
389                                              NowDead);
390              }
391
392              // Nodes can end up on the worklist more than once.  Make sure we do
393              // not process a node that has been replaced.
394              for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
395                removeFromWorkList(NowDead[i]);
396              // Finally, since the node is now dead, remove it from the graph.
397              DAG.DeleteNode(N);
398
399              // Replace the uses of Use with uses of the updated base value.
400              DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
401                                            Result.getValue(isLoad ? 1 : 0),
402                                            NowDead);
403              removeFromWorkList(Op);
404              for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
405                removeFromWorkList(NowDead[i]);
406              DAG.DeleteNode(Op);
407
408              return true;
409            }
410          }
411        }
412      }
413      return false;
414    }
415
416    /// visit - call the node-specific routine that knows how to fold each
417    /// particular type of node.
418    SDOperand visit(SDNode *N);
419
420    // Visitation implementation - Implement dag node combining for different
421    // node types.  The semantics are as follows:
422    // Return Value:
423    //   SDOperand.Val == 0   - No change was made
424    //   SDOperand.Val == N   - N was replaced, is dead, and is already handled.
425    //   otherwise            - N should be replaced by the returned Operand.
426    //
427    SDOperand visitTokenFactor(SDNode *N);
428    SDOperand visitADD(SDNode *N);
429    SDOperand visitSUB(SDNode *N);
430    SDOperand visitMUL(SDNode *N);
431    SDOperand visitSDIV(SDNode *N);
432    SDOperand visitUDIV(SDNode *N);
433    SDOperand visitSREM(SDNode *N);
434    SDOperand visitUREM(SDNode *N);
435    SDOperand visitMULHU(SDNode *N);
436    SDOperand visitMULHS(SDNode *N);
437    SDOperand visitAND(SDNode *N);
438    SDOperand visitOR(SDNode *N);
439    SDOperand visitXOR(SDNode *N);
440    SDOperand visitVBinOp(SDNode *N, ISD::NodeType IntOp, ISD::NodeType FPOp);
441    SDOperand visitSHL(SDNode *N);
442    SDOperand visitSRA(SDNode *N);
443    SDOperand visitSRL(SDNode *N);
444    SDOperand visitCTLZ(SDNode *N);
445    SDOperand visitCTTZ(SDNode *N);
446    SDOperand visitCTPOP(SDNode *N);
447    SDOperand visitSELECT(SDNode *N);
448    SDOperand visitSELECT_CC(SDNode *N);
449    SDOperand visitSETCC(SDNode *N);
450    SDOperand visitSIGN_EXTEND(SDNode *N);
451    SDOperand visitZERO_EXTEND(SDNode *N);
452    SDOperand visitANY_EXTEND(SDNode *N);
453    SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
454    SDOperand visitTRUNCATE(SDNode *N);
455    SDOperand visitBIT_CONVERT(SDNode *N);
456    SDOperand visitVBIT_CONVERT(SDNode *N);
457    SDOperand visitFADD(SDNode *N);
458    SDOperand visitFSUB(SDNode *N);
459    SDOperand visitFMUL(SDNode *N);
460    SDOperand visitFDIV(SDNode *N);
461    SDOperand visitFREM(SDNode *N);
462    SDOperand visitFCOPYSIGN(SDNode *N);
463    SDOperand visitSINT_TO_FP(SDNode *N);
464    SDOperand visitUINT_TO_FP(SDNode *N);
465    SDOperand visitFP_TO_SINT(SDNode *N);
466    SDOperand visitFP_TO_UINT(SDNode *N);
467    SDOperand visitFP_ROUND(SDNode *N);
468    SDOperand visitFP_ROUND_INREG(SDNode *N);
469    SDOperand visitFP_EXTEND(SDNode *N);
470    SDOperand visitFNEG(SDNode *N);
471    SDOperand visitFABS(SDNode *N);
472    SDOperand visitBRCOND(SDNode *N);
473    SDOperand visitBR_CC(SDNode *N);
474    SDOperand visitLOAD(SDNode *N);
475    SDOperand visitSTORE(SDNode *N);
476    SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
477    SDOperand visitVINSERT_VECTOR_ELT(SDNode *N);
478    SDOperand visitVBUILD_VECTOR(SDNode *N);
479    SDOperand visitVECTOR_SHUFFLE(SDNode *N);
480    SDOperand visitVVECTOR_SHUFFLE(SDNode *N);
481
482    SDOperand XformToShuffleWithZero(SDNode *N);
483    SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
484
485    bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
486    SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
487    SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
488    SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
489                               SDOperand N3, ISD::CondCode CC);
490    SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
491                            ISD::CondCode Cond, bool foldBooleans = true);
492    SDOperand ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(SDNode *, MVT::ValueType);
493    SDOperand BuildSDIV(SDNode *N);
494    SDOperand BuildUDIV(SDNode *N);
495    SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
496
497    /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
498    /// looking for aliasing nodes and adding them to the Aliases vector.
499    void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
500                          SmallVector<SDOperand, 8> &Aliases);
501
502    /// isAlias - Return true if there is any possibility that the two addresses
503    /// overlap.
504    bool isAlias(SDOperand Ptr1, int64_t Size1,
505                 const Value *SrcValue1, int SrcValueOffset1,
506                 SDOperand Ptr2, int64_t Size2,
507                 const Value *SrcValue2, int SrcValueOffset2);
508
509    /// FindAliasInfo - Extracts the relevant alias information from the memory
510    /// node.  Returns true if the operand was a load.
511    bool FindAliasInfo(SDNode *N,
512                       SDOperand &Ptr, int64_t &Size,
513                       const Value *&SrcValue, int &SrcValueOffset);
514
515    /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
516    /// looking for a better chain (aliasing node.)
517    SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
518
519public:
520    DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
521      : DAG(D),
522        TLI(D.getTargetLoweringInfo()),
523        AfterLegalize(false),
524        AA(A) {}
525
526    /// Run - runs the dag combiner on all nodes in the work list
527    void Run(bool RunningAfterLegalize);
528  };
529}
530
531//===----------------------------------------------------------------------===//
532//  TargetLowering::DAGCombinerInfo implementation
533//===----------------------------------------------------------------------===//
534
535void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
536  ((DAGCombiner*)DC)->AddToWorkList(N);
537}
538
539SDOperand TargetLowering::DAGCombinerInfo::
540CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
541  return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
542}
543
544SDOperand TargetLowering::DAGCombinerInfo::
545CombineTo(SDNode *N, SDOperand Res) {
546  return ((DAGCombiner*)DC)->CombineTo(N, Res);
547}
548
549
550SDOperand TargetLowering::DAGCombinerInfo::
551CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
552  return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
553}
554
555
556
557
558//===----------------------------------------------------------------------===//
559
560
561// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
562// that selects between the values 1 and 0, making it equivalent to a setcc.
563// Also, set the incoming LHS, RHS, and CC references to the appropriate
564// nodes based on the type of node we are checking.  This simplifies life a
565// bit for the callers.
566static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
567                              SDOperand &CC) {
568  if (N.getOpcode() == ISD::SETCC) {
569    LHS = N.getOperand(0);
570    RHS = N.getOperand(1);
571    CC  = N.getOperand(2);
572    return true;
573  }
574  if (N.getOpcode() == ISD::SELECT_CC &&
575      N.getOperand(2).getOpcode() == ISD::Constant &&
576      N.getOperand(3).getOpcode() == ISD::Constant &&
577      cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
578      cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
579    LHS = N.getOperand(0);
580    RHS = N.getOperand(1);
581    CC  = N.getOperand(4);
582    return true;
583  }
584  return false;
585}
586
587// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
588// one use.  If this is true, it allows the users to invert the operation for
589// free when it is profitable to do so.
590static bool isOneUseSetCC(SDOperand N) {
591  SDOperand N0, N1, N2;
592  if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
593    return true;
594  return false;
595}
596
597SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
598  MVT::ValueType VT = N0.getValueType();
599  // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
600  // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
601  if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
602    if (isa<ConstantSDNode>(N1)) {
603      SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
604      AddToWorkList(OpNode.Val);
605      return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
606    } else if (N0.hasOneUse()) {
607      SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
608      AddToWorkList(OpNode.Val);
609      return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
610    }
611  }
612  // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
613  // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
614  if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
615    if (isa<ConstantSDNode>(N0)) {
616      SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
617      AddToWorkList(OpNode.Val);
618      return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
619    } else if (N1.hasOneUse()) {
620      SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
621      AddToWorkList(OpNode.Val);
622      return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
623    }
624  }
625  return SDOperand();
626}
627
628void DAGCombiner::Run(bool RunningAfterLegalize) {
629  // set the instance variable, so that the various visit routines may use it.
630  AfterLegalize = RunningAfterLegalize;
631
632  // Add all the dag nodes to the worklist.
633  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
634       E = DAG.allnodes_end(); I != E; ++I)
635    WorkList.push_back(I);
636
637  // Create a dummy node (which is not added to allnodes), that adds a reference
638  // to the root node, preventing it from being deleted, and tracking any
639  // changes of the root.
640  HandleSDNode Dummy(DAG.getRoot());
641
642  // The root of the dag may dangle to deleted nodes until the dag combiner is
643  // done.  Set it to null to avoid confusion.
644  DAG.setRoot(SDOperand());
645
646  /// DagCombineInfo - Expose the DAG combiner to the target combiner impls.
647  TargetLowering::DAGCombinerInfo
648    DagCombineInfo(DAG, !RunningAfterLegalize, this);
649
650  // while the worklist isn't empty, inspect the node on the end of it and
651  // try and combine it.
652  while (!WorkList.empty()) {
653    SDNode *N = WorkList.back();
654    WorkList.pop_back();
655
656    // If N has no uses, it is dead.  Make sure to revisit all N's operands once
657    // N is deleted from the DAG, since they too may now be dead or may have a
658    // reduced number of uses, allowing other xforms.
659    if (N->use_empty() && N != &Dummy) {
660      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
661        AddToWorkList(N->getOperand(i).Val);
662
663      DAG.DeleteNode(N);
664      continue;
665    }
666
667    SDOperand RV = visit(N);
668
669    // If nothing happened, try a target-specific DAG combine.
670    if (RV.Val == 0) {
671      assert(N->getOpcode() != ISD::DELETED_NODE &&
672             "Node was deleted but visit returned NULL!");
673      if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
674          TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode()))
675        RV = TLI.PerformDAGCombine(N, DagCombineInfo);
676    }
677
678    if (RV.Val) {
679      ++NodesCombined;
680      // If we get back the same node we passed in, rather than a new node or
681      // zero, we know that the node must have defined multiple values and
682      // CombineTo was used.  Since CombineTo takes care of the worklist
683      // mechanics for us, we have no work to do in this case.
684      if (RV.Val != N) {
685        assert(N->getOpcode() != ISD::DELETED_NODE &&
686               RV.Val->getOpcode() != ISD::DELETED_NODE &&
687               "Node was deleted but visit returned new node!");
688
689        DEBUG(std::cerr << "\nReplacing.3 "; N->dump();
690              std::cerr << "\nWith: "; RV.Val->dump(&DAG);
691              std::cerr << '\n');
692        std::vector<SDNode*> NowDead;
693        if (N->getNumValues() == RV.Val->getNumValues())
694          DAG.ReplaceAllUsesWith(N, RV.Val, &NowDead);
695        else {
696          assert(N->getValueType(0) == RV.getValueType() && "Type mismatch");
697          SDOperand OpV = RV;
698          DAG.ReplaceAllUsesWith(N, &OpV, &NowDead);
699        }
700
701        // Push the new node and any users onto the worklist
702        AddToWorkList(RV.Val);
703        AddUsersToWorkList(RV.Val);
704
705        // Nodes can be reintroduced into the worklist.  Make sure we do not
706        // process a node that has been replaced.
707        removeFromWorkList(N);
708        for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
709          removeFromWorkList(NowDead[i]);
710
711        // Finally, since the node is now dead, remove it from the graph.
712        DAG.DeleteNode(N);
713      }
714    }
715  }
716
717  // If the root changed (e.g. it was a dead load, update the root).
718  DAG.setRoot(Dummy.getValue());
719}
720
721SDOperand DAGCombiner::visit(SDNode *N) {
722  switch(N->getOpcode()) {
723  default: break;
724  case ISD::TokenFactor:        return visitTokenFactor(N);
725  case ISD::ADD:                return visitADD(N);
726  case ISD::SUB:                return visitSUB(N);
727  case ISD::MUL:                return visitMUL(N);
728  case ISD::SDIV:               return visitSDIV(N);
729  case ISD::UDIV:               return visitUDIV(N);
730  case ISD::SREM:               return visitSREM(N);
731  case ISD::UREM:               return visitUREM(N);
732  case ISD::MULHU:              return visitMULHU(N);
733  case ISD::MULHS:              return visitMULHS(N);
734  case ISD::AND:                return visitAND(N);
735  case ISD::OR:                 return visitOR(N);
736  case ISD::XOR:                return visitXOR(N);
737  case ISD::SHL:                return visitSHL(N);
738  case ISD::SRA:                return visitSRA(N);
739  case ISD::SRL:                return visitSRL(N);
740  case ISD::CTLZ:               return visitCTLZ(N);
741  case ISD::CTTZ:               return visitCTTZ(N);
742  case ISD::CTPOP:              return visitCTPOP(N);
743  case ISD::SELECT:             return visitSELECT(N);
744  case ISD::SELECT_CC:          return visitSELECT_CC(N);
745  case ISD::SETCC:              return visitSETCC(N);
746  case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
747  case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
748  case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
749  case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
750  case ISD::TRUNCATE:           return visitTRUNCATE(N);
751  case ISD::BIT_CONVERT:        return visitBIT_CONVERT(N);
752  case ISD::VBIT_CONVERT:       return visitVBIT_CONVERT(N);
753  case ISD::FADD:               return visitFADD(N);
754  case ISD::FSUB:               return visitFSUB(N);
755  case ISD::FMUL:               return visitFMUL(N);
756  case ISD::FDIV:               return visitFDIV(N);
757  case ISD::FREM:               return visitFREM(N);
758  case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
759  case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
760  case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
761  case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
762  case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
763  case ISD::FP_ROUND:           return visitFP_ROUND(N);
764  case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
765  case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
766  case ISD::FNEG:               return visitFNEG(N);
767  case ISD::FABS:               return visitFABS(N);
768  case ISD::BRCOND:             return visitBRCOND(N);
769  case ISD::BR_CC:              return visitBR_CC(N);
770  case ISD::LOAD:               return visitLOAD(N);
771  case ISD::STORE:              return visitSTORE(N);
772  case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
773  case ISD::VINSERT_VECTOR_ELT: return visitVINSERT_VECTOR_ELT(N);
774  case ISD::VBUILD_VECTOR:      return visitVBUILD_VECTOR(N);
775  case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
776  case ISD::VVECTOR_SHUFFLE:    return visitVVECTOR_SHUFFLE(N);
777  case ISD::VADD:               return visitVBinOp(N, ISD::ADD , ISD::FADD);
778  case ISD::VSUB:               return visitVBinOp(N, ISD::SUB , ISD::FSUB);
779  case ISD::VMUL:               return visitVBinOp(N, ISD::MUL , ISD::FMUL);
780  case ISD::VSDIV:              return visitVBinOp(N, ISD::SDIV, ISD::FDIV);
781  case ISD::VUDIV:              return visitVBinOp(N, ISD::UDIV, ISD::UDIV);
782  case ISD::VAND:               return visitVBinOp(N, ISD::AND , ISD::AND);
783  case ISD::VOR:                return visitVBinOp(N, ISD::OR  , ISD::OR);
784  case ISD::VXOR:               return visitVBinOp(N, ISD::XOR , ISD::XOR);
785  }
786  return SDOperand();
787}
788
789/// getInputChainForNode - Given a node, return its input chain if it has one,
790/// otherwise return a null sd operand.
791static SDOperand getInputChainForNode(SDNode *N) {
792  if (unsigned NumOps = N->getNumOperands()) {
793    if (N->getOperand(0).getValueType() == MVT::Other)
794      return N->getOperand(0);
795    else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
796      return N->getOperand(NumOps-1);
797    for (unsigned i = 1; i < NumOps-1; ++i)
798      if (N->getOperand(i).getValueType() == MVT::Other)
799        return N->getOperand(i);
800  }
801  return SDOperand(0, 0);
802}
803
804SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
805  // If N has two operands, where one has an input chain equal to the other,
806  // the 'other' chain is redundant.
807  if (N->getNumOperands() == 2) {
808    if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
809      return N->getOperand(0);
810    if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
811      return N->getOperand(1);
812  }
813
814
815  SmallVector<SDNode *, 8> TFs;   // List of token factors to visit.
816  SmallVector<SDOperand, 8> Ops;  // Ops for replacing token factor.
817  bool Changed = false;           // If we should replace this token factor.
818
819  // Start out with this token factor.
820  TFs.push_back(N);
821
822  // Iterate through token factors.  The TFs grows when new token factors are
823  // encountered.
824  for (unsigned i = 0; i < TFs.size(); ++i) {
825    SDNode *TF = TFs[i];
826
827    // Check each of the operands.
828    for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
829      SDOperand Op = TF->getOperand(i);
830
831      switch (Op.getOpcode()) {
832      case ISD::EntryToken:
833        // Entry tokens don't need to be added to the list. They are
834        // rededundant.
835        Changed = true;
836        break;
837
838      case ISD::TokenFactor:
839        if ((CombinerAA || Op.hasOneUse()) &&
840            std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
841          // Queue up for processing.
842          TFs.push_back(Op.Val);
843          // Clean up in case the token factor is removed.
844          AddToWorkList(Op.Val);
845          Changed = true;
846          break;
847        }
848        // Fall thru
849
850      default:
851        // Only add if not there prior.
852        if (std::find(Ops.begin(), Ops.end(), Op) == Ops.end())
853          Ops.push_back(Op);
854        break;
855      }
856    }
857  }
858
859  SDOperand Result;
860
861  // If we've change things around then replace token factor.
862  if (Changed) {
863    if (Ops.size() == 0) {
864      // The entry token is the only possible outcome.
865      Result = DAG.getEntryNode();
866    } else {
867      // New and improved token factor.
868      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
869    }
870
871    // Don't add users to work list.
872    return CombineTo(N, Result, false);
873  }
874
875  return Result;
876}
877
878SDOperand DAGCombiner::visitADD(SDNode *N) {
879  SDOperand N0 = N->getOperand(0);
880  SDOperand N1 = N->getOperand(1);
881  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
882  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
883  MVT::ValueType VT = N0.getValueType();
884
885  // fold (add c1, c2) -> c1+c2
886  if (N0C && N1C)
887    return DAG.getNode(ISD::ADD, VT, N0, N1);
888  // canonicalize constant to RHS
889  if (N0C && !N1C)
890    return DAG.getNode(ISD::ADD, VT, N1, N0);
891  // fold (add x, 0) -> x
892  if (N1C && N1C->isNullValue())
893    return N0;
894  // fold ((c1-A)+c2) -> (c1+c2)-A
895  if (N1C && N0.getOpcode() == ISD::SUB)
896    if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
897      return DAG.getNode(ISD::SUB, VT,
898                         DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
899                         N0.getOperand(1));
900  // reassociate add
901  SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
902  if (RADD.Val != 0)
903    return RADD;
904  // fold ((0-A) + B) -> B-A
905  if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
906      cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
907    return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
908  // fold (A + (0-B)) -> A-B
909  if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
910      cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
911    return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
912  // fold (A+(B-A)) -> B
913  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
914    return N1.getOperand(0);
915
916  if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
917    return SDOperand(N, 0);
918
919  // fold (a+b) -> (a|b) iff a and b share no bits.
920  if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
921    uint64_t LHSZero, LHSOne;
922    uint64_t RHSZero, RHSOne;
923    uint64_t Mask = MVT::getIntVTBitMask(VT);
924    TLI.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
925    if (LHSZero) {
926      TLI.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
927
928      // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
929      // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
930      if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
931          (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
932        return DAG.getNode(ISD::OR, VT, N0, N1);
933    }
934  }
935
936  return SDOperand();
937}
938
939SDOperand DAGCombiner::visitSUB(SDNode *N) {
940  SDOperand N0 = N->getOperand(0);
941  SDOperand N1 = N->getOperand(1);
942  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
943  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
944  MVT::ValueType VT = N0.getValueType();
945
946  // fold (sub x, x) -> 0
947  if (N0 == N1)
948    return DAG.getConstant(0, N->getValueType(0));
949  // fold (sub c1, c2) -> c1-c2
950  if (N0C && N1C)
951    return DAG.getNode(ISD::SUB, VT, N0, N1);
952  // fold (sub x, c) -> (add x, -c)
953  if (N1C)
954    return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
955  // fold (A+B)-A -> B
956  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
957    return N0.getOperand(1);
958  // fold (A+B)-B -> A
959  if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
960    return N0.getOperand(0);
961  return SDOperand();
962}
963
964SDOperand DAGCombiner::visitMUL(SDNode *N) {
965  SDOperand N0 = N->getOperand(0);
966  SDOperand N1 = N->getOperand(1);
967  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
968  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
969  MVT::ValueType VT = N0.getValueType();
970
971  // fold (mul c1, c2) -> c1*c2
972  if (N0C && N1C)
973    return DAG.getNode(ISD::MUL, VT, N0, N1);
974  // canonicalize constant to RHS
975  if (N0C && !N1C)
976    return DAG.getNode(ISD::MUL, VT, N1, N0);
977  // fold (mul x, 0) -> 0
978  if (N1C && N1C->isNullValue())
979    return N1;
980  // fold (mul x, -1) -> 0-x
981  if (N1C && N1C->isAllOnesValue())
982    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
983  // fold (mul x, (1 << c)) -> x << c
984  if (N1C && isPowerOf2_64(N1C->getValue()))
985    return DAG.getNode(ISD::SHL, VT, N0,
986                       DAG.getConstant(Log2_64(N1C->getValue()),
987                                       TLI.getShiftAmountTy()));
988  // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
989  if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
990    // FIXME: If the input is something that is easily negated (e.g. a
991    // single-use add), we should put the negate there.
992    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
993                       DAG.getNode(ISD::SHL, VT, N0,
994                            DAG.getConstant(Log2_64(-N1C->getSignExtended()),
995                                            TLI.getShiftAmountTy())));
996  }
997
998  // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
999  if (N1C && N0.getOpcode() == ISD::SHL &&
1000      isa<ConstantSDNode>(N0.getOperand(1))) {
1001    SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1002    AddToWorkList(C3.Val);
1003    return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1004  }
1005
1006  // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1007  // use.
1008  {
1009    SDOperand Sh(0,0), Y(0,0);
1010    // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1011    if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1012        N0.Val->hasOneUse()) {
1013      Sh = N0; Y = N1;
1014    } else if (N1.getOpcode() == ISD::SHL &&
1015               isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1016      Sh = N1; Y = N0;
1017    }
1018    if (Sh.Val) {
1019      SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1020      return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1021    }
1022  }
1023  // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1024  if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1025      isa<ConstantSDNode>(N0.getOperand(1))) {
1026    return DAG.getNode(ISD::ADD, VT,
1027                       DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1028                       DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1029  }
1030
1031  // reassociate mul
1032  SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1033  if (RMUL.Val != 0)
1034    return RMUL;
1035  return SDOperand();
1036}
1037
1038SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1039  SDOperand N0 = N->getOperand(0);
1040  SDOperand N1 = N->getOperand(1);
1041  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1042  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1043  MVT::ValueType VT = N->getValueType(0);
1044
1045  // fold (sdiv c1, c2) -> c1/c2
1046  if (N0C && N1C && !N1C->isNullValue())
1047    return DAG.getNode(ISD::SDIV, VT, N0, N1);
1048  // fold (sdiv X, 1) -> X
1049  if (N1C && N1C->getSignExtended() == 1LL)
1050    return N0;
1051  // fold (sdiv X, -1) -> 0-X
1052  if (N1C && N1C->isAllOnesValue())
1053    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1054  // If we know the sign bits of both operands are zero, strength reduce to a
1055  // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1056  uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1057  if (TLI.MaskedValueIsZero(N1, SignBit) &&
1058      TLI.MaskedValueIsZero(N0, SignBit))
1059    return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1060  // fold (sdiv X, pow2) -> simple ops after legalize
1061  if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
1062      (isPowerOf2_64(N1C->getSignExtended()) ||
1063       isPowerOf2_64(-N1C->getSignExtended()))) {
1064    // If dividing by powers of two is cheap, then don't perform the following
1065    // fold.
1066    if (TLI.isPow2DivCheap())
1067      return SDOperand();
1068    int64_t pow2 = N1C->getSignExtended();
1069    int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1070    unsigned lg2 = Log2_64(abs2);
1071    // Splat the sign bit into the register
1072    SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1073                                DAG.getConstant(MVT::getSizeInBits(VT)-1,
1074                                                TLI.getShiftAmountTy()));
1075    AddToWorkList(SGN.Val);
1076    // Add (N0 < 0) ? abs2 - 1 : 0;
1077    SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1078                                DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
1079                                                TLI.getShiftAmountTy()));
1080    SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1081    AddToWorkList(SRL.Val);
1082    AddToWorkList(ADD.Val);    // Divide by pow2
1083    SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1084                                DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1085    // If we're dividing by a positive value, we're done.  Otherwise, we must
1086    // negate the result.
1087    if (pow2 > 0)
1088      return SRA;
1089    AddToWorkList(SRA.Val);
1090    return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1091  }
1092  // if integer divide is expensive and we satisfy the requirements, emit an
1093  // alternate sequence.
1094  if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1095      !TLI.isIntDivCheap()) {
1096    SDOperand Op = BuildSDIV(N);
1097    if (Op.Val) return Op;
1098  }
1099  return SDOperand();
1100}
1101
1102SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1103  SDOperand N0 = N->getOperand(0);
1104  SDOperand N1 = N->getOperand(1);
1105  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1106  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1107  MVT::ValueType VT = N->getValueType(0);
1108
1109  // fold (udiv c1, c2) -> c1/c2
1110  if (N0C && N1C && !N1C->isNullValue())
1111    return DAG.getNode(ISD::UDIV, VT, N0, N1);
1112  // fold (udiv x, (1 << c)) -> x >>u c
1113  if (N1C && isPowerOf2_64(N1C->getValue()))
1114    return DAG.getNode(ISD::SRL, VT, N0,
1115                       DAG.getConstant(Log2_64(N1C->getValue()),
1116                                       TLI.getShiftAmountTy()));
1117  // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1118  if (N1.getOpcode() == ISD::SHL) {
1119    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1120      if (isPowerOf2_64(SHC->getValue())) {
1121        MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
1122        SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1123                                    DAG.getConstant(Log2_64(SHC->getValue()),
1124                                                    ADDVT));
1125        AddToWorkList(Add.Val);
1126        return DAG.getNode(ISD::SRL, VT, N0, Add);
1127      }
1128    }
1129  }
1130  // fold (udiv x, c) -> alternate
1131  if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
1132    SDOperand Op = BuildUDIV(N);
1133    if (Op.Val) return Op;
1134  }
1135  return SDOperand();
1136}
1137
1138SDOperand DAGCombiner::visitSREM(SDNode *N) {
1139  SDOperand N0 = N->getOperand(0);
1140  SDOperand N1 = N->getOperand(1);
1141  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1142  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1143  MVT::ValueType VT = N->getValueType(0);
1144
1145  // fold (srem c1, c2) -> c1%c2
1146  if (N0C && N1C && !N1C->isNullValue())
1147    return DAG.getNode(ISD::SREM, VT, N0, N1);
1148  // If we know the sign bits of both operands are zero, strength reduce to a
1149  // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1150  uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1151  if (TLI.MaskedValueIsZero(N1, SignBit) &&
1152      TLI.MaskedValueIsZero(N0, SignBit))
1153    return DAG.getNode(ISD::UREM, VT, N0, N1);
1154
1155  // Unconditionally lower X%C -> X-X/C*C.  This allows the X/C logic to hack on
1156  // the remainder operation.
1157  if (N1C && !N1C->isNullValue()) {
1158    SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1159    SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
1160    SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1161    AddToWorkList(Div.Val);
1162    AddToWorkList(Mul.Val);
1163    return Sub;
1164  }
1165
1166  return SDOperand();
1167}
1168
1169SDOperand DAGCombiner::visitUREM(SDNode *N) {
1170  SDOperand N0 = N->getOperand(0);
1171  SDOperand N1 = N->getOperand(1);
1172  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1173  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1174  MVT::ValueType VT = N->getValueType(0);
1175
1176  // fold (urem c1, c2) -> c1%c2
1177  if (N0C && N1C && !N1C->isNullValue())
1178    return DAG.getNode(ISD::UREM, VT, N0, N1);
1179  // fold (urem x, pow2) -> (and x, pow2-1)
1180  if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
1181    return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
1182  // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1183  if (N1.getOpcode() == ISD::SHL) {
1184    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1185      if (isPowerOf2_64(SHC->getValue())) {
1186        SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
1187        AddToWorkList(Add.Val);
1188        return DAG.getNode(ISD::AND, VT, N0, Add);
1189      }
1190    }
1191  }
1192
1193  // Unconditionally lower X%C -> X-X/C*C.  This allows the X/C logic to hack on
1194  // the remainder operation.
1195  if (N1C && !N1C->isNullValue()) {
1196    SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1197    SDOperand Mul = DAG.getNode(ISD::MUL, VT, Div, N1);
1198    SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1199    AddToWorkList(Div.Val);
1200    AddToWorkList(Mul.Val);
1201    return Sub;
1202  }
1203
1204  return SDOperand();
1205}
1206
1207SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1208  SDOperand N0 = N->getOperand(0);
1209  SDOperand N1 = N->getOperand(1);
1210  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1211
1212  // fold (mulhs x, 0) -> 0
1213  if (N1C && N1C->isNullValue())
1214    return N1;
1215  // fold (mulhs x, 1) -> (sra x, size(x)-1)
1216  if (N1C && N1C->getValue() == 1)
1217    return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1218                       DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1219                                       TLI.getShiftAmountTy()));
1220  return SDOperand();
1221}
1222
1223SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1224  SDOperand N0 = N->getOperand(0);
1225  SDOperand N1 = N->getOperand(1);
1226  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1227
1228  // fold (mulhu x, 0) -> 0
1229  if (N1C && N1C->isNullValue())
1230    return N1;
1231  // fold (mulhu x, 1) -> 0
1232  if (N1C && N1C->getValue() == 1)
1233    return DAG.getConstant(0, N0.getValueType());
1234  return SDOperand();
1235}
1236
1237/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1238/// two operands of the same opcode, try to simplify it.
1239SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1240  SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1241  MVT::ValueType VT = N0.getValueType();
1242  assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1243
1244  // For each of OP in AND/OR/XOR:
1245  // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1246  // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1247  // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1248  // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1249  if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1250       N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1251      N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1252    SDOperand ORNode = DAG.getNode(N->getOpcode(),
1253                                   N0.getOperand(0).getValueType(),
1254                                   N0.getOperand(0), N1.getOperand(0));
1255    AddToWorkList(ORNode.Val);
1256    return DAG.getNode(N0.getOpcode(), VT, ORNode);
1257  }
1258
1259  // For each of OP in SHL/SRL/SRA/AND...
1260  //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1261  //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
1262  //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1263  if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1264       N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1265      N0.getOperand(1) == N1.getOperand(1)) {
1266    SDOperand ORNode = DAG.getNode(N->getOpcode(),
1267                                   N0.getOperand(0).getValueType(),
1268                                   N0.getOperand(0), N1.getOperand(0));
1269    AddToWorkList(ORNode.Val);
1270    return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1271  }
1272
1273  return SDOperand();
1274}
1275
1276SDOperand DAGCombiner::visitAND(SDNode *N) {
1277  SDOperand N0 = N->getOperand(0);
1278  SDOperand N1 = N->getOperand(1);
1279  SDOperand LL, LR, RL, RR, CC0, CC1;
1280  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1281  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1282  MVT::ValueType VT = N1.getValueType();
1283
1284  // fold (and c1, c2) -> c1&c2
1285  if (N0C && N1C)
1286    return DAG.getNode(ISD::AND, VT, N0, N1);
1287  // canonicalize constant to RHS
1288  if (N0C && !N1C)
1289    return DAG.getNode(ISD::AND, VT, N1, N0);
1290  // fold (and x, -1) -> x
1291  if (N1C && N1C->isAllOnesValue())
1292    return N0;
1293  // if (and x, c) is known to be zero, return 0
1294  if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1295    return DAG.getConstant(0, VT);
1296  // reassociate and
1297  SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1298  if (RAND.Val != 0)
1299    return RAND;
1300  // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1301  if (N1C && N0.getOpcode() == ISD::OR)
1302    if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1303      if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
1304        return N1;
1305  // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1306  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1307    unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
1308    if (TLI.MaskedValueIsZero(N0.getOperand(0),
1309                              ~N1C->getValue() & InMask)) {
1310      SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1311                                   N0.getOperand(0));
1312
1313      // Replace uses of the AND with uses of the Zero extend node.
1314      CombineTo(N, Zext);
1315
1316      // We actually want to replace all uses of the any_extend with the
1317      // zero_extend, to avoid duplicating things.  This will later cause this
1318      // AND to be folded.
1319      CombineTo(N0.Val, Zext);
1320      return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1321    }
1322  }
1323  // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1324  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1325    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1326    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1327
1328    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1329        MVT::isInteger(LL.getValueType())) {
1330      // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1331      if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
1332        SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1333        AddToWorkList(ORNode.Val);
1334        return DAG.getSetCC(VT, ORNode, LR, Op1);
1335      }
1336      // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1337      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1338        SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1339        AddToWorkList(ANDNode.Val);
1340        return DAG.getSetCC(VT, ANDNode, LR, Op1);
1341      }
1342      // fold (X >  -1) & (Y >  -1) -> (X|Y > -1)
1343      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1344        SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1345        AddToWorkList(ORNode.Val);
1346        return DAG.getSetCC(VT, ORNode, LR, Op1);
1347      }
1348    }
1349    // canonicalize equivalent to ll == rl
1350    if (LL == RR && LR == RL) {
1351      Op1 = ISD::getSetCCSwappedOperands(Op1);
1352      std::swap(RL, RR);
1353    }
1354    if (LL == RL && LR == RR) {
1355      bool isInteger = MVT::isInteger(LL.getValueType());
1356      ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1357      if (Result != ISD::SETCC_INVALID)
1358        return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1359    }
1360  }
1361
1362  // Simplify: and (op x...), (op y...)  -> (op (and x, y))
1363  if (N0.getOpcode() == N1.getOpcode()) {
1364    SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1365    if (Tmp.Val) return Tmp;
1366  }
1367
1368  // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1369  // fold (and (sra)) -> (and (srl)) when possible.
1370  if (!MVT::isVector(VT) &&
1371      SimplifyDemandedBits(SDOperand(N, 0)))
1372    return SDOperand(N, 0);
1373  // fold (zext_inreg (extload x)) -> (zextload x)
1374  if (ISD::isEXTLoad(N0.Val)) {
1375    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1376    MVT::ValueType EVT = LN0->getLoadedVT();
1377    // If we zero all the possible extended bits, then we can turn this into
1378    // a zextload if we are running before legalize or the operation is legal.
1379    if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1380        (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1381      SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1382                                         LN0->getBasePtr(), LN0->getSrcValue(),
1383                                         LN0->getSrcValueOffset(), EVT);
1384      AddToWorkList(N);
1385      CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1386      return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1387    }
1388  }
1389  // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1390  if (ISD::isSEXTLoad(N0.Val) && N0.hasOneUse()) {
1391    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1392    MVT::ValueType EVT = LN0->getLoadedVT();
1393    // If we zero all the possible extended bits, then we can turn this into
1394    // a zextload if we are running before legalize or the operation is legal.
1395    if (TLI.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1396        (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1397      SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1398                                         LN0->getBasePtr(), LN0->getSrcValue(),
1399                                         LN0->getSrcValueOffset(), EVT);
1400      AddToWorkList(N);
1401      CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1402      return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1403    }
1404  }
1405
1406  // fold (and (load x), 255) -> (zextload x, i8)
1407  // fold (and (extload x, i16), 255) -> (zextload x, i8)
1408  if (N1C && N0.getOpcode() == ISD::LOAD) {
1409    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1410    if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1411        N0.hasOneUse()) {
1412      MVT::ValueType EVT, LoadedVT;
1413      if (N1C->getValue() == 255)
1414        EVT = MVT::i8;
1415      else if (N1C->getValue() == 65535)
1416        EVT = MVT::i16;
1417      else if (N1C->getValue() == ~0U)
1418        EVT = MVT::i32;
1419      else
1420        EVT = MVT::Other;
1421
1422      LoadedVT = LN0->getLoadedVT();
1423      if (EVT != MVT::Other && LoadedVT > EVT &&
1424          (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1425        MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1426        // For big endian targets, we need to add an offset to the pointer to
1427        // load the correct bytes.  For little endian systems, we merely need to
1428        // read fewer bytes from the same pointer.
1429        unsigned PtrOff =
1430          (MVT::getSizeInBits(LoadedVT) - MVT::getSizeInBits(EVT)) / 8;
1431        SDOperand NewPtr = LN0->getBasePtr();
1432        if (!TLI.isLittleEndian())
1433          NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1434                               DAG.getConstant(PtrOff, PtrType));
1435        AddToWorkList(NewPtr.Val);
1436        SDOperand Load =
1437          DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1438                         LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT);
1439        AddToWorkList(N);
1440        CombineTo(N0.Val, Load, Load.getValue(1));
1441        return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
1442      }
1443    }
1444  }
1445
1446  return SDOperand();
1447}
1448
1449SDOperand DAGCombiner::visitOR(SDNode *N) {
1450  SDOperand N0 = N->getOperand(0);
1451  SDOperand N1 = N->getOperand(1);
1452  SDOperand LL, LR, RL, RR, CC0, CC1;
1453  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1454  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1455  MVT::ValueType VT = N1.getValueType();
1456  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1457
1458  // fold (or c1, c2) -> c1|c2
1459  if (N0C && N1C)
1460    return DAG.getNode(ISD::OR, VT, N0, N1);
1461  // canonicalize constant to RHS
1462  if (N0C && !N1C)
1463    return DAG.getNode(ISD::OR, VT, N1, N0);
1464  // fold (or x, 0) -> x
1465  if (N1C && N1C->isNullValue())
1466    return N0;
1467  // fold (or x, -1) -> -1
1468  if (N1C && N1C->isAllOnesValue())
1469    return N1;
1470  // fold (or x, c) -> c iff (x & ~c) == 0
1471  if (N1C &&
1472      TLI.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
1473    return N1;
1474  // reassociate or
1475  SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1476  if (ROR.Val != 0)
1477    return ROR;
1478  // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1479  if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1480             isa<ConstantSDNode>(N0.getOperand(1))) {
1481    ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1482    return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1483                                                 N1),
1484                       DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1485  }
1486  // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1487  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1488    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1489    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1490
1491    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1492        MVT::isInteger(LL.getValueType())) {
1493      // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1494      // fold (X <  0) | (Y <  0) -> (X|Y < 0)
1495      if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1496          (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1497        SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1498        AddToWorkList(ORNode.Val);
1499        return DAG.getSetCC(VT, ORNode, LR, Op1);
1500      }
1501      // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1502      // fold (X >  -1) | (Y >  -1) -> (X&Y >  -1)
1503      if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1504          (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1505        SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1506        AddToWorkList(ANDNode.Val);
1507        return DAG.getSetCC(VT, ANDNode, LR, Op1);
1508      }
1509    }
1510    // canonicalize equivalent to ll == rl
1511    if (LL == RR && LR == RL) {
1512      Op1 = ISD::getSetCCSwappedOperands(Op1);
1513      std::swap(RL, RR);
1514    }
1515    if (LL == RL && LR == RR) {
1516      bool isInteger = MVT::isInteger(LL.getValueType());
1517      ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1518      if (Result != ISD::SETCC_INVALID)
1519        return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1520    }
1521  }
1522
1523  // Simplify: or (op x...), (op y...)  -> (op (or x, y))
1524  if (N0.getOpcode() == N1.getOpcode()) {
1525    SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1526    if (Tmp.Val) return Tmp;
1527  }
1528
1529  // (X & C1) | (Y & C2)  -> (X|Y) & C3  if possible.
1530  if (N0.getOpcode() == ISD::AND &&
1531      N1.getOpcode() == ISD::AND &&
1532      N0.getOperand(1).getOpcode() == ISD::Constant &&
1533      N1.getOperand(1).getOpcode() == ISD::Constant &&
1534      // Don't increase # computations.
1535      (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1536    // We can only do this xform if we know that bits from X that are set in C2
1537    // but not in C1 are already zero.  Likewise for Y.
1538    uint64_t LHSMask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1539    uint64_t RHSMask = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
1540
1541    if (TLI.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1542        TLI.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1543      SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1544      return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1545    }
1546  }
1547
1548
1549  // See if this is some rotate idiom.
1550  if (SDNode *Rot = MatchRotate(N0, N1))
1551    return SDOperand(Rot, 0);
1552
1553  return SDOperand();
1554}
1555
1556
1557/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1558static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1559  if (Op.getOpcode() == ISD::AND) {
1560    if (isa<ConstantSDNode>(Op.getOperand(1))) {
1561      Mask = Op.getOperand(1);
1562      Op = Op.getOperand(0);
1563    } else {
1564      return false;
1565    }
1566  }
1567
1568  if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1569    Shift = Op;
1570    return true;
1571  }
1572  return false;
1573}
1574
1575
1576// MatchRotate - Handle an 'or' of two operands.  If this is one of the many
1577// idioms for rotate, and if the target supports rotation instructions, generate
1578// a rot[lr].
1579SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1580  // Must be a legal type.  Expanded an promoted things won't work with rotates.
1581  MVT::ValueType VT = LHS.getValueType();
1582  if (!TLI.isTypeLegal(VT)) return 0;
1583
1584  // The target must have at least one rotate flavor.
1585  bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1586  bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1587  if (!HasROTL && !HasROTR) return 0;
1588
1589  // Match "(X shl/srl V1) & V2" where V2 may not be present.
1590  SDOperand LHSShift;   // The shift.
1591  SDOperand LHSMask;    // AND value if any.
1592  if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1593    return 0; // Not part of a rotate.
1594
1595  SDOperand RHSShift;   // The shift.
1596  SDOperand RHSMask;    // AND value if any.
1597  if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1598    return 0; // Not part of a rotate.
1599
1600  if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1601    return 0;   // Not shifting the same value.
1602
1603  if (LHSShift.getOpcode() == RHSShift.getOpcode())
1604    return 0;   // Shifts must disagree.
1605
1606  // Canonicalize shl to left side in a shl/srl pair.
1607  if (RHSShift.getOpcode() == ISD::SHL) {
1608    std::swap(LHS, RHS);
1609    std::swap(LHSShift, RHSShift);
1610    std::swap(LHSMask , RHSMask );
1611  }
1612
1613  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1614
1615  // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1616  // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1617  if (LHSShift.getOperand(1).getOpcode() == ISD::Constant &&
1618      RHSShift.getOperand(1).getOpcode() == ISD::Constant) {
1619    uint64_t LShVal = cast<ConstantSDNode>(LHSShift.getOperand(1))->getValue();
1620    uint64_t RShVal = cast<ConstantSDNode>(RHSShift.getOperand(1))->getValue();
1621    if ((LShVal + RShVal) != OpSizeInBits)
1622      return 0;
1623
1624    SDOperand Rot;
1625    if (HasROTL)
1626      Rot = DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1627                        LHSShift.getOperand(1));
1628    else
1629      Rot = DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1630                        RHSShift.getOperand(1));
1631
1632    // If there is an AND of either shifted operand, apply it to the result.
1633    if (LHSMask.Val || RHSMask.Val) {
1634      uint64_t Mask = MVT::getIntVTBitMask(VT);
1635
1636      if (LHSMask.Val) {
1637        uint64_t RHSBits = (1ULL << LShVal)-1;
1638        Mask &= cast<ConstantSDNode>(LHSMask)->getValue() | RHSBits;
1639      }
1640      if (RHSMask.Val) {
1641        uint64_t LHSBits = ~((1ULL << (OpSizeInBits-RShVal))-1);
1642        Mask &= cast<ConstantSDNode>(RHSMask)->getValue() | LHSBits;
1643      }
1644
1645      Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
1646    }
1647
1648    return Rot.Val;
1649  }
1650
1651  // If there is a mask here, and we have a variable shift, we can't be sure
1652  // that we're masking out the right stuff.
1653  if (LHSMask.Val || RHSMask.Val)
1654    return 0;
1655
1656  // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
1657  // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
1658  if (RHSShift.getOperand(1).getOpcode() == ISD::SUB &&
1659      LHSShift.getOperand(1) == RHSShift.getOperand(1).getOperand(1)) {
1660    if (ConstantSDNode *SUBC =
1661          dyn_cast<ConstantSDNode>(RHSShift.getOperand(1).getOperand(0))) {
1662      if (SUBC->getValue() == OpSizeInBits)
1663        if (HasROTL)
1664          return DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1665                             LHSShift.getOperand(1)).Val;
1666        else
1667          return DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1668                             LHSShift.getOperand(1)).Val;
1669    }
1670  }
1671
1672  // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
1673  // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
1674  if (LHSShift.getOperand(1).getOpcode() == ISD::SUB &&
1675      RHSShift.getOperand(1) == LHSShift.getOperand(1).getOperand(1)) {
1676    if (ConstantSDNode *SUBC =
1677          dyn_cast<ConstantSDNode>(LHSShift.getOperand(1).getOperand(0))) {
1678      if (SUBC->getValue() == OpSizeInBits)
1679        if (HasROTL)
1680          return DAG.getNode(ISD::ROTL, VT, LHSShift.getOperand(0),
1681                             LHSShift.getOperand(1)).Val;
1682        else
1683          return DAG.getNode(ISD::ROTR, VT, LHSShift.getOperand(0),
1684                             RHSShift.getOperand(1)).Val;
1685    }
1686  }
1687
1688  return 0;
1689}
1690
1691
1692SDOperand DAGCombiner::visitXOR(SDNode *N) {
1693  SDOperand N0 = N->getOperand(0);
1694  SDOperand N1 = N->getOperand(1);
1695  SDOperand LHS, RHS, CC;
1696  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1697  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1698  MVT::ValueType VT = N0.getValueType();
1699
1700  // fold (xor c1, c2) -> c1^c2
1701  if (N0C && N1C)
1702    return DAG.getNode(ISD::XOR, VT, N0, N1);
1703  // canonicalize constant to RHS
1704  if (N0C && !N1C)
1705    return DAG.getNode(ISD::XOR, VT, N1, N0);
1706  // fold (xor x, 0) -> x
1707  if (N1C && N1C->isNullValue())
1708    return N0;
1709  // reassociate xor
1710  SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
1711  if (RXOR.Val != 0)
1712    return RXOR;
1713  // fold !(x cc y) -> (x !cc y)
1714  if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
1715    bool isInt = MVT::isInteger(LHS.getValueType());
1716    ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
1717                                               isInt);
1718    if (N0.getOpcode() == ISD::SETCC)
1719      return DAG.getSetCC(VT, LHS, RHS, NotCC);
1720    if (N0.getOpcode() == ISD::SELECT_CC)
1721      return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
1722    assert(0 && "Unhandled SetCC Equivalent!");
1723    abort();
1724  }
1725  // fold !(x or y) -> (!x and !y) iff x or y are setcc
1726  if (N1C && N1C->getValue() == 1 && VT == MVT::i1 &&
1727      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1728    SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1729    if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
1730      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1731      LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
1732      RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
1733      AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1734      return DAG.getNode(NewOpcode, VT, LHS, RHS);
1735    }
1736  }
1737  // fold !(x or y) -> (!x and !y) iff x or y are constants
1738  if (N1C && N1C->isAllOnesValue() &&
1739      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
1740    SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
1741    if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
1742      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
1743      LHS = DAG.getNode(ISD::XOR, VT, LHS, N1);  // RHS = ~LHS
1744      RHS = DAG.getNode(ISD::XOR, VT, RHS, N1);  // RHS = ~RHS
1745      AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
1746      return DAG.getNode(NewOpcode, VT, LHS, RHS);
1747    }
1748  }
1749  // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
1750  if (N1C && N0.getOpcode() == ISD::XOR) {
1751    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
1752    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1753    if (N00C)
1754      return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
1755                         DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
1756    if (N01C)
1757      return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
1758                         DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
1759  }
1760  // fold (xor x, x) -> 0
1761  if (N0 == N1) {
1762    if (!MVT::isVector(VT)) {
1763      return DAG.getConstant(0, VT);
1764    } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1765      // Produce a vector of zeros.
1766      SDOperand El = DAG.getConstant(0, MVT::getVectorBaseType(VT));
1767      std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
1768      return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1769    }
1770  }
1771
1772  // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
1773  if (N0.getOpcode() == N1.getOpcode()) {
1774    SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1775    if (Tmp.Val) return Tmp;
1776  }
1777
1778  // Simplify the expression using non-local knowledge.
1779  if (!MVT::isVector(VT) &&
1780      SimplifyDemandedBits(SDOperand(N, 0)))
1781    return SDOperand(N, 0);
1782
1783  return SDOperand();
1784}
1785
1786SDOperand DAGCombiner::visitSHL(SDNode *N) {
1787  SDOperand N0 = N->getOperand(0);
1788  SDOperand N1 = N->getOperand(1);
1789  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1790  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1791  MVT::ValueType VT = N0.getValueType();
1792  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1793
1794  // fold (shl c1, c2) -> c1<<c2
1795  if (N0C && N1C)
1796    return DAG.getNode(ISD::SHL, VT, N0, N1);
1797  // fold (shl 0, x) -> 0
1798  if (N0C && N0C->isNullValue())
1799    return N0;
1800  // fold (shl x, c >= size(x)) -> undef
1801  if (N1C && N1C->getValue() >= OpSizeInBits)
1802    return DAG.getNode(ISD::UNDEF, VT);
1803  // fold (shl x, 0) -> x
1804  if (N1C && N1C->isNullValue())
1805    return N0;
1806  // if (shl x, c) is known to be zero, return 0
1807  if (TLI.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1808    return DAG.getConstant(0, VT);
1809  if (SimplifyDemandedBits(SDOperand(N, 0)))
1810    return SDOperand(N, 0);
1811  // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
1812  if (N1C && N0.getOpcode() == ISD::SHL &&
1813      N0.getOperand(1).getOpcode() == ISD::Constant) {
1814    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1815    uint64_t c2 = N1C->getValue();
1816    if (c1 + c2 > OpSizeInBits)
1817      return DAG.getConstant(0, VT);
1818    return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
1819                       DAG.getConstant(c1 + c2, N1.getValueType()));
1820  }
1821  // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
1822  //                               (srl (and x, -1 << c1), c1-c2)
1823  if (N1C && N0.getOpcode() == ISD::SRL &&
1824      N0.getOperand(1).getOpcode() == ISD::Constant) {
1825    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1826    uint64_t c2 = N1C->getValue();
1827    SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1828                                 DAG.getConstant(~0ULL << c1, VT));
1829    if (c2 > c1)
1830      return DAG.getNode(ISD::SHL, VT, Mask,
1831                         DAG.getConstant(c2-c1, N1.getValueType()));
1832    else
1833      return DAG.getNode(ISD::SRL, VT, Mask,
1834                         DAG.getConstant(c1-c2, N1.getValueType()));
1835  }
1836  // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
1837  if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
1838    return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
1839                       DAG.getConstant(~0ULL << N1C->getValue(), VT));
1840  // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1<<c2)
1841  if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1842      isa<ConstantSDNode>(N0.getOperand(1))) {
1843    return DAG.getNode(ISD::ADD, VT,
1844                       DAG.getNode(ISD::SHL, VT, N0.getOperand(0), N1),
1845                       DAG.getNode(ISD::SHL, VT, N0.getOperand(1), N1));
1846  }
1847  return SDOperand();
1848}
1849
1850SDOperand DAGCombiner::visitSRA(SDNode *N) {
1851  SDOperand N0 = N->getOperand(0);
1852  SDOperand N1 = N->getOperand(1);
1853  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1854  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1855  MVT::ValueType VT = N0.getValueType();
1856
1857  // fold (sra c1, c2) -> c1>>c2
1858  if (N0C && N1C)
1859    return DAG.getNode(ISD::SRA, VT, N0, N1);
1860  // fold (sra 0, x) -> 0
1861  if (N0C && N0C->isNullValue())
1862    return N0;
1863  // fold (sra -1, x) -> -1
1864  if (N0C && N0C->isAllOnesValue())
1865    return N0;
1866  // fold (sra x, c >= size(x)) -> undef
1867  if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
1868    return DAG.getNode(ISD::UNDEF, VT);
1869  // fold (sra x, 0) -> x
1870  if (N1C && N1C->isNullValue())
1871    return N0;
1872  // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
1873  // sext_inreg.
1874  if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
1875    unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
1876    MVT::ValueType EVT;
1877    switch (LowBits) {
1878    default: EVT = MVT::Other; break;
1879    case  1: EVT = MVT::i1;    break;
1880    case  8: EVT = MVT::i8;    break;
1881    case 16: EVT = MVT::i16;   break;
1882    case 32: EVT = MVT::i32;   break;
1883    }
1884    if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
1885      return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
1886                         DAG.getValueType(EVT));
1887  }
1888
1889  // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
1890  if (N1C && N0.getOpcode() == ISD::SRA) {
1891    if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1892      unsigned Sum = N1C->getValue() + C1->getValue();
1893      if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
1894      return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
1895                         DAG.getConstant(Sum, N1C->getValueType(0)));
1896    }
1897  }
1898
1899  // Simplify, based on bits shifted out of the LHS.
1900  if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
1901    return SDOperand(N, 0);
1902
1903
1904  // If the sign bit is known to be zero, switch this to a SRL.
1905  if (TLI.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
1906    return DAG.getNode(ISD::SRL, VT, N0, N1);
1907  return SDOperand();
1908}
1909
1910SDOperand DAGCombiner::visitSRL(SDNode *N) {
1911  SDOperand N0 = N->getOperand(0);
1912  SDOperand N1 = N->getOperand(1);
1913  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1914  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1915  MVT::ValueType VT = N0.getValueType();
1916  unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1917
1918  // fold (srl c1, c2) -> c1 >>u c2
1919  if (N0C && N1C)
1920    return DAG.getNode(ISD::SRL, VT, N0, N1);
1921  // fold (srl 0, x) -> 0
1922  if (N0C && N0C->isNullValue())
1923    return N0;
1924  // fold (srl x, c >= size(x)) -> undef
1925  if (N1C && N1C->getValue() >= OpSizeInBits)
1926    return DAG.getNode(ISD::UNDEF, VT);
1927  // fold (srl x, 0) -> x
1928  if (N1C && N1C->isNullValue())
1929    return N0;
1930  // if (srl x, c) is known to be zero, return 0
1931  if (N1C && TLI.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
1932    return DAG.getConstant(0, VT);
1933  // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
1934  if (N1C && N0.getOpcode() == ISD::SRL &&
1935      N0.getOperand(1).getOpcode() == ISD::Constant) {
1936    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1937    uint64_t c2 = N1C->getValue();
1938    if (c1 + c2 > OpSizeInBits)
1939      return DAG.getConstant(0, VT);
1940    return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
1941                       DAG.getConstant(c1 + c2, N1.getValueType()));
1942  }
1943
1944  // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
1945  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1946    // Shifting in all undef bits?
1947    MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
1948    if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
1949      return DAG.getNode(ISD::UNDEF, VT);
1950
1951    SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
1952    AddToWorkList(SmallShift.Val);
1953    return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
1954  }
1955
1956  // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
1957  // bit, which is unmodified by sra.
1958  if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
1959    if (N0.getOpcode() == ISD::SRA)
1960      return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
1961  }
1962
1963  // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
1964  if (N1C && N0.getOpcode() == ISD::CTLZ &&
1965      N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
1966    uint64_t KnownZero, KnownOne, Mask = MVT::getIntVTBitMask(VT);
1967    TLI.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
1968
1969    // If any of the input bits are KnownOne, then the input couldn't be all
1970    // zeros, thus the result of the srl will always be zero.
1971    if (KnownOne) return DAG.getConstant(0, VT);
1972
1973    // If all of the bits input the to ctlz node are known to be zero, then
1974    // the result of the ctlz is "32" and the result of the shift is one.
1975    uint64_t UnknownBits = ~KnownZero & Mask;
1976    if (UnknownBits == 0) return DAG.getConstant(1, VT);
1977
1978    // Otherwise, check to see if there is exactly one bit input to the ctlz.
1979    if ((UnknownBits & (UnknownBits-1)) == 0) {
1980      // Okay, we know that only that the single bit specified by UnknownBits
1981      // could be set on input to the CTLZ node.  If this bit is set, the SRL
1982      // will return 0, if it is clear, it returns 1.  Change the CTLZ/SRL pair
1983      // to an SRL,XOR pair, which is likely to simplify more.
1984      unsigned ShAmt = CountTrailingZeros_64(UnknownBits);
1985      SDOperand Op = N0.getOperand(0);
1986      if (ShAmt) {
1987        Op = DAG.getNode(ISD::SRL, VT, Op,
1988                         DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
1989        AddToWorkList(Op.Val);
1990      }
1991      return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
1992    }
1993  }
1994
1995  return SDOperand();
1996}
1997
1998SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
1999  SDOperand N0 = N->getOperand(0);
2000  MVT::ValueType VT = N->getValueType(0);
2001
2002  // fold (ctlz c1) -> c2
2003  if (isa<ConstantSDNode>(N0))
2004    return DAG.getNode(ISD::CTLZ, VT, N0);
2005  return SDOperand();
2006}
2007
2008SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2009  SDOperand N0 = N->getOperand(0);
2010  MVT::ValueType VT = N->getValueType(0);
2011
2012  // fold (cttz c1) -> c2
2013  if (isa<ConstantSDNode>(N0))
2014    return DAG.getNode(ISD::CTTZ, VT, N0);
2015  return SDOperand();
2016}
2017
2018SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2019  SDOperand N0 = N->getOperand(0);
2020  MVT::ValueType VT = N->getValueType(0);
2021
2022  // fold (ctpop c1) -> c2
2023  if (isa<ConstantSDNode>(N0))
2024    return DAG.getNode(ISD::CTPOP, VT, N0);
2025  return SDOperand();
2026}
2027
2028SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2029  SDOperand N0 = N->getOperand(0);
2030  SDOperand N1 = N->getOperand(1);
2031  SDOperand N2 = N->getOperand(2);
2032  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2033  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2034  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2035  MVT::ValueType VT = N->getValueType(0);
2036
2037  // fold select C, X, X -> X
2038  if (N1 == N2)
2039    return N1;
2040  // fold select true, X, Y -> X
2041  if (N0C && !N0C->isNullValue())
2042    return N1;
2043  // fold select false, X, Y -> Y
2044  if (N0C && N0C->isNullValue())
2045    return N2;
2046  // fold select C, 1, X -> C | X
2047  if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
2048    return DAG.getNode(ISD::OR, VT, N0, N2);
2049  // fold select C, 0, X -> ~C & X
2050  // FIXME: this should check for C type == X type, not i1?
2051  if (MVT::i1 == VT && N1C && N1C->isNullValue()) {
2052    SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2053    AddToWorkList(XORNode.Val);
2054    return DAG.getNode(ISD::AND, VT, XORNode, N2);
2055  }
2056  // fold select C, X, 1 -> ~C | X
2057  if (MVT::i1 == VT && N2C && N2C->getValue() == 1) {
2058    SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2059    AddToWorkList(XORNode.Val);
2060    return DAG.getNode(ISD::OR, VT, XORNode, N1);
2061  }
2062  // fold select C, X, 0 -> C & X
2063  // FIXME: this should check for C type == X type, not i1?
2064  if (MVT::i1 == VT && N2C && N2C->isNullValue())
2065    return DAG.getNode(ISD::AND, VT, N0, N1);
2066  // fold  X ? X : Y --> X ? 1 : Y --> X | Y
2067  if (MVT::i1 == VT && N0 == N1)
2068    return DAG.getNode(ISD::OR, VT, N0, N2);
2069  // fold X ? Y : X --> X ? Y : 0 --> X & Y
2070  if (MVT::i1 == VT && N0 == N2)
2071    return DAG.getNode(ISD::AND, VT, N0, N1);
2072
2073  // If we can fold this based on the true/false value, do so.
2074  if (SimplifySelectOps(N, N1, N2))
2075    return SDOperand(N, 0);  // Don't revisit N.
2076
2077  // fold selects based on a setcc into other things, such as min/max/abs
2078  if (N0.getOpcode() == ISD::SETCC)
2079    // FIXME:
2080    // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2081    // having to say they don't support SELECT_CC on every type the DAG knows
2082    // about, since there is no way to mark an opcode illegal at all value types
2083    if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2084      return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2085                         N1, N2, N0.getOperand(2));
2086    else
2087      return SimplifySelect(N0, N1, N2);
2088  return SDOperand();
2089}
2090
2091SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2092  SDOperand N0 = N->getOperand(0);
2093  SDOperand N1 = N->getOperand(1);
2094  SDOperand N2 = N->getOperand(2);
2095  SDOperand N3 = N->getOperand(3);
2096  SDOperand N4 = N->getOperand(4);
2097  ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2098
2099  // fold select_cc lhs, rhs, x, x, cc -> x
2100  if (N2 == N3)
2101    return N2;
2102
2103  // Determine if the condition we're dealing with is constant
2104  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
2105  if (SCC.Val) AddToWorkList(SCC.Val);
2106
2107  if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2108    if (SCCC->getValue())
2109      return N2;    // cond always true -> true val
2110    else
2111      return N3;    // cond always false -> false val
2112  }
2113
2114  // Fold to a simpler select_cc
2115  if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2116    return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2117                       SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2118                       SCC.getOperand(2));
2119
2120  // If we can fold this based on the true/false value, do so.
2121  if (SimplifySelectOps(N, N2, N3))
2122    return SDOperand(N, 0);  // Don't revisit N.
2123
2124  // fold select_cc into other things, such as min/max/abs
2125  return SimplifySelectCC(N0, N1, N2, N3, CC);
2126}
2127
2128SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2129  return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2130                       cast<CondCodeSDNode>(N->getOperand(2))->get());
2131}
2132
2133SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2134  SDOperand N0 = N->getOperand(0);
2135  MVT::ValueType VT = N->getValueType(0);
2136
2137  // fold (sext c1) -> c1
2138  if (isa<ConstantSDNode>(N0))
2139    return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2140
2141  // fold (sext (sext x)) -> (sext x)
2142  // fold (sext (aext x)) -> (sext x)
2143  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2144    return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2145
2146  // fold (sext (truncate x)) -> (sextinreg x).
2147  if (N0.getOpcode() == ISD::TRUNCATE &&
2148      (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2149                                              N0.getValueType()))) {
2150    SDOperand Op = N0.getOperand(0);
2151    if (Op.getValueType() < VT) {
2152      Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2153    } else if (Op.getValueType() > VT) {
2154      Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2155    }
2156    return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2157                       DAG.getValueType(N0.getValueType()));
2158  }
2159
2160  // fold (sext (load x)) -> (sext (truncate (sextload x)))
2161  if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2162      (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
2163    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2164    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2165                                       LN0->getBasePtr(), LN0->getSrcValue(),
2166                                       LN0->getSrcValueOffset(),
2167                                       N0.getValueType());
2168    CombineTo(N, ExtLoad);
2169    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2170              ExtLoad.getValue(1));
2171    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2172  }
2173
2174  // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2175  // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2176  if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) && N0.hasOneUse()) {
2177    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2178    MVT::ValueType EVT = LN0->getLoadedVT();
2179    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2180                                       LN0->getBasePtr(), LN0->getSrcValue(),
2181                                       LN0->getSrcValueOffset(), EVT);
2182    CombineTo(N, ExtLoad);
2183    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2184              ExtLoad.getValue(1));
2185    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2186  }
2187
2188  return SDOperand();
2189}
2190
2191SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2192  SDOperand N0 = N->getOperand(0);
2193  MVT::ValueType VT = N->getValueType(0);
2194
2195  // fold (zext c1) -> c1
2196  if (isa<ConstantSDNode>(N0))
2197    return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2198  // fold (zext (zext x)) -> (zext x)
2199  // fold (zext (aext x)) -> (zext x)
2200  if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2201    return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2202
2203  // fold (zext (truncate x)) -> (and x, mask)
2204  if (N0.getOpcode() == ISD::TRUNCATE &&
2205      (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2206    SDOperand Op = N0.getOperand(0);
2207    if (Op.getValueType() < VT) {
2208      Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2209    } else if (Op.getValueType() > VT) {
2210      Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2211    }
2212    return DAG.getZeroExtendInReg(Op, N0.getValueType());
2213  }
2214
2215  // fold (zext (and (trunc x), cst)) -> (and x, cst).
2216  if (N0.getOpcode() == ISD::AND &&
2217      N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2218      N0.getOperand(1).getOpcode() == ISD::Constant) {
2219    SDOperand X = N0.getOperand(0).getOperand(0);
2220    if (X.getValueType() < VT) {
2221      X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2222    } else if (X.getValueType() > VT) {
2223      X = DAG.getNode(ISD::TRUNCATE, VT, X);
2224    }
2225    uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2226    return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2227  }
2228
2229  // fold (zext (load x)) -> (zext (truncate (zextload x)))
2230  if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2231      (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2232    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2233    SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2234                                       LN0->getBasePtr(), LN0->getSrcValue(),
2235                                       LN0->getSrcValueOffset(),
2236                                       N0.getValueType());
2237    CombineTo(N, ExtLoad);
2238    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2239              ExtLoad.getValue(1));
2240    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2241  }
2242
2243  // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2244  // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2245  if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) && N0.hasOneUse()) {
2246    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2247    MVT::ValueType EVT = LN0->getLoadedVT();
2248    SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2249                                       LN0->getBasePtr(), LN0->getSrcValue(),
2250                                       LN0->getSrcValueOffset(), EVT);
2251    CombineTo(N, ExtLoad);
2252    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2253              ExtLoad.getValue(1));
2254    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2255  }
2256  return SDOperand();
2257}
2258
2259SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
2260  SDOperand N0 = N->getOperand(0);
2261  MVT::ValueType VT = N->getValueType(0);
2262
2263  // fold (aext c1) -> c1
2264  if (isa<ConstantSDNode>(N0))
2265    return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
2266  // fold (aext (aext x)) -> (aext x)
2267  // fold (aext (zext x)) -> (zext x)
2268  // fold (aext (sext x)) -> (sext x)
2269  if (N0.getOpcode() == ISD::ANY_EXTEND  ||
2270      N0.getOpcode() == ISD::ZERO_EXTEND ||
2271      N0.getOpcode() == ISD::SIGN_EXTEND)
2272    return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2273
2274  // fold (aext (truncate x))
2275  if (N0.getOpcode() == ISD::TRUNCATE) {
2276    SDOperand TruncOp = N0.getOperand(0);
2277    if (TruncOp.getValueType() == VT)
2278      return TruncOp; // x iff x size == zext size.
2279    if (TruncOp.getValueType() > VT)
2280      return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
2281    return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
2282  }
2283
2284  // fold (aext (and (trunc x), cst)) -> (and x, cst).
2285  if (N0.getOpcode() == ISD::AND &&
2286      N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2287      N0.getOperand(1).getOpcode() == ISD::Constant) {
2288    SDOperand X = N0.getOperand(0).getOperand(0);
2289    if (X.getValueType() < VT) {
2290      X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2291    } else if (X.getValueType() > VT) {
2292      X = DAG.getNode(ISD::TRUNCATE, VT, X);
2293    }
2294    uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2295    return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2296  }
2297
2298  // fold (aext (load x)) -> (aext (truncate (extload x)))
2299  if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2300      (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2301    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2302    SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2303                                       LN0->getBasePtr(), LN0->getSrcValue(),
2304                                       LN0->getSrcValueOffset(),
2305                                       N0.getValueType());
2306    CombineTo(N, ExtLoad);
2307    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2308              ExtLoad.getValue(1));
2309    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2310  }
2311
2312  // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
2313  // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
2314  // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
2315  if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.Val) &&
2316      N0.hasOneUse()) {
2317    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2318    MVT::ValueType EVT = LN0->getLoadedVT();
2319    SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
2320                                       LN0->getChain(), LN0->getBasePtr(),
2321                                       LN0->getSrcValue(),
2322                                       LN0->getSrcValueOffset(), EVT);
2323    CombineTo(N, ExtLoad);
2324    CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2325              ExtLoad.getValue(1));
2326    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2327  }
2328  return SDOperand();
2329}
2330
2331
2332SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
2333  SDOperand N0 = N->getOperand(0);
2334  SDOperand N1 = N->getOperand(1);
2335  MVT::ValueType VT = N->getValueType(0);
2336  MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
2337  unsigned EVTBits = MVT::getSizeInBits(EVT);
2338
2339  // fold (sext_in_reg c1) -> c1
2340  if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
2341    return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
2342
2343  // If the input is already sign extended, just drop the extension.
2344  if (TLI.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
2345    return N0;
2346
2347  // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
2348  if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2349      EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
2350    return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
2351  }
2352
2353  // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is zero
2354  if (TLI.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
2355    return DAG.getZeroExtendInReg(N0, EVT);
2356
2357  // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
2358  // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
2359  // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
2360  if (N0.getOpcode() == ISD::SRL) {
2361    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2362      if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
2363        // We can turn this into an SRA iff the input to the SRL is already sign
2364        // extended enough.
2365        unsigned InSignBits = TLI.ComputeNumSignBits(N0.getOperand(0));
2366        if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
2367          return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
2368      }
2369  }
2370
2371  // fold (sext_inreg (extload x)) -> (sextload x)
2372  if (ISD::isEXTLoad(N0.Val) &&
2373      EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2374      (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2375    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2376    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2377                                       LN0->getBasePtr(), LN0->getSrcValue(),
2378                                       LN0->getSrcValueOffset(), EVT);
2379    CombineTo(N, ExtLoad);
2380    CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2381    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2382  }
2383  // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
2384  if (ISD::isZEXTLoad(N0.Val) && N0.hasOneUse() &&
2385      EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
2386      (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
2387    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2388    SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2389                                       LN0->getBasePtr(), LN0->getSrcValue(),
2390                                       LN0->getSrcValueOffset(), EVT);
2391    CombineTo(N, ExtLoad);
2392    CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
2393    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2394  }
2395  return SDOperand();
2396}
2397
2398SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
2399  SDOperand N0 = N->getOperand(0);
2400  MVT::ValueType VT = N->getValueType(0);
2401
2402  // noop truncate
2403  if (N0.getValueType() == N->getValueType(0))
2404    return N0;
2405  // fold (truncate c1) -> c1
2406  if (isa<ConstantSDNode>(N0))
2407    return DAG.getNode(ISD::TRUNCATE, VT, N0);
2408  // fold (truncate (truncate x)) -> (truncate x)
2409  if (N0.getOpcode() == ISD::TRUNCATE)
2410    return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
2411  // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
2412  if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
2413      N0.getOpcode() == ISD::ANY_EXTEND) {
2414    if (N0.getValueType() < VT)
2415      // if the source is smaller than the dest, we still need an extend
2416      return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2417    else if (N0.getValueType() > VT)
2418      // if the source is larger than the dest, than we just need the truncate
2419      return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
2420    else
2421      // if the source and dest are the same type, we can drop both the extend
2422      // and the truncate
2423      return N0.getOperand(0);
2424  }
2425  // fold (truncate (load x)) -> (smaller load x)
2426  if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse()) {
2427    assert(MVT::getSizeInBits(N0.getValueType()) > MVT::getSizeInBits(VT) &&
2428           "Cannot truncate to larger type!");
2429    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2430    MVT::ValueType PtrType = N0.getOperand(1).getValueType();
2431    // For big endian targets, we need to add an offset to the pointer to load
2432    // the correct bytes.  For little endian systems, we merely need to read
2433    // fewer bytes from the same pointer.
2434    uint64_t PtrOff =
2435      (MVT::getSizeInBits(N0.getValueType()) - MVT::getSizeInBits(VT)) / 8;
2436    SDOperand NewPtr = TLI.isLittleEndian() ? LN0->getBasePtr() :
2437      DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
2438                  DAG.getConstant(PtrOff, PtrType));
2439    AddToWorkList(NewPtr.Val);
2440    SDOperand Load = DAG.getLoad(VT, LN0->getChain(), NewPtr,
2441                                 LN0->getSrcValue(), LN0->getSrcValueOffset());
2442    AddToWorkList(N);
2443    CombineTo(N0.Val, Load, Load.getValue(1));
2444    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2445  }
2446  return SDOperand();
2447}
2448
2449SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
2450  SDOperand N0 = N->getOperand(0);
2451  MVT::ValueType VT = N->getValueType(0);
2452
2453  // If the input is a constant, let getNode() fold it.
2454  if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
2455    SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
2456    if (Res.Val != N) return Res;
2457  }
2458
2459  if (N0.getOpcode() == ISD::BIT_CONVERT)  // conv(conv(x,t1),t2) -> conv(x,t2)
2460    return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
2461
2462  // fold (conv (load x)) -> (load (conv*)x)
2463  // FIXME: These xforms need to know that the resultant load doesn't need a
2464  // higher alignment than the original!
2465  if (0 && ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse()) {
2466    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2467    SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
2468                                 LN0->getSrcValue(), LN0->getSrcValueOffset());
2469    AddToWorkList(N);
2470    CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
2471              Load.getValue(1));
2472    return Load;
2473  }
2474
2475  return SDOperand();
2476}
2477
2478SDOperand DAGCombiner::visitVBIT_CONVERT(SDNode *N) {
2479  SDOperand N0 = N->getOperand(0);
2480  MVT::ValueType VT = N->getValueType(0);
2481
2482  // If the input is a VBUILD_VECTOR with all constant elements, fold this now.
2483  // First check to see if this is all constant.
2484  if (N0.getOpcode() == ISD::VBUILD_VECTOR && N0.Val->hasOneUse() &&
2485      VT == MVT::Vector) {
2486    bool isSimple = true;
2487    for (unsigned i = 0, e = N0.getNumOperands()-2; i != e; ++i)
2488      if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
2489          N0.getOperand(i).getOpcode() != ISD::Constant &&
2490          N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
2491        isSimple = false;
2492        break;
2493      }
2494
2495    MVT::ValueType DestEltVT = cast<VTSDNode>(N->getOperand(2))->getVT();
2496    if (isSimple && !MVT::isVector(DestEltVT)) {
2497      return ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(N0.Val, DestEltVT);
2498    }
2499  }
2500
2501  return SDOperand();
2502}
2503
2504/// ConstantFoldVBIT_CONVERTofVBUILD_VECTOR - We know that BV is a vbuild_vector
2505/// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
2506/// destination element value type.
2507SDOperand DAGCombiner::
2508ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
2509  MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
2510
2511  // If this is already the right type, we're done.
2512  if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
2513
2514  unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
2515  unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
2516
2517  // If this is a conversion of N elements of one type to N elements of another
2518  // type, convert each element.  This handles FP<->INT cases.
2519  if (SrcBitSize == DstBitSize) {
2520    SmallVector<SDOperand, 8> Ops;
2521    for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) {
2522      Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
2523      AddToWorkList(Ops.back().Val);
2524    }
2525    Ops.push_back(*(BV->op_end()-2)); // Add num elements.
2526    Ops.push_back(DAG.getValueType(DstEltVT));
2527    return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2528  }
2529
2530  // Otherwise, we're growing or shrinking the elements.  To avoid having to
2531  // handle annoying details of growing/shrinking FP values, we convert them to
2532  // int first.
2533  if (MVT::isFloatingPoint(SrcEltVT)) {
2534    // Convert the input float vector to a int vector where the elements are the
2535    // same sizes.
2536    assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
2537    MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2538    BV = ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(BV, IntVT).Val;
2539    SrcEltVT = IntVT;
2540  }
2541
2542  // Now we know the input is an integer vector.  If the output is a FP type,
2543  // convert to integer first, then to FP of the right size.
2544  if (MVT::isFloatingPoint(DstEltVT)) {
2545    assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
2546    MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
2547    SDNode *Tmp = ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(BV, TmpVT).Val;
2548
2549    // Next, convert to FP elements of the same size.
2550    return ConstantFoldVBIT_CONVERTofVBUILD_VECTOR(Tmp, DstEltVT);
2551  }
2552
2553  // Okay, we know the src/dst types are both integers of differing types.
2554  // Handling growing first.
2555  assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
2556  if (SrcBitSize < DstBitSize) {
2557    unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
2558
2559    SmallVector<SDOperand, 8> Ops;
2560    for (unsigned i = 0, e = BV->getNumOperands()-2; i != e;
2561         i += NumInputsPerOutput) {
2562      bool isLE = TLI.isLittleEndian();
2563      uint64_t NewBits = 0;
2564      bool EltIsUndef = true;
2565      for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
2566        // Shift the previously computed bits over.
2567        NewBits <<= SrcBitSize;
2568        SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
2569        if (Op.getOpcode() == ISD::UNDEF) continue;
2570        EltIsUndef = false;
2571
2572        NewBits |= cast<ConstantSDNode>(Op)->getValue();
2573      }
2574
2575      if (EltIsUndef)
2576        Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2577      else
2578        Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
2579    }
2580
2581    Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements.
2582    Ops.push_back(DAG.getValueType(DstEltVT));            // Add element size.
2583    return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2584  }
2585
2586  // Finally, this must be the case where we are shrinking elements: each input
2587  // turns into multiple outputs.
2588  unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
2589  SmallVector<SDOperand, 8> Ops;
2590  for (unsigned i = 0, e = BV->getNumOperands()-2; i != e; ++i) {
2591    if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
2592      for (unsigned j = 0; j != NumOutputsPerInput; ++j)
2593        Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
2594      continue;
2595    }
2596    uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
2597
2598    for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
2599      unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
2600      OpVal >>= DstBitSize;
2601      Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
2602    }
2603
2604    // For big endian targets, swap the order of the pieces of each element.
2605    if (!TLI.isLittleEndian())
2606      std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
2607  }
2608  Ops.push_back(DAG.getConstant(Ops.size(), MVT::i32)); // Add num elements.
2609  Ops.push_back(DAG.getValueType(DstEltVT));            // Add element size.
2610  return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
2611}
2612
2613
2614
2615SDOperand DAGCombiner::visitFADD(SDNode *N) {
2616  SDOperand N0 = N->getOperand(0);
2617  SDOperand N1 = N->getOperand(1);
2618  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2619  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2620  MVT::ValueType VT = N->getValueType(0);
2621
2622  // fold (fadd c1, c2) -> c1+c2
2623  if (N0CFP && N1CFP)
2624    return DAG.getNode(ISD::FADD, VT, N0, N1);
2625  // canonicalize constant to RHS
2626  if (N0CFP && !N1CFP)
2627    return DAG.getNode(ISD::FADD, VT, N1, N0);
2628  // fold (A + (-B)) -> A-B
2629  if (N1.getOpcode() == ISD::FNEG)
2630    return DAG.getNode(ISD::FSUB, VT, N0, N1.getOperand(0));
2631  // fold ((-A) + B) -> B-A
2632  if (N0.getOpcode() == ISD::FNEG)
2633    return DAG.getNode(ISD::FSUB, VT, N1, N0.getOperand(0));
2634  return SDOperand();
2635}
2636
2637SDOperand DAGCombiner::visitFSUB(SDNode *N) {
2638  SDOperand N0 = N->getOperand(0);
2639  SDOperand N1 = N->getOperand(1);
2640  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2641  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2642  MVT::ValueType VT = N->getValueType(0);
2643
2644  // fold (fsub c1, c2) -> c1-c2
2645  if (N0CFP && N1CFP)
2646    return DAG.getNode(ISD::FSUB, VT, N0, N1);
2647  // fold (A-(-B)) -> A+B
2648  if (N1.getOpcode() == ISD::FNEG)
2649    return DAG.getNode(ISD::FADD, VT, N0, N1.getOperand(0));
2650  return SDOperand();
2651}
2652
2653SDOperand DAGCombiner::visitFMUL(SDNode *N) {
2654  SDOperand N0 = N->getOperand(0);
2655  SDOperand N1 = N->getOperand(1);
2656  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2657  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2658  MVT::ValueType VT = N->getValueType(0);
2659
2660  // fold (fmul c1, c2) -> c1*c2
2661  if (N0CFP && N1CFP)
2662    return DAG.getNode(ISD::FMUL, VT, N0, N1);
2663  // canonicalize constant to RHS
2664  if (N0CFP && !N1CFP)
2665    return DAG.getNode(ISD::FMUL, VT, N1, N0);
2666  // fold (fmul X, 2.0) -> (fadd X, X)
2667  if (N1CFP && N1CFP->isExactlyValue(+2.0))
2668    return DAG.getNode(ISD::FADD, VT, N0, N0);
2669  return SDOperand();
2670}
2671
2672SDOperand DAGCombiner::visitFDIV(SDNode *N) {
2673  SDOperand N0 = N->getOperand(0);
2674  SDOperand N1 = N->getOperand(1);
2675  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2676  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2677  MVT::ValueType VT = N->getValueType(0);
2678
2679  // fold (fdiv c1, c2) -> c1/c2
2680  if (N0CFP && N1CFP)
2681    return DAG.getNode(ISD::FDIV, VT, N0, N1);
2682  return SDOperand();
2683}
2684
2685SDOperand DAGCombiner::visitFREM(SDNode *N) {
2686  SDOperand N0 = N->getOperand(0);
2687  SDOperand N1 = N->getOperand(1);
2688  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2689  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2690  MVT::ValueType VT = N->getValueType(0);
2691
2692  // fold (frem c1, c2) -> fmod(c1,c2)
2693  if (N0CFP && N1CFP)
2694    return DAG.getNode(ISD::FREM, VT, N0, N1);
2695  return SDOperand();
2696}
2697
2698SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
2699  SDOperand N0 = N->getOperand(0);
2700  SDOperand N1 = N->getOperand(1);
2701  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2702  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2703  MVT::ValueType VT = N->getValueType(0);
2704
2705  if (N0CFP && N1CFP)  // Constant fold
2706    return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
2707
2708  if (N1CFP) {
2709    // copysign(x, c1) -> fabs(x)       iff ispos(c1)
2710    // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
2711    union {
2712      double d;
2713      int64_t i;
2714    } u;
2715    u.d = N1CFP->getValue();
2716    if (u.i >= 0)
2717      return DAG.getNode(ISD::FABS, VT, N0);
2718    else
2719      return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
2720  }
2721
2722  // copysign(fabs(x), y) -> copysign(x, y)
2723  // copysign(fneg(x), y) -> copysign(x, y)
2724  // copysign(copysign(x,z), y) -> copysign(x, y)
2725  if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
2726      N0.getOpcode() == ISD::FCOPYSIGN)
2727    return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
2728
2729  // copysign(x, abs(y)) -> abs(x)
2730  if (N1.getOpcode() == ISD::FABS)
2731    return DAG.getNode(ISD::FABS, VT, N0);
2732
2733  // copysign(x, copysign(y,z)) -> copysign(x, z)
2734  if (N1.getOpcode() == ISD::FCOPYSIGN)
2735    return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
2736
2737  // copysign(x, fp_extend(y)) -> copysign(x, y)
2738  // copysign(x, fp_round(y)) -> copysign(x, y)
2739  if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
2740    return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
2741
2742  return SDOperand();
2743}
2744
2745
2746
2747SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
2748  SDOperand N0 = N->getOperand(0);
2749  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2750  MVT::ValueType VT = N->getValueType(0);
2751
2752  // fold (sint_to_fp c1) -> c1fp
2753  if (N0C)
2754    return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
2755  return SDOperand();
2756}
2757
2758SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
2759  SDOperand N0 = N->getOperand(0);
2760  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2761  MVT::ValueType VT = N->getValueType(0);
2762
2763  // fold (uint_to_fp c1) -> c1fp
2764  if (N0C)
2765    return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
2766  return SDOperand();
2767}
2768
2769SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
2770  SDOperand N0 = N->getOperand(0);
2771  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2772  MVT::ValueType VT = N->getValueType(0);
2773
2774  // fold (fp_to_sint c1fp) -> c1
2775  if (N0CFP)
2776    return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
2777  return SDOperand();
2778}
2779
2780SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
2781  SDOperand N0 = N->getOperand(0);
2782  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2783  MVT::ValueType VT = N->getValueType(0);
2784
2785  // fold (fp_to_uint c1fp) -> c1
2786  if (N0CFP)
2787    return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
2788  return SDOperand();
2789}
2790
2791SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
2792  SDOperand N0 = N->getOperand(0);
2793  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2794  MVT::ValueType VT = N->getValueType(0);
2795
2796  // fold (fp_round c1fp) -> c1fp
2797  if (N0CFP)
2798    return DAG.getNode(ISD::FP_ROUND, VT, N0);
2799
2800  // fold (fp_round (fp_extend x)) -> x
2801  if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
2802    return N0.getOperand(0);
2803
2804  // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
2805  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
2806    SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0));
2807    AddToWorkList(Tmp.Val);
2808    return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
2809  }
2810
2811  return SDOperand();
2812}
2813
2814SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
2815  SDOperand N0 = N->getOperand(0);
2816  MVT::ValueType VT = N->getValueType(0);
2817  MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2818  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2819
2820  // fold (fp_round_inreg c1fp) -> c1fp
2821  if (N0CFP) {
2822    SDOperand Round = DAG.getConstantFP(N0CFP->getValue(), EVT);
2823    return DAG.getNode(ISD::FP_EXTEND, VT, Round);
2824  }
2825  return SDOperand();
2826}
2827
2828SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
2829  SDOperand N0 = N->getOperand(0);
2830  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2831  MVT::ValueType VT = N->getValueType(0);
2832
2833  // fold (fp_extend c1fp) -> c1fp
2834  if (N0CFP)
2835    return DAG.getNode(ISD::FP_EXTEND, VT, N0);
2836
2837  // fold (fpext (load x)) -> (fpext (fpround (extload x)))
2838  if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2839      (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2840    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2841    SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2842                                       LN0->getBasePtr(), LN0->getSrcValue(),
2843                                       LN0->getSrcValueOffset(),
2844                                       N0.getValueType());
2845    CombineTo(N, ExtLoad);
2846    CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad),
2847              ExtLoad.getValue(1));
2848    return SDOperand(N, 0);   // Return N so it doesn't get rechecked!
2849  }
2850
2851
2852  return SDOperand();
2853}
2854
2855SDOperand DAGCombiner::visitFNEG(SDNode *N) {
2856  SDOperand N0 = N->getOperand(0);
2857  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2858  MVT::ValueType VT = N->getValueType(0);
2859
2860  // fold (fneg c1) -> -c1
2861  if (N0CFP)
2862    return DAG.getNode(ISD::FNEG, VT, N0);
2863  // fold (fneg (sub x, y)) -> (sub y, x)
2864  if (N0.getOpcode() == ISD::SUB)
2865    return DAG.getNode(ISD::SUB, VT, N0.getOperand(1), N0.getOperand(0));
2866  // fold (fneg (fneg x)) -> x
2867  if (N0.getOpcode() == ISD::FNEG)
2868    return N0.getOperand(0);
2869  return SDOperand();
2870}
2871
2872SDOperand DAGCombiner::visitFABS(SDNode *N) {
2873  SDOperand N0 = N->getOperand(0);
2874  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
2875  MVT::ValueType VT = N->getValueType(0);
2876
2877  // fold (fabs c1) -> fabs(c1)
2878  if (N0CFP)
2879    return DAG.getNode(ISD::FABS, VT, N0);
2880  // fold (fabs (fabs x)) -> (fabs x)
2881  if (N0.getOpcode() == ISD::FABS)
2882    return N->getOperand(0);
2883  // fold (fabs (fneg x)) -> (fabs x)
2884  // fold (fabs (fcopysign x, y)) -> (fabs x)
2885  if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
2886    return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
2887
2888  return SDOperand();
2889}
2890
2891SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
2892  SDOperand Chain = N->getOperand(0);
2893  SDOperand N1 = N->getOperand(1);
2894  SDOperand N2 = N->getOperand(2);
2895  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2896
2897  // never taken branch, fold to chain
2898  if (N1C && N1C->isNullValue())
2899    return Chain;
2900  // unconditional branch
2901  if (N1C && N1C->getValue() == 1)
2902    return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
2903  // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
2904  // on the target.
2905  if (N1.getOpcode() == ISD::SETCC &&
2906      TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
2907    return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
2908                       N1.getOperand(0), N1.getOperand(1), N2);
2909  }
2910  return SDOperand();
2911}
2912
2913// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
2914//
2915SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
2916  CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
2917  SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
2918
2919  // Use SimplifySetCC  to simplify SETCC's.
2920  SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
2921  if (Simp.Val) AddToWorkList(Simp.Val);
2922
2923  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
2924
2925  // fold br_cc true, dest -> br dest (unconditional branch)
2926  if (SCCC && SCCC->getValue())
2927    return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
2928                       N->getOperand(4));
2929  // fold br_cc false, dest -> unconditional fall through
2930  if (SCCC && SCCC->isNullValue())
2931    return N->getOperand(0);
2932
2933  // fold to a simpler setcc
2934  if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
2935    return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
2936                       Simp.getOperand(2), Simp.getOperand(0),
2937                       Simp.getOperand(1), N->getOperand(4));
2938  return SDOperand();
2939}
2940
2941SDOperand DAGCombiner::visitLOAD(SDNode *N) {
2942  LoadSDNode *LD  = cast<LoadSDNode>(N);
2943  SDOperand Chain = LD->getChain();
2944  SDOperand Ptr   = LD->getBasePtr();
2945
2946  // If there are no uses of the loaded value, change uses of the chain value
2947  // into uses of the chain input (i.e. delete the dead load).
2948  if (N->hasNUsesOfValue(0, 0))
2949    return CombineTo(N, DAG.getNode(ISD::UNDEF, N->getValueType(0)), Chain);
2950
2951  // If this load is directly stored, replace the load value with the stored
2952  // value.
2953  // TODO: Handle store large -> read small portion.
2954  // TODO: Handle TRUNCSTORE/LOADEXT
2955  if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
2956    if (ISD::isNON_TRUNCStore(Chain.Val)) {
2957      StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
2958      if (PrevST->getBasePtr() == Ptr &&
2959          PrevST->getValue().getValueType() == N->getValueType(0))
2960      return CombineTo(N, Chain.getOperand(1), Chain);
2961    }
2962  }
2963
2964  if (CombinerAA) {
2965    // Walk up chain skipping non-aliasing memory nodes.
2966    SDOperand BetterChain = FindBetterChain(N, Chain);
2967
2968    // If there is a better chain.
2969    if (Chain != BetterChain) {
2970      SDOperand ReplLoad;
2971
2972      // Replace the chain to void dependency.
2973      if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
2974        ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
2975                              LD->getSrcValue(), LD->getSrcValueOffset());
2976      } else {
2977        ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
2978                                  LD->getValueType(0),
2979                                  BetterChain, Ptr, LD->getSrcValue(),
2980                                  LD->getSrcValueOffset(),
2981                                  LD->getLoadedVT());
2982      }
2983
2984      // Create token factor to keep old chain connected.
2985      SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
2986                                    Chain, ReplLoad.getValue(1));
2987
2988      // Replace uses with load result and token factor. Don't add users
2989      // to work list.
2990      return CombineTo(N, ReplLoad.getValue(0), Token, false);
2991    }
2992  }
2993
2994  // Try transforming N to an indexed load.
2995  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
2996    return SDOperand(N, 0);
2997
2998  return SDOperand();
2999}
3000
3001SDOperand DAGCombiner::visitSTORE(SDNode *N) {
3002  StoreSDNode *ST  = cast<StoreSDNode>(N);
3003  SDOperand Chain = ST->getChain();
3004  SDOperand Value = ST->getValue();
3005  SDOperand Ptr   = ST->getBasePtr();
3006
3007  // If this is a store of a bit convert, store the input value.
3008  // FIXME: This needs to know that the resultant store does not need a
3009  // higher alignment than the original.
3010  if (0 && Value.getOpcode() == ISD::BIT_CONVERT) {
3011    return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
3012                        ST->getSrcValueOffset());
3013  }
3014
3015  if (CombinerAA) {
3016    // Walk up chain skipping non-aliasing memory nodes.
3017    SDOperand BetterChain = FindBetterChain(N, Chain);
3018
3019    // If there is a better chain.
3020    if (Chain != BetterChain) {
3021      // Replace the chain to avoid dependency.
3022      SDOperand ReplStore;
3023      if (ST->isTruncatingStore()) {
3024        ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
3025          ST->getSrcValue(),ST->getSrcValueOffset(), ST->getStoredVT());
3026      } else {
3027        ReplStore = DAG.getStore(BetterChain, Value, Ptr,
3028          ST->getSrcValue(), ST->getSrcValueOffset());
3029      }
3030
3031      // Create token to keep both nodes around.
3032      SDOperand Token =
3033        DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
3034
3035      // Don't add users to work list.
3036      return CombineTo(N, Token, false);
3037    }
3038  }
3039
3040  // Try transforming N to an indexed store.
3041  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
3042    return SDOperand(N, 0);
3043
3044  return SDOperand();
3045}
3046
3047SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
3048  SDOperand InVec = N->getOperand(0);
3049  SDOperand InVal = N->getOperand(1);
3050  SDOperand EltNo = N->getOperand(2);
3051
3052  // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
3053  // vector with the inserted element.
3054  if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
3055    unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
3056    SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
3057    if (Elt < Ops.size())
3058      Ops[Elt] = InVal;
3059    return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
3060                       &Ops[0], Ops.size());
3061  }
3062
3063  return SDOperand();
3064}
3065
3066SDOperand DAGCombiner::visitVINSERT_VECTOR_ELT(SDNode *N) {
3067  SDOperand InVec = N->getOperand(0);
3068  SDOperand InVal = N->getOperand(1);
3069  SDOperand EltNo = N->getOperand(2);
3070  SDOperand NumElts = N->getOperand(3);
3071  SDOperand EltType = N->getOperand(4);
3072
3073  // If the invec is a VBUILD_VECTOR and if EltNo is a constant, build a new
3074  // vector with the inserted element.
3075  if (InVec.getOpcode() == ISD::VBUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
3076    unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
3077    SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
3078    if (Elt < Ops.size()-2)
3079      Ops[Elt] = InVal;
3080    return DAG.getNode(ISD::VBUILD_VECTOR, InVec.getValueType(),
3081                       &Ops[0], Ops.size());
3082  }
3083
3084  return SDOperand();
3085}
3086
3087SDOperand DAGCombiner::visitVBUILD_VECTOR(SDNode *N) {
3088  unsigned NumInScalars = N->getNumOperands()-2;
3089  SDOperand NumElts = N->getOperand(NumInScalars);
3090  SDOperand EltType = N->getOperand(NumInScalars+1);
3091
3092  // Check to see if this is a VBUILD_VECTOR of a bunch of VEXTRACT_VECTOR_ELT
3093  // operations.  If so, and if the EXTRACT_ELT vector inputs come from at most
3094  // two distinct vectors, turn this into a shuffle node.
3095  SDOperand VecIn1, VecIn2;
3096  for (unsigned i = 0; i != NumInScalars; ++i) {
3097    // Ignore undef inputs.
3098    if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
3099
3100    // If this input is something other than a VEXTRACT_VECTOR_ELT with a
3101    // constant index, bail out.
3102    if (N->getOperand(i).getOpcode() != ISD::VEXTRACT_VECTOR_ELT ||
3103        !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
3104      VecIn1 = VecIn2 = SDOperand(0, 0);
3105      break;
3106    }
3107
3108    // If the input vector type disagrees with the result of the vbuild_vector,
3109    // we can't make a shuffle.
3110    SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
3111    if (*(ExtractedFromVec.Val->op_end()-2) != NumElts ||
3112        *(ExtractedFromVec.Val->op_end()-1) != EltType) {
3113      VecIn1 = VecIn2 = SDOperand(0, 0);
3114      break;
3115    }
3116
3117    // Otherwise, remember this.  We allow up to two distinct input vectors.
3118    if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
3119      continue;
3120
3121    if (VecIn1.Val == 0) {
3122      VecIn1 = ExtractedFromVec;
3123    } else if (VecIn2.Val == 0) {
3124      VecIn2 = ExtractedFromVec;
3125    } else {
3126      // Too many inputs.
3127      VecIn1 = VecIn2 = SDOperand(0, 0);
3128      break;
3129    }
3130  }
3131
3132  // If everything is good, we can make a shuffle operation.
3133  if (VecIn1.Val) {
3134    SmallVector<SDOperand, 8> BuildVecIndices;
3135    for (unsigned i = 0; i != NumInScalars; ++i) {
3136      if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
3137        BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3138        continue;
3139      }
3140
3141      SDOperand Extract = N->getOperand(i);
3142
3143      // If extracting from the first vector, just use the index directly.
3144      if (Extract.getOperand(0) == VecIn1) {
3145        BuildVecIndices.push_back(Extract.getOperand(1));
3146        continue;
3147      }
3148
3149      // Otherwise, use InIdx + VecSize
3150      unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
3151      BuildVecIndices.push_back(DAG.getConstant(Idx+NumInScalars, MVT::i32));
3152    }
3153
3154    // Add count and size info.
3155    BuildVecIndices.push_back(NumElts);
3156    BuildVecIndices.push_back(DAG.getValueType(MVT::i32));
3157
3158    // Return the new VVECTOR_SHUFFLE node.
3159    SDOperand Ops[5];
3160    Ops[0] = VecIn1;
3161    if (VecIn2.Val) {
3162      Ops[1] = VecIn2;
3163    } else {
3164       // Use an undef vbuild_vector as input for the second operand.
3165      std::vector<SDOperand> UnOps(NumInScalars,
3166                                   DAG.getNode(ISD::UNDEF,
3167                                           cast<VTSDNode>(EltType)->getVT()));
3168      UnOps.push_back(NumElts);
3169      UnOps.push_back(EltType);
3170      Ops[1] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3171                           &UnOps[0], UnOps.size());
3172      AddToWorkList(Ops[1].Val);
3173    }
3174    Ops[2] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3175                         &BuildVecIndices[0], BuildVecIndices.size());
3176    Ops[3] = NumElts;
3177    Ops[4] = EltType;
3178    return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector, Ops, 5);
3179  }
3180
3181  return SDOperand();
3182}
3183
3184SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
3185  SDOperand ShufMask = N->getOperand(2);
3186  unsigned NumElts = ShufMask.getNumOperands();
3187
3188  // If the shuffle mask is an identity operation on the LHS, return the LHS.
3189  bool isIdentity = true;
3190  for (unsigned i = 0; i != NumElts; ++i) {
3191    if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3192        cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
3193      isIdentity = false;
3194      break;
3195    }
3196  }
3197  if (isIdentity) return N->getOperand(0);
3198
3199  // If the shuffle mask is an identity operation on the RHS, return the RHS.
3200  isIdentity = true;
3201  for (unsigned i = 0; i != NumElts; ++i) {
3202    if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3203        cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
3204      isIdentity = false;
3205      break;
3206    }
3207  }
3208  if (isIdentity) return N->getOperand(1);
3209
3210  // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
3211  // needed at all.
3212  bool isUnary = true;
3213  bool isSplat = true;
3214  int VecNum = -1;
3215  unsigned BaseIdx = 0;
3216  for (unsigned i = 0; i != NumElts; ++i)
3217    if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
3218      unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
3219      int V = (Idx < NumElts) ? 0 : 1;
3220      if (VecNum == -1) {
3221        VecNum = V;
3222        BaseIdx = Idx;
3223      } else {
3224        if (BaseIdx != Idx)
3225          isSplat = false;
3226        if (VecNum != V) {
3227          isUnary = false;
3228          break;
3229        }
3230      }
3231    }
3232
3233  SDOperand N0 = N->getOperand(0);
3234  SDOperand N1 = N->getOperand(1);
3235  // Normalize unary shuffle so the RHS is undef.
3236  if (isUnary && VecNum == 1)
3237    std::swap(N0, N1);
3238
3239  // If it is a splat, check if the argument vector is a build_vector with
3240  // all scalar elements the same.
3241  if (isSplat) {
3242    SDNode *V = N0.Val;
3243    if (V->getOpcode() == ISD::BIT_CONVERT)
3244      V = V->getOperand(0).Val;
3245    if (V->getOpcode() == ISD::BUILD_VECTOR) {
3246      unsigned NumElems = V->getNumOperands()-2;
3247      if (NumElems > BaseIdx) {
3248        SDOperand Base;
3249        bool AllSame = true;
3250        for (unsigned i = 0; i != NumElems; ++i) {
3251          if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
3252            Base = V->getOperand(i);
3253            break;
3254          }
3255        }
3256        // Splat of <u, u, u, u>, return <u, u, u, u>
3257        if (!Base.Val)
3258          return N0;
3259        for (unsigned i = 0; i != NumElems; ++i) {
3260          if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
3261              V->getOperand(i) != Base) {
3262            AllSame = false;
3263            break;
3264          }
3265        }
3266        // Splat of <x, x, x, x>, return <x, x, x, x>
3267        if (AllSame)
3268          return N0;
3269      }
3270    }
3271  }
3272
3273  // If it is a unary or the LHS and the RHS are the same node, turn the RHS
3274  // into an undef.
3275  if (isUnary || N0 == N1) {
3276    if (N0.getOpcode() == ISD::UNDEF)
3277      return DAG.getNode(ISD::UNDEF, N->getValueType(0));
3278    // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
3279    // first operand.
3280    SmallVector<SDOperand, 8> MappedOps;
3281    for (unsigned i = 0, e = ShufMask.getNumOperands(); i != e; ++i) {
3282      if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
3283          cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
3284        MappedOps.push_back(ShufMask.getOperand(i));
3285      } else {
3286        unsigned NewIdx =
3287           cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
3288        MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
3289      }
3290    }
3291    ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
3292                           &MappedOps[0], MappedOps.size());
3293    AddToWorkList(ShufMask.Val);
3294    return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
3295                       N0,
3296                       DAG.getNode(ISD::UNDEF, N->getValueType(0)),
3297                       ShufMask);
3298  }
3299
3300  return SDOperand();
3301}
3302
3303SDOperand DAGCombiner::visitVVECTOR_SHUFFLE(SDNode *N) {
3304  SDOperand ShufMask = N->getOperand(2);
3305  unsigned NumElts = ShufMask.getNumOperands()-2;
3306
3307  // If the shuffle mask is an identity operation on the LHS, return the LHS.
3308  bool isIdentity = true;
3309  for (unsigned i = 0; i != NumElts; ++i) {
3310    if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3311        cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
3312      isIdentity = false;
3313      break;
3314    }
3315  }
3316  if (isIdentity) return N->getOperand(0);
3317
3318  // If the shuffle mask is an identity operation on the RHS, return the RHS.
3319  isIdentity = true;
3320  for (unsigned i = 0; i != NumElts; ++i) {
3321    if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
3322        cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
3323      isIdentity = false;
3324      break;
3325    }
3326  }
3327  if (isIdentity) return N->getOperand(1);
3328
3329  // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
3330  // needed at all.
3331  bool isUnary = true;
3332  bool isSplat = true;
3333  int VecNum = -1;
3334  unsigned BaseIdx = 0;
3335  for (unsigned i = 0; i != NumElts; ++i)
3336    if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
3337      unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
3338      int V = (Idx < NumElts) ? 0 : 1;
3339      if (VecNum == -1) {
3340        VecNum = V;
3341        BaseIdx = Idx;
3342      } else {
3343        if (BaseIdx != Idx)
3344          isSplat = false;
3345        if (VecNum != V) {
3346          isUnary = false;
3347          break;
3348        }
3349      }
3350    }
3351
3352  SDOperand N0 = N->getOperand(0);
3353  SDOperand N1 = N->getOperand(1);
3354  // Normalize unary shuffle so the RHS is undef.
3355  if (isUnary && VecNum == 1)
3356    std::swap(N0, N1);
3357
3358  // If it is a splat, check if the argument vector is a build_vector with
3359  // all scalar elements the same.
3360  if (isSplat) {
3361    SDNode *V = N0.Val;
3362
3363    // If this is a vbit convert that changes the element type of the vector but
3364    // not the number of vector elements, look through it.  Be careful not to
3365    // look though conversions that change things like v4f32 to v2f64.
3366    if (V->getOpcode() == ISD::VBIT_CONVERT) {
3367      SDOperand ConvInput = V->getOperand(0);
3368      if (ConvInput.getValueType() == MVT::Vector &&
3369          NumElts ==
3370          ConvInput.getConstantOperandVal(ConvInput.getNumOperands()-2))
3371        V = ConvInput.Val;
3372    }
3373
3374    if (V->getOpcode() == ISD::VBUILD_VECTOR) {
3375      unsigned NumElems = V->getNumOperands()-2;
3376      if (NumElems > BaseIdx) {
3377        SDOperand Base;
3378        bool AllSame = true;
3379        for (unsigned i = 0; i != NumElems; ++i) {
3380          if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
3381            Base = V->getOperand(i);
3382            break;
3383          }
3384        }
3385        // Splat of <u, u, u, u>, return <u, u, u, u>
3386        if (!Base.Val)
3387          return N0;
3388        for (unsigned i = 0; i != NumElems; ++i) {
3389          if (V->getOperand(i).getOpcode() != ISD::UNDEF &&
3390              V->getOperand(i) != Base) {
3391            AllSame = false;
3392            break;
3393          }
3394        }
3395        // Splat of <x, x, x, x>, return <x, x, x, x>
3396        if (AllSame)
3397          return N0;
3398      }
3399    }
3400  }
3401
3402  // If it is a unary or the LHS and the RHS are the same node, turn the RHS
3403  // into an undef.
3404  if (isUnary || N0 == N1) {
3405    // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
3406    // first operand.
3407    SmallVector<SDOperand, 8> MappedOps;
3408    for (unsigned i = 0; i != NumElts; ++i) {
3409      if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
3410          cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
3411        MappedOps.push_back(ShufMask.getOperand(i));
3412      } else {
3413        unsigned NewIdx =
3414          cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
3415        MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
3416      }
3417    }
3418    // Add the type/#elts values.
3419    MappedOps.push_back(ShufMask.getOperand(NumElts));
3420    MappedOps.push_back(ShufMask.getOperand(NumElts+1));
3421
3422    ShufMask = DAG.getNode(ISD::VBUILD_VECTOR, ShufMask.getValueType(),
3423                           &MappedOps[0], MappedOps.size());
3424    AddToWorkList(ShufMask.Val);
3425
3426    // Build the undef vector.
3427    SDOperand UDVal = DAG.getNode(ISD::UNDEF, MappedOps[0].getValueType());
3428    for (unsigned i = 0; i != NumElts; ++i)
3429      MappedOps[i] = UDVal;
3430    MappedOps[NumElts  ] = *(N0.Val->op_end()-2);
3431    MappedOps[NumElts+1] = *(N0.Val->op_end()-1);
3432    UDVal = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3433                        &MappedOps[0], MappedOps.size());
3434
3435    return DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
3436                       N0, UDVal, ShufMask,
3437                       MappedOps[NumElts], MappedOps[NumElts+1]);
3438  }
3439
3440  return SDOperand();
3441}
3442
3443/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
3444/// a VAND to a vector_shuffle with the destination vector and a zero vector.
3445/// e.g. VAND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
3446///      vector_shuffle V, Zero, <0, 4, 2, 4>
3447SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
3448  SDOperand LHS = N->getOperand(0);
3449  SDOperand RHS = N->getOperand(1);
3450  if (N->getOpcode() == ISD::VAND) {
3451    SDOperand DstVecSize = *(LHS.Val->op_end()-2);
3452    SDOperand DstVecEVT  = *(LHS.Val->op_end()-1);
3453    if (RHS.getOpcode() == ISD::VBIT_CONVERT)
3454      RHS = RHS.getOperand(0);
3455    if (RHS.getOpcode() == ISD::VBUILD_VECTOR) {
3456      std::vector<SDOperand> IdxOps;
3457      unsigned NumOps = RHS.getNumOperands();
3458      unsigned NumElts = NumOps-2;
3459      MVT::ValueType EVT = cast<VTSDNode>(RHS.getOperand(NumOps-1))->getVT();
3460      for (unsigned i = 0; i != NumElts; ++i) {
3461        SDOperand Elt = RHS.getOperand(i);
3462        if (!isa<ConstantSDNode>(Elt))
3463          return SDOperand();
3464        else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
3465          IdxOps.push_back(DAG.getConstant(i, EVT));
3466        else if (cast<ConstantSDNode>(Elt)->isNullValue())
3467          IdxOps.push_back(DAG.getConstant(NumElts, EVT));
3468        else
3469          return SDOperand();
3470      }
3471
3472      // Let's see if the target supports this vector_shuffle.
3473      if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
3474        return SDOperand();
3475
3476      // Return the new VVECTOR_SHUFFLE node.
3477      SDOperand NumEltsNode = DAG.getConstant(NumElts, MVT::i32);
3478      SDOperand EVTNode = DAG.getValueType(EVT);
3479      std::vector<SDOperand> Ops;
3480      LHS = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, LHS, NumEltsNode,
3481                        EVTNode);
3482      Ops.push_back(LHS);
3483      AddToWorkList(LHS.Val);
3484      std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
3485      ZeroOps.push_back(NumEltsNode);
3486      ZeroOps.push_back(EVTNode);
3487      Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3488                                &ZeroOps[0], ZeroOps.size()));
3489      IdxOps.push_back(NumEltsNode);
3490      IdxOps.push_back(EVTNode);
3491      Ops.push_back(DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
3492                                &IdxOps[0], IdxOps.size()));
3493      Ops.push_back(NumEltsNode);
3494      Ops.push_back(EVTNode);
3495      SDOperand Result = DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
3496                                     &Ops[0], Ops.size());
3497      if (NumEltsNode != DstVecSize || EVTNode != DstVecEVT) {
3498        Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
3499                             DstVecSize, DstVecEVT);
3500      }
3501      return Result;
3502    }
3503  }
3504  return SDOperand();
3505}
3506
3507/// visitVBinOp - Visit a binary vector operation, like VADD.  IntOp indicates
3508/// the scalar operation of the vop if it is operating on an integer vector
3509/// (e.g. ADD) and FPOp indicates the FP version (e.g. FADD).
3510SDOperand DAGCombiner::visitVBinOp(SDNode *N, ISD::NodeType IntOp,
3511                                   ISD::NodeType FPOp) {
3512  MVT::ValueType EltType = cast<VTSDNode>(*(N->op_end()-1))->getVT();
3513  ISD::NodeType ScalarOp = MVT::isInteger(EltType) ? IntOp : FPOp;
3514  SDOperand LHS = N->getOperand(0);
3515  SDOperand RHS = N->getOperand(1);
3516  SDOperand Shuffle = XformToShuffleWithZero(N);
3517  if (Shuffle.Val) return Shuffle;
3518
3519  // If the LHS and RHS are VBUILD_VECTOR nodes, see if we can constant fold
3520  // this operation.
3521  if (LHS.getOpcode() == ISD::VBUILD_VECTOR &&
3522      RHS.getOpcode() == ISD::VBUILD_VECTOR) {
3523    SmallVector<SDOperand, 8> Ops;
3524    for (unsigned i = 0, e = LHS.getNumOperands()-2; i != e; ++i) {
3525      SDOperand LHSOp = LHS.getOperand(i);
3526      SDOperand RHSOp = RHS.getOperand(i);
3527      // If these two elements can't be folded, bail out.
3528      if ((LHSOp.getOpcode() != ISD::UNDEF &&
3529           LHSOp.getOpcode() != ISD::Constant &&
3530           LHSOp.getOpcode() != ISD::ConstantFP) ||
3531          (RHSOp.getOpcode() != ISD::UNDEF &&
3532           RHSOp.getOpcode() != ISD::Constant &&
3533           RHSOp.getOpcode() != ISD::ConstantFP))
3534        break;
3535      // Can't fold divide by zero.
3536      if (N->getOpcode() == ISD::VSDIV || N->getOpcode() == ISD::VUDIV) {
3537        if ((RHSOp.getOpcode() == ISD::Constant &&
3538             cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
3539            (RHSOp.getOpcode() == ISD::ConstantFP &&
3540             !cast<ConstantFPSDNode>(RHSOp.Val)->getValue()))
3541          break;
3542      }
3543      Ops.push_back(DAG.getNode(ScalarOp, EltType, LHSOp, RHSOp));
3544      AddToWorkList(Ops.back().Val);
3545      assert((Ops.back().getOpcode() == ISD::UNDEF ||
3546              Ops.back().getOpcode() == ISD::Constant ||
3547              Ops.back().getOpcode() == ISD::ConstantFP) &&
3548             "Scalar binop didn't fold!");
3549    }
3550
3551    if (Ops.size() == LHS.getNumOperands()-2) {
3552      Ops.push_back(*(LHS.Val->op_end()-2));
3553      Ops.push_back(*(LHS.Val->op_end()-1));
3554      return DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
3555    }
3556  }
3557
3558  return SDOperand();
3559}
3560
3561SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
3562  assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
3563
3564  SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
3565                                 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3566  // If we got a simplified select_cc node back from SimplifySelectCC, then
3567  // break it down into a new SETCC node, and a new SELECT node, and then return
3568  // the SELECT node, since we were called with a SELECT node.
3569  if (SCC.Val) {
3570    // Check to see if we got a select_cc back (to turn into setcc/select).
3571    // Otherwise, just return whatever node we got back, like fabs.
3572    if (SCC.getOpcode() == ISD::SELECT_CC) {
3573      SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
3574                                    SCC.getOperand(0), SCC.getOperand(1),
3575                                    SCC.getOperand(4));
3576      AddToWorkList(SETCC.Val);
3577      return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
3578                         SCC.getOperand(3), SETCC);
3579    }
3580    return SCC;
3581  }
3582  return SDOperand();
3583}
3584
3585/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
3586/// are the two values being selected between, see if we can simplify the
3587/// select.  Callers of this should assume that TheSelect is deleted if this
3588/// returns true.  As such, they should return the appropriate thing (e.g. the
3589/// node) back to the top-level of the DAG combiner loop to avoid it being
3590/// looked at.
3591///
3592bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
3593                                    SDOperand RHS) {
3594
3595  // If this is a select from two identical things, try to pull the operation
3596  // through the select.
3597  if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
3598    // If this is a load and the token chain is identical, replace the select
3599    // of two loads with a load through a select of the address to load from.
3600    // This triggers in things like "select bool X, 10.0, 123.0" after the FP
3601    // constants have been dropped into the constant pool.
3602    if (LHS.getOpcode() == ISD::LOAD &&
3603        // Token chains must be identical.
3604        LHS.getOperand(0) == RHS.getOperand(0)) {
3605      LoadSDNode *LLD = cast<LoadSDNode>(LHS);
3606      LoadSDNode *RLD = cast<LoadSDNode>(RHS);
3607
3608      // If this is an EXTLOAD, the VT's must match.
3609      if (LLD->getLoadedVT() == RLD->getLoadedVT()) {
3610        // FIXME: this conflates two src values, discarding one.  This is not
3611        // the right thing to do, but nothing uses srcvalues now.  When they do,
3612        // turn SrcValue into a list of locations.
3613        SDOperand Addr;
3614        if (TheSelect->getOpcode() == ISD::SELECT)
3615          Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
3616                             TheSelect->getOperand(0), LLD->getBasePtr(),
3617                             RLD->getBasePtr());
3618        else
3619          Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
3620                             TheSelect->getOperand(0),
3621                             TheSelect->getOperand(1),
3622                             LLD->getBasePtr(), RLD->getBasePtr(),
3623                             TheSelect->getOperand(4));
3624
3625        SDOperand Load;
3626        if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
3627          Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
3628                             Addr,LLD->getSrcValue(), LLD->getSrcValueOffset());
3629        else {
3630          Load = DAG.getExtLoad(LLD->getExtensionType(),
3631                                TheSelect->getValueType(0),
3632                                LLD->getChain(), Addr, LLD->getSrcValue(),
3633                                LLD->getSrcValueOffset(),
3634                                LLD->getLoadedVT());
3635        }
3636        // Users of the select now use the result of the load.
3637        CombineTo(TheSelect, Load);
3638
3639        // Users of the old loads now use the new load's chain.  We know the
3640        // old-load value is dead now.
3641        CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
3642        CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
3643        return true;
3644      }
3645    }
3646  }
3647
3648  return false;
3649}
3650
3651SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
3652                                        SDOperand N2, SDOperand N3,
3653                                        ISD::CondCode CC) {
3654
3655  MVT::ValueType VT = N2.getValueType();
3656  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
3657  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
3658  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
3659
3660  // Determine if the condition we're dealing with is constant
3661  SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
3662  if (SCC.Val) AddToWorkList(SCC.Val);
3663  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
3664
3665  // fold select_cc true, x, y -> x
3666  if (SCCC && SCCC->getValue())
3667    return N2;
3668  // fold select_cc false, x, y -> y
3669  if (SCCC && SCCC->getValue() == 0)
3670    return N3;
3671
3672  // Check to see if we can simplify the select into an fabs node
3673  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
3674    // Allow either -0.0 or 0.0
3675    if (CFP->getValue() == 0.0) {
3676      // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
3677      if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
3678          N0 == N2 && N3.getOpcode() == ISD::FNEG &&
3679          N2 == N3.getOperand(0))
3680        return DAG.getNode(ISD::FABS, VT, N0);
3681
3682      // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
3683      if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
3684          N0 == N3 && N2.getOpcode() == ISD::FNEG &&
3685          N2.getOperand(0) == N3)
3686        return DAG.getNode(ISD::FABS, VT, N3);
3687    }
3688  }
3689
3690  // Check to see if we can perform the "gzip trick", transforming
3691  // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
3692  if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
3693      MVT::isInteger(N0.getValueType()) &&
3694      MVT::isInteger(N2.getValueType()) &&
3695      (N1C->isNullValue() ||                    // (a < 0) ? b : 0
3696       (N1C->getValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
3697    MVT::ValueType XType = N0.getValueType();
3698    MVT::ValueType AType = N2.getValueType();
3699    if (XType >= AType) {
3700      // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
3701      // single-bit constant.
3702      if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
3703        unsigned ShCtV = Log2_64(N2C->getValue());
3704        ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
3705        SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
3706        SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
3707        AddToWorkList(Shift.Val);
3708        if (XType > AType) {
3709          Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
3710          AddToWorkList(Shift.Val);
3711        }
3712        return DAG.getNode(ISD::AND, AType, Shift, N2);
3713      }
3714      SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
3715                                    DAG.getConstant(MVT::getSizeInBits(XType)-1,
3716                                                    TLI.getShiftAmountTy()));
3717      AddToWorkList(Shift.Val);
3718      if (XType > AType) {
3719        Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
3720        AddToWorkList(Shift.Val);
3721      }
3722      return DAG.getNode(ISD::AND, AType, Shift, N2);
3723    }
3724  }
3725
3726  // fold select C, 16, 0 -> shl C, 4
3727  if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
3728      TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
3729    // Get a SetCC of the condition
3730    // FIXME: Should probably make sure that setcc is legal if we ever have a
3731    // target where it isn't.
3732    SDOperand Temp, SCC;
3733    // cast from setcc result type to select result type
3734    if (AfterLegalize) {
3735      SCC  = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
3736      Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
3737    } else {
3738      SCC  = DAG.getSetCC(MVT::i1, N0, N1, CC);
3739      Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
3740    }
3741    AddToWorkList(SCC.Val);
3742    AddToWorkList(Temp.Val);
3743    // shl setcc result by log2 n2c
3744    return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
3745                       DAG.getConstant(Log2_64(N2C->getValue()),
3746                                       TLI.getShiftAmountTy()));
3747  }
3748
3749  // Check to see if this is the equivalent of setcc
3750  // FIXME: Turn all of these into setcc if setcc if setcc is legal
3751  // otherwise, go ahead with the folds.
3752  if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
3753    MVT::ValueType XType = N0.getValueType();
3754    if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
3755      SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
3756      if (Res.getValueType() != VT)
3757        Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
3758      return Res;
3759    }
3760
3761    // seteq X, 0 -> srl (ctlz X, log2(size(X)))
3762    if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
3763        TLI.isOperationLegal(ISD::CTLZ, XType)) {
3764      SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
3765      return DAG.getNode(ISD::SRL, XType, Ctlz,
3766                         DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
3767                                         TLI.getShiftAmountTy()));
3768    }
3769    // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
3770    if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
3771      SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
3772                                    N0);
3773      SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
3774                                    DAG.getConstant(~0ULL, XType));
3775      return DAG.getNode(ISD::SRL, XType,
3776                         DAG.getNode(ISD::AND, XType, NegN0, NotN0),
3777                         DAG.getConstant(MVT::getSizeInBits(XType)-1,
3778                                         TLI.getShiftAmountTy()));
3779    }
3780    // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
3781    if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
3782      SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
3783                                   DAG.getConstant(MVT::getSizeInBits(XType)-1,
3784                                                   TLI.getShiftAmountTy()));
3785      return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
3786    }
3787  }
3788
3789  // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
3790  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
3791  if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
3792      N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1)) {
3793    if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0))) {
3794      MVT::ValueType XType = N0.getValueType();
3795      if (SubC->isNullValue() && MVT::isInteger(XType)) {
3796        SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
3797                                    DAG.getConstant(MVT::getSizeInBits(XType)-1,
3798                                                    TLI.getShiftAmountTy()));
3799        SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
3800        AddToWorkList(Shift.Val);
3801        AddToWorkList(Add.Val);
3802        return DAG.getNode(ISD::XOR, XType, Add, Shift);
3803      }
3804    }
3805  }
3806
3807  return SDOperand();
3808}
3809
3810SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
3811                                     SDOperand N1, ISD::CondCode Cond,
3812                                     bool foldBooleans) {
3813  // These setcc operations always fold.
3814  switch (Cond) {
3815  default: break;
3816  case ISD::SETFALSE:
3817  case ISD::SETFALSE2: return DAG.getConstant(0, VT);
3818  case ISD::SETTRUE:
3819  case ISD::SETTRUE2:  return DAG.getConstant(1, VT);
3820  }
3821
3822  if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
3823    uint64_t C1 = N1C->getValue();
3824    if (isa<ConstantSDNode>(N0.Val)) {
3825      return DAG.FoldSetCC(VT, N0, N1, Cond);
3826    } else {
3827      // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3828      // equality comparison, then we're just comparing whether X itself is
3829      // zero.
3830      if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
3831          N0.getOperand(0).getOpcode() == ISD::CTLZ &&
3832          N0.getOperand(1).getOpcode() == ISD::Constant) {
3833        unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
3834        if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3835            ShAmt == Log2_32(MVT::getSizeInBits(N0.getValueType()))) {
3836          if ((C1 == 0) == (Cond == ISD::SETEQ)) {
3837            // (srl (ctlz x), 5) == 0  -> X != 0
3838            // (srl (ctlz x), 5) != 1  -> X != 0
3839            Cond = ISD::SETNE;
3840          } else {
3841            // (srl (ctlz x), 5) != 0  -> X == 0
3842            // (srl (ctlz x), 5) == 1  -> X == 0
3843            Cond = ISD::SETEQ;
3844          }
3845          SDOperand Zero = DAG.getConstant(0, N0.getValueType());
3846          return DAG.getSetCC(VT, N0.getOperand(0).getOperand(0),
3847                              Zero, Cond);
3848        }
3849      }
3850
3851      // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3852      if (N0.getOpcode() == ISD::ZERO_EXTEND) {
3853        unsigned InSize = MVT::getSizeInBits(N0.getOperand(0).getValueType());
3854
3855        // If the comparison constant has bits in the upper part, the
3856        // zero-extended value could never match.
3857        if (C1 & (~0ULL << InSize)) {
3858          unsigned VSize = MVT::getSizeInBits(N0.getValueType());
3859          switch (Cond) {
3860          case ISD::SETUGT:
3861          case ISD::SETUGE:
3862          case ISD::SETEQ: return DAG.getConstant(0, VT);
3863          case ISD::SETULT:
3864          case ISD::SETULE:
3865          case ISD::SETNE: return DAG.getConstant(1, VT);
3866          case ISD::SETGT:
3867          case ISD::SETGE:
3868            // True if the sign bit of C1 is set.
3869            return DAG.getConstant((C1 & (1ULL << VSize)) != 0, VT);
3870          case ISD::SETLT:
3871          case ISD::SETLE:
3872            // True if the sign bit of C1 isn't set.
3873            return DAG.getConstant((C1 & (1ULL << VSize)) == 0, VT);
3874          default:
3875            break;
3876          }
3877        }
3878
3879        // Otherwise, we can perform the comparison with the low bits.
3880        switch (Cond) {
3881        case ISD::SETEQ:
3882        case ISD::SETNE:
3883        case ISD::SETUGT:
3884        case ISD::SETUGE:
3885        case ISD::SETULT:
3886        case ISD::SETULE:
3887          return DAG.getSetCC(VT, N0.getOperand(0),
3888                          DAG.getConstant(C1, N0.getOperand(0).getValueType()),
3889                          Cond);
3890        default:
3891          break;   // todo, be more careful with signed comparisons
3892        }
3893      } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3894                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3895        MVT::ValueType ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
3896        unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
3897        MVT::ValueType ExtDstTy = N0.getValueType();
3898        unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
3899
3900        // If the extended part has any inconsistent bits, it cannot ever
3901        // compare equal.  In other words, they have to be all ones or all
3902        // zeros.
3903        uint64_t ExtBits =
3904          (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
3905        if ((C1 & ExtBits) != 0 && (C1 & ExtBits) != ExtBits)
3906          return DAG.getConstant(Cond == ISD::SETNE, VT);
3907
3908        SDOperand ZextOp;
3909        MVT::ValueType Op0Ty = N0.getOperand(0).getValueType();
3910        if (Op0Ty == ExtSrcTy) {
3911          ZextOp = N0.getOperand(0);
3912        } else {
3913          int64_t Imm = ~0ULL >> (64-ExtSrcTyBits);
3914          ZextOp = DAG.getNode(ISD::AND, Op0Ty, N0.getOperand(0),
3915                               DAG.getConstant(Imm, Op0Ty));
3916        }
3917        AddToWorkList(ZextOp.Val);
3918        // Otherwise, make this a use of a zext.
3919        return DAG.getSetCC(VT, ZextOp,
3920                            DAG.getConstant(C1 & (~0ULL>>(64-ExtSrcTyBits)),
3921                                            ExtDstTy),
3922                            Cond);
3923      } else if ((N1C->getValue() == 0 || N1C->getValue() == 1) &&
3924                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3925
3926        // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
3927        if (N0.getOpcode() == ISD::SETCC) {
3928          bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getValue() != 1);
3929          if (TrueWhenTrue)
3930            return N0;
3931
3932          // Invert the condition.
3933          ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
3934          CC = ISD::getSetCCInverse(CC,
3935                               MVT::isInteger(N0.getOperand(0).getValueType()));
3936          return DAG.getSetCC(VT, N0.getOperand(0), N0.getOperand(1), CC);
3937        }
3938
3939        if ((N0.getOpcode() == ISD::XOR ||
3940             (N0.getOpcode() == ISD::AND &&
3941              N0.getOperand(0).getOpcode() == ISD::XOR &&
3942              N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
3943            isa<ConstantSDNode>(N0.getOperand(1)) &&
3944            cast<ConstantSDNode>(N0.getOperand(1))->getValue() == 1) {
3945          // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
3946          // can only do this if the top bits are known zero.
3947          if (TLI.MaskedValueIsZero(N0,
3948                                    MVT::getIntVTBitMask(N0.getValueType())-1)){
3949            // Okay, get the un-inverted input value.
3950            SDOperand Val;
3951            if (N0.getOpcode() == ISD::XOR)
3952              Val = N0.getOperand(0);
3953            else {
3954              assert(N0.getOpcode() == ISD::AND &&
3955                     N0.getOperand(0).getOpcode() == ISD::XOR);
3956              // ((X^1)&1)^1 -> X & 1
3957              Val = DAG.getNode(ISD::AND, N0.getValueType(),
3958                                N0.getOperand(0).getOperand(0),
3959                                N0.getOperand(1));
3960            }
3961            return DAG.getSetCC(VT, Val, N1,
3962                                Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3963          }
3964        }
3965      }
3966
3967      uint64_t MinVal, MaxVal;
3968      unsigned OperandBitSize = MVT::getSizeInBits(N1C->getValueType(0));
3969      if (ISD::isSignedIntSetCC(Cond)) {
3970        MinVal = 1ULL << (OperandBitSize-1);
3971        if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
3972          MaxVal = ~0ULL >> (65-OperandBitSize);
3973        else
3974          MaxVal = 0;
3975      } else {
3976        MinVal = 0;
3977        MaxVal = ~0ULL >> (64-OperandBitSize);
3978      }
3979
3980      // Canonicalize GE/LE comparisons to use GT/LT comparisons.
3981      if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
3982        if (C1 == MinVal) return DAG.getConstant(1, VT);   // X >= MIN --> true
3983        --C1;                                          // X >= C0 --> X > (C0-1)
3984        return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
3985                        (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
3986      }
3987
3988      if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
3989        if (C1 == MaxVal) return DAG.getConstant(1, VT);   // X <= MAX --> true
3990        ++C1;                                          // X <= C0 --> X < (C0+1)
3991        return DAG.getSetCC(VT, N0, DAG.getConstant(C1, N1.getValueType()),
3992                        (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
3993      }
3994
3995      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
3996        return DAG.getConstant(0, VT);      // X < MIN --> false
3997
3998      // Canonicalize setgt X, Min --> setne X, Min
3999      if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
4000        return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
4001      // Canonicalize setlt X, Max --> setne X, Max
4002      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
4003        return DAG.getSetCC(VT, N0, N1, ISD::SETNE);
4004
4005      // If we have setult X, 1, turn it into seteq X, 0
4006      if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
4007        return DAG.getSetCC(VT, N0, DAG.getConstant(MinVal, N0.getValueType()),
4008                        ISD::SETEQ);
4009      // If we have setugt X, Max-1, turn it into seteq X, Max
4010      else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
4011        return DAG.getSetCC(VT, N0, DAG.getConstant(MaxVal, N0.getValueType()),
4012                        ISD::SETEQ);
4013
4014      // If we have "setcc X, C0", check to see if we can shrink the immediate
4015      // by changing cc.
4016
4017      // SETUGT X, SINTMAX  -> SETLT X, 0
4018      if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
4019          C1 == (~0ULL >> (65-OperandBitSize)))
4020        return DAG.getSetCC(VT, N0, DAG.getConstant(0, N1.getValueType()),
4021                            ISD::SETLT);
4022
4023      // FIXME: Implement the rest of these.
4024
4025      // Fold bit comparisons when we can.
4026      if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4027          VT == N0.getValueType() && N0.getOpcode() == ISD::AND)
4028        if (ConstantSDNode *AndRHS =
4029                    dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4030          if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
4031            // Perform the xform if the AND RHS is a single bit.
4032            if (isPowerOf2_64(AndRHS->getValue())) {
4033              return DAG.getNode(ISD::SRL, VT, N0,
4034                             DAG.getConstant(Log2_64(AndRHS->getValue()),
4035                                                   TLI.getShiftAmountTy()));
4036            }
4037          } else if (Cond == ISD::SETEQ && C1 == AndRHS->getValue()) {
4038            // (X & 8) == 8  -->  (X & 8) >> 3
4039            // Perform the xform if C1 is a single bit.
4040            if (isPowerOf2_64(C1)) {
4041              return DAG.getNode(ISD::SRL, VT, N0,
4042                          DAG.getConstant(Log2_64(C1),TLI.getShiftAmountTy()));
4043            }
4044          }
4045        }
4046    }
4047  } else if (isa<ConstantSDNode>(N0.Val)) {
4048      // Ensure that the constant occurs on the RHS.
4049    return DAG.getSetCC(VT, N1, N0, ISD::getSetCCSwappedOperands(Cond));
4050  }
4051
4052  if (isa<ConstantFPSDNode>(N0.Val)) {
4053    // Constant fold or commute setcc.
4054    SDOperand O = DAG.FoldSetCC(VT, N0, N1, Cond);
4055    if (O.Val) return O;
4056  }
4057
4058  if (N0 == N1) {
4059    // We can always fold X == X for integer setcc's.
4060    if (MVT::isInteger(N0.getValueType()))
4061      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
4062    unsigned UOF = ISD::getUnorderedFlavor(Cond);
4063    if (UOF == 2)   // FP operators that are undefined on NaNs.
4064      return DAG.getConstant(ISD::isTrueWhenEqual(Cond), VT);
4065    if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
4066      return DAG.getConstant(UOF, VT);
4067    // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
4068    // if it is not already.
4069    ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
4070    if (NewCond != Cond)
4071      return DAG.getSetCC(VT, N0, N1, NewCond);
4072  }
4073
4074  if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4075      MVT::isInteger(N0.getValueType())) {
4076    if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
4077        N0.getOpcode() == ISD::XOR) {
4078      // Simplify (X+Y) == (X+Z) -->  Y == Z
4079      if (N0.getOpcode() == N1.getOpcode()) {
4080        if (N0.getOperand(0) == N1.getOperand(0))
4081          return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(1), Cond);
4082        if (N0.getOperand(1) == N1.getOperand(1))
4083          return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(0), Cond);
4084        if (DAG.isCommutativeBinOp(N0.getOpcode())) {
4085          // If X op Y == Y op X, try other combinations.
4086          if (N0.getOperand(0) == N1.getOperand(1))
4087            return DAG.getSetCC(VT, N0.getOperand(1), N1.getOperand(0), Cond);
4088          if (N0.getOperand(1) == N1.getOperand(0))
4089            return DAG.getSetCC(VT, N0.getOperand(0), N1.getOperand(1), Cond);
4090        }
4091      }
4092
4093      if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
4094        if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4095          // Turn (X+C1) == C2 --> X == C2-C1
4096          if (N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse()) {
4097            return DAG.getSetCC(VT, N0.getOperand(0),
4098                              DAG.getConstant(RHSC->getValue()-LHSR->getValue(),
4099                                N0.getValueType()), Cond);
4100          }
4101
4102          // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
4103          if (N0.getOpcode() == ISD::XOR)
4104            // If we know that all of the inverted bits are zero, don't bother
4105            // performing the inversion.
4106            if (TLI.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getValue()))
4107              return DAG.getSetCC(VT, N0.getOperand(0),
4108                              DAG.getConstant(LHSR->getValue()^RHSC->getValue(),
4109                                              N0.getValueType()), Cond);
4110        }
4111
4112        // Turn (C1-X) == C2 --> X == C1-C2
4113        if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
4114          if (N0.getOpcode() == ISD::SUB && N0.Val->hasOneUse()) {
4115            return DAG.getSetCC(VT, N0.getOperand(1),
4116                             DAG.getConstant(SUBC->getValue()-RHSC->getValue(),
4117                                             N0.getValueType()), Cond);
4118          }
4119        }
4120      }
4121
4122      // Simplify (X+Z) == X -->  Z == 0
4123      if (N0.getOperand(0) == N1)
4124        return DAG.getSetCC(VT, N0.getOperand(1),
4125                        DAG.getConstant(0, N0.getValueType()), Cond);
4126      if (N0.getOperand(1) == N1) {
4127        if (DAG.isCommutativeBinOp(N0.getOpcode()))
4128          return DAG.getSetCC(VT, N0.getOperand(0),
4129                          DAG.getConstant(0, N0.getValueType()), Cond);
4130        else {
4131          assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
4132          // (Z-X) == X  --> Z == X<<1
4133          SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(),
4134                                     N1,
4135                                     DAG.getConstant(1,TLI.getShiftAmountTy()));
4136          AddToWorkList(SH.Val);
4137          return DAG.getSetCC(VT, N0.getOperand(0), SH, Cond);
4138        }
4139      }
4140    }
4141
4142    if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
4143        N1.getOpcode() == ISD::XOR) {
4144      // Simplify  X == (X+Z) -->  Z == 0
4145      if (N1.getOperand(0) == N0) {
4146        return DAG.getSetCC(VT, N1.getOperand(1),
4147                        DAG.getConstant(0, N1.getValueType()), Cond);
4148      } else if (N1.getOperand(1) == N0) {
4149        if (DAG.isCommutativeBinOp(N1.getOpcode())) {
4150          return DAG.getSetCC(VT, N1.getOperand(0),
4151                          DAG.getConstant(0, N1.getValueType()), Cond);
4152        } else {
4153          assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
4154          // X == (Z-X)  --> X<<1 == Z
4155          SDOperand SH = DAG.getNode(ISD::SHL, N1.getValueType(), N0,
4156                                     DAG.getConstant(1,TLI.getShiftAmountTy()));
4157          AddToWorkList(SH.Val);
4158          return DAG.getSetCC(VT, SH, N1.getOperand(0), Cond);
4159        }
4160      }
4161    }
4162  }
4163
4164  // Fold away ALL boolean setcc's.
4165  SDOperand Temp;
4166  if (N0.getValueType() == MVT::i1 && foldBooleans) {
4167    switch (Cond) {
4168    default: assert(0 && "Unknown integer setcc!");
4169    case ISD::SETEQ:  // X == Y  -> (X^Y)^1
4170      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
4171      N0 = DAG.getNode(ISD::XOR, MVT::i1, Temp, DAG.getConstant(1, MVT::i1));
4172      AddToWorkList(Temp.Val);
4173      break;
4174    case ISD::SETNE:  // X != Y   -->  (X^Y)
4175      N0 = DAG.getNode(ISD::XOR, MVT::i1, N0, N1);
4176      break;
4177    case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
4178    case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
4179      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
4180      N0 = DAG.getNode(ISD::AND, MVT::i1, N1, Temp);
4181      AddToWorkList(Temp.Val);
4182      break;
4183    case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
4184    case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
4185      Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
4186      N0 = DAG.getNode(ISD::AND, MVT::i1, N0, Temp);
4187      AddToWorkList(Temp.Val);
4188      break;
4189    case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
4190    case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
4191      Temp = DAG.getNode(ISD::XOR, MVT::i1, N0, DAG.getConstant(1, MVT::i1));
4192      N0 = DAG.getNode(ISD::OR, MVT::i1, N1, Temp);
4193      AddToWorkList(Temp.Val);
4194      break;
4195    case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
4196    case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
4197      Temp = DAG.getNode(ISD::XOR, MVT::i1, N1, DAG.getConstant(1, MVT::i1));
4198      N0 = DAG.getNode(ISD::OR, MVT::i1, N0, Temp);
4199      break;
4200    }
4201    if (VT != MVT::i1) {
4202      AddToWorkList(N0.Val);
4203      // FIXME: If running after legalize, we probably can't do this.
4204      N0 = DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
4205    }
4206    return N0;
4207  }
4208
4209  // Could not fold it.
4210  return SDOperand();
4211}
4212
4213/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
4214/// return a DAG expression to select that will generate the same value by
4215/// multiplying by a magic number.  See:
4216/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4217SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
4218  std::vector<SDNode*> Built;
4219  SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
4220
4221  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4222       ii != ee; ++ii)
4223    AddToWorkList(*ii);
4224  return S;
4225}
4226
4227/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
4228/// return a DAG expression to select that will generate the same value by
4229/// multiplying by a magic number.  See:
4230/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
4231SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
4232  std::vector<SDNode*> Built;
4233  SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
4234
4235  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
4236       ii != ee; ++ii)
4237    AddToWorkList(*ii);
4238  return S;
4239}
4240
4241/// FindBaseOffset - Return true if base is known not to alias with anything
4242/// but itself.  Provides base object and offset as results.
4243static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
4244  // Assume it is a primitive operation.
4245  Base = Ptr; Offset = 0;
4246
4247  // If it's an adding a simple constant then integrate the offset.
4248  if (Base.getOpcode() == ISD::ADD) {
4249    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
4250      Base = Base.getOperand(0);
4251      Offset += C->getValue();
4252    }
4253  }
4254
4255  // If it's any of the following then it can't alias with anything but itself.
4256  return isa<FrameIndexSDNode>(Base) ||
4257         isa<ConstantPoolSDNode>(Base) ||
4258         isa<GlobalAddressSDNode>(Base);
4259}
4260
4261/// isAlias - Return true if there is any possibility that the two addresses
4262/// overlap.
4263bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
4264                          const Value *SrcValue1, int SrcValueOffset1,
4265                          SDOperand Ptr2, int64_t Size2,
4266                          const Value *SrcValue2, int SrcValueOffset2)
4267{
4268  // If they are the same then they must be aliases.
4269  if (Ptr1 == Ptr2) return true;
4270
4271  // Gather base node and offset information.
4272  SDOperand Base1, Base2;
4273  int64_t Offset1, Offset2;
4274  bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
4275  bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
4276
4277  // If they have a same base address then...
4278  if (Base1 == Base2) {
4279    // Check to see if the addresses overlap.
4280    return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
4281  }
4282
4283  // If we know both bases then they can't alias.
4284  if (KnownBase1 && KnownBase2) return false;
4285
4286  if (CombinerGlobalAA) {
4287    // Use alias analysis information.
4288    int Overlap1 = Size1 + SrcValueOffset1 + Offset1;
4289    int Overlap2 = Size2 + SrcValueOffset2 + Offset2;
4290    AliasAnalysis::AliasResult AAResult =
4291                             AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
4292    if (AAResult == AliasAnalysis::NoAlias)
4293      return false;
4294  }
4295
4296  // Otherwise we have to assume they alias.
4297  return true;
4298}
4299
4300/// FindAliasInfo - Extracts the relevant alias information from the memory
4301/// node.  Returns true if the operand was a load.
4302bool DAGCombiner::FindAliasInfo(SDNode *N,
4303                        SDOperand &Ptr, int64_t &Size,
4304                        const Value *&SrcValue, int &SrcValueOffset) {
4305  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4306    Ptr = LD->getBasePtr();
4307    Size = MVT::getSizeInBits(LD->getLoadedVT()) >> 3;
4308    SrcValue = LD->getSrcValue();
4309    SrcValueOffset = LD->getSrcValueOffset();
4310    return true;
4311  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4312    Ptr = ST->getBasePtr();
4313    Size = MVT::getSizeInBits(ST->getStoredVT()) >> 3;
4314    SrcValue = ST->getSrcValue();
4315    SrcValueOffset = ST->getSrcValueOffset();
4316  } else {
4317    assert(0 && "FindAliasInfo expected a memory operand");
4318  }
4319
4320  return false;
4321}
4322
4323/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
4324/// looking for aliasing nodes and adding them to the Aliases vector.
4325void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
4326                                   SmallVector<SDOperand, 8> &Aliases) {
4327  SmallVector<SDOperand, 8> Chains;     // List of chains to visit.
4328  std::set<SDNode *> Visited;           // Visited node set.
4329
4330  // Get alias information for node.
4331  SDOperand Ptr;
4332  int64_t Size;
4333  const Value *SrcValue;
4334  int SrcValueOffset;
4335  bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
4336
4337  // Starting off.
4338  Chains.push_back(OriginalChain);
4339
4340  // Look at each chain and determine if it is an alias.  If so, add it to the
4341  // aliases list.  If not, then continue up the chain looking for the next
4342  // candidate.
4343  while (!Chains.empty()) {
4344    SDOperand Chain = Chains.back();
4345    Chains.pop_back();
4346
4347     // Don't bother if we've been before.
4348    if (Visited.find(Chain.Val) != Visited.end()) continue;
4349    Visited.insert(Chain.Val);
4350
4351    switch (Chain.getOpcode()) {
4352    case ISD::EntryToken:
4353      // Entry token is ideal chain operand, but handled in FindBetterChain.
4354      break;
4355
4356    case ISD::LOAD:
4357    case ISD::STORE: {
4358      // Get alias information for Chain.
4359      SDOperand OpPtr;
4360      int64_t OpSize;
4361      const Value *OpSrcValue;
4362      int OpSrcValueOffset;
4363      bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
4364                                    OpSrcValue, OpSrcValueOffset);
4365
4366      // If chain is alias then stop here.
4367      if (!(IsLoad && IsOpLoad) &&
4368          isAlias(Ptr, Size, SrcValue, SrcValueOffset,
4369                  OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
4370        Aliases.push_back(Chain);
4371      } else {
4372        // Look further up the chain.
4373        Chains.push_back(Chain.getOperand(0));
4374        // Clean up old chain.
4375        AddToWorkList(Chain.Val);
4376      }
4377      break;
4378    }
4379
4380    case ISD::TokenFactor:
4381      // We have to check each of the operands of the token factor, so we queue
4382      // then up.  Adding the  operands to the queue (stack) in reverse order
4383      // maintains the original order and increases the likelihood that getNode
4384      // will find a matching token factor (CSE.)
4385      for (unsigned n = Chain.getNumOperands(); n;)
4386        Chains.push_back(Chain.getOperand(--n));
4387      // Eliminate the token factor if we can.
4388      AddToWorkList(Chain.Val);
4389      break;
4390
4391    default:
4392      // For all other instructions we will just have to take what we can get.
4393      Aliases.push_back(Chain);
4394      break;
4395    }
4396  }
4397}
4398
4399/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
4400/// for a better chain (aliasing node.)
4401SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
4402  SmallVector<SDOperand, 8> Aliases;  // Ops for replacing token factor.
4403
4404  // Accumulate all the aliases to this node.
4405  GatherAllAliases(N, OldChain, Aliases);
4406
4407  if (Aliases.size() == 0) {
4408    // If no operands then chain to entry token.
4409    return DAG.getEntryNode();
4410  } else if (Aliases.size() == 1) {
4411    // If a single operand then chain to it.  We don't need to revisit it.
4412    return Aliases[0];
4413  }
4414
4415  // Construct a custom tailored token factor.
4416  SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4417                                   &Aliases[0], Aliases.size());
4418
4419  // Make sure the old chain gets cleaned up.
4420  if (NewChain != OldChain) AddToWorkList(OldChain.Val);
4421
4422  return NewChain;
4423}
4424
4425// SelectionDAG::Combine - This is the entry point for the file.
4426//
4427void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
4428  /// run - This is the main entry point to this class.
4429  ///
4430  DAGCombiner(*this, AA).Run(RunningAfterLegalize);
4431}
4432