DAGCombiner.cpp revision 89e88e30bff4a5f4303dc9e44d3faa89b81af5a8
16e34636749217654f43221885afb7a29bb5ca96aAdam Powell//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
26e34636749217654f43221885afb7a29bb5ca96aAdam Powell//
36e34636749217654f43221885afb7a29bb5ca96aAdam Powell//                     The LLVM Compiler Infrastructure
46e34636749217654f43221885afb7a29bb5ca96aAdam Powell//
56e34636749217654f43221885afb7a29bb5ca96aAdam Powell// This file is distributed under the University of Illinois Open Source
66e34636749217654f43221885afb7a29bb5ca96aAdam Powell// License. See LICENSE.TXT for details.
76e34636749217654f43221885afb7a29bb5ca96aAdam Powell//
86e34636749217654f43221885afb7a29bb5ca96aAdam Powell//===----------------------------------------------------------------------===//
96e34636749217654f43221885afb7a29bb5ca96aAdam Powell//
106e34636749217654f43221885afb7a29bb5ca96aAdam Powell// This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
116e34636749217654f43221885afb7a29bb5ca96aAdam Powell// both before and after the DAG is legalized.
126e34636749217654f43221885afb7a29bb5ca96aAdam Powell//
136e34636749217654f43221885afb7a29bb5ca96aAdam Powell// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
146e34636749217654f43221885afb7a29bb5ca96aAdam Powell// primarily intended to handle simplification opportunities that are implicit
156e34636749217654f43221885afb7a29bb5ca96aAdam Powell// in the LLVM IR and exposed by the various codegen lowering phases.
166e34636749217654f43221885afb7a29bb5ca96aAdam Powell//
176e34636749217654f43221885afb7a29bb5ca96aAdam Powell//===----------------------------------------------------------------------===//
186e34636749217654f43221885afb7a29bb5ca96aAdam Powell
196e34636749217654f43221885afb7a29bb5ca96aAdam Powell#define DEBUG_TYPE "dagcombine"
206e34636749217654f43221885afb7a29bb5ca96aAdam Powell#include "llvm/CodeGen/SelectionDAG.h"
215e0959393426371dadef2c7905d5c915a1ac2dd4Scott Main#include "llvm/ADT/SmallPtrSet.h"
225e0959393426371dadef2c7905d5c915a1ac2dd4Scott Main#include "llvm/ADT/Statistic.h"
235e0959393426371dadef2c7905d5c915a1ac2dd4Scott Main#include "llvm/Analysis/AliasAnalysis.h"
245e0959393426371dadef2c7905d5c915a1ac2dd4Scott Main#include "llvm/CodeGen/MachineFrameInfo.h"
255e0959393426371dadef2c7905d5c915a1ac2dd4Scott Main#include "llvm/CodeGen/MachineFunction.h"
265e0959393426371dadef2c7905d5c915a1ac2dd4Scott Main#include "llvm/IR/DataLayout.h"
27ef0314b2c693c6cfa34680a784210dfb540fe36cScott Main#include "llvm/IR/DerivedTypes.h"
285e0959393426371dadef2c7905d5c915a1ac2dd4Scott Main#include "llvm/IR/Function.h"
295e0959393426371dadef2c7905d5c915a1ac2dd4Scott Main#include "llvm/IR/LLVMContext.h"
306e34636749217654f43221885afb7a29bb5ca96aAdam Powell#include "llvm/Support/CommandLine.h"
316e34636749217654f43221885afb7a29bb5ca96aAdam Powell#include "llvm/Support/Debug.h"
32f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell#include "llvm/Support/ErrorHandling.h"
33785c447b2bc625209706fd128ce61781c3a4183bAdam Powell#include "llvm/Support/MathExtras.h"
34f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell#include "llvm/Support/raw_ostream.h"
35f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell#include "llvm/Target/TargetLowering.h"
36f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell#include "llvm/Target/TargetMachine.h"
37f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell#include "llvm/Target/TargetOptions.h"
38f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell#include <algorithm>
39f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powellusing namespace llvm;
40f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell
41f178737f823cf22d9a07df6f51071b7189a95e7eAdam PowellSTATISTIC(NodesCombined   , "Number of dag nodes combined");
42f178737f823cf22d9a07df6f51071b7189a95e7eAdam PowellSTATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
43f178737f823cf22d9a07df6f51071b7189a95e7eAdam PowellSTATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
44f178737f823cf22d9a07df6f51071b7189a95e7eAdam PowellSTATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
45f178737f823cf22d9a07df6f51071b7189a95e7eAdam PowellSTATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
46f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell
47f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powellnamespace {
48f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell  static cl::opt<bool>
49f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell    CombinerAA("combiner-alias-analysis", cl::Hidden,
50f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell               cl::desc("Turn on alias analysis during testing"));
51f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell
52f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell  static cl::opt<bool>
53f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell    CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell               cl::desc("Include global information in alias analysis"));
55f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell
56f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell//------------------------------ DAGCombiner ---------------------------------//
57f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell
58f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell  class DAGCombiner {
59f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell    SelectionDAG &DAG;
60f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell    const TargetLowering &TLI;
61f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell    CombineLevel Level;
62f178737f823cf22d9a07df6f51071b7189a95e7eAdam Powell    CodeGenOpt::Level OptLevel;
636e34636749217654f43221885afb7a29bb5ca96aAdam Powell    bool LegalOperations;
646e34636749217654f43221885afb7a29bb5ca96aAdam Powell    bool LegalTypes;
656e34636749217654f43221885afb7a29bb5ca96aAdam Powell
666e34636749217654f43221885afb7a29bb5ca96aAdam Powell    // Worklist of all of the nodes that need to be simplified.
676e34636749217654f43221885afb7a29bb5ca96aAdam Powell    //
686e34636749217654f43221885afb7a29bb5ca96aAdam Powell    // This has the semantics that when adding to the worklist,
69c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    // the item added must be next to be processed. It should
706e34636749217654f43221885afb7a29bb5ca96aAdam Powell    // also only appear once. The naive approach to this takes
716e34636749217654f43221885afb7a29bb5ca96aAdam Powell    // linear time.
726e34636749217654f43221885afb7a29bb5ca96aAdam Powell    //
736e34636749217654f43221885afb7a29bb5ca96aAdam Powell    // To reduce the insert/remove time to logarithmic, we use
746e34636749217654f43221885afb7a29bb5ca96aAdam Powell    // a set and a vector to maintain our worklist.
75c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    //
76c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    // The set contains the items on the worklist, but does not
77c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    // maintain the order they should be visited.
78c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    //
79c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    // The vector maintains the order nodes should be visited, but may
80c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    // contain duplicate or removed nodes. When choosing a node to
81c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    // visit, we pop off the order stack until we find an item that is
82c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    // also in the contents set. All operations are O(log N).
83c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    SmallPtrSet<SDNode*, 64> WorkListContents;
84c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    SmallVector<SDNode*, 64> WorkListOrder;
85c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell
866e34636749217654f43221885afb7a29bb5ca96aAdam Powell    // AA - Used for DAG load/store alias analysis.
876e34636749217654f43221885afb7a29bb5ca96aAdam Powell    AliasAnalysis &AA;
886e34636749217654f43221885afb7a29bb5ca96aAdam Powell
896e34636749217654f43221885afb7a29bb5ca96aAdam Powell    /// AddUsersToWorkList - When an instruction is simplified, add all users of
906e34636749217654f43221885afb7a29bb5ca96aAdam Powell    /// the instruction to the work lists because they might get more simplified
91c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    /// now.
926e34636749217654f43221885afb7a29bb5ca96aAdam Powell    ///
936e34636749217654f43221885afb7a29bb5ca96aAdam Powell    void AddUsersToWorkList(SDNode *N) {
946e34636749217654f43221885afb7a29bb5ca96aAdam Powell      for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
956e34636749217654f43221885afb7a29bb5ca96aAdam Powell           UI != UE; ++UI)
966e34636749217654f43221885afb7a29bb5ca96aAdam Powell        AddToWorkList(*UI);
97c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    }
98c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell
99c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    /// visit - call the node-specific routine that knows how to fold each
100c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    /// particular type of node.
101c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    SDValue visit(SDNode *N);
102c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell
103c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell  public:
104c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    /// AddToWorkList - Add to the work list making sure its instance is at the
105c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    /// back (next to be processed.)
106c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell    void AddToWorkList(SDNode *N) {
107c9ae2a24dc1fa274ca0916c91a2e9a2764ba4bb3Adam Powell      WorkListContents.insert(N);
108b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell      WorkListOrder.push_back(N);
109b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    }
110b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell
111b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    /// removeFromWorkList - remove all instances of N from the worklist.
112b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    ///
113b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    void removeFromWorkList(SDNode *N) {
114b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell      WorkListContents.erase(N);
115b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    }
116b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell
117b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
118b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell                      bool AddTo = true);
119b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell
120b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
121b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell      return CombineTo(N, &Res, 1, AddTo);
122b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    }
123785c447b2bc625209706fd128ce61781c3a4183bAdam Powell
124785c447b2bc625209706fd128ce61781c3a4183bAdam Powell    SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
125785c447b2bc625209706fd128ce61781c3a4183bAdam Powell                      bool AddTo = true) {
126785c447b2bc625209706fd128ce61781c3a4183bAdam Powell      SDValue To[] = { Res0, Res1 };
127785c447b2bc625209706fd128ce61781c3a4183bAdam Powell      return CombineTo(N, To, 2, AddTo);
128785c447b2bc625209706fd128ce61781c3a4183bAdam Powell    }
129785c447b2bc625209706fd128ce61781c3a4183bAdam Powell
130785c447b2bc625209706fd128ce61781c3a4183bAdam Powell    void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
131785c447b2bc625209706fd128ce61781c3a4183bAdam Powell
132785c447b2bc625209706fd128ce61781c3a4183bAdam Powell  private:
133785c447b2bc625209706fd128ce61781c3a4183bAdam Powell
134785c447b2bc625209706fd128ce61781c3a4183bAdam Powell    /// SimplifyDemandedBits - Check the specified integer node value to see if
135b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    /// it can be simplified or if things it uses can be simplified by bit
136b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    /// propagation.  If so, return true.
137b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    bool SimplifyDemandedBits(SDValue Op) {
138b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell      unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
139b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell      APInt Demanded = APInt::getAllOnesValue(BitWidth);
140b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell      return SimplifyDemandedBits(Op, Demanded);
141b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    }
142b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell
143b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
144b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell
145b98a81f86ab87f1d718f329f03256111fdabd8d1Adam Powell    bool CombineToPreIndexedLoadStore(SDNode *N);
1466e34636749217654f43221885afb7a29bb5ca96aAdam Powell    bool CombineToPostIndexedLoadStore(SDNode *N);
1476e34636749217654f43221885afb7a29bb5ca96aAdam Powell
1486e34636749217654f43221885afb7a29bb5ca96aAdam Powell    void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
1496e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
1506e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
1516e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
1526e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue PromoteIntBinOp(SDValue Op);
1536e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue PromoteIntShiftOp(SDValue Op);
1546e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue PromoteExtend(SDValue Op);
1556e34636749217654f43221885afb7a29bb5ca96aAdam Powell    bool PromoteLoad(SDValue Op);
1566e34636749217654f43221885afb7a29bb5ca96aAdam Powell
1576e34636749217654f43221885afb7a29bb5ca96aAdam Powell    void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
1586e34636749217654f43221885afb7a29bb5ca96aAdam Powell                         SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
1596e34636749217654f43221885afb7a29bb5ca96aAdam Powell                         ISD::NodeType ExtType);
1606e34636749217654f43221885afb7a29bb5ca96aAdam Powell
1616e34636749217654f43221885afb7a29bb5ca96aAdam Powell    /// combine - call the node-specific routine that knows how to fold each
1626e34636749217654f43221885afb7a29bb5ca96aAdam Powell    /// particular type of node. If that doesn't do anything, try the
1636e34636749217654f43221885afb7a29bb5ca96aAdam Powell    /// target-specific DAG combines.
1646e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue combine(SDNode *N);
1656e34636749217654f43221885afb7a29bb5ca96aAdam Powell
1666e34636749217654f43221885afb7a29bb5ca96aAdam Powell    // Visitation implementation - Implement dag node combining for different
1676e34636749217654f43221885afb7a29bb5ca96aAdam Powell    // node types.  The semantics are as follows:
1686e34636749217654f43221885afb7a29bb5ca96aAdam Powell    // Return Value:
1696e34636749217654f43221885afb7a29bb5ca96aAdam Powell    //   SDValue.getNode() == 0 - No change was made
1706e34636749217654f43221885afb7a29bb5ca96aAdam Powell    //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
1716e34636749217654f43221885afb7a29bb5ca96aAdam Powell    //   otherwise              - N should be replaced by the returned Operand.
1726e34636749217654f43221885afb7a29bb5ca96aAdam Powell    //
1736e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitTokenFactor(SDNode *N);
1746e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitMERGE_VALUES(SDNode *N);
1756e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitADD(SDNode *N);
1766e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitSUB(SDNode *N);
1776e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitADDC(SDNode *N);
1786e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitSUBC(SDNode *N);
1796e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitADDE(SDNode *N);
1806e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitSUBE(SDNode *N);
1816e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitMUL(SDNode *N);
1826e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitSDIV(SDNode *N);
1836e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitUDIV(SDNode *N);
1846e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitSREM(SDNode *N);
1856e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitUREM(SDNode *N);
1866e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitMULHU(SDNode *N);
1876e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitMULHS(SDNode *N);
1886e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitSMUL_LOHI(SDNode *N);
1896e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitUMUL_LOHI(SDNode *N);
1906e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitSMULO(SDNode *N);
1916e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitUMULO(SDNode *N);
1926e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitSDIVREM(SDNode *N);
1936e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitUDIVREM(SDNode *N);
1946e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitAND(SDNode *N);
1956e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitOR(SDNode *N);
1969168f0b170c6a99371ae46e7d3f5d66c8c4c930dAdam Powell    SDValue visitXOR(SDNode *N);
1979168f0b170c6a99371ae46e7d3f5d66c8c4c930dAdam Powell    SDValue SimplifyVBinOp(SDNode *N);
1989168f0b170c6a99371ae46e7d3f5d66c8c4c930dAdam Powell    SDValue SimplifyVUnaryOp(SDNode *N);
1999168f0b170c6a99371ae46e7d3f5d66c8c4c930dAdam Powell    SDValue visitSHL(SDNode *N);
2009168f0b170c6a99371ae46e7d3f5d66c8c4c930dAdam Powell    SDValue visitSRA(SDNode *N);
201f8419a0299680ed580975b0fcb758990b4367db8Adam Powell    SDValue visitSRL(SDNode *N);
202f8419a0299680ed580975b0fcb758990b4367db8Adam Powell    SDValue visitCTLZ(SDNode *N);
203f8419a0299680ed580975b0fcb758990b4367db8Adam Powell    SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
204f8419a0299680ed580975b0fcb758990b4367db8Adam Powell    SDValue visitCTTZ(SDNode *N);
205f8419a0299680ed580975b0fcb758990b4367db8Adam Powell    SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
206f8419a0299680ed580975b0fcb758990b4367db8Adam Powell    SDValue visitCTPOP(SDNode *N);
207f8419a0299680ed580975b0fcb758990b4367db8Adam Powell    SDValue visitSELECT(SDNode *N);
208f8419a0299680ed580975b0fcb758990b4367db8Adam Powell    SDValue visitSELECT_CC(SDNode *N);
209f8419a0299680ed580975b0fcb758990b4367db8Adam Powell    SDValue visitSETCC(SDNode *N);
210f8419a0299680ed580975b0fcb758990b4367db8Adam Powell    SDValue visitSIGN_EXTEND(SDNode *N);
211f8419a0299680ed580975b0fcb758990b4367db8Adam Powell    SDValue visitZERO_EXTEND(SDNode *N);
212f8419a0299680ed580975b0fcb758990b4367db8Adam Powell    SDValue visitANY_EXTEND(SDNode *N);
2136e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitSIGN_EXTEND_INREG(SDNode *N);
2146e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitTRUNCATE(SDNode *N);
2156e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitBITCAST(SDNode *N);
2166e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitBUILD_PAIR(SDNode *N);
2176e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFADD(SDNode *N);
2186e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFSUB(SDNode *N);
2196e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFMUL(SDNode *N);
2206e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFMA(SDNode *N);
2216e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFDIV(SDNode *N);
2226e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFREM(SDNode *N);
2236e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFCOPYSIGN(SDNode *N);
2246e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitSINT_TO_FP(SDNode *N);
2256e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitUINT_TO_FP(SDNode *N);
2266e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFP_TO_SINT(SDNode *N);
2276e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFP_TO_UINT(SDNode *N);
2286e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFP_ROUND(SDNode *N);
2296e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFP_ROUND_INREG(SDNode *N);
2306e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFP_EXTEND(SDNode *N);
2316e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFNEG(SDNode *N);
2326e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFABS(SDNode *N);
2336e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFCEIL(SDNode *N);
2346e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFTRUNC(SDNode *N);
2356e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitFFLOOR(SDNode *N);
2366e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitBRCOND(SDNode *N);
2376e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitBR_CC(SDNode *N);
2386e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitLOAD(SDNode *N);
2396e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitSTORE(SDNode *N);
2406e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitINSERT_VECTOR_ELT(SDNode *N);
2416e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
2426e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitBUILD_VECTOR(SDNode *N);
2436e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitCONCAT_VECTORS(SDNode *N);
2446e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
2456e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitVECTOR_SHUFFLE(SDNode *N);
2466e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitMEMBARRIER(SDNode *N);
2476e34636749217654f43221885afb7a29bb5ca96aAdam Powell
2486e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue XformToShuffleWithZero(SDNode *N);
2496e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
2506e34636749217654f43221885afb7a29bb5ca96aAdam Powell
2516e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
2526e34636749217654f43221885afb7a29bb5ca96aAdam Powell
2536e34636749217654f43221885afb7a29bb5ca96aAdam Powell    bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
2546e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
2556e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
2566e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
2576e34636749217654f43221885afb7a29bb5ca96aAdam Powell                             SDValue N3, ISD::CondCode CC,
2586e34636749217654f43221885afb7a29bb5ca96aAdam Powell                             bool NotExtCompare = false);
2596e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
2606e34636749217654f43221885afb7a29bb5ca96aAdam Powell                          DebugLoc DL, bool foldBooleans = true);
2616e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2626e34636749217654f43221885afb7a29bb5ca96aAdam Powell                                         unsigned HiOp);
2636e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
2646e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
2656e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue BuildSDIV(SDNode *N);
2666e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue BuildUDIV(SDNode *N);
2676e34636749217654f43221885afb7a29bb5ca96aAdam Powell    SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
268                               bool DemandHighBits = true);
269    SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
270    SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
271    SDValue ReduceLoadWidth(SDNode *N);
272    SDValue ReduceLoadOpStoreWidth(SDNode *N);
273    SDValue TransformFPLoadStorePair(SDNode *N);
274    SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
275    SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
276
277    SDValue GetDemandedBits(SDValue V, const APInt &Mask);
278
279    /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
280    /// looking for aliasing nodes and adding them to the Aliases vector.
281    void GatherAllAliases(SDNode *N, SDValue OriginalChain,
282                          SmallVector<SDValue, 8> &Aliases);
283
284    /// isAlias - Return true if there is any possibility that the two addresses
285    /// overlap.
286    bool isAlias(SDValue Ptr1, int64_t Size1,
287                 const Value *SrcValue1, int SrcValueOffset1,
288                 unsigned SrcValueAlign1,
289                 const MDNode *TBAAInfo1,
290                 SDValue Ptr2, int64_t Size2,
291                 const Value *SrcValue2, int SrcValueOffset2,
292                 unsigned SrcValueAlign2,
293                 const MDNode *TBAAInfo2) const;
294
295    /// isAlias - Return true if there is any possibility that the two addresses
296    /// overlap.
297    bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
298
299    /// FindAliasInfo - Extracts the relevant alias information from the memory
300    /// node.  Returns true if the operand was a load.
301    bool FindAliasInfo(SDNode *N,
302                       SDValue &Ptr, int64_t &Size,
303                       const Value *&SrcValue, int &SrcValueOffset,
304                       unsigned &SrcValueAlignment,
305                       const MDNode *&TBAAInfo) const;
306
307    /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
308    /// looking for a better chain (aliasing node.)
309    SDValue FindBetterChain(SDNode *N, SDValue Chain);
310
311    /// Merge consecutive store operations into a wide store.
312    /// This optimization uses wide integers or vectors when possible.
313    /// \return True if some memory operations were changed.
314    bool MergeConsecutiveStores(StoreSDNode *N);
315
316  public:
317    DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
318      : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
319        OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
320
321    /// Run - runs the dag combiner on all nodes in the work list
322    void Run(CombineLevel AtLevel);
323
324    SelectionDAG &getDAG() const { return DAG; }
325
326    /// getShiftAmountTy - Returns a type large enough to hold any valid
327    /// shift amount - before type legalization these can be huge.
328    EVT getShiftAmountTy(EVT LHSTy) {
329      return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
330    }
331
332    /// isTypeLegal - This method returns true if we are running before type
333    /// legalization or if the specified VT is legal.
334    bool isTypeLegal(const EVT &VT) {
335      if (!LegalTypes) return true;
336      return TLI.isTypeLegal(VT);
337    }
338  };
339}
340
341
342namespace {
343/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
344/// nodes from the worklist.
345class WorkListRemover : public SelectionDAG::DAGUpdateListener {
346  DAGCombiner &DC;
347public:
348  explicit WorkListRemover(DAGCombiner &dc)
349    : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
350
351  virtual void NodeDeleted(SDNode *N, SDNode *E) {
352    DC.removeFromWorkList(N);
353  }
354};
355}
356
357//===----------------------------------------------------------------------===//
358//  TargetLowering::DAGCombinerInfo implementation
359//===----------------------------------------------------------------------===//
360
361void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
362  ((DAGCombiner*)DC)->AddToWorkList(N);
363}
364
365void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
366  ((DAGCombiner*)DC)->removeFromWorkList(N);
367}
368
369SDValue TargetLowering::DAGCombinerInfo::
370CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
371  return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
372}
373
374SDValue TargetLowering::DAGCombinerInfo::
375CombineTo(SDNode *N, SDValue Res, bool AddTo) {
376  return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
377}
378
379
380SDValue TargetLowering::DAGCombinerInfo::
381CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
382  return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
383}
384
385void TargetLowering::DAGCombinerInfo::
386CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
387  return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
388}
389
390//===----------------------------------------------------------------------===//
391// Helper Functions
392//===----------------------------------------------------------------------===//
393
394/// isNegatibleForFree - Return 1 if we can compute the negated form of the
395/// specified expression for the same cost as the expression itself, or 2 if we
396/// can compute the negated form more cheaply than the expression itself.
397static char isNegatibleForFree(SDValue Op, bool LegalOperations,
398                               const TargetLowering &TLI,
399                               const TargetOptions *Options,
400                               unsigned Depth = 0) {
401  // fneg is removable even if it has multiple uses.
402  if (Op.getOpcode() == ISD::FNEG) return 2;
403
404  // Don't allow anything with multiple uses.
405  if (!Op.hasOneUse()) return 0;
406
407  // Don't recurse exponentially.
408  if (Depth > 6) return 0;
409
410  switch (Op.getOpcode()) {
411  default: return false;
412  case ISD::ConstantFP:
413    // Don't invert constant FP values after legalize.  The negated constant
414    // isn't necessarily legal.
415    return LegalOperations ? 0 : 1;
416  case ISD::FADD:
417    // FIXME: determine better conditions for this xform.
418    if (!Options->UnsafeFPMath) return 0;
419
420    // After operation legalization, it might not be legal to create new FSUBs.
421    if (LegalOperations &&
422        !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
423      return 0;
424
425    // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
426    if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
427                                    Options, Depth + 1))
428      return V;
429    // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
430    return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
431                              Depth + 1);
432  case ISD::FSUB:
433    // We can't turn -(A-B) into B-A when we honor signed zeros.
434    if (!Options->UnsafeFPMath) return 0;
435
436    // fold (fneg (fsub A, B)) -> (fsub B, A)
437    return 1;
438
439  case ISD::FMUL:
440  case ISD::FDIV:
441    if (Options->HonorSignDependentRoundingFPMath()) return 0;
442
443    // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
444    if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
445                                    Options, Depth + 1))
446      return V;
447
448    return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
449                              Depth + 1);
450
451  case ISD::FP_EXTEND:
452  case ISD::FP_ROUND:
453  case ISD::FSIN:
454    return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
455                              Depth + 1);
456  }
457}
458
459/// GetNegatedExpression - If isNegatibleForFree returns true, this function
460/// returns the newly negated expression.
461static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
462                                    bool LegalOperations, unsigned Depth = 0) {
463  // fneg is removable even if it has multiple uses.
464  if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
465
466  // Don't allow anything with multiple uses.
467  assert(Op.hasOneUse() && "Unknown reuse!");
468
469  assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
470  switch (Op.getOpcode()) {
471  default: llvm_unreachable("Unknown code");
472  case ISD::ConstantFP: {
473    APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
474    V.changeSign();
475    return DAG.getConstantFP(V, Op.getValueType());
476  }
477  case ISD::FADD:
478    // FIXME: determine better conditions for this xform.
479    assert(DAG.getTarget().Options.UnsafeFPMath);
480
481    // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
482    if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
483                           DAG.getTargetLoweringInfo(),
484                           &DAG.getTarget().Options, Depth+1))
485      return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
486                         GetNegatedExpression(Op.getOperand(0), DAG,
487                                              LegalOperations, Depth+1),
488                         Op.getOperand(1));
489    // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
490    return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
491                       GetNegatedExpression(Op.getOperand(1), DAG,
492                                            LegalOperations, Depth+1),
493                       Op.getOperand(0));
494  case ISD::FSUB:
495    // We can't turn -(A-B) into B-A when we honor signed zeros.
496    assert(DAG.getTarget().Options.UnsafeFPMath);
497
498    // fold (fneg (fsub 0, B)) -> B
499    if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
500      if (N0CFP->getValueAPF().isZero())
501        return Op.getOperand(1);
502
503    // fold (fneg (fsub A, B)) -> (fsub B, A)
504    return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
505                       Op.getOperand(1), Op.getOperand(0));
506
507  case ISD::FMUL:
508  case ISD::FDIV:
509    assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
510
511    // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
512    if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
513                           DAG.getTargetLoweringInfo(),
514                           &DAG.getTarget().Options, Depth+1))
515      return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
516                         GetNegatedExpression(Op.getOperand(0), DAG,
517                                              LegalOperations, Depth+1),
518                         Op.getOperand(1));
519
520    // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
521    return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
522                       Op.getOperand(0),
523                       GetNegatedExpression(Op.getOperand(1), DAG,
524                                            LegalOperations, Depth+1));
525
526  case ISD::FP_EXTEND:
527  case ISD::FSIN:
528    return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
529                       GetNegatedExpression(Op.getOperand(0), DAG,
530                                            LegalOperations, Depth+1));
531  case ISD::FP_ROUND:
532      return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
533                         GetNegatedExpression(Op.getOperand(0), DAG,
534                                              LegalOperations, Depth+1),
535                         Op.getOperand(1));
536  }
537}
538
539
540// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
541// that selects between the values 1 and 0, making it equivalent to a setcc.
542// Also, set the incoming LHS, RHS, and CC references to the appropriate
543// nodes based on the type of node we are checking.  This simplifies life a
544// bit for the callers.
545static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
546                              SDValue &CC) {
547  if (N.getOpcode() == ISD::SETCC) {
548    LHS = N.getOperand(0);
549    RHS = N.getOperand(1);
550    CC  = N.getOperand(2);
551    return true;
552  }
553  if (N.getOpcode() == ISD::SELECT_CC &&
554      N.getOperand(2).getOpcode() == ISD::Constant &&
555      N.getOperand(3).getOpcode() == ISD::Constant &&
556      cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
557      cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
558    LHS = N.getOperand(0);
559    RHS = N.getOperand(1);
560    CC  = N.getOperand(4);
561    return true;
562  }
563  return false;
564}
565
566// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
567// one use.  If this is true, it allows the users to invert the operation for
568// free when it is profitable to do so.
569static bool isOneUseSetCC(SDValue N) {
570  SDValue N0, N1, N2;
571  if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
572    return true;
573  return false;
574}
575
576SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
577                                    SDValue N0, SDValue N1) {
578  EVT VT = N0.getValueType();
579  if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
580    if (isa<ConstantSDNode>(N1)) {
581      // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
582      SDValue OpNode =
583        DAG.FoldConstantArithmetic(Opc, VT,
584                                   cast<ConstantSDNode>(N0.getOperand(1)),
585                                   cast<ConstantSDNode>(N1));
586      return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
587    }
588    if (N0.hasOneUse()) {
589      // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
590      SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
591                                   N0.getOperand(0), N1);
592      AddToWorkList(OpNode.getNode());
593      return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
594    }
595  }
596
597  if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
598    if (isa<ConstantSDNode>(N0)) {
599      // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
600      SDValue OpNode =
601        DAG.FoldConstantArithmetic(Opc, VT,
602                                   cast<ConstantSDNode>(N1.getOperand(1)),
603                                   cast<ConstantSDNode>(N0));
604      return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
605    }
606    if (N1.hasOneUse()) {
607      // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
608      SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
609                                   N1.getOperand(0), N0);
610      AddToWorkList(OpNode.getNode());
611      return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
612    }
613  }
614
615  return SDValue();
616}
617
618SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
619                               bool AddTo) {
620  assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
621  ++NodesCombined;
622  DEBUG(dbgs() << "\nReplacing.1 ";
623        N->dump(&DAG);
624        dbgs() << "\nWith: ";
625        To[0].getNode()->dump(&DAG);
626        dbgs() << " and " << NumTo-1 << " other values\n";
627        for (unsigned i = 0, e = NumTo; i != e; ++i)
628          assert((!To[i].getNode() ||
629                  N->getValueType(i) == To[i].getValueType()) &&
630                 "Cannot combine value to value of different type!"));
631  WorkListRemover DeadNodes(*this);
632  DAG.ReplaceAllUsesWith(N, To);
633  if (AddTo) {
634    // Push the new nodes and any users onto the worklist
635    for (unsigned i = 0, e = NumTo; i != e; ++i) {
636      if (To[i].getNode()) {
637        AddToWorkList(To[i].getNode());
638        AddUsersToWorkList(To[i].getNode());
639      }
640    }
641  }
642
643  // Finally, if the node is now dead, remove it from the graph.  The node
644  // may not be dead if the replacement process recursively simplified to
645  // something else needing this node.
646  if (N->use_empty()) {
647    // Nodes can be reintroduced into the worklist.  Make sure we do not
648    // process a node that has been replaced.
649    removeFromWorkList(N);
650
651    // Finally, since the node is now dead, remove it from the graph.
652    DAG.DeleteNode(N);
653  }
654  return SDValue(N, 0);
655}
656
657void DAGCombiner::
658CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
659  // Replace all uses.  If any nodes become isomorphic to other nodes and
660  // are deleted, make sure to remove them from our worklist.
661  WorkListRemover DeadNodes(*this);
662  DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
663
664  // Push the new node and any (possibly new) users onto the worklist.
665  AddToWorkList(TLO.New.getNode());
666  AddUsersToWorkList(TLO.New.getNode());
667
668  // Finally, if the node is now dead, remove it from the graph.  The node
669  // may not be dead if the replacement process recursively simplified to
670  // something else needing this node.
671  if (TLO.Old.getNode()->use_empty()) {
672    removeFromWorkList(TLO.Old.getNode());
673
674    // If the operands of this node are only used by the node, they will now
675    // be dead.  Make sure to visit them first to delete dead nodes early.
676    for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
677      if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
678        AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
679
680    DAG.DeleteNode(TLO.Old.getNode());
681  }
682}
683
684/// SimplifyDemandedBits - Check the specified integer node value to see if
685/// it can be simplified or if things it uses can be simplified by bit
686/// propagation.  If so, return true.
687bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
688  TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
689  APInt KnownZero, KnownOne;
690  if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
691    return false;
692
693  // Revisit the node.
694  AddToWorkList(Op.getNode());
695
696  // Replace the old value with the new one.
697  ++NodesCombined;
698  DEBUG(dbgs() << "\nReplacing.2 ";
699        TLO.Old.getNode()->dump(&DAG);
700        dbgs() << "\nWith: ";
701        TLO.New.getNode()->dump(&DAG);
702        dbgs() << '\n');
703
704  CommitTargetLoweringOpt(TLO);
705  return true;
706}
707
708void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
709  DebugLoc dl = Load->getDebugLoc();
710  EVT VT = Load->getValueType(0);
711  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
712
713  DEBUG(dbgs() << "\nReplacing.9 ";
714        Load->dump(&DAG);
715        dbgs() << "\nWith: ";
716        Trunc.getNode()->dump(&DAG);
717        dbgs() << '\n');
718  WorkListRemover DeadNodes(*this);
719  DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
720  DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
721  removeFromWorkList(Load);
722  DAG.DeleteNode(Load);
723  AddToWorkList(Trunc.getNode());
724}
725
726SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
727  Replace = false;
728  DebugLoc dl = Op.getDebugLoc();
729  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
730    EVT MemVT = LD->getMemoryVT();
731    ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
732      ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
733                                                  : ISD::EXTLOAD)
734      : LD->getExtensionType();
735    Replace = true;
736    return DAG.getExtLoad(ExtType, dl, PVT,
737                          LD->getChain(), LD->getBasePtr(),
738                          LD->getPointerInfo(),
739                          MemVT, LD->isVolatile(),
740                          LD->isNonTemporal(), LD->getAlignment());
741  }
742
743  unsigned Opc = Op.getOpcode();
744  switch (Opc) {
745  default: break;
746  case ISD::AssertSext:
747    return DAG.getNode(ISD::AssertSext, dl, PVT,
748                       SExtPromoteOperand(Op.getOperand(0), PVT),
749                       Op.getOperand(1));
750  case ISD::AssertZext:
751    return DAG.getNode(ISD::AssertZext, dl, PVT,
752                       ZExtPromoteOperand(Op.getOperand(0), PVT),
753                       Op.getOperand(1));
754  case ISD::Constant: {
755    unsigned ExtOpc =
756      Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
757    return DAG.getNode(ExtOpc, dl, PVT, Op);
758  }
759  }
760
761  if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
762    return SDValue();
763  return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
764}
765
766SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
767  if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
768    return SDValue();
769  EVT OldVT = Op.getValueType();
770  DebugLoc dl = Op.getDebugLoc();
771  bool Replace = false;
772  SDValue NewOp = PromoteOperand(Op, PVT, Replace);
773  if (NewOp.getNode() == 0)
774    return SDValue();
775  AddToWorkList(NewOp.getNode());
776
777  if (Replace)
778    ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
779  return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
780                     DAG.getValueType(OldVT));
781}
782
783SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
784  EVT OldVT = Op.getValueType();
785  DebugLoc dl = Op.getDebugLoc();
786  bool Replace = false;
787  SDValue NewOp = PromoteOperand(Op, PVT, Replace);
788  if (NewOp.getNode() == 0)
789    return SDValue();
790  AddToWorkList(NewOp.getNode());
791
792  if (Replace)
793    ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
794  return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
795}
796
797/// PromoteIntBinOp - Promote the specified integer binary operation if the
798/// target indicates it is beneficial. e.g. On x86, it's usually better to
799/// promote i16 operations to i32 since i16 instructions are longer.
800SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
801  if (!LegalOperations)
802    return SDValue();
803
804  EVT VT = Op.getValueType();
805  if (VT.isVector() || !VT.isInteger())
806    return SDValue();
807
808  // If operation type is 'undesirable', e.g. i16 on x86, consider
809  // promoting it.
810  unsigned Opc = Op.getOpcode();
811  if (TLI.isTypeDesirableForOp(Opc, VT))
812    return SDValue();
813
814  EVT PVT = VT;
815  // Consult target whether it is a good idea to promote this operation and
816  // what's the right type to promote it to.
817  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
818    assert(PVT != VT && "Don't know what type to promote to!");
819
820    bool Replace0 = false;
821    SDValue N0 = Op.getOperand(0);
822    SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
823    if (NN0.getNode() == 0)
824      return SDValue();
825
826    bool Replace1 = false;
827    SDValue N1 = Op.getOperand(1);
828    SDValue NN1;
829    if (N0 == N1)
830      NN1 = NN0;
831    else {
832      NN1 = PromoteOperand(N1, PVT, Replace1);
833      if (NN1.getNode() == 0)
834        return SDValue();
835    }
836
837    AddToWorkList(NN0.getNode());
838    if (NN1.getNode())
839      AddToWorkList(NN1.getNode());
840
841    if (Replace0)
842      ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
843    if (Replace1)
844      ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
845
846    DEBUG(dbgs() << "\nPromoting ";
847          Op.getNode()->dump(&DAG));
848    DebugLoc dl = Op.getDebugLoc();
849    return DAG.getNode(ISD::TRUNCATE, dl, VT,
850                       DAG.getNode(Opc, dl, PVT, NN0, NN1));
851  }
852  return SDValue();
853}
854
855/// PromoteIntShiftOp - Promote the specified integer shift operation if the
856/// target indicates it is beneficial. e.g. On x86, it's usually better to
857/// promote i16 operations to i32 since i16 instructions are longer.
858SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
859  if (!LegalOperations)
860    return SDValue();
861
862  EVT VT = Op.getValueType();
863  if (VT.isVector() || !VT.isInteger())
864    return SDValue();
865
866  // If operation type is 'undesirable', e.g. i16 on x86, consider
867  // promoting it.
868  unsigned Opc = Op.getOpcode();
869  if (TLI.isTypeDesirableForOp(Opc, VT))
870    return SDValue();
871
872  EVT PVT = VT;
873  // Consult target whether it is a good idea to promote this operation and
874  // what's the right type to promote it to.
875  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
876    assert(PVT != VT && "Don't know what type to promote to!");
877
878    bool Replace = false;
879    SDValue N0 = Op.getOperand(0);
880    if (Opc == ISD::SRA)
881      N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
882    else if (Opc == ISD::SRL)
883      N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
884    else
885      N0 = PromoteOperand(N0, PVT, Replace);
886    if (N0.getNode() == 0)
887      return SDValue();
888
889    AddToWorkList(N0.getNode());
890    if (Replace)
891      ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
892
893    DEBUG(dbgs() << "\nPromoting ";
894          Op.getNode()->dump(&DAG));
895    DebugLoc dl = Op.getDebugLoc();
896    return DAG.getNode(ISD::TRUNCATE, dl, VT,
897                       DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
898  }
899  return SDValue();
900}
901
902SDValue DAGCombiner::PromoteExtend(SDValue Op) {
903  if (!LegalOperations)
904    return SDValue();
905
906  EVT VT = Op.getValueType();
907  if (VT.isVector() || !VT.isInteger())
908    return SDValue();
909
910  // If operation type is 'undesirable', e.g. i16 on x86, consider
911  // promoting it.
912  unsigned Opc = Op.getOpcode();
913  if (TLI.isTypeDesirableForOp(Opc, VT))
914    return SDValue();
915
916  EVT PVT = VT;
917  // Consult target whether it is a good idea to promote this operation and
918  // what's the right type to promote it to.
919  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
920    assert(PVT != VT && "Don't know what type to promote to!");
921    // fold (aext (aext x)) -> (aext x)
922    // fold (aext (zext x)) -> (zext x)
923    // fold (aext (sext x)) -> (sext x)
924    DEBUG(dbgs() << "\nPromoting ";
925          Op.getNode()->dump(&DAG));
926    return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
927  }
928  return SDValue();
929}
930
931bool DAGCombiner::PromoteLoad(SDValue Op) {
932  if (!LegalOperations)
933    return false;
934
935  EVT VT = Op.getValueType();
936  if (VT.isVector() || !VT.isInteger())
937    return false;
938
939  // If operation type is 'undesirable', e.g. i16 on x86, consider
940  // promoting it.
941  unsigned Opc = Op.getOpcode();
942  if (TLI.isTypeDesirableForOp(Opc, VT))
943    return false;
944
945  EVT PVT = VT;
946  // Consult target whether it is a good idea to promote this operation and
947  // what's the right type to promote it to.
948  if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
949    assert(PVT != VT && "Don't know what type to promote to!");
950
951    DebugLoc dl = Op.getDebugLoc();
952    SDNode *N = Op.getNode();
953    LoadSDNode *LD = cast<LoadSDNode>(N);
954    EVT MemVT = LD->getMemoryVT();
955    ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
956      ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
957                                                  : ISD::EXTLOAD)
958      : LD->getExtensionType();
959    SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
960                                   LD->getChain(), LD->getBasePtr(),
961                                   LD->getPointerInfo(),
962                                   MemVT, LD->isVolatile(),
963                                   LD->isNonTemporal(), LD->getAlignment());
964    SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
965
966    DEBUG(dbgs() << "\nPromoting ";
967          N->dump(&DAG);
968          dbgs() << "\nTo: ";
969          Result.getNode()->dump(&DAG);
970          dbgs() << '\n');
971    WorkListRemover DeadNodes(*this);
972    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
973    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
974    removeFromWorkList(N);
975    DAG.DeleteNode(N);
976    AddToWorkList(Result.getNode());
977    return true;
978  }
979  return false;
980}
981
982
983//===----------------------------------------------------------------------===//
984//  Main DAG Combiner implementation
985//===----------------------------------------------------------------------===//
986
987void DAGCombiner::Run(CombineLevel AtLevel) {
988  // set the instance variables, so that the various visit routines may use it.
989  Level = AtLevel;
990  LegalOperations = Level >= AfterLegalizeVectorOps;
991  LegalTypes = Level >= AfterLegalizeTypes;
992
993  // Add all the dag nodes to the worklist.
994  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
995       E = DAG.allnodes_end(); I != E; ++I)
996    AddToWorkList(I);
997
998  // Create a dummy node (which is not added to allnodes), that adds a reference
999  // to the root node, preventing it from being deleted, and tracking any
1000  // changes of the root.
1001  HandleSDNode Dummy(DAG.getRoot());
1002
1003  // The root of the dag may dangle to deleted nodes until the dag combiner is
1004  // done.  Set it to null to avoid confusion.
1005  DAG.setRoot(SDValue());
1006
1007  // while the worklist isn't empty, find a node and
1008  // try and combine it.
1009  while (!WorkListContents.empty()) {
1010    SDNode *N;
1011    // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1012    // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1013    // worklist *should* contain, and check the node we want to visit is should
1014    // actually be visited.
1015    do {
1016      N = WorkListOrder.pop_back_val();
1017    } while (!WorkListContents.erase(N));
1018
1019    // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1020    // N is deleted from the DAG, since they too may now be dead or may have a
1021    // reduced number of uses, allowing other xforms.
1022    if (N->use_empty() && N != &Dummy) {
1023      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1024        AddToWorkList(N->getOperand(i).getNode());
1025
1026      DAG.DeleteNode(N);
1027      continue;
1028    }
1029
1030    SDValue RV = combine(N);
1031
1032    if (RV.getNode() == 0)
1033      continue;
1034
1035    ++NodesCombined;
1036
1037    // If we get back the same node we passed in, rather than a new node or
1038    // zero, we know that the node must have defined multiple values and
1039    // CombineTo was used.  Since CombineTo takes care of the worklist
1040    // mechanics for us, we have no work to do in this case.
1041    if (RV.getNode() == N)
1042      continue;
1043
1044    assert(N->getOpcode() != ISD::DELETED_NODE &&
1045           RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1046           "Node was deleted but visit returned new node!");
1047
1048    DEBUG(dbgs() << "\nReplacing.3 ";
1049          N->dump(&DAG);
1050          dbgs() << "\nWith: ";
1051          RV.getNode()->dump(&DAG);
1052          dbgs() << '\n');
1053
1054    // Transfer debug value.
1055    DAG.TransferDbgValues(SDValue(N, 0), RV);
1056    WorkListRemover DeadNodes(*this);
1057    if (N->getNumValues() == RV.getNode()->getNumValues())
1058      DAG.ReplaceAllUsesWith(N, RV.getNode());
1059    else {
1060      assert(N->getValueType(0) == RV.getValueType() &&
1061             N->getNumValues() == 1 && "Type mismatch");
1062      SDValue OpV = RV;
1063      DAG.ReplaceAllUsesWith(N, &OpV);
1064    }
1065
1066    // Push the new node and any users onto the worklist
1067    AddToWorkList(RV.getNode());
1068    AddUsersToWorkList(RV.getNode());
1069
1070    // Add any uses of the old node to the worklist in case this node is the
1071    // last one that uses them.  They may become dead after this node is
1072    // deleted.
1073    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1074      AddToWorkList(N->getOperand(i).getNode());
1075
1076    // Finally, if the node is now dead, remove it from the graph.  The node
1077    // may not be dead if the replacement process recursively simplified to
1078    // something else needing this node.
1079    if (N->use_empty()) {
1080      // Nodes can be reintroduced into the worklist.  Make sure we do not
1081      // process a node that has been replaced.
1082      removeFromWorkList(N);
1083
1084      // Finally, since the node is now dead, remove it from the graph.
1085      DAG.DeleteNode(N);
1086    }
1087  }
1088
1089  // If the root changed (e.g. it was a dead load, update the root).
1090  DAG.setRoot(Dummy.getValue());
1091  DAG.RemoveDeadNodes();
1092}
1093
1094SDValue DAGCombiner::visit(SDNode *N) {
1095  switch (N->getOpcode()) {
1096  default: break;
1097  case ISD::TokenFactor:        return visitTokenFactor(N);
1098  case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1099  case ISD::ADD:                return visitADD(N);
1100  case ISD::SUB:                return visitSUB(N);
1101  case ISD::ADDC:               return visitADDC(N);
1102  case ISD::SUBC:               return visitSUBC(N);
1103  case ISD::ADDE:               return visitADDE(N);
1104  case ISD::SUBE:               return visitSUBE(N);
1105  case ISD::MUL:                return visitMUL(N);
1106  case ISD::SDIV:               return visitSDIV(N);
1107  case ISD::UDIV:               return visitUDIV(N);
1108  case ISD::SREM:               return visitSREM(N);
1109  case ISD::UREM:               return visitUREM(N);
1110  case ISD::MULHU:              return visitMULHU(N);
1111  case ISD::MULHS:              return visitMULHS(N);
1112  case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1113  case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1114  case ISD::SMULO:              return visitSMULO(N);
1115  case ISD::UMULO:              return visitUMULO(N);
1116  case ISD::SDIVREM:            return visitSDIVREM(N);
1117  case ISD::UDIVREM:            return visitUDIVREM(N);
1118  case ISD::AND:                return visitAND(N);
1119  case ISD::OR:                 return visitOR(N);
1120  case ISD::XOR:                return visitXOR(N);
1121  case ISD::SHL:                return visitSHL(N);
1122  case ISD::SRA:                return visitSRA(N);
1123  case ISD::SRL:                return visitSRL(N);
1124  case ISD::CTLZ:               return visitCTLZ(N);
1125  case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1126  case ISD::CTTZ:               return visitCTTZ(N);
1127  case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1128  case ISD::CTPOP:              return visitCTPOP(N);
1129  case ISD::SELECT:             return visitSELECT(N);
1130  case ISD::SELECT_CC:          return visitSELECT_CC(N);
1131  case ISD::SETCC:              return visitSETCC(N);
1132  case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1133  case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1134  case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1135  case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1136  case ISD::TRUNCATE:           return visitTRUNCATE(N);
1137  case ISD::BITCAST:            return visitBITCAST(N);
1138  case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1139  case ISD::FADD:               return visitFADD(N);
1140  case ISD::FSUB:               return visitFSUB(N);
1141  case ISD::FMUL:               return visitFMUL(N);
1142  case ISD::FMA:                return visitFMA(N);
1143  case ISD::FDIV:               return visitFDIV(N);
1144  case ISD::FREM:               return visitFREM(N);
1145  case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1146  case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1147  case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1148  case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1149  case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1150  case ISD::FP_ROUND:           return visitFP_ROUND(N);
1151  case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1152  case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1153  case ISD::FNEG:               return visitFNEG(N);
1154  case ISD::FABS:               return visitFABS(N);
1155  case ISD::FFLOOR:             return visitFFLOOR(N);
1156  case ISD::FCEIL:              return visitFCEIL(N);
1157  case ISD::FTRUNC:             return visitFTRUNC(N);
1158  case ISD::BRCOND:             return visitBRCOND(N);
1159  case ISD::BR_CC:              return visitBR_CC(N);
1160  case ISD::LOAD:               return visitLOAD(N);
1161  case ISD::STORE:              return visitSTORE(N);
1162  case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1163  case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1164  case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1165  case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1166  case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1167  case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1168  case ISD::MEMBARRIER:         return visitMEMBARRIER(N);
1169  }
1170  return SDValue();
1171}
1172
1173SDValue DAGCombiner::combine(SDNode *N) {
1174  SDValue RV = visit(N);
1175
1176  // If nothing happened, try a target-specific DAG combine.
1177  if (RV.getNode() == 0) {
1178    assert(N->getOpcode() != ISD::DELETED_NODE &&
1179           "Node was deleted but visit returned NULL!");
1180
1181    if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1182        TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1183
1184      // Expose the DAG combiner to the target combiner impls.
1185      TargetLowering::DAGCombinerInfo
1186        DagCombineInfo(DAG, Level, false, this);
1187
1188      RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1189    }
1190  }
1191
1192  // If nothing happened still, try promoting the operation.
1193  if (RV.getNode() == 0) {
1194    switch (N->getOpcode()) {
1195    default: break;
1196    case ISD::ADD:
1197    case ISD::SUB:
1198    case ISD::MUL:
1199    case ISD::AND:
1200    case ISD::OR:
1201    case ISD::XOR:
1202      RV = PromoteIntBinOp(SDValue(N, 0));
1203      break;
1204    case ISD::SHL:
1205    case ISD::SRA:
1206    case ISD::SRL:
1207      RV = PromoteIntShiftOp(SDValue(N, 0));
1208      break;
1209    case ISD::SIGN_EXTEND:
1210    case ISD::ZERO_EXTEND:
1211    case ISD::ANY_EXTEND:
1212      RV = PromoteExtend(SDValue(N, 0));
1213      break;
1214    case ISD::LOAD:
1215      if (PromoteLoad(SDValue(N, 0)))
1216        RV = SDValue(N, 0);
1217      break;
1218    }
1219  }
1220
1221  // If N is a commutative binary node, try commuting it to enable more
1222  // sdisel CSE.
1223  if (RV.getNode() == 0 &&
1224      SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1225      N->getNumValues() == 1) {
1226    SDValue N0 = N->getOperand(0);
1227    SDValue N1 = N->getOperand(1);
1228
1229    // Constant operands are canonicalized to RHS.
1230    if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1231      SDValue Ops[] = { N1, N0 };
1232      SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1233                                            Ops, 2);
1234      if (CSENode)
1235        return SDValue(CSENode, 0);
1236    }
1237  }
1238
1239  return RV;
1240}
1241
1242/// getInputChainForNode - Given a node, return its input chain if it has one,
1243/// otherwise return a null sd operand.
1244static SDValue getInputChainForNode(SDNode *N) {
1245  if (unsigned NumOps = N->getNumOperands()) {
1246    if (N->getOperand(0).getValueType() == MVT::Other)
1247      return N->getOperand(0);
1248    else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1249      return N->getOperand(NumOps-1);
1250    for (unsigned i = 1; i < NumOps-1; ++i)
1251      if (N->getOperand(i).getValueType() == MVT::Other)
1252        return N->getOperand(i);
1253  }
1254  return SDValue();
1255}
1256
1257SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1258  // If N has two operands, where one has an input chain equal to the other,
1259  // the 'other' chain is redundant.
1260  if (N->getNumOperands() == 2) {
1261    if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1262      return N->getOperand(0);
1263    if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1264      return N->getOperand(1);
1265  }
1266
1267  SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1268  SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1269  SmallPtrSet<SDNode*, 16> SeenOps;
1270  bool Changed = false;             // If we should replace this token factor.
1271
1272  // Start out with this token factor.
1273  TFs.push_back(N);
1274
1275  // Iterate through token factors.  The TFs grows when new token factors are
1276  // encountered.
1277  for (unsigned i = 0; i < TFs.size(); ++i) {
1278    SDNode *TF = TFs[i];
1279
1280    // Check each of the operands.
1281    for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1282      SDValue Op = TF->getOperand(i);
1283
1284      switch (Op.getOpcode()) {
1285      case ISD::EntryToken:
1286        // Entry tokens don't need to be added to the list. They are
1287        // rededundant.
1288        Changed = true;
1289        break;
1290
1291      case ISD::TokenFactor:
1292        if (Op.hasOneUse() &&
1293            std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1294          // Queue up for processing.
1295          TFs.push_back(Op.getNode());
1296          // Clean up in case the token factor is removed.
1297          AddToWorkList(Op.getNode());
1298          Changed = true;
1299          break;
1300        }
1301        // Fall thru
1302
1303      default:
1304        // Only add if it isn't already in the list.
1305        if (SeenOps.insert(Op.getNode()))
1306          Ops.push_back(Op);
1307        else
1308          Changed = true;
1309        break;
1310      }
1311    }
1312  }
1313
1314  SDValue Result;
1315
1316  // If we've change things around then replace token factor.
1317  if (Changed) {
1318    if (Ops.empty()) {
1319      // The entry token is the only possible outcome.
1320      Result = DAG.getEntryNode();
1321    } else {
1322      // New and improved token factor.
1323      Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1324                           MVT::Other, &Ops[0], Ops.size());
1325    }
1326
1327    // Don't add users to work list.
1328    return CombineTo(N, Result, false);
1329  }
1330
1331  return Result;
1332}
1333
1334/// MERGE_VALUES can always be eliminated.
1335SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1336  WorkListRemover DeadNodes(*this);
1337  // Replacing results may cause a different MERGE_VALUES to suddenly
1338  // be CSE'd with N, and carry its uses with it. Iterate until no
1339  // uses remain, to ensure that the node can be safely deleted.
1340  // First add the users of this node to the work list so that they
1341  // can be tried again once they have new operands.
1342  AddUsersToWorkList(N);
1343  do {
1344    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1345      DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1346  } while (!N->use_empty());
1347  removeFromWorkList(N);
1348  DAG.DeleteNode(N);
1349  return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1350}
1351
1352static
1353SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1354                              SelectionDAG &DAG) {
1355  EVT VT = N0.getValueType();
1356  SDValue N00 = N0.getOperand(0);
1357  SDValue N01 = N0.getOperand(1);
1358  ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1359
1360  if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1361      isa<ConstantSDNode>(N00.getOperand(1))) {
1362    // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1363    N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1364                     DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1365                                 N00.getOperand(0), N01),
1366                     DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1367                                 N00.getOperand(1), N01));
1368    return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1369  }
1370
1371  return SDValue();
1372}
1373
1374SDValue DAGCombiner::visitADD(SDNode *N) {
1375  SDValue N0 = N->getOperand(0);
1376  SDValue N1 = N->getOperand(1);
1377  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1378  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1379  EVT VT = N0.getValueType();
1380
1381  // fold vector ops
1382  if (VT.isVector()) {
1383    SDValue FoldedVOp = SimplifyVBinOp(N);
1384    if (FoldedVOp.getNode()) return FoldedVOp;
1385
1386    // fold (add x, 0) -> x, vector edition
1387    if (ISD::isBuildVectorAllZeros(N1.getNode()))
1388      return N0;
1389    if (ISD::isBuildVectorAllZeros(N0.getNode()))
1390      return N1;
1391  }
1392
1393  // fold (add x, undef) -> undef
1394  if (N0.getOpcode() == ISD::UNDEF)
1395    return N0;
1396  if (N1.getOpcode() == ISD::UNDEF)
1397    return N1;
1398  // fold (add c1, c2) -> c1+c2
1399  if (N0C && N1C)
1400    return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1401  // canonicalize constant to RHS
1402  if (N0C && !N1C)
1403    return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1404  // fold (add x, 0) -> x
1405  if (N1C && N1C->isNullValue())
1406    return N0;
1407  // fold (add Sym, c) -> Sym+c
1408  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1409    if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1410        GA->getOpcode() == ISD::GlobalAddress)
1411      return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1412                                  GA->getOffset() +
1413                                    (uint64_t)N1C->getSExtValue());
1414  // fold ((c1-A)+c2) -> (c1+c2)-A
1415  if (N1C && N0.getOpcode() == ISD::SUB)
1416    if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1417      return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1418                         DAG.getConstant(N1C->getAPIntValue()+
1419                                         N0C->getAPIntValue(), VT),
1420                         N0.getOperand(1));
1421  // reassociate add
1422  SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1423  if (RADD.getNode() != 0)
1424    return RADD;
1425  // fold ((0-A) + B) -> B-A
1426  if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1427      cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1428    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1429  // fold (A + (0-B)) -> A-B
1430  if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1431      cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1432    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1433  // fold (A+(B-A)) -> B
1434  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1435    return N1.getOperand(0);
1436  // fold ((B-A)+A) -> B
1437  if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1438    return N0.getOperand(0);
1439  // fold (A+(B-(A+C))) to (B-C)
1440  if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1441      N0 == N1.getOperand(1).getOperand(0))
1442    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1443                       N1.getOperand(1).getOperand(1));
1444  // fold (A+(B-(C+A))) to (B-C)
1445  if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1446      N0 == N1.getOperand(1).getOperand(1))
1447    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1448                       N1.getOperand(1).getOperand(0));
1449  // fold (A+((B-A)+or-C)) to (B+or-C)
1450  if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1451      N1.getOperand(0).getOpcode() == ISD::SUB &&
1452      N0 == N1.getOperand(0).getOperand(1))
1453    return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1454                       N1.getOperand(0).getOperand(0), N1.getOperand(1));
1455
1456  // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1457  if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1458    SDValue N00 = N0.getOperand(0);
1459    SDValue N01 = N0.getOperand(1);
1460    SDValue N10 = N1.getOperand(0);
1461    SDValue N11 = N1.getOperand(1);
1462
1463    if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1464      return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1465                         DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1466                         DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1467  }
1468
1469  if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1470    return SDValue(N, 0);
1471
1472  // fold (a+b) -> (a|b) iff a and b share no bits.
1473  if (VT.isInteger() && !VT.isVector()) {
1474    APInt LHSZero, LHSOne;
1475    APInt RHSZero, RHSOne;
1476    DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1477
1478    if (LHSZero.getBoolValue()) {
1479      DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1480
1481      // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1482      // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1483      if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1484        return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1485    }
1486  }
1487
1488  // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1489  if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1490    SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1491    if (Result.getNode()) return Result;
1492  }
1493  if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1494    SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1495    if (Result.getNode()) return Result;
1496  }
1497
1498  // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1499  if (N1.getOpcode() == ISD::SHL &&
1500      N1.getOperand(0).getOpcode() == ISD::SUB)
1501    if (ConstantSDNode *C =
1502          dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1503      if (C->getAPIntValue() == 0)
1504        return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1505                           DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1506                                       N1.getOperand(0).getOperand(1),
1507                                       N1.getOperand(1)));
1508  if (N0.getOpcode() == ISD::SHL &&
1509      N0.getOperand(0).getOpcode() == ISD::SUB)
1510    if (ConstantSDNode *C =
1511          dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1512      if (C->getAPIntValue() == 0)
1513        return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1514                           DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1515                                       N0.getOperand(0).getOperand(1),
1516                                       N0.getOperand(1)));
1517
1518  if (N1.getOpcode() == ISD::AND) {
1519    SDValue AndOp0 = N1.getOperand(0);
1520    ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1521    unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1522    unsigned DestBits = VT.getScalarType().getSizeInBits();
1523
1524    // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1525    // and similar xforms where the inner op is either ~0 or 0.
1526    if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1527      DebugLoc DL = N->getDebugLoc();
1528      return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1529    }
1530  }
1531
1532  // add (sext i1), X -> sub X, (zext i1)
1533  if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1534      N0.getOperand(0).getValueType() == MVT::i1 &&
1535      !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1536    DebugLoc DL = N->getDebugLoc();
1537    SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1538    return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1539  }
1540
1541  return SDValue();
1542}
1543
1544SDValue DAGCombiner::visitADDC(SDNode *N) {
1545  SDValue N0 = N->getOperand(0);
1546  SDValue N1 = N->getOperand(1);
1547  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1548  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1549  EVT VT = N0.getValueType();
1550
1551  // If the flag result is dead, turn this into an ADD.
1552  if (!N->hasAnyUseOfValue(1))
1553    return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1),
1554                     DAG.getNode(ISD::CARRY_FALSE,
1555                                 N->getDebugLoc(), MVT::Glue));
1556
1557  // canonicalize constant to RHS.
1558  if (N0C && !N1C)
1559    return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1560
1561  // fold (addc x, 0) -> x + no carry out
1562  if (N1C && N1C->isNullValue())
1563    return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1564                                        N->getDebugLoc(), MVT::Glue));
1565
1566  // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1567  APInt LHSZero, LHSOne;
1568  APInt RHSZero, RHSOne;
1569  DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1570
1571  if (LHSZero.getBoolValue()) {
1572    DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1573
1574    // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1575    // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1576    if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1577      return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1578                       DAG.getNode(ISD::CARRY_FALSE,
1579                                   N->getDebugLoc(), MVT::Glue));
1580  }
1581
1582  return SDValue();
1583}
1584
1585SDValue DAGCombiner::visitADDE(SDNode *N) {
1586  SDValue N0 = N->getOperand(0);
1587  SDValue N1 = N->getOperand(1);
1588  SDValue CarryIn = N->getOperand(2);
1589  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1590  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1591
1592  // canonicalize constant to RHS
1593  if (N0C && !N1C)
1594    return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1595                       N1, N0, CarryIn);
1596
1597  // fold (adde x, y, false) -> (addc x, y)
1598  if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1599    return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1);
1600
1601  return SDValue();
1602}
1603
1604// Since it may not be valid to emit a fold to zero for vector initializers
1605// check if we can before folding.
1606static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1607                             SelectionDAG &DAG, bool LegalOperations) {
1608  if (!VT.isVector()) {
1609    return DAG.getConstant(0, VT);
1610  }
1611  if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1612    // Produce a vector of zeros.
1613    SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1614    std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1615    return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1616      &Ops[0], Ops.size());
1617  }
1618  return SDValue();
1619}
1620
1621SDValue DAGCombiner::visitSUB(SDNode *N) {
1622  SDValue N0 = N->getOperand(0);
1623  SDValue N1 = N->getOperand(1);
1624  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1625  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1626  ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1627    dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1628  EVT VT = N0.getValueType();
1629
1630  // fold vector ops
1631  if (VT.isVector()) {
1632    SDValue FoldedVOp = SimplifyVBinOp(N);
1633    if (FoldedVOp.getNode()) return FoldedVOp;
1634
1635    // fold (sub x, 0) -> x, vector edition
1636    if (ISD::isBuildVectorAllZeros(N1.getNode()))
1637      return N0;
1638  }
1639
1640  // fold (sub x, x) -> 0
1641  // FIXME: Refactor this and xor and other similar operations together.
1642  if (N0 == N1)
1643    return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1644  // fold (sub c1, c2) -> c1-c2
1645  if (N0C && N1C)
1646    return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1647  // fold (sub x, c) -> (add x, -c)
1648  if (N1C)
1649    return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1650                       DAG.getConstant(-N1C->getAPIntValue(), VT));
1651  // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1652  if (N0C && N0C->isAllOnesValue())
1653    return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1654  // fold A-(A-B) -> B
1655  if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1656    return N1.getOperand(1);
1657  // fold (A+B)-A -> B
1658  if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1659    return N0.getOperand(1);
1660  // fold (A+B)-B -> A
1661  if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1662    return N0.getOperand(0);
1663  // fold C2-(A+C1) -> (C2-C1)-A
1664  if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1665    SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1666                                   VT);
1667    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
1668                       N1.getOperand(0));
1669  }
1670  // fold ((A+(B+or-C))-B) -> A+or-C
1671  if (N0.getOpcode() == ISD::ADD &&
1672      (N0.getOperand(1).getOpcode() == ISD::SUB ||
1673       N0.getOperand(1).getOpcode() == ISD::ADD) &&
1674      N0.getOperand(1).getOperand(0) == N1)
1675    return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1676                       N0.getOperand(0), N0.getOperand(1).getOperand(1));
1677  // fold ((A+(C+B))-B) -> A+C
1678  if (N0.getOpcode() == ISD::ADD &&
1679      N0.getOperand(1).getOpcode() == ISD::ADD &&
1680      N0.getOperand(1).getOperand(1) == N1)
1681    return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1682                       N0.getOperand(0), N0.getOperand(1).getOperand(0));
1683  // fold ((A-(B-C))-C) -> A-B
1684  if (N0.getOpcode() == ISD::SUB &&
1685      N0.getOperand(1).getOpcode() == ISD::SUB &&
1686      N0.getOperand(1).getOperand(1) == N1)
1687    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1688                       N0.getOperand(0), N0.getOperand(1).getOperand(0));
1689
1690  // If either operand of a sub is undef, the result is undef
1691  if (N0.getOpcode() == ISD::UNDEF)
1692    return N0;
1693  if (N1.getOpcode() == ISD::UNDEF)
1694    return N1;
1695
1696  // If the relocation model supports it, consider symbol offsets.
1697  if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1698    if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1699      // fold (sub Sym, c) -> Sym-c
1700      if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1701        return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1702                                    GA->getOffset() -
1703                                      (uint64_t)N1C->getSExtValue());
1704      // fold (sub Sym+c1, Sym+c2) -> c1-c2
1705      if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1706        if (GA->getGlobal() == GB->getGlobal())
1707          return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1708                                 VT);
1709    }
1710
1711  return SDValue();
1712}
1713
1714SDValue DAGCombiner::visitSUBC(SDNode *N) {
1715  SDValue N0 = N->getOperand(0);
1716  SDValue N1 = N->getOperand(1);
1717  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1718  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1719  EVT VT = N0.getValueType();
1720
1721  // If the flag result is dead, turn this into an SUB.
1722  if (!N->hasAnyUseOfValue(1))
1723    return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1),
1724                     DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1725                                 MVT::Glue));
1726
1727  // fold (subc x, x) -> 0 + no borrow
1728  if (N0 == N1)
1729    return CombineTo(N, DAG.getConstant(0, VT),
1730                     DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1731                                 MVT::Glue));
1732
1733  // fold (subc x, 0) -> x + no borrow
1734  if (N1C && N1C->isNullValue())
1735    return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1736                                        MVT::Glue));
1737
1738  // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1739  if (N0C && N0C->isAllOnesValue())
1740    return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0),
1741                     DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1742                                 MVT::Glue));
1743
1744  return SDValue();
1745}
1746
1747SDValue DAGCombiner::visitSUBE(SDNode *N) {
1748  SDValue N0 = N->getOperand(0);
1749  SDValue N1 = N->getOperand(1);
1750  SDValue CarryIn = N->getOperand(2);
1751
1752  // fold (sube x, y, false) -> (subc x, y)
1753  if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1754    return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1);
1755
1756  return SDValue();
1757}
1758
1759SDValue DAGCombiner::visitMUL(SDNode *N) {
1760  SDValue N0 = N->getOperand(0);
1761  SDValue N1 = N->getOperand(1);
1762  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1763  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1764  EVT VT = N0.getValueType();
1765
1766  // fold vector ops
1767  if (VT.isVector()) {
1768    SDValue FoldedVOp = SimplifyVBinOp(N);
1769    if (FoldedVOp.getNode()) return FoldedVOp;
1770  }
1771
1772  // fold (mul x, undef) -> 0
1773  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1774    return DAG.getConstant(0, VT);
1775  // fold (mul c1, c2) -> c1*c2
1776  if (N0C && N1C)
1777    return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1778  // canonicalize constant to RHS
1779  if (N0C && !N1C)
1780    return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1781  // fold (mul x, 0) -> 0
1782  if (N1C && N1C->isNullValue())
1783    return N1;
1784  // fold (mul x, -1) -> 0-x
1785  if (N1C && N1C->isAllOnesValue())
1786    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1787                       DAG.getConstant(0, VT), N0);
1788  // fold (mul x, (1 << c)) -> x << c
1789  if (N1C && N1C->getAPIntValue().isPowerOf2())
1790    return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1791                       DAG.getConstant(N1C->getAPIntValue().logBase2(),
1792                                       getShiftAmountTy(N0.getValueType())));
1793  // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1794  if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1795    unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1796    // FIXME: If the input is something that is easily negated (e.g. a
1797    // single-use add), we should put the negate there.
1798    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1799                       DAG.getConstant(0, VT),
1800                       DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1801                            DAG.getConstant(Log2Val,
1802                                      getShiftAmountTy(N0.getValueType()))));
1803  }
1804  // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1805  if (N1C && N0.getOpcode() == ISD::SHL &&
1806      isa<ConstantSDNode>(N0.getOperand(1))) {
1807    SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1808                             N1, N0.getOperand(1));
1809    AddToWorkList(C3.getNode());
1810    return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1811                       N0.getOperand(0), C3);
1812  }
1813
1814  // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1815  // use.
1816  {
1817    SDValue Sh(0,0), Y(0,0);
1818    // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1819    if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1820        N0.getNode()->hasOneUse()) {
1821      Sh = N0; Y = N1;
1822    } else if (N1.getOpcode() == ISD::SHL &&
1823               isa<ConstantSDNode>(N1.getOperand(1)) &&
1824               N1.getNode()->hasOneUse()) {
1825      Sh = N1; Y = N0;
1826    }
1827
1828    if (Sh.getNode()) {
1829      SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1830                                Sh.getOperand(0), Y);
1831      return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1832                         Mul, Sh.getOperand(1));
1833    }
1834  }
1835
1836  // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1837  if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1838      isa<ConstantSDNode>(N0.getOperand(1)))
1839    return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1840                       DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1841                                   N0.getOperand(0), N1),
1842                       DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1843                                   N0.getOperand(1), N1));
1844
1845  // reassociate mul
1846  SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1847  if (RMUL.getNode() != 0)
1848    return RMUL;
1849
1850  return SDValue();
1851}
1852
1853SDValue DAGCombiner::visitSDIV(SDNode *N) {
1854  SDValue N0 = N->getOperand(0);
1855  SDValue N1 = N->getOperand(1);
1856  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1857  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1858  EVT VT = N->getValueType(0);
1859
1860  // fold vector ops
1861  if (VT.isVector()) {
1862    SDValue FoldedVOp = SimplifyVBinOp(N);
1863    if (FoldedVOp.getNode()) return FoldedVOp;
1864  }
1865
1866  // fold (sdiv c1, c2) -> c1/c2
1867  if (N0C && N1C && !N1C->isNullValue())
1868    return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1869  // fold (sdiv X, 1) -> X
1870  if (N1C && N1C->getAPIntValue() == 1LL)
1871    return N0;
1872  // fold (sdiv X, -1) -> 0-X
1873  if (N1C && N1C->isAllOnesValue())
1874    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1875                       DAG.getConstant(0, VT), N0);
1876  // If we know the sign bits of both operands are zero, strength reduce to a
1877  // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1878  if (!VT.isVector()) {
1879    if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1880      return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1881                         N0, N1);
1882  }
1883  // fold (sdiv X, pow2) -> simple ops after legalize
1884  if (N1C && !N1C->isNullValue() &&
1885      (N1C->getAPIntValue().isPowerOf2() ||
1886       (-N1C->getAPIntValue()).isPowerOf2())) {
1887    // If dividing by powers of two is cheap, then don't perform the following
1888    // fold.
1889    if (TLI.isPow2DivCheap())
1890      return SDValue();
1891
1892    unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1893
1894    // Splat the sign bit into the register
1895    SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1896                              DAG.getConstant(VT.getSizeInBits()-1,
1897                                       getShiftAmountTy(N0.getValueType())));
1898    AddToWorkList(SGN.getNode());
1899
1900    // Add (N0 < 0) ? abs2 - 1 : 0;
1901    SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1902                              DAG.getConstant(VT.getSizeInBits() - lg2,
1903                                       getShiftAmountTy(SGN.getValueType())));
1904    SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1905    AddToWorkList(SRL.getNode());
1906    AddToWorkList(ADD.getNode());    // Divide by pow2
1907    SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1908                  DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1909
1910    // If we're dividing by a positive value, we're done.  Otherwise, we must
1911    // negate the result.
1912    if (N1C->getAPIntValue().isNonNegative())
1913      return SRA;
1914
1915    AddToWorkList(SRA.getNode());
1916    return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1917                       DAG.getConstant(0, VT), SRA);
1918  }
1919
1920  // if integer divide is expensive and we satisfy the requirements, emit an
1921  // alternate sequence.
1922  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1923    SDValue Op = BuildSDIV(N);
1924    if (Op.getNode()) return Op;
1925  }
1926
1927  // undef / X -> 0
1928  if (N0.getOpcode() == ISD::UNDEF)
1929    return DAG.getConstant(0, VT);
1930  // X / undef -> undef
1931  if (N1.getOpcode() == ISD::UNDEF)
1932    return N1;
1933
1934  return SDValue();
1935}
1936
1937SDValue DAGCombiner::visitUDIV(SDNode *N) {
1938  SDValue N0 = N->getOperand(0);
1939  SDValue N1 = N->getOperand(1);
1940  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1941  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1942  EVT VT = N->getValueType(0);
1943
1944  // fold vector ops
1945  if (VT.isVector()) {
1946    SDValue FoldedVOp = SimplifyVBinOp(N);
1947    if (FoldedVOp.getNode()) return FoldedVOp;
1948  }
1949
1950  // fold (udiv c1, c2) -> c1/c2
1951  if (N0C && N1C && !N1C->isNullValue())
1952    return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1953  // fold (udiv x, (1 << c)) -> x >>u c
1954  if (N1C && N1C->getAPIntValue().isPowerOf2())
1955    return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1956                       DAG.getConstant(N1C->getAPIntValue().logBase2(),
1957                                       getShiftAmountTy(N0.getValueType())));
1958  // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1959  if (N1.getOpcode() == ISD::SHL) {
1960    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1961      if (SHC->getAPIntValue().isPowerOf2()) {
1962        EVT ADDVT = N1.getOperand(1).getValueType();
1963        SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1964                                  N1.getOperand(1),
1965                                  DAG.getConstant(SHC->getAPIntValue()
1966                                                                  .logBase2(),
1967                                                  ADDVT));
1968        AddToWorkList(Add.getNode());
1969        return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1970      }
1971    }
1972  }
1973  // fold (udiv x, c) -> alternate
1974  if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1975    SDValue Op = BuildUDIV(N);
1976    if (Op.getNode()) return Op;
1977  }
1978
1979  // undef / X -> 0
1980  if (N0.getOpcode() == ISD::UNDEF)
1981    return DAG.getConstant(0, VT);
1982  // X / undef -> undef
1983  if (N1.getOpcode() == ISD::UNDEF)
1984    return N1;
1985
1986  return SDValue();
1987}
1988
1989SDValue DAGCombiner::visitSREM(SDNode *N) {
1990  SDValue N0 = N->getOperand(0);
1991  SDValue N1 = N->getOperand(1);
1992  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1993  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1994  EVT VT = N->getValueType(0);
1995
1996  // fold (srem c1, c2) -> c1%c2
1997  if (N0C && N1C && !N1C->isNullValue())
1998    return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1999  // If we know the sign bits of both operands are zero, strength reduce to a
2000  // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2001  if (!VT.isVector()) {
2002    if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2003      return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
2004  }
2005
2006  // If X/C can be simplified by the division-by-constant logic, lower
2007  // X%C to the equivalent of X-X/C*C.
2008  if (N1C && !N1C->isNullValue()) {
2009    SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
2010    AddToWorkList(Div.getNode());
2011    SDValue OptimizedDiv = combine(Div.getNode());
2012    if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2013      SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2014                                OptimizedDiv, N1);
2015      SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2016      AddToWorkList(Mul.getNode());
2017      return Sub;
2018    }
2019  }
2020
2021  // undef % X -> 0
2022  if (N0.getOpcode() == ISD::UNDEF)
2023    return DAG.getConstant(0, VT);
2024  // X % undef -> undef
2025  if (N1.getOpcode() == ISD::UNDEF)
2026    return N1;
2027
2028  return SDValue();
2029}
2030
2031SDValue DAGCombiner::visitUREM(SDNode *N) {
2032  SDValue N0 = N->getOperand(0);
2033  SDValue N1 = N->getOperand(1);
2034  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2035  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2036  EVT VT = N->getValueType(0);
2037
2038  // fold (urem c1, c2) -> c1%c2
2039  if (N0C && N1C && !N1C->isNullValue())
2040    return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2041  // fold (urem x, pow2) -> (and x, pow2-1)
2042  if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2043    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
2044                       DAG.getConstant(N1C->getAPIntValue()-1,VT));
2045  // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2046  if (N1.getOpcode() == ISD::SHL) {
2047    if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2048      if (SHC->getAPIntValue().isPowerOf2()) {
2049        SDValue Add =
2050          DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
2051                 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2052                                 VT));
2053        AddToWorkList(Add.getNode());
2054        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
2055      }
2056    }
2057  }
2058
2059  // If X/C can be simplified by the division-by-constant logic, lower
2060  // X%C to the equivalent of X-X/C*C.
2061  if (N1C && !N1C->isNullValue()) {
2062    SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
2063    AddToWorkList(Div.getNode());
2064    SDValue OptimizedDiv = combine(Div.getNode());
2065    if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2066      SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2067                                OptimizedDiv, N1);
2068      SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2069      AddToWorkList(Mul.getNode());
2070      return Sub;
2071    }
2072  }
2073
2074  // undef % X -> 0
2075  if (N0.getOpcode() == ISD::UNDEF)
2076    return DAG.getConstant(0, VT);
2077  // X % undef -> undef
2078  if (N1.getOpcode() == ISD::UNDEF)
2079    return N1;
2080
2081  return SDValue();
2082}
2083
2084SDValue DAGCombiner::visitMULHS(SDNode *N) {
2085  SDValue N0 = N->getOperand(0);
2086  SDValue N1 = N->getOperand(1);
2087  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2088  EVT VT = N->getValueType(0);
2089  DebugLoc DL = N->getDebugLoc();
2090
2091  // fold (mulhs x, 0) -> 0
2092  if (N1C && N1C->isNullValue())
2093    return N1;
2094  // fold (mulhs x, 1) -> (sra x, size(x)-1)
2095  if (N1C && N1C->getAPIntValue() == 1)
2096    return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
2097                       DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2098                                       getShiftAmountTy(N0.getValueType())));
2099  // fold (mulhs x, undef) -> 0
2100  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2101    return DAG.getConstant(0, VT);
2102
2103  // If the type twice as wide is legal, transform the mulhs to a wider multiply
2104  // plus a shift.
2105  if (VT.isSimple() && !VT.isVector()) {
2106    MVT Simple = VT.getSimpleVT();
2107    unsigned SimpleSize = Simple.getSizeInBits();
2108    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2109    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2110      N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2111      N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2112      N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2113      N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2114            DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2115      return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2116    }
2117  }
2118
2119  return SDValue();
2120}
2121
2122SDValue DAGCombiner::visitMULHU(SDNode *N) {
2123  SDValue N0 = N->getOperand(0);
2124  SDValue N1 = N->getOperand(1);
2125  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2126  EVT VT = N->getValueType(0);
2127  DebugLoc DL = N->getDebugLoc();
2128
2129  // fold (mulhu x, 0) -> 0
2130  if (N1C && N1C->isNullValue())
2131    return N1;
2132  // fold (mulhu x, 1) -> 0
2133  if (N1C && N1C->getAPIntValue() == 1)
2134    return DAG.getConstant(0, N0.getValueType());
2135  // fold (mulhu x, undef) -> 0
2136  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2137    return DAG.getConstant(0, VT);
2138
2139  // If the type twice as wide is legal, transform the mulhu to a wider multiply
2140  // plus a shift.
2141  if (VT.isSimple() && !VT.isVector()) {
2142    MVT Simple = VT.getSimpleVT();
2143    unsigned SimpleSize = Simple.getSizeInBits();
2144    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2145    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2146      N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2147      N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2148      N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2149      N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2150            DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2151      return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2152    }
2153  }
2154
2155  return SDValue();
2156}
2157
2158/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2159/// compute two values. LoOp and HiOp give the opcodes for the two computations
2160/// that are being performed. Return true if a simplification was made.
2161///
2162SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2163                                                unsigned HiOp) {
2164  // If the high half is not needed, just compute the low half.
2165  bool HiExists = N->hasAnyUseOfValue(1);
2166  if (!HiExists &&
2167      (!LegalOperations ||
2168       TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2169    SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2170                              N->op_begin(), N->getNumOperands());
2171    return CombineTo(N, Res, Res);
2172  }
2173
2174  // If the low half is not needed, just compute the high half.
2175  bool LoExists = N->hasAnyUseOfValue(0);
2176  if (!LoExists &&
2177      (!LegalOperations ||
2178       TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2179    SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2180                              N->op_begin(), N->getNumOperands());
2181    return CombineTo(N, Res, Res);
2182  }
2183
2184  // If both halves are used, return as it is.
2185  if (LoExists && HiExists)
2186    return SDValue();
2187
2188  // If the two computed results can be simplified separately, separate them.
2189  if (LoExists) {
2190    SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2191                             N->op_begin(), N->getNumOperands());
2192    AddToWorkList(Lo.getNode());
2193    SDValue LoOpt = combine(Lo.getNode());
2194    if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2195        (!LegalOperations ||
2196         TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2197      return CombineTo(N, LoOpt, LoOpt);
2198  }
2199
2200  if (HiExists) {
2201    SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2202                             N->op_begin(), N->getNumOperands());
2203    AddToWorkList(Hi.getNode());
2204    SDValue HiOpt = combine(Hi.getNode());
2205    if (HiOpt.getNode() && HiOpt != Hi &&
2206        (!LegalOperations ||
2207         TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2208      return CombineTo(N, HiOpt, HiOpt);
2209  }
2210
2211  return SDValue();
2212}
2213
2214SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2215  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2216  if (Res.getNode()) return Res;
2217
2218  EVT VT = N->getValueType(0);
2219  DebugLoc DL = N->getDebugLoc();
2220
2221  // If the type twice as wide is legal, transform the mulhu to a wider multiply
2222  // plus a shift.
2223  if (VT.isSimple() && !VT.isVector()) {
2224    MVT Simple = VT.getSimpleVT();
2225    unsigned SimpleSize = Simple.getSizeInBits();
2226    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2227    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2228      SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2229      SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2230      Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2231      // Compute the high part as N1.
2232      Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2233            DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2234      Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2235      // Compute the low part as N0.
2236      Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2237      return CombineTo(N, Lo, Hi);
2238    }
2239  }
2240
2241  return SDValue();
2242}
2243
2244SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2245  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2246  if (Res.getNode()) return Res;
2247
2248  EVT VT = N->getValueType(0);
2249  DebugLoc DL = N->getDebugLoc();
2250
2251  // If the type twice as wide is legal, transform the mulhu to a wider multiply
2252  // plus a shift.
2253  if (VT.isSimple() && !VT.isVector()) {
2254    MVT Simple = VT.getSimpleVT();
2255    unsigned SimpleSize = Simple.getSizeInBits();
2256    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2257    if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2258      SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2259      SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2260      Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2261      // Compute the high part as N1.
2262      Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2263            DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2264      Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2265      // Compute the low part as N0.
2266      Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2267      return CombineTo(N, Lo, Hi);
2268    }
2269  }
2270
2271  return SDValue();
2272}
2273
2274SDValue DAGCombiner::visitSMULO(SDNode *N) {
2275  // (smulo x, 2) -> (saddo x, x)
2276  if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2277    if (C2->getAPIntValue() == 2)
2278      return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2279                         N->getOperand(0), N->getOperand(0));
2280
2281  return SDValue();
2282}
2283
2284SDValue DAGCombiner::visitUMULO(SDNode *N) {
2285  // (umulo x, 2) -> (uaddo x, x)
2286  if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2287    if (C2->getAPIntValue() == 2)
2288      return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2289                         N->getOperand(0), N->getOperand(0));
2290
2291  return SDValue();
2292}
2293
2294SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2295  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2296  if (Res.getNode()) return Res;
2297
2298  return SDValue();
2299}
2300
2301SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2302  SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2303  if (Res.getNode()) return Res;
2304
2305  return SDValue();
2306}
2307
2308/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2309/// two operands of the same opcode, try to simplify it.
2310SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2311  SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2312  EVT VT = N0.getValueType();
2313  assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2314
2315  // Bail early if none of these transforms apply.
2316  if (N0.getNode()->getNumOperands() == 0) return SDValue();
2317
2318  // For each of OP in AND/OR/XOR:
2319  // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2320  // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2321  // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2322  // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2323  //
2324  // do not sink logical op inside of a vector extend, since it may combine
2325  // into a vsetcc.
2326  EVT Op0VT = N0.getOperand(0).getValueType();
2327  if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2328       N0.getOpcode() == ISD::SIGN_EXTEND ||
2329       // Avoid infinite looping with PromoteIntBinOp.
2330       (N0.getOpcode() == ISD::ANY_EXTEND &&
2331        (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2332       (N0.getOpcode() == ISD::TRUNCATE &&
2333        (!TLI.isZExtFree(VT, Op0VT) ||
2334         !TLI.isTruncateFree(Op0VT, VT)) &&
2335        TLI.isTypeLegal(Op0VT))) &&
2336      !VT.isVector() &&
2337      Op0VT == N1.getOperand(0).getValueType() &&
2338      (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2339    SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2340                                 N0.getOperand(0).getValueType(),
2341                                 N0.getOperand(0), N1.getOperand(0));
2342    AddToWorkList(ORNode.getNode());
2343    return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2344  }
2345
2346  // For each of OP in SHL/SRL/SRA/AND...
2347  //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2348  //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2349  //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2350  if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2351       N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2352      N0.getOperand(1) == N1.getOperand(1)) {
2353    SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2354                                 N0.getOperand(0).getValueType(),
2355                                 N0.getOperand(0), N1.getOperand(0));
2356    AddToWorkList(ORNode.getNode());
2357    return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2358                       ORNode, N0.getOperand(1));
2359  }
2360
2361  // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2362  // Only perform this optimization after type legalization and before
2363  // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2364  // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2365  // we don't want to undo this promotion.
2366  // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2367  // on scalars.
2368  if ((N0.getOpcode() == ISD::BITCAST ||
2369       N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2370      Level == AfterLegalizeTypes) {
2371    SDValue In0 = N0.getOperand(0);
2372    SDValue In1 = N1.getOperand(0);
2373    EVT In0Ty = In0.getValueType();
2374    EVT In1Ty = In1.getValueType();
2375    DebugLoc DL = N->getDebugLoc();
2376    // If both incoming values are integers, and the original types are the
2377    // same.
2378    if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2379      SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2380      SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2381      AddToWorkList(Op.getNode());
2382      return BC;
2383    }
2384  }
2385
2386  // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2387  // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2388  // If both shuffles use the same mask, and both shuffle within a single
2389  // vector, then it is worthwhile to move the swizzle after the operation.
2390  // The type-legalizer generates this pattern when loading illegal
2391  // vector types from memory. In many cases this allows additional shuffle
2392  // optimizations.
2393  if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2394      N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2395      N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2396    ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2397    ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2398
2399    assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2400           "Inputs to shuffles are not the same type");
2401
2402    unsigned NumElts = VT.getVectorNumElements();
2403
2404    // Check that both shuffles use the same mask. The masks are known to be of
2405    // the same length because the result vector type is the same.
2406    bool SameMask = true;
2407    for (unsigned i = 0; i != NumElts; ++i) {
2408      int Idx0 = SVN0->getMaskElt(i);
2409      int Idx1 = SVN1->getMaskElt(i);
2410      if (Idx0 != Idx1) {
2411        SameMask = false;
2412        break;
2413      }
2414    }
2415
2416    if (SameMask) {
2417      SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
2418                               N0.getOperand(0), N1.getOperand(0));
2419      AddToWorkList(Op.getNode());
2420      return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op,
2421                                  DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2422    }
2423  }
2424
2425  return SDValue();
2426}
2427
2428SDValue DAGCombiner::visitAND(SDNode *N) {
2429  SDValue N0 = N->getOperand(0);
2430  SDValue N1 = N->getOperand(1);
2431  SDValue LL, LR, RL, RR, CC0, CC1;
2432  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2433  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2434  EVT VT = N1.getValueType();
2435  unsigned BitWidth = VT.getScalarType().getSizeInBits();
2436
2437  // fold vector ops
2438  if (VT.isVector()) {
2439    SDValue FoldedVOp = SimplifyVBinOp(N);
2440    if (FoldedVOp.getNode()) return FoldedVOp;
2441
2442    // fold (and x, 0) -> 0, vector edition
2443    if (ISD::isBuildVectorAllZeros(N0.getNode()))
2444      return N0;
2445    if (ISD::isBuildVectorAllZeros(N1.getNode()))
2446      return N1;
2447
2448    // fold (and x, -1) -> x, vector edition
2449    if (ISD::isBuildVectorAllOnes(N0.getNode()))
2450      return N1;
2451    if (ISD::isBuildVectorAllOnes(N1.getNode()))
2452      return N0;
2453  }
2454
2455  // fold (and x, undef) -> 0
2456  if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2457    return DAG.getConstant(0, VT);
2458  // fold (and c1, c2) -> c1&c2
2459  if (N0C && N1C)
2460    return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2461  // canonicalize constant to RHS
2462  if (N0C && !N1C)
2463    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2464  // fold (and x, -1) -> x
2465  if (N1C && N1C->isAllOnesValue())
2466    return N0;
2467  // if (and x, c) is known to be zero, return 0
2468  if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2469                                   APInt::getAllOnesValue(BitWidth)))
2470    return DAG.getConstant(0, VT);
2471  // reassociate and
2472  SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2473  if (RAND.getNode() != 0)
2474    return RAND;
2475  // fold (and (or x, C), D) -> D if (C & D) == D
2476  if (N1C && N0.getOpcode() == ISD::OR)
2477    if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2478      if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2479        return N1;
2480  // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2481  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2482    SDValue N0Op0 = N0.getOperand(0);
2483    APInt Mask = ~N1C->getAPIntValue();
2484    Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2485    if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2486      SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2487                                 N0.getValueType(), N0Op0);
2488
2489      // Replace uses of the AND with uses of the Zero extend node.
2490      CombineTo(N, Zext);
2491
2492      // We actually want to replace all uses of the any_extend with the
2493      // zero_extend, to avoid duplicating things.  This will later cause this
2494      // AND to be folded.
2495      CombineTo(N0.getNode(), Zext);
2496      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2497    }
2498  }
2499  // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2500  // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2501  // already be zero by virtue of the width of the base type of the load.
2502  //
2503  // the 'X' node here can either be nothing or an extract_vector_elt to catch
2504  // more cases.
2505  if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2506       N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2507      N0.getOpcode() == ISD::LOAD) {
2508    LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2509                                         N0 : N0.getOperand(0) );
2510
2511    // Get the constant (if applicable) the zero'th operand is being ANDed with.
2512    // This can be a pure constant or a vector splat, in which case we treat the
2513    // vector as a scalar and use the splat value.
2514    APInt Constant = APInt::getNullValue(1);
2515    if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2516      Constant = C->getAPIntValue();
2517    } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2518      APInt SplatValue, SplatUndef;
2519      unsigned SplatBitSize;
2520      bool HasAnyUndefs;
2521      bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2522                                             SplatBitSize, HasAnyUndefs);
2523      if (IsSplat) {
2524        // Undef bits can contribute to a possible optimisation if set, so
2525        // set them.
2526        SplatValue |= SplatUndef;
2527
2528        // The splat value may be something like "0x00FFFFFF", which means 0 for
2529        // the first vector value and FF for the rest, repeating. We need a mask
2530        // that will apply equally to all members of the vector, so AND all the
2531        // lanes of the constant together.
2532        EVT VT = Vector->getValueType(0);
2533        unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2534
2535        // If the splat value has been compressed to a bitlength lower
2536        // than the size of the vector lane, we need to re-expand it to
2537        // the lane size.
2538        if (BitWidth > SplatBitSize)
2539          for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2540               SplatBitSize < BitWidth;
2541               SplatBitSize = SplatBitSize * 2)
2542            SplatValue |= SplatValue.shl(SplatBitSize);
2543
2544        Constant = APInt::getAllOnesValue(BitWidth);
2545        for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2546          Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2547      }
2548    }
2549
2550    // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2551    // actually legal and isn't going to get expanded, else this is a false
2552    // optimisation.
2553    bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2554                                                    Load->getMemoryVT());
2555
2556    // Resize the constant to the same size as the original memory access before
2557    // extension. If it is still the AllOnesValue then this AND is completely
2558    // unneeded.
2559    Constant =
2560      Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2561
2562    bool B;
2563    switch (Load->getExtensionType()) {
2564    default: B = false; break;
2565    case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2566    case ISD::ZEXTLOAD:
2567    case ISD::NON_EXTLOAD: B = true; break;
2568    }
2569
2570    if (B && Constant.isAllOnesValue()) {
2571      // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2572      // preserve semantics once we get rid of the AND.
2573      SDValue NewLoad(Load, 0);
2574      if (Load->getExtensionType() == ISD::EXTLOAD) {
2575        NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2576                              Load->getValueType(0), Load->getDebugLoc(),
2577                              Load->getChain(), Load->getBasePtr(),
2578                              Load->getOffset(), Load->getMemoryVT(),
2579                              Load->getMemOperand());
2580        // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2581        if (Load->getNumValues() == 3) {
2582          // PRE/POST_INC loads have 3 values.
2583          SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2584                           NewLoad.getValue(2) };
2585          CombineTo(Load, To, 3, true);
2586        } else {
2587          CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2588        }
2589      }
2590
2591      // Fold the AND away, taking care not to fold to the old load node if we
2592      // replaced it.
2593      CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2594
2595      return SDValue(N, 0); // Return N so it doesn't get rechecked!
2596    }
2597  }
2598  // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2599  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2600    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2601    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2602
2603    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2604        LL.getValueType().isInteger()) {
2605      // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2606      if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2607        SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2608                                     LR.getValueType(), LL, RL);
2609        AddToWorkList(ORNode.getNode());
2610        return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2611      }
2612      // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2613      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2614        SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2615                                      LR.getValueType(), LL, RL);
2616        AddToWorkList(ANDNode.getNode());
2617        return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2618      }
2619      // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2620      if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2621        SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2622                                     LR.getValueType(), LL, RL);
2623        AddToWorkList(ORNode.getNode());
2624        return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2625      }
2626    }
2627    // canonicalize equivalent to ll == rl
2628    if (LL == RR && LR == RL) {
2629      Op1 = ISD::getSetCCSwappedOperands(Op1);
2630      std::swap(RL, RR);
2631    }
2632    if (LL == RL && LR == RR) {
2633      bool isInteger = LL.getValueType().isInteger();
2634      ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2635      if (Result != ISD::SETCC_INVALID &&
2636          (!LegalOperations ||
2637           TLI.isCondCodeLegal(Result, LL.getSimpleValueType())))
2638        return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2639                            LL, LR, Result);
2640    }
2641  }
2642
2643  // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2644  if (N0.getOpcode() == N1.getOpcode()) {
2645    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2646    if (Tmp.getNode()) return Tmp;
2647  }
2648
2649  // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2650  // fold (and (sra)) -> (and (srl)) when possible.
2651  if (!VT.isVector() &&
2652      SimplifyDemandedBits(SDValue(N, 0)))
2653    return SDValue(N, 0);
2654
2655  // fold (zext_inreg (extload x)) -> (zextload x)
2656  if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2657    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2658    EVT MemVT = LN0->getMemoryVT();
2659    // If we zero all the possible extended bits, then we can turn this into
2660    // a zextload if we are running before legalize or the operation is legal.
2661    unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2662    if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2663                           BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2664        ((!LegalOperations && !LN0->isVolatile()) ||
2665         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2666      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2667                                       LN0->getChain(), LN0->getBasePtr(),
2668                                       LN0->getPointerInfo(), MemVT,
2669                                       LN0->isVolatile(), LN0->isNonTemporal(),
2670                                       LN0->getAlignment());
2671      AddToWorkList(N);
2672      CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2673      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2674    }
2675  }
2676  // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2677  if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2678      N0.hasOneUse()) {
2679    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2680    EVT MemVT = LN0->getMemoryVT();
2681    // If we zero all the possible extended bits, then we can turn this into
2682    // a zextload if we are running before legalize or the operation is legal.
2683    unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2684    if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2685                           BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2686        ((!LegalOperations && !LN0->isVolatile()) ||
2687         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2688      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2689                                       LN0->getChain(),
2690                                       LN0->getBasePtr(), LN0->getPointerInfo(),
2691                                       MemVT,
2692                                       LN0->isVolatile(), LN0->isNonTemporal(),
2693                                       LN0->getAlignment());
2694      AddToWorkList(N);
2695      CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2696      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2697    }
2698  }
2699
2700  // fold (and (load x), 255) -> (zextload x, i8)
2701  // fold (and (extload x, i16), 255) -> (zextload x, i8)
2702  // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2703  if (N1C && (N0.getOpcode() == ISD::LOAD ||
2704              (N0.getOpcode() == ISD::ANY_EXTEND &&
2705               N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2706    bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2707    LoadSDNode *LN0 = HasAnyExt
2708      ? cast<LoadSDNode>(N0.getOperand(0))
2709      : cast<LoadSDNode>(N0);
2710    if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2711        LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2712      uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2713      if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2714        EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2715        EVT LoadedVT = LN0->getMemoryVT();
2716
2717        if (ExtVT == LoadedVT &&
2718            (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2719          EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2720
2721          SDValue NewLoad =
2722            DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2723                           LN0->getChain(), LN0->getBasePtr(),
2724                           LN0->getPointerInfo(),
2725                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2726                           LN0->getAlignment());
2727          AddToWorkList(N);
2728          CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2729          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2730        }
2731
2732        // Do not change the width of a volatile load.
2733        // Do not generate loads of non-round integer types since these can
2734        // be expensive (and would be wrong if the type is not byte sized).
2735        if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2736            (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2737          EVT PtrType = LN0->getOperand(1).getValueType();
2738
2739          unsigned Alignment = LN0->getAlignment();
2740          SDValue NewPtr = LN0->getBasePtr();
2741
2742          // For big endian targets, we need to add an offset to the pointer
2743          // to load the correct bytes.  For little endian systems, we merely
2744          // need to read fewer bytes from the same pointer.
2745          if (TLI.isBigEndian()) {
2746            unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2747            unsigned EVTStoreBytes = ExtVT.getStoreSize();
2748            unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2749            NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2750                                 NewPtr, DAG.getConstant(PtrOff, PtrType));
2751            Alignment = MinAlign(Alignment, PtrOff);
2752          }
2753
2754          AddToWorkList(NewPtr.getNode());
2755
2756          EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2757          SDValue Load =
2758            DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2759                           LN0->getChain(), NewPtr,
2760                           LN0->getPointerInfo(),
2761                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2762                           Alignment);
2763          AddToWorkList(N);
2764          CombineTo(LN0, Load, Load.getValue(1));
2765          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2766        }
2767      }
2768    }
2769  }
2770
2771  if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2772      VT.getSizeInBits() <= 64) {
2773    if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2774      APInt ADDC = ADDI->getAPIntValue();
2775      if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2776        // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2777        // immediate for an add, but it is legal if its top c2 bits are set,
2778        // transform the ADD so the immediate doesn't need to be materialized
2779        // in a register.
2780        if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2781          APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2782                                             SRLI->getZExtValue());
2783          if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2784            ADDC |= Mask;
2785            if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2786              SDValue NewAdd =
2787                DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
2788                            N0.getOperand(0), DAG.getConstant(ADDC, VT));
2789              CombineTo(N0.getNode(), NewAdd);
2790              return SDValue(N, 0); // Return N so it doesn't get rechecked!
2791            }
2792          }
2793        }
2794      }
2795    }
2796  }
2797
2798  return SDValue();
2799}
2800
2801/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2802///
2803SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2804                                        bool DemandHighBits) {
2805  if (!LegalOperations)
2806    return SDValue();
2807
2808  EVT VT = N->getValueType(0);
2809  if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2810    return SDValue();
2811  if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2812    return SDValue();
2813
2814  // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2815  bool LookPassAnd0 = false;
2816  bool LookPassAnd1 = false;
2817  if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2818      std::swap(N0, N1);
2819  if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2820      std::swap(N0, N1);
2821  if (N0.getOpcode() == ISD::AND) {
2822    if (!N0.getNode()->hasOneUse())
2823      return SDValue();
2824    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2825    if (!N01C || N01C->getZExtValue() != 0xFF00)
2826      return SDValue();
2827    N0 = N0.getOperand(0);
2828    LookPassAnd0 = true;
2829  }
2830
2831  if (N1.getOpcode() == ISD::AND) {
2832    if (!N1.getNode()->hasOneUse())
2833      return SDValue();
2834    ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2835    if (!N11C || N11C->getZExtValue() != 0xFF)
2836      return SDValue();
2837    N1 = N1.getOperand(0);
2838    LookPassAnd1 = true;
2839  }
2840
2841  if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2842    std::swap(N0, N1);
2843  if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2844    return SDValue();
2845  if (!N0.getNode()->hasOneUse() ||
2846      !N1.getNode()->hasOneUse())
2847    return SDValue();
2848
2849  ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2850  ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2851  if (!N01C || !N11C)
2852    return SDValue();
2853  if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2854    return SDValue();
2855
2856  // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2857  SDValue N00 = N0->getOperand(0);
2858  if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2859    if (!N00.getNode()->hasOneUse())
2860      return SDValue();
2861    ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2862    if (!N001C || N001C->getZExtValue() != 0xFF)
2863      return SDValue();
2864    N00 = N00.getOperand(0);
2865    LookPassAnd0 = true;
2866  }
2867
2868  SDValue N10 = N1->getOperand(0);
2869  if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2870    if (!N10.getNode()->hasOneUse())
2871      return SDValue();
2872    ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2873    if (!N101C || N101C->getZExtValue() != 0xFF00)
2874      return SDValue();
2875    N10 = N10.getOperand(0);
2876    LookPassAnd1 = true;
2877  }
2878
2879  if (N00 != N10)
2880    return SDValue();
2881
2882  // Make sure everything beyond the low halfword is zero since the SRL 16
2883  // will clear the top bits.
2884  unsigned OpSizeInBits = VT.getSizeInBits();
2885  if (DemandHighBits && OpSizeInBits > 16 &&
2886      (!LookPassAnd0 || !LookPassAnd1) &&
2887      !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2888    return SDValue();
2889
2890  SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
2891  if (OpSizeInBits > 16)
2892    Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
2893                      DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2894  return Res;
2895}
2896
2897/// isBSwapHWordElement - Return true if the specified node is an element
2898/// that makes up a 32-bit packed halfword byteswap. i.e.
2899/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2900static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2901  if (!N.getNode()->hasOneUse())
2902    return false;
2903
2904  unsigned Opc = N.getOpcode();
2905  if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2906    return false;
2907
2908  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2909  if (!N1C)
2910    return false;
2911
2912  unsigned Num;
2913  switch (N1C->getZExtValue()) {
2914  default:
2915    return false;
2916  case 0xFF:       Num = 0; break;
2917  case 0xFF00:     Num = 1; break;
2918  case 0xFF0000:   Num = 2; break;
2919  case 0xFF000000: Num = 3; break;
2920  }
2921
2922  // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2923  SDValue N0 = N.getOperand(0);
2924  if (Opc == ISD::AND) {
2925    if (Num == 0 || Num == 2) {
2926      // (x >> 8) & 0xff
2927      // (x >> 8) & 0xff0000
2928      if (N0.getOpcode() != ISD::SRL)
2929        return false;
2930      ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2931      if (!C || C->getZExtValue() != 8)
2932        return false;
2933    } else {
2934      // (x << 8) & 0xff00
2935      // (x << 8) & 0xff000000
2936      if (N0.getOpcode() != ISD::SHL)
2937        return false;
2938      ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2939      if (!C || C->getZExtValue() != 8)
2940        return false;
2941    }
2942  } else if (Opc == ISD::SHL) {
2943    // (x & 0xff) << 8
2944    // (x & 0xff0000) << 8
2945    if (Num != 0 && Num != 2)
2946      return false;
2947    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2948    if (!C || C->getZExtValue() != 8)
2949      return false;
2950  } else { // Opc == ISD::SRL
2951    // (x & 0xff00) >> 8
2952    // (x & 0xff000000) >> 8
2953    if (Num != 1 && Num != 3)
2954      return false;
2955    ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2956    if (!C || C->getZExtValue() != 8)
2957      return false;
2958  }
2959
2960  if (Parts[Num])
2961    return false;
2962
2963  Parts[Num] = N0.getOperand(0).getNode();
2964  return true;
2965}
2966
2967/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2968/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2969/// => (rotl (bswap x), 16)
2970SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2971  if (!LegalOperations)
2972    return SDValue();
2973
2974  EVT VT = N->getValueType(0);
2975  if (VT != MVT::i32)
2976    return SDValue();
2977  if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2978    return SDValue();
2979
2980  SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2981  // Look for either
2982  // (or (or (and), (and)), (or (and), (and)))
2983  // (or (or (or (and), (and)), (and)), (and))
2984  if (N0.getOpcode() != ISD::OR)
2985    return SDValue();
2986  SDValue N00 = N0.getOperand(0);
2987  SDValue N01 = N0.getOperand(1);
2988
2989  if (N1.getOpcode() == ISD::OR &&
2990      N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
2991    // (or (or (and), (and)), (or (and), (and)))
2992    SDValue N000 = N00.getOperand(0);
2993    if (!isBSwapHWordElement(N000, Parts))
2994      return SDValue();
2995
2996    SDValue N001 = N00.getOperand(1);
2997    if (!isBSwapHWordElement(N001, Parts))
2998      return SDValue();
2999    SDValue N010 = N01.getOperand(0);
3000    if (!isBSwapHWordElement(N010, Parts))
3001      return SDValue();
3002    SDValue N011 = N01.getOperand(1);
3003    if (!isBSwapHWordElement(N011, Parts))
3004      return SDValue();
3005  } else {
3006    // (or (or (or (and), (and)), (and)), (and))
3007    if (!isBSwapHWordElement(N1, Parts))
3008      return SDValue();
3009    if (!isBSwapHWordElement(N01, Parts))
3010      return SDValue();
3011    if (N00.getOpcode() != ISD::OR)
3012      return SDValue();
3013    SDValue N000 = N00.getOperand(0);
3014    if (!isBSwapHWordElement(N000, Parts))
3015      return SDValue();
3016    SDValue N001 = N00.getOperand(1);
3017    if (!isBSwapHWordElement(N001, Parts))
3018      return SDValue();
3019  }
3020
3021  // Make sure the parts are all coming from the same node.
3022  if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3023    return SDValue();
3024
3025  SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
3026                              SDValue(Parts[0],0));
3027
3028  // Result of the bswap should be rotated by 16. If it's not legal, than
3029  // do  (x << 16) | (x >> 16).
3030  SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3031  if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3032    return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
3033  if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3034    return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
3035  return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
3036                     DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
3037                     DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
3038}
3039
3040SDValue DAGCombiner::visitOR(SDNode *N) {
3041  SDValue N0 = N->getOperand(0);
3042  SDValue N1 = N->getOperand(1);
3043  SDValue LL, LR, RL, RR, CC0, CC1;
3044  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3045  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3046  EVT VT = N1.getValueType();
3047
3048  // fold vector ops
3049  if (VT.isVector()) {
3050    SDValue FoldedVOp = SimplifyVBinOp(N);
3051    if (FoldedVOp.getNode()) return FoldedVOp;
3052
3053    // fold (or x, 0) -> x, vector edition
3054    if (ISD::isBuildVectorAllZeros(N0.getNode()))
3055      return N1;
3056    if (ISD::isBuildVectorAllZeros(N1.getNode()))
3057      return N0;
3058
3059    // fold (or x, -1) -> -1, vector edition
3060    if (ISD::isBuildVectorAllOnes(N0.getNode()))
3061      return N0;
3062    if (ISD::isBuildVectorAllOnes(N1.getNode()))
3063      return N1;
3064  }
3065
3066  // fold (or x, undef) -> -1
3067  if (!LegalOperations &&
3068      (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3069    EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3070    return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3071  }
3072  // fold (or c1, c2) -> c1|c2
3073  if (N0C && N1C)
3074    return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3075  // canonicalize constant to RHS
3076  if (N0C && !N1C)
3077    return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
3078  // fold (or x, 0) -> x
3079  if (N1C && N1C->isNullValue())
3080    return N0;
3081  // fold (or x, -1) -> -1
3082  if (N1C && N1C->isAllOnesValue())
3083    return N1;
3084  // fold (or x, c) -> c iff (x & ~c) == 0
3085  if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3086    return N1;
3087
3088  // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3089  SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3090  if (BSwap.getNode() != 0)
3091    return BSwap;
3092  BSwap = MatchBSwapHWordLow(N, N0, N1);
3093  if (BSwap.getNode() != 0)
3094    return BSwap;
3095
3096  // reassociate or
3097  SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
3098  if (ROR.getNode() != 0)
3099    return ROR;
3100  // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3101  // iff (c1 & c2) == 0.
3102  if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3103             isa<ConstantSDNode>(N0.getOperand(1))) {
3104    ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3105    if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3106      return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3107                         DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3108                                     N0.getOperand(0), N1),
3109                         DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3110  }
3111  // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3112  if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3113    ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3114    ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3115
3116    if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3117        LL.getValueType().isInteger()) {
3118      // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3119      // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3120      if (cast<ConstantSDNode>(LR)->isNullValue() &&
3121          (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3122        SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
3123                                     LR.getValueType(), LL, RL);
3124        AddToWorkList(ORNode.getNode());
3125        return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
3126      }
3127      // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3128      // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3129      if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3130          (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3131        SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
3132                                      LR.getValueType(), LL, RL);
3133        AddToWorkList(ANDNode.getNode());
3134        return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
3135      }
3136    }
3137    // canonicalize equivalent to ll == rl
3138    if (LL == RR && LR == RL) {
3139      Op1 = ISD::getSetCCSwappedOperands(Op1);
3140      std::swap(RL, RR);
3141    }
3142    if (LL == RL && LR == RR) {
3143      bool isInteger = LL.getValueType().isInteger();
3144      ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3145      if (Result != ISD::SETCC_INVALID &&
3146          (!LegalOperations ||
3147           TLI.isCondCodeLegal(Result, LL.getSimpleValueType())))
3148        return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
3149                            LL, LR, Result);
3150    }
3151  }
3152
3153  // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3154  if (N0.getOpcode() == N1.getOpcode()) {
3155    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3156    if (Tmp.getNode()) return Tmp;
3157  }
3158
3159  // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3160  if (N0.getOpcode() == ISD::AND &&
3161      N1.getOpcode() == ISD::AND &&
3162      N0.getOperand(1).getOpcode() == ISD::Constant &&
3163      N1.getOperand(1).getOpcode() == ISD::Constant &&
3164      // Don't increase # computations.
3165      (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3166    // We can only do this xform if we know that bits from X that are set in C2
3167    // but not in C1 are already zero.  Likewise for Y.
3168    const APInt &LHSMask =
3169      cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3170    const APInt &RHSMask =
3171      cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3172
3173    if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3174        DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3175      SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3176                              N0.getOperand(0), N1.getOperand(0));
3177      return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
3178                         DAG.getConstant(LHSMask | RHSMask, VT));
3179    }
3180  }
3181
3182  // See if this is some rotate idiom.
3183  if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
3184    return SDValue(Rot, 0);
3185
3186  // Simplify the operands using demanded-bits information.
3187  if (!VT.isVector() &&
3188      SimplifyDemandedBits(SDValue(N, 0)))
3189    return SDValue(N, 0);
3190
3191  return SDValue();
3192}
3193
3194/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3195static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3196  if (Op.getOpcode() == ISD::AND) {
3197    if (isa<ConstantSDNode>(Op.getOperand(1))) {
3198      Mask = Op.getOperand(1);
3199      Op = Op.getOperand(0);
3200    } else {
3201      return false;
3202    }
3203  }
3204
3205  if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3206    Shift = Op;
3207    return true;
3208  }
3209
3210  return false;
3211}
3212
3213// MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3214// idioms for rotate, and if the target supports rotation instructions, generate
3215// a rot[lr].
3216SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
3217  // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3218  EVT VT = LHS.getValueType();
3219  if (!TLI.isTypeLegal(VT)) return 0;
3220
3221  // The target must have at least one rotate flavor.
3222  bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3223  bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3224  if (!HasROTL && !HasROTR) return 0;
3225
3226  // Match "(X shl/srl V1) & V2" where V2 may not be present.
3227  SDValue LHSShift;   // The shift.
3228  SDValue LHSMask;    // AND value if any.
3229  if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3230    return 0; // Not part of a rotate.
3231
3232  SDValue RHSShift;   // The shift.
3233  SDValue RHSMask;    // AND value if any.
3234  if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3235    return 0; // Not part of a rotate.
3236
3237  if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3238    return 0;   // Not shifting the same value.
3239
3240  if (LHSShift.getOpcode() == RHSShift.getOpcode())
3241    return 0;   // Shifts must disagree.
3242
3243  // Canonicalize shl to left side in a shl/srl pair.
3244  if (RHSShift.getOpcode() == ISD::SHL) {
3245    std::swap(LHS, RHS);
3246    std::swap(LHSShift, RHSShift);
3247    std::swap(LHSMask , RHSMask );
3248  }
3249
3250  unsigned OpSizeInBits = VT.getSizeInBits();
3251  SDValue LHSShiftArg = LHSShift.getOperand(0);
3252  SDValue LHSShiftAmt = LHSShift.getOperand(1);
3253  SDValue RHSShiftAmt = RHSShift.getOperand(1);
3254
3255  // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3256  // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3257  if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3258      RHSShiftAmt.getOpcode() == ISD::Constant) {
3259    uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3260    uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3261    if ((LShVal + RShVal) != OpSizeInBits)
3262      return 0;
3263
3264    SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3265                              LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3266
3267    // If there is an AND of either shifted operand, apply it to the result.
3268    if (LHSMask.getNode() || RHSMask.getNode()) {
3269      APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3270
3271      if (LHSMask.getNode()) {
3272        APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3273        Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3274      }
3275      if (RHSMask.getNode()) {
3276        APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3277        Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3278      }
3279
3280      Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3281    }
3282
3283    return Rot.getNode();
3284  }
3285
3286  // If there is a mask here, and we have a variable shift, we can't be sure
3287  // that we're masking out the right stuff.
3288  if (LHSMask.getNode() || RHSMask.getNode())
3289    return 0;
3290
3291  // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3292  // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3293  if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3294      LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3295    if (ConstantSDNode *SUBC =
3296          dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3297      if (SUBC->getAPIntValue() == OpSizeInBits) {
3298        return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3299                           HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3300      }
3301    }
3302  }
3303
3304  // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3305  // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3306  if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3307      RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
3308    if (ConstantSDNode *SUBC =
3309          dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3310      if (SUBC->getAPIntValue() == OpSizeInBits) {
3311        return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3312                           HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3313      }
3314    }
3315  }
3316
3317  // Look for sign/zext/any-extended or truncate cases:
3318  if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3319       LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3320       LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3321       LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3322      (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3323       RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3324       RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3325       RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3326    SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3327    SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3328    if (RExtOp0.getOpcode() == ISD::SUB &&
3329        RExtOp0.getOperand(1) == LExtOp0) {
3330      // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3331      //   (rotl x, y)
3332      // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3333      //   (rotr x, (sub 32, y))
3334      if (ConstantSDNode *SUBC =
3335            dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3336        if (SUBC->getAPIntValue() == OpSizeInBits) {
3337          return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3338                             LHSShiftArg,
3339                             HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3340        }
3341      }
3342    } else if (LExtOp0.getOpcode() == ISD::SUB &&
3343               RExtOp0 == LExtOp0.getOperand(1)) {
3344      // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3345      //   (rotr x, y)
3346      // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3347      //   (rotl x, (sub 32, y))
3348      if (ConstantSDNode *SUBC =
3349            dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3350        if (SUBC->getAPIntValue() == OpSizeInBits) {
3351          return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3352                             LHSShiftArg,
3353                             HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3354        }
3355      }
3356    }
3357  }
3358
3359  return 0;
3360}
3361
3362SDValue DAGCombiner::visitXOR(SDNode *N) {
3363  SDValue N0 = N->getOperand(0);
3364  SDValue N1 = N->getOperand(1);
3365  SDValue LHS, RHS, CC;
3366  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3367  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3368  EVT VT = N0.getValueType();
3369
3370  // fold vector ops
3371  if (VT.isVector()) {
3372    SDValue FoldedVOp = SimplifyVBinOp(N);
3373    if (FoldedVOp.getNode()) return FoldedVOp;
3374
3375    // fold (xor x, 0) -> x, vector edition
3376    if (ISD::isBuildVectorAllZeros(N0.getNode()))
3377      return N1;
3378    if (ISD::isBuildVectorAllZeros(N1.getNode()))
3379      return N0;
3380  }
3381
3382  // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3383  if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3384    return DAG.getConstant(0, VT);
3385  // fold (xor x, undef) -> undef
3386  if (N0.getOpcode() == ISD::UNDEF)
3387    return N0;
3388  if (N1.getOpcode() == ISD::UNDEF)
3389    return N1;
3390  // fold (xor c1, c2) -> c1^c2
3391  if (N0C && N1C)
3392    return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3393  // canonicalize constant to RHS
3394  if (N0C && !N1C)
3395    return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
3396  // fold (xor x, 0) -> x
3397  if (N1C && N1C->isNullValue())
3398    return N0;
3399  // reassociate xor
3400  SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
3401  if (RXOR.getNode() != 0)
3402    return RXOR;
3403
3404  // fold !(x cc y) -> (x !cc y)
3405  if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3406    bool isInt = LHS.getValueType().isInteger();
3407    ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3408                                               isInt);
3409
3410    if (!LegalOperations ||
3411        TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3412      switch (N0.getOpcode()) {
3413      default:
3414        llvm_unreachable("Unhandled SetCC Equivalent!");
3415      case ISD::SETCC:
3416        return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
3417      case ISD::SELECT_CC:
3418        return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
3419                               N0.getOperand(3), NotCC);
3420      }
3421    }
3422  }
3423
3424  // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3425  if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3426      N0.getNode()->hasOneUse() &&
3427      isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3428    SDValue V = N0.getOperand(0);
3429    V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
3430                    DAG.getConstant(1, V.getValueType()));
3431    AddToWorkList(V.getNode());
3432    return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
3433  }
3434
3435  // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3436  if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3437      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3438    SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3439    if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3440      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3441      LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3442      RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3443      AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3444      return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3445    }
3446  }
3447  // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3448  if (N1C && N1C->isAllOnesValue() &&
3449      (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3450    SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3451    if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3452      unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3453      LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3454      RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3455      AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3456      return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3457    }
3458  }
3459  // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3460  if (N1C && N0.getOpcode() == ISD::XOR) {
3461    ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3462    ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3463    if (N00C)
3464      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
3465                         DAG.getConstant(N1C->getAPIntValue() ^
3466                                         N00C->getAPIntValue(), VT));
3467    if (N01C)
3468      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
3469                         DAG.getConstant(N1C->getAPIntValue() ^
3470                                         N01C->getAPIntValue(), VT));
3471  }
3472  // fold (xor x, x) -> 0
3473  if (N0 == N1)
3474    return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
3475
3476  // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3477  if (N0.getOpcode() == N1.getOpcode()) {
3478    SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3479    if (Tmp.getNode()) return Tmp;
3480  }
3481
3482  // Simplify the expression using non-local knowledge.
3483  if (!VT.isVector() &&
3484      SimplifyDemandedBits(SDValue(N, 0)))
3485    return SDValue(N, 0);
3486
3487  return SDValue();
3488}
3489
3490/// visitShiftByConstant - Handle transforms common to the three shifts, when
3491/// the shift amount is a constant.
3492SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3493  SDNode *LHS = N->getOperand(0).getNode();
3494  if (!LHS->hasOneUse()) return SDValue();
3495
3496  // We want to pull some binops through shifts, so that we have (and (shift))
3497  // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3498  // thing happens with address calculations, so it's important to canonicalize
3499  // it.
3500  bool HighBitSet = false;  // Can we transform this if the high bit is set?
3501
3502  switch (LHS->getOpcode()) {
3503  default: return SDValue();
3504  case ISD::OR:
3505  case ISD::XOR:
3506    HighBitSet = false; // We can only transform sra if the high bit is clear.
3507    break;
3508  case ISD::AND:
3509    HighBitSet = true;  // We can only transform sra if the high bit is set.
3510    break;
3511  case ISD::ADD:
3512    if (N->getOpcode() != ISD::SHL)
3513      return SDValue(); // only shl(add) not sr[al](add).
3514    HighBitSet = false; // We can only transform sra if the high bit is clear.
3515    break;
3516  }
3517
3518  // We require the RHS of the binop to be a constant as well.
3519  ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3520  if (!BinOpCst) return SDValue();
3521
3522  // FIXME: disable this unless the input to the binop is a shift by a constant.
3523  // If it is not a shift, it pessimizes some common cases like:
3524  //
3525  //    void foo(int *X, int i) { X[i & 1235] = 1; }
3526  //    int bar(int *X, int i) { return X[i & 255]; }
3527  SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3528  if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3529       BinOpLHSVal->getOpcode() != ISD::SRA &&
3530       BinOpLHSVal->getOpcode() != ISD::SRL) ||
3531      !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3532    return SDValue();
3533
3534  EVT VT = N->getValueType(0);
3535
3536  // If this is a signed shift right, and the high bit is modified by the
3537  // logical operation, do not perform the transformation. The highBitSet
3538  // boolean indicates the value of the high bit of the constant which would
3539  // cause it to be modified for this operation.
3540  if (N->getOpcode() == ISD::SRA) {
3541    bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3542    if (BinOpRHSSignSet != HighBitSet)
3543      return SDValue();
3544  }
3545
3546  // Fold the constants, shifting the binop RHS by the shift amount.
3547  SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3548                               N->getValueType(0),
3549                               LHS->getOperand(1), N->getOperand(1));
3550
3551  // Create the new shift.
3552  SDValue NewShift = DAG.getNode(N->getOpcode(),
3553                                 LHS->getOperand(0).getDebugLoc(),
3554                                 VT, LHS->getOperand(0), N->getOperand(1));
3555
3556  // Create the new binop.
3557  return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3558}
3559
3560SDValue DAGCombiner::visitSHL(SDNode *N) {
3561  SDValue N0 = N->getOperand(0);
3562  SDValue N1 = N->getOperand(1);
3563  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3564  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3565  EVT VT = N0.getValueType();
3566  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3567
3568  // fold (shl c1, c2) -> c1<<c2
3569  if (N0C && N1C)
3570    return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3571  // fold (shl 0, x) -> 0
3572  if (N0C && N0C->isNullValue())
3573    return N0;
3574  // fold (shl x, c >= size(x)) -> undef
3575  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3576    return DAG.getUNDEF(VT);
3577  // fold (shl x, 0) -> x
3578  if (N1C && N1C->isNullValue())
3579    return N0;
3580  // fold (shl undef, x) -> 0
3581  if (N0.getOpcode() == ISD::UNDEF)
3582    return DAG.getConstant(0, VT);
3583  // if (shl x, c) is known to be zero, return 0
3584  if (DAG.MaskedValueIsZero(SDValue(N, 0),
3585                            APInt::getAllOnesValue(OpSizeInBits)))
3586    return DAG.getConstant(0, VT);
3587  // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3588  if (N1.getOpcode() == ISD::TRUNCATE &&
3589      N1.getOperand(0).getOpcode() == ISD::AND &&
3590      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3591    SDValue N101 = N1.getOperand(0).getOperand(1);
3592    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3593      EVT TruncVT = N1.getValueType();
3594      SDValue N100 = N1.getOperand(0).getOperand(0);
3595      APInt TruncC = N101C->getAPIntValue();
3596      TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3597      return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3598                         DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3599                                     DAG.getNode(ISD::TRUNCATE,
3600                                                 N->getDebugLoc(),
3601                                                 TruncVT, N100),
3602                                     DAG.getConstant(TruncC, TruncVT)));
3603    }
3604  }
3605
3606  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3607    return SDValue(N, 0);
3608
3609  // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3610  if (N1C && N0.getOpcode() == ISD::SHL &&
3611      N0.getOperand(1).getOpcode() == ISD::Constant) {
3612    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3613    uint64_t c2 = N1C->getZExtValue();
3614    if (c1 + c2 >= OpSizeInBits)
3615      return DAG.getConstant(0, VT);
3616    return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3617                       DAG.getConstant(c1 + c2, N1.getValueType()));
3618  }
3619
3620  // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3621  // For this to be valid, the second form must not preserve any of the bits
3622  // that are shifted out by the inner shift in the first form.  This means
3623  // the outer shift size must be >= the number of bits added by the ext.
3624  // As a corollary, we don't care what kind of ext it is.
3625  if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3626              N0.getOpcode() == ISD::ANY_EXTEND ||
3627              N0.getOpcode() == ISD::SIGN_EXTEND) &&
3628      N0.getOperand(0).getOpcode() == ISD::SHL &&
3629      isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3630    uint64_t c1 =
3631      cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3632    uint64_t c2 = N1C->getZExtValue();
3633    EVT InnerShiftVT = N0.getOperand(0).getValueType();
3634    uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3635    if (c2 >= OpSizeInBits - InnerShiftSize) {
3636      if (c1 + c2 >= OpSizeInBits)
3637        return DAG.getConstant(0, VT);
3638      return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3639                         DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3640                                     N0.getOperand(0)->getOperand(0)),
3641                         DAG.getConstant(c1 + c2, N1.getValueType()));
3642    }
3643  }
3644
3645  // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3646  //                               (and (srl x, (sub c1, c2), MASK)
3647  // Only fold this if the inner shift has no other uses -- if it does, folding
3648  // this will increase the total number of instructions.
3649  if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3650      N0.getOperand(1).getOpcode() == ISD::Constant) {
3651    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3652    if (c1 < VT.getSizeInBits()) {
3653      uint64_t c2 = N1C->getZExtValue();
3654      APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3655                                         VT.getSizeInBits() - c1);
3656      SDValue Shift;
3657      if (c2 > c1) {
3658        Mask = Mask.shl(c2-c1);
3659        Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3660                            DAG.getConstant(c2-c1, N1.getValueType()));
3661      } else {
3662        Mask = Mask.lshr(c1-c2);
3663        Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3664                            DAG.getConstant(c1-c2, N1.getValueType()));
3665      }
3666      return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3667                         DAG.getConstant(Mask, VT));
3668    }
3669  }
3670  // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3671  if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3672    SDValue HiBitsMask =
3673      DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3674                                            VT.getSizeInBits() -
3675                                              N1C->getZExtValue()),
3676                      VT);
3677    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3678                       HiBitsMask);
3679  }
3680
3681  if (N1C) {
3682    SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3683    if (NewSHL.getNode())
3684      return NewSHL;
3685  }
3686
3687  return SDValue();
3688}
3689
3690SDValue DAGCombiner::visitSRA(SDNode *N) {
3691  SDValue N0 = N->getOperand(0);
3692  SDValue N1 = N->getOperand(1);
3693  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3694  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3695  EVT VT = N0.getValueType();
3696  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3697
3698  // fold (sra c1, c2) -> (sra c1, c2)
3699  if (N0C && N1C)
3700    return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3701  // fold (sra 0, x) -> 0
3702  if (N0C && N0C->isNullValue())
3703    return N0;
3704  // fold (sra -1, x) -> -1
3705  if (N0C && N0C->isAllOnesValue())
3706    return N0;
3707  // fold (sra x, (setge c, size(x))) -> undef
3708  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3709    return DAG.getUNDEF(VT);
3710  // fold (sra x, 0) -> x
3711  if (N1C && N1C->isNullValue())
3712    return N0;
3713  // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3714  // sext_inreg.
3715  if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3716    unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3717    EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3718    if (VT.isVector())
3719      ExtVT = EVT::getVectorVT(*DAG.getContext(),
3720                               ExtVT, VT.getVectorNumElements());
3721    if ((!LegalOperations ||
3722         TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3723      return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3724                         N0.getOperand(0), DAG.getValueType(ExtVT));
3725  }
3726
3727  // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3728  if (N1C && N0.getOpcode() == ISD::SRA) {
3729    if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3730      unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3731      if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3732      return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3733                         DAG.getConstant(Sum, N1C->getValueType(0)));
3734    }
3735  }
3736
3737  // fold (sra (shl X, m), (sub result_size, n))
3738  // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3739  // result_size - n != m.
3740  // If truncate is free for the target sext(shl) is likely to result in better
3741  // code.
3742  if (N0.getOpcode() == ISD::SHL) {
3743    // Get the two constanst of the shifts, CN0 = m, CN = n.
3744    const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3745    if (N01C && N1C) {
3746      // Determine what the truncate's result bitsize and type would be.
3747      EVT TruncVT =
3748        EVT::getIntegerVT(*DAG.getContext(),
3749                          OpSizeInBits - N1C->getZExtValue());
3750      // Determine the residual right-shift amount.
3751      signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3752
3753      // If the shift is not a no-op (in which case this should be just a sign
3754      // extend already), the truncated to type is legal, sign_extend is legal
3755      // on that type, and the truncate to that type is both legal and free,
3756      // perform the transform.
3757      if ((ShiftAmt > 0) &&
3758          TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3759          TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3760          TLI.isTruncateFree(VT, TruncVT)) {
3761
3762          SDValue Amt = DAG.getConstant(ShiftAmt,
3763              getShiftAmountTy(N0.getOperand(0).getValueType()));
3764          SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3765                                      N0.getOperand(0), Amt);
3766          SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3767                                      Shift);
3768          return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3769                             N->getValueType(0), Trunc);
3770      }
3771    }
3772  }
3773
3774  // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3775  if (N1.getOpcode() == ISD::TRUNCATE &&
3776      N1.getOperand(0).getOpcode() == ISD::AND &&
3777      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3778    SDValue N101 = N1.getOperand(0).getOperand(1);
3779    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3780      EVT TruncVT = N1.getValueType();
3781      SDValue N100 = N1.getOperand(0).getOperand(0);
3782      APInt TruncC = N101C->getAPIntValue();
3783      TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3784      return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3785                         DAG.getNode(ISD::AND, N->getDebugLoc(),
3786                                     TruncVT,
3787                                     DAG.getNode(ISD::TRUNCATE,
3788                                                 N->getDebugLoc(),
3789                                                 TruncVT, N100),
3790                                     DAG.getConstant(TruncC, TruncVT)));
3791    }
3792  }
3793
3794  // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3795  //      if c1 is equal to the number of bits the trunc removes
3796  if (N0.getOpcode() == ISD::TRUNCATE &&
3797      (N0.getOperand(0).getOpcode() == ISD::SRL ||
3798       N0.getOperand(0).getOpcode() == ISD::SRA) &&
3799      N0.getOperand(0).hasOneUse() &&
3800      N0.getOperand(0).getOperand(1).hasOneUse() &&
3801      N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3802    EVT LargeVT = N0.getOperand(0).getValueType();
3803    ConstantSDNode *LargeShiftAmt =
3804      cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3805
3806    if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3807        LargeShiftAmt->getZExtValue()) {
3808      SDValue Amt =
3809        DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3810              getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3811      SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3812                                N0.getOperand(0).getOperand(0), Amt);
3813      return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3814    }
3815  }
3816
3817  // Simplify, based on bits shifted out of the LHS.
3818  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3819    return SDValue(N, 0);
3820
3821
3822  // If the sign bit is known to be zero, switch this to a SRL.
3823  if (DAG.SignBitIsZero(N0))
3824    return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3825
3826  if (N1C) {
3827    SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3828    if (NewSRA.getNode())
3829      return NewSRA;
3830  }
3831
3832  return SDValue();
3833}
3834
3835SDValue DAGCombiner::visitSRL(SDNode *N) {
3836  SDValue N0 = N->getOperand(0);
3837  SDValue N1 = N->getOperand(1);
3838  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3839  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3840  EVT VT = N0.getValueType();
3841  unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3842
3843  // fold (srl c1, c2) -> c1 >>u c2
3844  if (N0C && N1C)
3845    return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3846  // fold (srl 0, x) -> 0
3847  if (N0C && N0C->isNullValue())
3848    return N0;
3849  // fold (srl x, c >= size(x)) -> undef
3850  if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3851    return DAG.getUNDEF(VT);
3852  // fold (srl x, 0) -> x
3853  if (N1C && N1C->isNullValue())
3854    return N0;
3855  // if (srl x, c) is known to be zero, return 0
3856  if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3857                                   APInt::getAllOnesValue(OpSizeInBits)))
3858    return DAG.getConstant(0, VT);
3859
3860  // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3861  if (N1C && N0.getOpcode() == ISD::SRL &&
3862      N0.getOperand(1).getOpcode() == ISD::Constant) {
3863    uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3864    uint64_t c2 = N1C->getZExtValue();
3865    if (c1 + c2 >= OpSizeInBits)
3866      return DAG.getConstant(0, VT);
3867    return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3868                       DAG.getConstant(c1 + c2, N1.getValueType()));
3869  }
3870
3871  // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3872  if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3873      N0.getOperand(0).getOpcode() == ISD::SRL &&
3874      isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3875    uint64_t c1 =
3876      cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3877    uint64_t c2 = N1C->getZExtValue();
3878    EVT InnerShiftVT = N0.getOperand(0).getValueType();
3879    EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3880    uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3881    // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3882    if (c1 + OpSizeInBits == InnerShiftSize) {
3883      if (c1 + c2 >= InnerShiftSize)
3884        return DAG.getConstant(0, VT);
3885      return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3886                         DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3887                                     N0.getOperand(0)->getOperand(0),
3888                                     DAG.getConstant(c1 + c2, ShiftCountVT)));
3889    }
3890  }
3891
3892  // fold (srl (shl x, c), c) -> (and x, cst2)
3893  if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3894      N0.getValueSizeInBits() <= 64) {
3895    uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3896    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3897                       DAG.getConstant(~0ULL >> ShAmt, VT));
3898  }
3899
3900
3901  // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3902  if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3903    // Shifting in all undef bits?
3904    EVT SmallVT = N0.getOperand(0).getValueType();
3905    if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3906      return DAG.getUNDEF(VT);
3907
3908    if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3909      uint64_t ShiftAmt = N1C->getZExtValue();
3910      SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3911                                       N0.getOperand(0),
3912                          DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3913      AddToWorkList(SmallShift.getNode());
3914      return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3915    }
3916  }
3917
3918  // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
3919  // bit, which is unmodified by sra.
3920  if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3921    if (N0.getOpcode() == ISD::SRA)
3922      return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3923  }
3924
3925  // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
3926  if (N1C && N0.getOpcode() == ISD::CTLZ &&
3927      N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3928    APInt KnownZero, KnownOne;
3929    DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3930
3931    // If any of the input bits are KnownOne, then the input couldn't be all
3932    // zeros, thus the result of the srl will always be zero.
3933    if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3934
3935    // If all of the bits input the to ctlz node are known to be zero, then
3936    // the result of the ctlz is "32" and the result of the shift is one.
3937    APInt UnknownBits = ~KnownZero;
3938    if (UnknownBits == 0) return DAG.getConstant(1, VT);
3939
3940    // Otherwise, check to see if there is exactly one bit input to the ctlz.
3941    if ((UnknownBits & (UnknownBits - 1)) == 0) {
3942      // Okay, we know that only that the single bit specified by UnknownBits
3943      // could be set on input to the CTLZ node. If this bit is set, the SRL
3944      // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3945      // to an SRL/XOR pair, which is likely to simplify more.
3946      unsigned ShAmt = UnknownBits.countTrailingZeros();
3947      SDValue Op = N0.getOperand(0);
3948
3949      if (ShAmt) {
3950        Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3951                  DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3952        AddToWorkList(Op.getNode());
3953      }
3954
3955      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3956                         Op, DAG.getConstant(1, VT));
3957    }
3958  }
3959
3960  // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3961  if (N1.getOpcode() == ISD::TRUNCATE &&
3962      N1.getOperand(0).getOpcode() == ISD::AND &&
3963      N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3964    SDValue N101 = N1.getOperand(0).getOperand(1);
3965    if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3966      EVT TruncVT = N1.getValueType();
3967      SDValue N100 = N1.getOperand(0).getOperand(0);
3968      APInt TruncC = N101C->getAPIntValue();
3969      TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3970      return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3971                         DAG.getNode(ISD::AND, N->getDebugLoc(),
3972                                     TruncVT,
3973                                     DAG.getNode(ISD::TRUNCATE,
3974                                                 N->getDebugLoc(),
3975                                                 TruncVT, N100),
3976                                     DAG.getConstant(TruncC, TruncVT)));
3977    }
3978  }
3979
3980  // fold operands of srl based on knowledge that the low bits are not
3981  // demanded.
3982  if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3983    return SDValue(N, 0);
3984
3985  if (N1C) {
3986    SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3987    if (NewSRL.getNode())
3988      return NewSRL;
3989  }
3990
3991  // Attempt to convert a srl of a load into a narrower zero-extending load.
3992  SDValue NarrowLoad = ReduceLoadWidth(N);
3993  if (NarrowLoad.getNode())
3994    return NarrowLoad;
3995
3996  // Here is a common situation. We want to optimize:
3997  //
3998  //   %a = ...
3999  //   %b = and i32 %a, 2
4000  //   %c = srl i32 %b, 1
4001  //   brcond i32 %c ...
4002  //
4003  // into
4004  //
4005  //   %a = ...
4006  //   %b = and %a, 2
4007  //   %c = setcc eq %b, 0
4008  //   brcond %c ...
4009  //
4010  // However when after the source operand of SRL is optimized into AND, the SRL
4011  // itself may not be optimized further. Look for it and add the BRCOND into
4012  // the worklist.
4013  if (N->hasOneUse()) {
4014    SDNode *Use = *N->use_begin();
4015    if (Use->getOpcode() == ISD::BRCOND)
4016      AddToWorkList(Use);
4017    else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4018      // Also look pass the truncate.
4019      Use = *Use->use_begin();
4020      if (Use->getOpcode() == ISD::BRCOND)
4021        AddToWorkList(Use);
4022    }
4023  }
4024
4025  return SDValue();
4026}
4027
4028SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4029  SDValue N0 = N->getOperand(0);
4030  EVT VT = N->getValueType(0);
4031
4032  // fold (ctlz c1) -> c2
4033  if (isa<ConstantSDNode>(N0))
4034    return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
4035  return SDValue();
4036}
4037
4038SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4039  SDValue N0 = N->getOperand(0);
4040  EVT VT = N->getValueType(0);
4041
4042  // fold (ctlz_zero_undef c1) -> c2
4043  if (isa<ConstantSDNode>(N0))
4044    return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4045  return SDValue();
4046}
4047
4048SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4049  SDValue N0 = N->getOperand(0);
4050  EVT VT = N->getValueType(0);
4051
4052  // fold (cttz c1) -> c2
4053  if (isa<ConstantSDNode>(N0))
4054    return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
4055  return SDValue();
4056}
4057
4058SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4059  SDValue N0 = N->getOperand(0);
4060  EVT VT = N->getValueType(0);
4061
4062  // fold (cttz_zero_undef c1) -> c2
4063  if (isa<ConstantSDNode>(N0))
4064    return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4065  return SDValue();
4066}
4067
4068SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4069  SDValue N0 = N->getOperand(0);
4070  EVT VT = N->getValueType(0);
4071
4072  // fold (ctpop c1) -> c2
4073  if (isa<ConstantSDNode>(N0))
4074    return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
4075  return SDValue();
4076}
4077
4078SDValue DAGCombiner::visitSELECT(SDNode *N) {
4079  SDValue N0 = N->getOperand(0);
4080  SDValue N1 = N->getOperand(1);
4081  SDValue N2 = N->getOperand(2);
4082  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4083  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4084  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4085  EVT VT = N->getValueType(0);
4086  EVT VT0 = N0.getValueType();
4087
4088  // fold (select C, X, X) -> X
4089  if (N1 == N2)
4090    return N1;
4091  // fold (select true, X, Y) -> X
4092  if (N0C && !N0C->isNullValue())
4093    return N1;
4094  // fold (select false, X, Y) -> Y
4095  if (N0C && N0C->isNullValue())
4096    return N2;
4097  // fold (select C, 1, X) -> (or C, X)
4098  if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4099    return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4100  // fold (select C, 0, 1) -> (xor C, 1)
4101  if (VT.isInteger() &&
4102      (VT0 == MVT::i1 ||
4103       (VT0.isInteger() &&
4104        TLI.getBooleanContents(false) ==
4105        TargetLowering::ZeroOrOneBooleanContent)) &&
4106      N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4107    SDValue XORNode;
4108    if (VT == VT0)
4109      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
4110                         N0, DAG.getConstant(1, VT0));
4111    XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
4112                          N0, DAG.getConstant(1, VT0));
4113    AddToWorkList(XORNode.getNode());
4114    if (VT.bitsGT(VT0))
4115      return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
4116    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
4117  }
4118  // fold (select C, 0, X) -> (and (not C), X)
4119  if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4120    SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4121    AddToWorkList(NOTNode.getNode());
4122    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
4123  }
4124  // fold (select C, X, 1) -> (or (not C), X)
4125  if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4126    SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4127    AddToWorkList(NOTNode.getNode());
4128    return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
4129  }
4130  // fold (select C, X, 0) -> (and C, X)
4131  if (VT == MVT::i1 && N2C && N2C->isNullValue())
4132    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4133  // fold (select X, X, Y) -> (or X, Y)
4134  // fold (select X, 1, Y) -> (or X, Y)
4135  if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4136    return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4137  // fold (select X, Y, X) -> (and X, Y)
4138  // fold (select X, Y, 0) -> (and X, Y)
4139  if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4140    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4141
4142  // If we can fold this based on the true/false value, do so.
4143  if (SimplifySelectOps(N, N1, N2))
4144    return SDValue(N, 0);  // Don't revisit N.
4145
4146  // fold selects based on a setcc into other things, such as min/max/abs
4147  if (N0.getOpcode() == ISD::SETCC) {
4148    // FIXME:
4149    // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4150    // having to say they don't support SELECT_CC on every type the DAG knows
4151    // about, since there is no way to mark an opcode illegal at all value types
4152    if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4153        TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4154      return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
4155                         N0.getOperand(0), N0.getOperand(1),
4156                         N1, N2, N0.getOperand(2));
4157    return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
4158  }
4159
4160  return SDValue();
4161}
4162
4163SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4164  SDValue N0 = N->getOperand(0);
4165  SDValue N1 = N->getOperand(1);
4166  SDValue N2 = N->getOperand(2);
4167  SDValue N3 = N->getOperand(3);
4168  SDValue N4 = N->getOperand(4);
4169  ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4170
4171  // fold select_cc lhs, rhs, x, x, cc -> x
4172  if (N2 == N3)
4173    return N2;
4174
4175  // Determine if the condition we're dealing with is constant
4176  SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
4177                              N0, N1, CC, N->getDebugLoc(), false);
4178  if (SCC.getNode()) AddToWorkList(SCC.getNode());
4179
4180  if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
4181    if (!SCCC->isNullValue())
4182      return N2;    // cond always true -> true val
4183    else
4184      return N3;    // cond always false -> false val
4185  }
4186
4187  // Fold to a simpler select_cc
4188  if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
4189    return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
4190                       SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4191                       SCC.getOperand(2));
4192
4193  // If we can fold this based on the true/false value, do so.
4194  if (SimplifySelectOps(N, N2, N3))
4195    return SDValue(N, 0);  // Don't revisit N.
4196
4197  // fold select_cc into other things, such as min/max/abs
4198  return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
4199}
4200
4201SDValue DAGCombiner::visitSETCC(SDNode *N) {
4202  return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4203                       cast<CondCodeSDNode>(N->getOperand(2))->get(),
4204                       N->getDebugLoc());
4205}
4206
4207// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4208// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4209// transformation. Returns true if extension are possible and the above
4210// mentioned transformation is profitable.
4211static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4212                                    unsigned ExtOpc,
4213                                    SmallVector<SDNode*, 4> &ExtendNodes,
4214                                    const TargetLowering &TLI) {
4215  bool HasCopyToRegUses = false;
4216  bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4217  for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4218                            UE = N0.getNode()->use_end();
4219       UI != UE; ++UI) {
4220    SDNode *User = *UI;
4221    if (User == N)
4222      continue;
4223    if (UI.getUse().getResNo() != N0.getResNo())
4224      continue;
4225    // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4226    if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4227      ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4228      if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4229        // Sign bits will be lost after a zext.
4230        return false;
4231      bool Add = false;
4232      for (unsigned i = 0; i != 2; ++i) {
4233        SDValue UseOp = User->getOperand(i);
4234        if (UseOp == N0)
4235          continue;
4236        if (!isa<ConstantSDNode>(UseOp))
4237          return false;
4238        Add = true;
4239      }
4240      if (Add)
4241        ExtendNodes.push_back(User);
4242      continue;
4243    }
4244    // If truncates aren't free and there are users we can't
4245    // extend, it isn't worthwhile.
4246    if (!isTruncFree)
4247      return false;
4248    // Remember if this value is live-out.
4249    if (User->getOpcode() == ISD::CopyToReg)
4250      HasCopyToRegUses = true;
4251  }
4252
4253  if (HasCopyToRegUses) {
4254    bool BothLiveOut = false;
4255    for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4256         UI != UE; ++UI) {
4257      SDUse &Use = UI.getUse();
4258      if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4259        BothLiveOut = true;
4260        break;
4261      }
4262    }
4263    if (BothLiveOut)
4264      // Both unextended and extended values are live out. There had better be
4265      // a good reason for the transformation.
4266      return ExtendNodes.size();
4267  }
4268  return true;
4269}
4270
4271void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4272                                  SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
4273                                  ISD::NodeType ExtType) {
4274  // Extend SetCC uses if necessary.
4275  for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4276    SDNode *SetCC = SetCCs[i];
4277    SmallVector<SDValue, 4> Ops;
4278
4279    for (unsigned j = 0; j != 2; ++j) {
4280      SDValue SOp = SetCC->getOperand(j);
4281      if (SOp == Trunc)
4282        Ops.push_back(ExtLoad);
4283      else
4284        Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4285    }
4286
4287    Ops.push_back(SetCC->getOperand(2));
4288    CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4289                                 &Ops[0], Ops.size()));
4290  }
4291}
4292
4293SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4294  SDValue N0 = N->getOperand(0);
4295  EVT VT = N->getValueType(0);
4296
4297  // fold (sext c1) -> c1
4298  if (isa<ConstantSDNode>(N0))
4299    return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
4300
4301  // fold (sext (sext x)) -> (sext x)
4302  // fold (sext (aext x)) -> (sext x)
4303  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4304    return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
4305                       N0.getOperand(0));
4306
4307  if (N0.getOpcode() == ISD::TRUNCATE) {
4308    // fold (sext (truncate (load x))) -> (sext (smaller load x))
4309    // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4310    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4311    if (NarrowLoad.getNode()) {
4312      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4313      if (NarrowLoad.getNode() != N0.getNode()) {
4314        CombineTo(N0.getNode(), NarrowLoad);
4315        // CombineTo deleted the truncate, if needed, but not what's under it.
4316        AddToWorkList(oye);
4317      }
4318      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4319    }
4320
4321    // See if the value being truncated is already sign extended.  If so, just
4322    // eliminate the trunc/sext pair.
4323    SDValue Op = N0.getOperand(0);
4324    unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4325    unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4326    unsigned DestBits = VT.getScalarType().getSizeInBits();
4327    unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4328
4329    if (OpBits == DestBits) {
4330      // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4331      // bits, it is already ready.
4332      if (NumSignBits > DestBits-MidBits)
4333        return Op;
4334    } else if (OpBits < DestBits) {
4335      // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4336      // bits, just sext from i32.
4337      if (NumSignBits > OpBits-MidBits)
4338        return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
4339    } else {
4340      // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4341      // bits, just truncate to i32.
4342      if (NumSignBits > OpBits-MidBits)
4343        return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4344    }
4345
4346    // fold (sext (truncate x)) -> (sextinreg x).
4347    if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4348                                                 N0.getValueType())) {
4349      if (OpBits < DestBits)
4350        Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
4351      else if (OpBits > DestBits)
4352        Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
4353      return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
4354                         DAG.getValueType(N0.getValueType()));
4355    }
4356  }
4357
4358  // fold (sext (load x)) -> (sext (truncate (sextload x)))
4359  // None of the supported targets knows how to perform load and sign extend
4360  // on vectors in one instruction.  We only perform this transformation on
4361  // scalars.
4362  if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4363      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4364       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4365    bool DoXform = true;
4366    SmallVector<SDNode*, 4> SetCCs;
4367    if (!N0.hasOneUse())
4368      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4369    if (DoXform) {
4370      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4371      SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4372                                       LN0->getChain(),
4373                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4374                                       N0.getValueType(),
4375                                       LN0->isVolatile(), LN0->isNonTemporal(),
4376                                       LN0->getAlignment());
4377      CombineTo(N, ExtLoad);
4378      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4379                                  N0.getValueType(), ExtLoad);
4380      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4381      ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4382                      ISD::SIGN_EXTEND);
4383      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4384    }
4385  }
4386
4387  // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4388  // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4389  if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4390      ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4391    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4392    EVT MemVT = LN0->getMemoryVT();
4393    if ((!LegalOperations && !LN0->isVolatile()) ||
4394        TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4395      SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4396                                       LN0->getChain(),
4397                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4398                                       MemVT,
4399                                       LN0->isVolatile(), LN0->isNonTemporal(),
4400                                       LN0->getAlignment());
4401      CombineTo(N, ExtLoad);
4402      CombineTo(N0.getNode(),
4403                DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4404                            N0.getValueType(), ExtLoad),
4405                ExtLoad.getValue(1));
4406      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4407    }
4408  }
4409
4410  // fold (sext (and/or/xor (load x), cst)) ->
4411  //      (and/or/xor (sextload x), (sext cst))
4412  if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4413       N0.getOpcode() == ISD::XOR) &&
4414      isa<LoadSDNode>(N0.getOperand(0)) &&
4415      N0.getOperand(1).getOpcode() == ISD::Constant &&
4416      TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4417      (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4418    LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4419    if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4420      bool DoXform = true;
4421      SmallVector<SDNode*, 4> SetCCs;
4422      if (!N0.hasOneUse())
4423        DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4424                                          SetCCs, TLI);
4425      if (DoXform) {
4426        SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
4427                                         LN0->getChain(), LN0->getBasePtr(),
4428                                         LN0->getPointerInfo(),
4429                                         LN0->getMemoryVT(),
4430                                         LN0->isVolatile(),
4431                                         LN0->isNonTemporal(),
4432                                         LN0->getAlignment());
4433        APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4434        Mask = Mask.sext(VT.getSizeInBits());
4435        SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4436                                  ExtLoad, DAG.getConstant(Mask, VT));
4437        SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4438                                    N0.getOperand(0).getDebugLoc(),
4439                                    N0.getOperand(0).getValueType(), ExtLoad);
4440        CombineTo(N, And);
4441        CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4442        ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4443                        ISD::SIGN_EXTEND);
4444        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4445      }
4446    }
4447  }
4448
4449  if (N0.getOpcode() == ISD::SETCC) {
4450    // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4451    // Only do this before legalize for now.
4452    if (VT.isVector() && !LegalOperations) {
4453      EVT N0VT = N0.getOperand(0).getValueType();
4454      // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4455      // of the same size as the compared operands. Only optimize sext(setcc())
4456      // if this is the case.
4457      EVT SVT = TLI.getSetCCResultType(N0VT);
4458
4459      // We know that the # elements of the results is the same as the
4460      // # elements of the compare (and the # elements of the compare result
4461      // for that matter).  Check to see that they are the same size.  If so,
4462      // we know that the element size of the sext'd result matches the
4463      // element size of the compare operands.
4464      if (VT.getSizeInBits() == SVT.getSizeInBits())
4465        return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4466                             N0.getOperand(1),
4467                             cast<CondCodeSDNode>(N0.getOperand(2))->get());
4468      // If the desired elements are smaller or larger than the source
4469      // elements we can use a matching integer vector type and then
4470      // truncate/sign extend
4471      EVT MatchingElementType =
4472        EVT::getIntegerVT(*DAG.getContext(),
4473                          N0VT.getScalarType().getSizeInBits());
4474      EVT MatchingVectorType =
4475        EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4476                         N0VT.getVectorNumElements());
4477
4478      if (SVT == MatchingVectorType) {
4479        SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType,
4480                               N0.getOperand(0), N0.getOperand(1),
4481                               cast<CondCodeSDNode>(N0.getOperand(2))->get());
4482        return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4483      }
4484    }
4485
4486    // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4487    unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4488    SDValue NegOne =
4489      DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4490    SDValue SCC =
4491      SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4492                       NegOne, DAG.getConstant(0, VT),
4493                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4494    if (SCC.getNode()) return SCC;
4495    if (!LegalOperations ||
4496        TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
4497      return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
4498                         DAG.getSetCC(N->getDebugLoc(),
4499                                      TLI.getSetCCResultType(VT),
4500                                      N0.getOperand(0), N0.getOperand(1),
4501                                 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4502                         NegOne, DAG.getConstant(0, VT));
4503  }
4504
4505  // fold (sext x) -> (zext x) if the sign bit is known zero.
4506  if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4507      DAG.SignBitIsZero(N0))
4508    return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4509
4510  return SDValue();
4511}
4512
4513// isTruncateOf - If N is a truncate of some other value, return true, record
4514// the value being truncated in Op and which of Op's bits are zero in KnownZero.
4515// This function computes KnownZero to avoid a duplicated call to
4516// ComputeMaskedBits in the caller.
4517static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4518                         APInt &KnownZero) {
4519  APInt KnownOne;
4520  if (N->getOpcode() == ISD::TRUNCATE) {
4521    Op = N->getOperand(0);
4522    DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4523    return true;
4524  }
4525
4526  if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4527      cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4528    return false;
4529
4530  SDValue Op0 = N->getOperand(0);
4531  SDValue Op1 = N->getOperand(1);
4532  assert(Op0.getValueType() == Op1.getValueType());
4533
4534  ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4535  ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4536  if (COp0 && COp0->isNullValue())
4537    Op = Op1;
4538  else if (COp1 && COp1->isNullValue())
4539    Op = Op0;
4540  else
4541    return false;
4542
4543  DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4544
4545  if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4546    return false;
4547
4548  return true;
4549}
4550
4551SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4552  SDValue N0 = N->getOperand(0);
4553  EVT VT = N->getValueType(0);
4554
4555  // fold (zext c1) -> c1
4556  if (isa<ConstantSDNode>(N0))
4557    return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4558  // fold (zext (zext x)) -> (zext x)
4559  // fold (zext (aext x)) -> (zext x)
4560  if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4561    return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
4562                       N0.getOperand(0));
4563
4564  // fold (zext (truncate x)) -> (zext x) or
4565  //      (zext (truncate x)) -> (truncate x)
4566  // This is valid when the truncated bits of x are already zero.
4567  // FIXME: We should extend this to work for vectors too.
4568  SDValue Op;
4569  APInt KnownZero;
4570  if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4571    APInt TruncatedBits =
4572      (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4573      APInt(Op.getValueSizeInBits(), 0) :
4574      APInt::getBitsSet(Op.getValueSizeInBits(),
4575                        N0.getValueSizeInBits(),
4576                        std::min(Op.getValueSizeInBits(),
4577                                 VT.getSizeInBits()));
4578    if (TruncatedBits == (KnownZero & TruncatedBits)) {
4579      if (VT.bitsGT(Op.getValueType()))
4580        return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op);
4581      if (VT.bitsLT(Op.getValueType()))
4582        return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4583
4584      return Op;
4585    }
4586  }
4587
4588  // fold (zext (truncate (load x))) -> (zext (smaller load x))
4589  // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4590  if (N0.getOpcode() == ISD::TRUNCATE) {
4591    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4592    if (NarrowLoad.getNode()) {
4593      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4594      if (NarrowLoad.getNode() != N0.getNode()) {
4595        CombineTo(N0.getNode(), NarrowLoad);
4596        // CombineTo deleted the truncate, if needed, but not what's under it.
4597        AddToWorkList(oye);
4598      }
4599      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4600    }
4601  }
4602
4603  // fold (zext (truncate x)) -> (and x, mask)
4604  if (N0.getOpcode() == ISD::TRUNCATE &&
4605      (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4606
4607    // fold (zext (truncate (load x))) -> (zext (smaller load x))
4608    // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4609    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4610    if (NarrowLoad.getNode()) {
4611      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4612      if (NarrowLoad.getNode() != N0.getNode()) {
4613        CombineTo(N0.getNode(), NarrowLoad);
4614        // CombineTo deleted the truncate, if needed, but not what's under it.
4615        AddToWorkList(oye);
4616      }
4617      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4618    }
4619
4620    SDValue Op = N0.getOperand(0);
4621    if (Op.getValueType().bitsLT(VT)) {
4622      Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
4623      AddToWorkList(Op.getNode());
4624    } else if (Op.getValueType().bitsGT(VT)) {
4625      Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4626      AddToWorkList(Op.getNode());
4627    }
4628    return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
4629                                  N0.getValueType().getScalarType());
4630  }
4631
4632  // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4633  // if either of the casts is not free.
4634  if (N0.getOpcode() == ISD::AND &&
4635      N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4636      N0.getOperand(1).getOpcode() == ISD::Constant &&
4637      (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4638                           N0.getValueType()) ||
4639       !TLI.isZExtFree(N0.getValueType(), VT))) {
4640    SDValue X = N0.getOperand(0).getOperand(0);
4641    if (X.getValueType().bitsLT(VT)) {
4642      X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4643    } else if (X.getValueType().bitsGT(VT)) {
4644      X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4645    }
4646    APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4647    Mask = Mask.zext(VT.getSizeInBits());
4648    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4649                       X, DAG.getConstant(Mask, VT));
4650  }
4651
4652  // fold (zext (load x)) -> (zext (truncate (zextload x)))
4653  // None of the supported targets knows how to perform load and vector_zext
4654  // on vectors in one instruction.  We only perform this transformation on
4655  // scalars.
4656  if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4657      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4658       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4659    bool DoXform = true;
4660    SmallVector<SDNode*, 4> SetCCs;
4661    if (!N0.hasOneUse())
4662      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4663    if (DoXform) {
4664      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4665      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4666                                       LN0->getChain(),
4667                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4668                                       N0.getValueType(),
4669                                       LN0->isVolatile(), LN0->isNonTemporal(),
4670                                       LN0->getAlignment());
4671      CombineTo(N, ExtLoad);
4672      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4673                                  N0.getValueType(), ExtLoad);
4674      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4675
4676      ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4677                      ISD::ZERO_EXTEND);
4678      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4679    }
4680  }
4681
4682  // fold (zext (and/or/xor (load x), cst)) ->
4683  //      (and/or/xor (zextload x), (zext cst))
4684  if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4685       N0.getOpcode() == ISD::XOR) &&
4686      isa<LoadSDNode>(N0.getOperand(0)) &&
4687      N0.getOperand(1).getOpcode() == ISD::Constant &&
4688      TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4689      (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4690    LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4691    if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4692      bool DoXform = true;
4693      SmallVector<SDNode*, 4> SetCCs;
4694      if (!N0.hasOneUse())
4695        DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4696                                          SetCCs, TLI);
4697      if (DoXform) {
4698        SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4699                                         LN0->getChain(), LN0->getBasePtr(),
4700                                         LN0->getPointerInfo(),
4701                                         LN0->getMemoryVT(),
4702                                         LN0->isVolatile(),
4703                                         LN0->isNonTemporal(),
4704                                         LN0->getAlignment());
4705        APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4706        Mask = Mask.zext(VT.getSizeInBits());
4707        SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4708                                  ExtLoad, DAG.getConstant(Mask, VT));
4709        SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4710                                    N0.getOperand(0).getDebugLoc(),
4711                                    N0.getOperand(0).getValueType(), ExtLoad);
4712        CombineTo(N, And);
4713        CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4714        ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4715                        ISD::ZERO_EXTEND);
4716        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4717      }
4718    }
4719  }
4720
4721  // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4722  // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4723  if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4724      ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4725    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4726    EVT MemVT = LN0->getMemoryVT();
4727    if ((!LegalOperations && !LN0->isVolatile()) ||
4728        TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4729      SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4730                                       LN0->getChain(),
4731                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4732                                       MemVT,
4733                                       LN0->isVolatile(), LN0->isNonTemporal(),
4734                                       LN0->getAlignment());
4735      CombineTo(N, ExtLoad);
4736      CombineTo(N0.getNode(),
4737                DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4738                            ExtLoad),
4739                ExtLoad.getValue(1));
4740      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4741    }
4742  }
4743
4744  if (N0.getOpcode() == ISD::SETCC) {
4745    if (!LegalOperations && VT.isVector()) {
4746      // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4747      // Only do this before legalize for now.
4748      EVT N0VT = N0.getOperand(0).getValueType();
4749      EVT EltVT = VT.getVectorElementType();
4750      SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4751                                    DAG.getConstant(1, EltVT));
4752      if (VT.getSizeInBits() == N0VT.getSizeInBits())
4753        // We know that the # elements of the results is the same as the
4754        // # elements of the compare (and the # elements of the compare result
4755        // for that matter).  Check to see that they are the same size.  If so,
4756        // we know that the element size of the sext'd result matches the
4757        // element size of the compare operands.
4758        return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4759                           DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4760                                         N0.getOperand(1),
4761                                 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4762                           DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4763                                       &OneOps[0], OneOps.size()));
4764
4765      // If the desired elements are smaller or larger than the source
4766      // elements we can use a matching integer vector type and then
4767      // truncate/sign extend
4768      EVT MatchingElementType =
4769        EVT::getIntegerVT(*DAG.getContext(),
4770                          N0VT.getScalarType().getSizeInBits());
4771      EVT MatchingVectorType =
4772        EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4773                         N0VT.getVectorNumElements());
4774      SDValue VsetCC =
4775        DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4776                      N0.getOperand(1),
4777                      cast<CondCodeSDNode>(N0.getOperand(2))->get());
4778      return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4779                         DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4780                         DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4781                                     &OneOps[0], OneOps.size()));
4782    }
4783
4784    // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4785    SDValue SCC =
4786      SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4787                       DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4788                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4789    if (SCC.getNode()) return SCC;
4790  }
4791
4792  // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4793  if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4794      isa<ConstantSDNode>(N0.getOperand(1)) &&
4795      N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4796      N0.hasOneUse()) {
4797    SDValue ShAmt = N0.getOperand(1);
4798    unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4799    if (N0.getOpcode() == ISD::SHL) {
4800      SDValue InnerZExt = N0.getOperand(0);
4801      // If the original shl may be shifting out bits, do not perform this
4802      // transformation.
4803      unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4804        InnerZExt.getOperand(0).getValueType().getSizeInBits();
4805      if (ShAmtVal > KnownZeroBits)
4806        return SDValue();
4807    }
4808
4809    DebugLoc DL = N->getDebugLoc();
4810
4811    // Ensure that the shift amount is wide enough for the shifted value.
4812    if (VT.getSizeInBits() >= 256)
4813      ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4814
4815    return DAG.getNode(N0.getOpcode(), DL, VT,
4816                       DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4817                       ShAmt);
4818  }
4819
4820  return SDValue();
4821}
4822
4823SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4824  SDValue N0 = N->getOperand(0);
4825  EVT VT = N->getValueType(0);
4826
4827  // fold (aext c1) -> c1
4828  if (isa<ConstantSDNode>(N0))
4829    return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4830  // fold (aext (aext x)) -> (aext x)
4831  // fold (aext (zext x)) -> (zext x)
4832  // fold (aext (sext x)) -> (sext x)
4833  if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4834      N0.getOpcode() == ISD::ZERO_EXTEND ||
4835      N0.getOpcode() == ISD::SIGN_EXTEND)
4836    return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4837
4838  // fold (aext (truncate (load x))) -> (aext (smaller load x))
4839  // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4840  if (N0.getOpcode() == ISD::TRUNCATE) {
4841    SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4842    if (NarrowLoad.getNode()) {
4843      SDNode* oye = N0.getNode()->getOperand(0).getNode();
4844      if (NarrowLoad.getNode() != N0.getNode()) {
4845        CombineTo(N0.getNode(), NarrowLoad);
4846        // CombineTo deleted the truncate, if needed, but not what's under it.
4847        AddToWorkList(oye);
4848      }
4849      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4850    }
4851  }
4852
4853  // fold (aext (truncate x))
4854  if (N0.getOpcode() == ISD::TRUNCATE) {
4855    SDValue TruncOp = N0.getOperand(0);
4856    if (TruncOp.getValueType() == VT)
4857      return TruncOp; // x iff x size == zext size.
4858    if (TruncOp.getValueType().bitsGT(VT))
4859      return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4860    return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4861  }
4862
4863  // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4864  // if the trunc is not free.
4865  if (N0.getOpcode() == ISD::AND &&
4866      N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4867      N0.getOperand(1).getOpcode() == ISD::Constant &&
4868      !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4869                          N0.getValueType())) {
4870    SDValue X = N0.getOperand(0).getOperand(0);
4871    if (X.getValueType().bitsLT(VT)) {
4872      X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4873    } else if (X.getValueType().bitsGT(VT)) {
4874      X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4875    }
4876    APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4877    Mask = Mask.zext(VT.getSizeInBits());
4878    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4879                       X, DAG.getConstant(Mask, VT));
4880  }
4881
4882  // fold (aext (load x)) -> (aext (truncate (extload x)))
4883  // None of the supported targets knows how to perform load and any_ext
4884  // on vectors in one instruction.  We only perform this transformation on
4885  // scalars.
4886  if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4887      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4888       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4889    bool DoXform = true;
4890    SmallVector<SDNode*, 4> SetCCs;
4891    if (!N0.hasOneUse())
4892      DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4893    if (DoXform) {
4894      LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4895      SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4896                                       LN0->getChain(),
4897                                       LN0->getBasePtr(), LN0->getPointerInfo(),
4898                                       N0.getValueType(),
4899                                       LN0->isVolatile(), LN0->isNonTemporal(),
4900                                       LN0->getAlignment());
4901      CombineTo(N, ExtLoad);
4902      SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4903                                  N0.getValueType(), ExtLoad);
4904      CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4905      ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4906                      ISD::ANY_EXTEND);
4907      return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4908    }
4909  }
4910
4911  // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4912  // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4913  // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
4914  if (N0.getOpcode() == ISD::LOAD &&
4915      !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4916      N0.hasOneUse()) {
4917    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4918    EVT MemVT = LN0->getMemoryVT();
4919    SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4920                                     VT, LN0->getChain(), LN0->getBasePtr(),
4921                                     LN0->getPointerInfo(), MemVT,
4922                                     LN0->isVolatile(), LN0->isNonTemporal(),
4923                                     LN0->getAlignment());
4924    CombineTo(N, ExtLoad);
4925    CombineTo(N0.getNode(),
4926              DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4927                          N0.getValueType(), ExtLoad),
4928              ExtLoad.getValue(1));
4929    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4930  }
4931
4932  if (N0.getOpcode() == ISD::SETCC) {
4933    // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4934    // Only do this before legalize for now.
4935    if (VT.isVector() && !LegalOperations) {
4936      EVT N0VT = N0.getOperand(0).getValueType();
4937        // We know that the # elements of the results is the same as the
4938        // # elements of the compare (and the # elements of the compare result
4939        // for that matter).  Check to see that they are the same size.  If so,
4940        // we know that the element size of the sext'd result matches the
4941        // element size of the compare operands.
4942      if (VT.getSizeInBits() == N0VT.getSizeInBits())
4943        return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4944                             N0.getOperand(1),
4945                             cast<CondCodeSDNode>(N0.getOperand(2))->get());
4946      // If the desired elements are smaller or larger than the source
4947      // elements we can use a matching integer vector type and then
4948      // truncate/sign extend
4949      else {
4950        EVT MatchingElementType =
4951          EVT::getIntegerVT(*DAG.getContext(),
4952                            N0VT.getScalarType().getSizeInBits());
4953        EVT MatchingVectorType =
4954          EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4955                           N0VT.getVectorNumElements());
4956        SDValue VsetCC =
4957          DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4958                        N0.getOperand(1),
4959                        cast<CondCodeSDNode>(N0.getOperand(2))->get());
4960        return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4961      }
4962    }
4963
4964    // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4965    SDValue SCC =
4966      SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4967                       DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4968                       cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4969    if (SCC.getNode())
4970      return SCC;
4971  }
4972
4973  return SDValue();
4974}
4975
4976/// GetDemandedBits - See if the specified operand can be simplified with the
4977/// knowledge that only the bits specified by Mask are used.  If so, return the
4978/// simpler operand, otherwise return a null SDValue.
4979SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4980  switch (V.getOpcode()) {
4981  default: break;
4982  case ISD::Constant: {
4983    const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
4984    assert(CV != 0 && "Const value should be ConstSDNode.");
4985    const APInt &CVal = CV->getAPIntValue();
4986    APInt NewVal = CVal & Mask;
4987    if (NewVal != CVal) {
4988      return DAG.getConstant(NewVal, V.getValueType());
4989    }
4990    break;
4991  }
4992  case ISD::OR:
4993  case ISD::XOR:
4994    // If the LHS or RHS don't contribute bits to the or, drop them.
4995    if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4996      return V.getOperand(1);
4997    if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4998      return V.getOperand(0);
4999    break;
5000  case ISD::SRL:
5001    // Only look at single-use SRLs.
5002    if (!V.getNode()->hasOneUse())
5003      break;
5004    if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5005      // See if we can recursively simplify the LHS.
5006      unsigned Amt = RHSC->getZExtValue();
5007
5008      // Watch out for shift count overflow though.
5009      if (Amt >= Mask.getBitWidth()) break;
5010      APInt NewMask = Mask << Amt;
5011      SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5012      if (SimplifyLHS.getNode())
5013        return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
5014                           SimplifyLHS, V.getOperand(1));
5015    }
5016  }
5017  return SDValue();
5018}
5019
5020/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5021/// bits and then truncated to a narrower type and where N is a multiple
5022/// of number of bits of the narrower type, transform it to a narrower load
5023/// from address + N / num of bits of new type. If the result is to be
5024/// extended, also fold the extension to form a extending load.
5025SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5026  unsigned Opc = N->getOpcode();
5027
5028  ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5029  SDValue N0 = N->getOperand(0);
5030  EVT VT = N->getValueType(0);
5031  EVT ExtVT = VT;
5032
5033  // This transformation isn't valid for vector loads.
5034  if (VT.isVector())
5035    return SDValue();
5036
5037  // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5038  // extended to VT.
5039  if (Opc == ISD::SIGN_EXTEND_INREG) {
5040    ExtType = ISD::SEXTLOAD;
5041    ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5042  } else if (Opc == ISD::SRL) {
5043    // Another special-case: SRL is basically zero-extending a narrower value.
5044    ExtType = ISD::ZEXTLOAD;
5045    N0 = SDValue(N, 0);
5046    ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5047    if (!N01) return SDValue();
5048    ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5049                              VT.getSizeInBits() - N01->getZExtValue());
5050  }
5051  if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5052    return SDValue();
5053
5054  unsigned EVTBits = ExtVT.getSizeInBits();
5055
5056  // Do not generate loads of non-round integer types since these can
5057  // be expensive (and would be wrong if the type is not byte sized).
5058  if (!ExtVT.isRound())
5059    return SDValue();
5060
5061  unsigned ShAmt = 0;
5062  if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5063    if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5064      ShAmt = N01->getZExtValue();
5065      // Is the shift amount a multiple of size of VT?
5066      if ((ShAmt & (EVTBits-1)) == 0) {
5067        N0 = N0.getOperand(0);
5068        // Is the load width a multiple of size of VT?
5069        if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5070          return SDValue();
5071      }
5072
5073      // At this point, we must have a load or else we can't do the transform.
5074      if (!isa<LoadSDNode>(N0)) return SDValue();
5075
5076      // Because a SRL must be assumed to *need* to zero-extend the high bits
5077      // (as opposed to anyext the high bits), we can't combine the zextload
5078      // lowering of SRL and an sextload.
5079      if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5080        return SDValue();
5081
5082      // If the shift amount is larger than the input type then we're not
5083      // accessing any of the loaded bytes.  If the load was a zextload/extload
5084      // then the result of the shift+trunc is zero/undef (handled elsewhere).
5085      if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5086        return SDValue();
5087    }
5088  }
5089
5090  // If the load is shifted left (and the result isn't shifted back right),
5091  // we can fold the truncate through the shift.
5092  unsigned ShLeftAmt = 0;
5093  if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5094      ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5095    if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5096      ShLeftAmt = N01->getZExtValue();
5097      N0 = N0.getOperand(0);
5098    }
5099  }
5100
5101  // If we haven't found a load, we can't narrow it.  Don't transform one with
5102  // multiple uses, this would require adding a new load.
5103  if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5104    return SDValue();
5105
5106  // Don't change the width of a volatile load.
5107  LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5108  if (LN0->isVolatile())
5109    return SDValue();
5110
5111  // Verify that we are actually reducing a load width here.
5112  if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5113    return SDValue();
5114
5115  // For the transform to be legal, the load must produce only two values
5116  // (the value loaded and the chain).  Don't transform a pre-increment
5117  // load, for example, which produces an extra value.  Otherwise the
5118  // transformation is not equivalent, and the downstream logic to replace
5119  // uses gets things wrong.
5120  if (LN0->getNumValues() > 2)
5121    return SDValue();
5122
5123  EVT PtrType = N0.getOperand(1).getValueType();
5124
5125  if (PtrType == MVT::Untyped || PtrType.isExtended())
5126    // It's not possible to generate a constant of extended or untyped type.
5127    return SDValue();
5128
5129  // For big endian targets, we need to adjust the offset to the pointer to
5130  // load the correct bytes.
5131  if (TLI.isBigEndian()) {
5132    unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5133    unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5134    ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5135  }
5136
5137  uint64_t PtrOff = ShAmt / 8;
5138  unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5139  SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
5140                               PtrType, LN0->getBasePtr(),
5141                               DAG.getConstant(PtrOff, PtrType));
5142  AddToWorkList(NewPtr.getNode());
5143
5144  SDValue Load;
5145  if (ExtType == ISD::NON_EXTLOAD)
5146    Load =  DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
5147                        LN0->getPointerInfo().getWithOffset(PtrOff),
5148                        LN0->isVolatile(), LN0->isNonTemporal(),
5149                        LN0->isInvariant(), NewAlign);
5150  else
5151    Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
5152                          LN0->getPointerInfo().getWithOffset(PtrOff),
5153                          ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5154                          NewAlign);
5155
5156  // Replace the old load's chain with the new load's chain.
5157  WorkListRemover DeadNodes(*this);
5158  DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5159
5160  // Shift the result left, if we've swallowed a left shift.
5161  SDValue Result = Load;
5162  if (ShLeftAmt != 0) {
5163    EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5164    if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5165      ShImmTy = VT;
5166    Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
5167                         Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5168  }
5169
5170  // Return the new loaded value.
5171  return Result;
5172}
5173
5174SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5175  SDValue N0 = N->getOperand(0);
5176  SDValue N1 = N->getOperand(1);
5177  EVT VT = N->getValueType(0);
5178  EVT EVT = cast<VTSDNode>(N1)->getVT();
5179  unsigned VTBits = VT.getScalarType().getSizeInBits();
5180  unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5181
5182  // fold (sext_in_reg c1) -> c1
5183  if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5184    return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
5185
5186  // If the input is already sign extended, just drop the extension.
5187  if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5188    return N0;
5189
5190  // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5191  if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5192      EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
5193    return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5194                       N0.getOperand(0), N1);
5195  }
5196
5197  // fold (sext_in_reg (sext x)) -> (sext x)
5198  // fold (sext_in_reg (aext x)) -> (sext x)
5199  // if x is small enough.
5200  if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5201    SDValue N00 = N0.getOperand(0);
5202    if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5203        (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5204      return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
5205  }
5206
5207  // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5208  if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5209    return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
5210
5211  // fold operands of sext_in_reg based on knowledge that the top bits are not
5212  // demanded.
5213  if (SimplifyDemandedBits(SDValue(N, 0)))
5214    return SDValue(N, 0);
5215
5216  // fold (sext_in_reg (load x)) -> (smaller sextload x)
5217  // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5218  SDValue NarrowLoad = ReduceLoadWidth(N);
5219  if (NarrowLoad.getNode())
5220    return NarrowLoad;
5221
5222  // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5223  // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5224  // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5225  if (N0.getOpcode() == ISD::SRL) {
5226    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5227      if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5228        // We can turn this into an SRA iff the input to the SRL is already sign
5229        // extended enough.
5230        unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5231        if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5232          return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
5233                             N0.getOperand(0), N0.getOperand(1));
5234      }
5235  }
5236
5237  // fold (sext_inreg (extload x)) -> (sextload x)
5238  if (ISD::isEXTLoad(N0.getNode()) &&
5239      ISD::isUNINDEXEDLoad(N0.getNode()) &&
5240      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5241      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5242       TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5243    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5244    SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5245                                     LN0->getChain(),
5246                                     LN0->getBasePtr(), LN0->getPointerInfo(),
5247                                     EVT,
5248                                     LN0->isVolatile(), LN0->isNonTemporal(),
5249                                     LN0->getAlignment());
5250    CombineTo(N, ExtLoad);
5251    CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5252    AddToWorkList(ExtLoad.getNode());
5253    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5254  }
5255  // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5256  if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5257      N0.hasOneUse() &&
5258      EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5259      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5260       TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5261    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5262    SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5263                                     LN0->getChain(),
5264                                     LN0->getBasePtr(), LN0->getPointerInfo(),
5265                                     EVT,
5266                                     LN0->isVolatile(), LN0->isNonTemporal(),
5267                                     LN0->getAlignment());
5268    CombineTo(N, ExtLoad);
5269    CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5270    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5271  }
5272
5273  // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5274  if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5275    SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5276                                       N0.getOperand(1), false);
5277    if (BSwap.getNode() != 0)
5278      return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5279                         BSwap, N1);
5280  }
5281
5282  return SDValue();
5283}
5284
5285SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5286  SDValue N0 = N->getOperand(0);
5287  EVT VT = N->getValueType(0);
5288  bool isLE = TLI.isLittleEndian();
5289
5290  // noop truncate
5291  if (N0.getValueType() == N->getValueType(0))
5292    return N0;
5293  // fold (truncate c1) -> c1
5294  if (isa<ConstantSDNode>(N0))
5295    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
5296  // fold (truncate (truncate x)) -> (truncate x)
5297  if (N0.getOpcode() == ISD::TRUNCATE)
5298    return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5299  // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5300  if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5301      N0.getOpcode() == ISD::SIGN_EXTEND ||
5302      N0.getOpcode() == ISD::ANY_EXTEND) {
5303    if (N0.getOperand(0).getValueType().bitsLT(VT))
5304      // if the source is smaller than the dest, we still need an extend
5305      return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
5306                         N0.getOperand(0));
5307    if (N0.getOperand(0).getValueType().bitsGT(VT))
5308      // if the source is larger than the dest, than we just need the truncate
5309      return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5310    // if the source and dest are the same type, we can drop both the extend
5311    // and the truncate.
5312    return N0.getOperand(0);
5313  }
5314
5315  // Fold extract-and-trunc into a narrow extract. For example:
5316  //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5317  //   i32 y = TRUNCATE(i64 x)
5318  //        -- becomes --
5319  //   v16i8 b = BITCAST (v2i64 val)
5320  //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5321  //
5322  // Note: We only run this optimization after type legalization (which often
5323  // creates this pattern) and before operation legalization after which
5324  // we need to be more careful about the vector instructions that we generate.
5325  if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5326      LegalTypes && !LegalOperations && N0->hasOneUse()) {
5327
5328    EVT VecTy = N0.getOperand(0).getValueType();
5329    EVT ExTy = N0.getValueType();
5330    EVT TrTy = N->getValueType(0);
5331
5332    unsigned NumElem = VecTy.getVectorNumElements();
5333    unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5334
5335    EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5336    assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5337
5338    SDValue EltNo = N0->getOperand(1);
5339    if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5340      int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5341      EVT IndexTy = N0->getOperand(1).getValueType();
5342      int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5343
5344      SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5345                              NVT, N0.getOperand(0));
5346
5347      return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5348                         N->getDebugLoc(), TrTy, V,
5349                         DAG.getConstant(Index, IndexTy));
5350    }
5351  }
5352
5353  // See if we can simplify the input to this truncate through knowledge that
5354  // only the low bits are being used.
5355  // For example "trunc (or (shl x, 8), y)" // -> trunc y
5356  // Currently we only perform this optimization on scalars because vectors
5357  // may have different active low bits.
5358  if (!VT.isVector()) {
5359    SDValue Shorter =
5360      GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5361                                               VT.getSizeInBits()));
5362    if (Shorter.getNode())
5363      return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
5364  }
5365  // fold (truncate (load x)) -> (smaller load x)
5366  // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5367  if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5368    SDValue Reduced = ReduceLoadWidth(N);
5369    if (Reduced.getNode())
5370      return Reduced;
5371  }
5372  // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5373  // where ... are all 'undef'.
5374  if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5375    SmallVector<EVT, 8> VTs;
5376    SDValue V;
5377    unsigned Idx = 0;
5378    unsigned NumDefs = 0;
5379
5380    for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5381      SDValue X = N0.getOperand(i);
5382      if (X.getOpcode() != ISD::UNDEF) {
5383        V = X;
5384        Idx = i;
5385        NumDefs++;
5386      }
5387      // Stop if more than one members are non-undef.
5388      if (NumDefs > 1)
5389        break;
5390      VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5391                                     VT.getVectorElementType(),
5392                                     X.getValueType().getVectorNumElements()));
5393    }
5394
5395    if (NumDefs == 0)
5396      return DAG.getUNDEF(VT);
5397
5398    if (NumDefs == 1) {
5399      assert(V.getNode() && "The single defined operand is empty!");
5400      SmallVector<SDValue, 8> Opnds;
5401      for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5402        if (i != Idx) {
5403          Opnds.push_back(DAG.getUNDEF(VTs[i]));
5404          continue;
5405        }
5406        SDValue NV = DAG.getNode(ISD::TRUNCATE, V.getDebugLoc(), VTs[i], V);
5407        AddToWorkList(NV.getNode());
5408        Opnds.push_back(NV);
5409      }
5410      return DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
5411                         &Opnds[0], Opnds.size());
5412    }
5413  }
5414
5415  // Simplify the operands using demanded-bits information.
5416  if (!VT.isVector() &&
5417      SimplifyDemandedBits(SDValue(N, 0)))
5418    return SDValue(N, 0);
5419
5420  return SDValue();
5421}
5422
5423static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5424  SDValue Elt = N->getOperand(i);
5425  if (Elt.getOpcode() != ISD::MERGE_VALUES)
5426    return Elt.getNode();
5427  return Elt.getOperand(Elt.getResNo()).getNode();
5428}
5429
5430/// CombineConsecutiveLoads - build_pair (load, load) -> load
5431/// if load locations are consecutive.
5432SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5433  assert(N->getOpcode() == ISD::BUILD_PAIR);
5434
5435  LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5436  LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5437  if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5438      LD1->getPointerInfo().getAddrSpace() !=
5439         LD2->getPointerInfo().getAddrSpace())
5440    return SDValue();
5441  EVT LD1VT = LD1->getValueType(0);
5442
5443  if (ISD::isNON_EXTLoad(LD2) &&
5444      LD2->hasOneUse() &&
5445      // If both are volatile this would reduce the number of volatile loads.
5446      // If one is volatile it might be ok, but play conservative and bail out.
5447      !LD1->isVolatile() &&
5448      !LD2->isVolatile() &&
5449      DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5450    unsigned Align = LD1->getAlignment();
5451    unsigned NewAlign = TLI.getDataLayout()->
5452      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5453
5454    if (NewAlign <= Align &&
5455        (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5456      return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
5457                         LD1->getBasePtr(), LD1->getPointerInfo(),
5458                         false, false, false, Align);
5459  }
5460
5461  return SDValue();
5462}
5463
5464SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5465  SDValue N0 = N->getOperand(0);
5466  EVT VT = N->getValueType(0);
5467
5468  // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5469  // Only do this before legalize, since afterward the target may be depending
5470  // on the bitconvert.
5471  // First check to see if this is all constant.
5472  if (!LegalTypes &&
5473      N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5474      VT.isVector()) {
5475    bool isSimple = true;
5476    for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5477      if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5478          N0.getOperand(i).getOpcode() != ISD::Constant &&
5479          N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5480        isSimple = false;
5481        break;
5482      }
5483
5484    EVT DestEltVT = N->getValueType(0).getVectorElementType();
5485    assert(!DestEltVT.isVector() &&
5486           "Element type of vector ValueType must not be vector!");
5487    if (isSimple)
5488      return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5489  }
5490
5491  // If the input is a constant, let getNode fold it.
5492  if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5493    SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
5494    if (Res.getNode() != N) {
5495      if (!LegalOperations ||
5496          TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5497        return Res;
5498
5499      // Folding it resulted in an illegal node, and it's too late to
5500      // do that. Clean up the old node and forego the transformation.
5501      // Ideally this won't happen very often, because instcombine
5502      // and the earlier dagcombine runs (where illegal nodes are
5503      // permitted) should have folded most of them already.
5504      DAG.DeleteNode(Res.getNode());
5505    }
5506  }
5507
5508  // (conv (conv x, t1), t2) -> (conv x, t2)
5509  if (N0.getOpcode() == ISD::BITCAST)
5510    return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
5511                       N0.getOperand(0));
5512
5513  // fold (conv (load x)) -> (load (conv*)x)
5514  // If the resultant load doesn't need a higher alignment than the original!
5515  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5516      // Do not change the width of a volatile load.
5517      !cast<LoadSDNode>(N0)->isVolatile() &&
5518      (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5519    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5520    unsigned Align = TLI.getDataLayout()->
5521      getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5522    unsigned OrigAlign = LN0->getAlignment();
5523
5524    if (Align <= OrigAlign) {
5525      SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
5526                                 LN0->getBasePtr(), LN0->getPointerInfo(),
5527                                 LN0->isVolatile(), LN0->isNonTemporal(),
5528                                 LN0->isInvariant(), OrigAlign);
5529      AddToWorkList(N);
5530      CombineTo(N0.getNode(),
5531                DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5532                            N0.getValueType(), Load),
5533                Load.getValue(1));
5534      return Load;
5535    }
5536  }
5537
5538  // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5539  // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5540  // This often reduces constant pool loads.
5541  if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5542       (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5543      N0.getNode()->hasOneUse() && VT.isInteger() &&
5544      !VT.isVector() && !N0.getValueType().isVector()) {
5545    SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
5546                                  N0.getOperand(0));
5547    AddToWorkList(NewConv.getNode());
5548
5549    APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5550    if (N0.getOpcode() == ISD::FNEG)
5551      return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
5552                         NewConv, DAG.getConstant(SignBit, VT));
5553    assert(N0.getOpcode() == ISD::FABS);
5554    return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
5555                       NewConv, DAG.getConstant(~SignBit, VT));
5556  }
5557
5558  // fold (bitconvert (fcopysign cst, x)) ->
5559  //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5560  // Note that we don't handle (copysign x, cst) because this can always be
5561  // folded to an fneg or fabs.
5562  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5563      isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5564      VT.isInteger() && !VT.isVector()) {
5565    unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5566    EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5567    if (isTypeLegal(IntXVT)) {
5568      SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5569                              IntXVT, N0.getOperand(1));
5570      AddToWorkList(X.getNode());
5571
5572      // If X has a different width than the result/lhs, sext it or truncate it.
5573      unsigned VTWidth = VT.getSizeInBits();
5574      if (OrigXWidth < VTWidth) {
5575        X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
5576        AddToWorkList(X.getNode());
5577      } else if (OrigXWidth > VTWidth) {
5578        // To get the sign bit in the right place, we have to shift it right
5579        // before truncating.
5580        X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
5581                        X.getValueType(), X,
5582                        DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5583        AddToWorkList(X.getNode());
5584        X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
5585        AddToWorkList(X.getNode());
5586      }
5587
5588      APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5589      X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
5590                      X, DAG.getConstant(SignBit, VT));
5591      AddToWorkList(X.getNode());
5592
5593      SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5594                                VT, N0.getOperand(0));
5595      Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
5596                        Cst, DAG.getConstant(~SignBit, VT));
5597      AddToWorkList(Cst.getNode());
5598
5599      return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
5600    }
5601  }
5602
5603  // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5604  if (N0.getOpcode() == ISD::BUILD_PAIR) {
5605    SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5606    if (CombineLD.getNode())
5607      return CombineLD;
5608  }
5609
5610  return SDValue();
5611}
5612
5613SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5614  EVT VT = N->getValueType(0);
5615  return CombineConsecutiveLoads(N, VT);
5616}
5617
5618/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5619/// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5620/// destination element value type.
5621SDValue DAGCombiner::
5622ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5623  EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5624
5625  // If this is already the right type, we're done.
5626  if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5627
5628  unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5629  unsigned DstBitSize = DstEltVT.getSizeInBits();
5630
5631  // If this is a conversion of N elements of one type to N elements of another
5632  // type, convert each element.  This handles FP<->INT cases.
5633  if (SrcBitSize == DstBitSize) {
5634    EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5635                              BV->getValueType(0).getVectorNumElements());
5636
5637    // Due to the FP element handling below calling this routine recursively,
5638    // we can end up with a scalar-to-vector node here.
5639    if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5640      return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5641                         DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5642                                     DstEltVT, BV->getOperand(0)));
5643
5644    SmallVector<SDValue, 8> Ops;
5645    for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5646      SDValue Op = BV->getOperand(i);
5647      // If the vector element type is not legal, the BUILD_VECTOR operands
5648      // are promoted and implicitly truncated.  Make that explicit here.
5649      if (Op.getValueType() != SrcEltVT)
5650        Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
5651      Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5652                                DstEltVT, Op));
5653      AddToWorkList(Ops.back().getNode());
5654    }
5655    return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5656                       &Ops[0], Ops.size());
5657  }
5658
5659  // Otherwise, we're growing or shrinking the elements.  To avoid having to
5660  // handle annoying details of growing/shrinking FP values, we convert them to
5661  // int first.
5662  if (SrcEltVT.isFloatingPoint()) {
5663    // Convert the input float vector to a int vector where the elements are the
5664    // same sizes.
5665    assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5666    EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5667    BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5668    SrcEltVT = IntVT;
5669  }
5670
5671  // Now we know the input is an integer vector.  If the output is a FP type,
5672  // convert to integer first, then to FP of the right size.
5673  if (DstEltVT.isFloatingPoint()) {
5674    assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5675    EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5676    SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5677
5678    // Next, convert to FP elements of the same size.
5679    return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5680  }
5681
5682  // Okay, we know the src/dst types are both integers of differing types.
5683  // Handling growing first.
5684  assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5685  if (SrcBitSize < DstBitSize) {
5686    unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5687
5688    SmallVector<SDValue, 8> Ops;
5689    for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5690         i += NumInputsPerOutput) {
5691      bool isLE = TLI.isLittleEndian();
5692      APInt NewBits = APInt(DstBitSize, 0);
5693      bool EltIsUndef = true;
5694      for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5695        // Shift the previously computed bits over.
5696        NewBits <<= SrcBitSize;
5697        SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5698        if (Op.getOpcode() == ISD::UNDEF) continue;
5699        EltIsUndef = false;
5700
5701        NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5702                   zextOrTrunc(SrcBitSize).zext(DstBitSize);
5703      }
5704
5705      if (EltIsUndef)
5706        Ops.push_back(DAG.getUNDEF(DstEltVT));
5707      else
5708        Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5709    }
5710
5711    EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5712    return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5713                       &Ops[0], Ops.size());
5714  }
5715
5716  // Finally, this must be the case where we are shrinking elements: each input
5717  // turns into multiple outputs.
5718  bool isS2V = ISD::isScalarToVector(BV);
5719  unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5720  EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5721                            NumOutputsPerInput*BV->getNumOperands());
5722  SmallVector<SDValue, 8> Ops;
5723
5724  for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5725    if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5726      for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5727        Ops.push_back(DAG.getUNDEF(DstEltVT));
5728      continue;
5729    }
5730
5731    APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5732                  getAPIntValue().zextOrTrunc(SrcBitSize);
5733
5734    for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5735      APInt ThisVal = OpVal.trunc(DstBitSize);
5736      Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5737      if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5738        // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5739        return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5740                           Ops[0]);
5741      OpVal = OpVal.lshr(DstBitSize);
5742    }
5743
5744    // For big endian targets, swap the order of the pieces of each element.
5745    if (TLI.isBigEndian())
5746      std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5747  }
5748
5749  return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5750                     &Ops[0], Ops.size());
5751}
5752
5753SDValue DAGCombiner::visitFADD(SDNode *N) {
5754  SDValue N0 = N->getOperand(0);
5755  SDValue N1 = N->getOperand(1);
5756  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5757  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5758  EVT VT = N->getValueType(0);
5759
5760  // fold vector ops
5761  if (VT.isVector()) {
5762    SDValue FoldedVOp = SimplifyVBinOp(N);
5763    if (FoldedVOp.getNode()) return FoldedVOp;
5764  }
5765
5766  // fold (fadd c1, c2) -> c1 + c2
5767  if (N0CFP && N1CFP)
5768    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5769  // canonicalize constant to RHS
5770  if (N0CFP && !N1CFP)
5771    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5772  // fold (fadd A, 0) -> A
5773  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5774      N1CFP->getValueAPF().isZero())
5775    return N0;
5776  // fold (fadd A, (fneg B)) -> (fsub A, B)
5777  if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5778    isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5779    return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5780                       GetNegatedExpression(N1, DAG, LegalOperations));
5781  // fold (fadd (fneg A), B) -> (fsub B, A)
5782  if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5783    isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5784    return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5785                       GetNegatedExpression(N0, DAG, LegalOperations));
5786
5787  // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5788  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5789      N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5790      isa<ConstantFPSDNode>(N0.getOperand(1)))
5791    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5792                       DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5793                                   N0.getOperand(1), N1));
5794
5795  // If allow, fold (fadd (fneg x), x) -> 0.0
5796  if (DAG.getTarget().Options.UnsafeFPMath &&
5797      N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) {
5798    return DAG.getConstantFP(0.0, VT);
5799  }
5800
5801    // If allow, fold (fadd x, (fneg x)) -> 0.0
5802  if (DAG.getTarget().Options.UnsafeFPMath &&
5803      N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) {
5804    return DAG.getConstantFP(0.0, VT);
5805  }
5806
5807  // In unsafe math mode, we can fold chains of FADD's of the same value
5808  // into multiplications.  This transform is not safe in general because
5809  // we are reducing the number of rounding steps.
5810  if (DAG.getTarget().Options.UnsafeFPMath &&
5811      TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
5812      !N0CFP && !N1CFP) {
5813    if (N0.getOpcode() == ISD::FMUL) {
5814      ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
5815      ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
5816
5817      // (fadd (fmul c, x), x) -> (fmul c+1, x)
5818      if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
5819        SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5820                                     SDValue(CFP00, 0),
5821                                     DAG.getConstantFP(1.0, VT));
5822        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5823                           N1, NewCFP);
5824      }
5825
5826      // (fadd (fmul x, c), x) -> (fmul c+1, x)
5827      if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
5828        SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5829                                     SDValue(CFP01, 0),
5830                                     DAG.getConstantFP(1.0, VT));
5831        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5832                           N1, NewCFP);
5833      }
5834
5835      // (fadd (fadd x, x), x) -> (fmul 3.0, x)
5836      if (!CFP00 && !CFP01 && N0.getOperand(0) == N0.getOperand(1) &&
5837          N0.getOperand(0) == N1) {
5838        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5839                           N1, DAG.getConstantFP(3.0, VT));
5840      }
5841
5842      // (fadd (fmul c, x), (fadd x, x)) -> (fmul c+2, x)
5843      if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
5844          N1.getOperand(0) == N1.getOperand(1) &&
5845          N0.getOperand(1) == N1.getOperand(0)) {
5846        SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5847                                     SDValue(CFP00, 0),
5848                                     DAG.getConstantFP(2.0, VT));
5849        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5850                           N0.getOperand(1), NewCFP);
5851      }
5852
5853      // (fadd (fmul x, c), (fadd x, x)) -> (fmul c+2, x)
5854      if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
5855          N1.getOperand(0) == N1.getOperand(1) &&
5856          N0.getOperand(0) == N1.getOperand(0)) {
5857        SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5858                                     SDValue(CFP01, 0),
5859                                     DAG.getConstantFP(2.0, VT));
5860        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5861                           N0.getOperand(0), NewCFP);
5862      }
5863    }
5864
5865    if (N1.getOpcode() == ISD::FMUL) {
5866      ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
5867      ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
5868
5869      // (fadd x, (fmul c, x)) -> (fmul c+1, x)
5870      if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
5871        SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5872                                     SDValue(CFP10, 0),
5873                                     DAG.getConstantFP(1.0, VT));
5874        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5875                           N0, NewCFP);
5876      }
5877
5878      // (fadd x, (fmul x, c)) -> (fmul c+1, x)
5879      if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
5880        SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5881                                     SDValue(CFP11, 0),
5882                                     DAG.getConstantFP(1.0, VT));
5883        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5884                           N0, NewCFP);
5885      }
5886
5887      // (fadd x, (fadd x, x)) -> (fmul 3.0, x)
5888      if (!CFP10 && !CFP11 && N1.getOperand(0) == N1.getOperand(1) &&
5889          N1.getOperand(0) == N0) {
5890        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5891                           N0, DAG.getConstantFP(3.0, VT));
5892      }
5893
5894      // (fadd (fadd x, x), (fmul c, x)) -> (fmul c+2, x)
5895      if (CFP10 && !CFP11 && N1.getOpcode() == ISD::FADD &&
5896          N1.getOperand(0) == N1.getOperand(1) &&
5897          N0.getOperand(1) == N1.getOperand(0)) {
5898        SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5899                                     SDValue(CFP10, 0),
5900                                     DAG.getConstantFP(2.0, VT));
5901        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5902                           N0.getOperand(1), NewCFP);
5903      }
5904
5905      // (fadd (fadd x, x), (fmul x, c)) -> (fmul c+2, x)
5906      if (CFP11 && !CFP10 && N1.getOpcode() == ISD::FADD &&
5907          N1.getOperand(0) == N1.getOperand(1) &&
5908          N0.getOperand(0) == N1.getOperand(0)) {
5909        SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5910                                     SDValue(CFP11, 0),
5911                                     DAG.getConstantFP(2.0, VT));
5912        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5913                           N0.getOperand(0), NewCFP);
5914      }
5915    }
5916
5917    // (fadd (fadd x, x), (fadd x, x)) -> (fmul 4.0, x)
5918    if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
5919        N0.getOperand(0) == N0.getOperand(1) &&
5920        N1.getOperand(0) == N1.getOperand(1) &&
5921        N0.getOperand(0) == N1.getOperand(0)) {
5922      return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5923                         N0.getOperand(0),
5924                         DAG.getConstantFP(4.0, VT));
5925    }
5926  }
5927
5928  // FADD -> FMA combines:
5929  if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
5930       DAG.getTarget().Options.UnsafeFPMath) &&
5931      DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
5932      TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
5933
5934    // fold (fadd (fmul x, y), z) -> (fma x, y, z)
5935    if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
5936      return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5937                         N0.getOperand(0), N0.getOperand(1), N1);
5938    }
5939
5940    // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
5941    // Note: Commutes FADD operands.
5942    if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
5943      return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
5944                         N1.getOperand(0), N1.getOperand(1), N0);
5945    }
5946  }
5947
5948  return SDValue();
5949}
5950
5951SDValue DAGCombiner::visitFSUB(SDNode *N) {
5952  SDValue N0 = N->getOperand(0);
5953  SDValue N1 = N->getOperand(1);
5954  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5955  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5956  EVT VT = N->getValueType(0);
5957  DebugLoc dl = N->getDebugLoc();
5958
5959  // fold vector ops
5960  if (VT.isVector()) {
5961    SDValue FoldedVOp = SimplifyVBinOp(N);
5962    if (FoldedVOp.getNode()) return FoldedVOp;
5963  }
5964
5965  // fold (fsub c1, c2) -> c1-c2
5966  if (N0CFP && N1CFP)
5967    return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
5968  // fold (fsub A, 0) -> A
5969  if (DAG.getTarget().Options.UnsafeFPMath &&
5970      N1CFP && N1CFP->getValueAPF().isZero())
5971    return N0;
5972  // fold (fsub 0, B) -> -B
5973  if (DAG.getTarget().Options.UnsafeFPMath &&
5974      N0CFP && N0CFP->getValueAPF().isZero()) {
5975    if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5976      return GetNegatedExpression(N1, DAG, LegalOperations);
5977    if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5978      return DAG.getNode(ISD::FNEG, dl, VT, N1);
5979  }
5980  // fold (fsub A, (fneg B)) -> (fadd A, B)
5981  if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
5982    return DAG.getNode(ISD::FADD, dl, VT, N0,
5983                       GetNegatedExpression(N1, DAG, LegalOperations));
5984
5985  // If 'unsafe math' is enabled, fold
5986  //    (fsub x, x) -> 0.0 &
5987  //    (fsub x, (fadd x, y)) -> (fneg y) &
5988  //    (fsub x, (fadd y, x)) -> (fneg y)
5989  if (DAG.getTarget().Options.UnsafeFPMath) {
5990    if (N0 == N1)
5991      return DAG.getConstantFP(0.0f, VT);
5992
5993    if (N1.getOpcode() == ISD::FADD) {
5994      SDValue N10 = N1->getOperand(0);
5995      SDValue N11 = N1->getOperand(1);
5996
5997      if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
5998                                          &DAG.getTarget().Options))
5999        return GetNegatedExpression(N11, DAG, LegalOperations);
6000      else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6001                                               &DAG.getTarget().Options))
6002        return GetNegatedExpression(N10, DAG, LegalOperations);
6003    }
6004  }
6005
6006  // FSUB -> FMA combines:
6007  if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6008       DAG.getTarget().Options.UnsafeFPMath) &&
6009      DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
6010      TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
6011
6012    // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6013    if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
6014      return DAG.getNode(ISD::FMA, dl, VT,
6015                         N0.getOperand(0), N0.getOperand(1),
6016                         DAG.getNode(ISD::FNEG, dl, VT, N1));
6017    }
6018
6019    // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6020    // Note: Commutes FSUB operands.
6021    if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
6022      return DAG.getNode(ISD::FMA, dl, VT,
6023                         DAG.getNode(ISD::FNEG, dl, VT,
6024                         N1.getOperand(0)),
6025                         N1.getOperand(1), N0);
6026    }
6027
6028    // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6029    if (N0.getOpcode() == ISD::FNEG &&
6030        N0.getOperand(0).getOpcode() == ISD::FMUL &&
6031        N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6032      SDValue N00 = N0.getOperand(0).getOperand(0);
6033      SDValue N01 = N0.getOperand(0).getOperand(1);
6034      return DAG.getNode(ISD::FMA, dl, VT,
6035                         DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6036                         DAG.getNode(ISD::FNEG, dl, VT, N1));
6037    }
6038  }
6039
6040  return SDValue();
6041}
6042
6043SDValue DAGCombiner::visitFMUL(SDNode *N) {
6044  SDValue N0 = N->getOperand(0);
6045  SDValue N1 = N->getOperand(1);
6046  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6047  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6048  EVT VT = N->getValueType(0);
6049  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6050
6051  // fold vector ops
6052  if (VT.isVector()) {
6053    SDValue FoldedVOp = SimplifyVBinOp(N);
6054    if (FoldedVOp.getNode()) return FoldedVOp;
6055  }
6056
6057  // fold (fmul c1, c2) -> c1*c2
6058  if (N0CFP && N1CFP)
6059    return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
6060  // canonicalize constant to RHS
6061  if (N0CFP && !N1CFP)
6062    return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
6063  // fold (fmul A, 0) -> 0
6064  if (DAG.getTarget().Options.UnsafeFPMath &&
6065      N1CFP && N1CFP->getValueAPF().isZero())
6066    return N1;
6067  // fold (fmul A, 0) -> 0, vector edition.
6068  if (DAG.getTarget().Options.UnsafeFPMath &&
6069      ISD::isBuildVectorAllZeros(N1.getNode()))
6070    return N1;
6071  // fold (fmul A, 1.0) -> A
6072  if (N1CFP && N1CFP->isExactlyValue(1.0))
6073    return N0;
6074  // fold (fmul X, 2.0) -> (fadd X, X)
6075  if (N1CFP && N1CFP->isExactlyValue(+2.0))
6076    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
6077  // fold (fmul X, -1.0) -> (fneg X)
6078  if (N1CFP && N1CFP->isExactlyValue(-1.0))
6079    if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6080      return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
6081
6082  // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6083  if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6084                                       &DAG.getTarget().Options)) {
6085    if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6086                                         &DAG.getTarget().Options)) {
6087      // Both can be negated for free, check to see if at least one is cheaper
6088      // negated.
6089      if (LHSNeg == 2 || RHSNeg == 2)
6090        return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6091                           GetNegatedExpression(N0, DAG, LegalOperations),
6092                           GetNegatedExpression(N1, DAG, LegalOperations));
6093    }
6094  }
6095
6096  // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6097  if (DAG.getTarget().Options.UnsafeFPMath &&
6098      N1CFP && N0.getOpcode() == ISD::FMUL &&
6099      N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6100    return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
6101                       DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6102                                   N0.getOperand(1), N1));
6103
6104  return SDValue();
6105}
6106
6107SDValue DAGCombiner::visitFMA(SDNode *N) {
6108  SDValue N0 = N->getOperand(0);
6109  SDValue N1 = N->getOperand(1);
6110  SDValue N2 = N->getOperand(2);
6111  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6112  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6113  EVT VT = N->getValueType(0);
6114  DebugLoc dl = N->getDebugLoc();
6115
6116  if (DAG.getTarget().Options.UnsafeFPMath) {
6117    if (N0CFP && N0CFP->isZero())
6118      return N2;
6119    if (N1CFP && N1CFP->isZero())
6120      return N2;
6121  }
6122  if (N0CFP && N0CFP->isExactlyValue(1.0))
6123    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2);
6124  if (N1CFP && N1CFP->isExactlyValue(1.0))
6125    return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2);
6126
6127  // Canonicalize (fma c, x, y) -> (fma x, c, y)
6128  if (N0CFP && !N1CFP)
6129    return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2);
6130
6131  // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6132  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6133      N2.getOpcode() == ISD::FMUL &&
6134      N0 == N2.getOperand(0) &&
6135      N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6136    return DAG.getNode(ISD::FMUL, dl, VT, N0,
6137                       DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6138  }
6139
6140
6141  // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6142  if (DAG.getTarget().Options.UnsafeFPMath &&
6143      N0.getOpcode() == ISD::FMUL && N1CFP &&
6144      N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6145    return DAG.getNode(ISD::FMA, dl, VT,
6146                       N0.getOperand(0),
6147                       DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6148                       N2);
6149  }
6150
6151  // (fma x, 1, y) -> (fadd x, y)
6152  // (fma x, -1, y) -> (fadd (fneg x), y)
6153  if (N1CFP) {
6154    if (N1CFP->isExactlyValue(1.0))
6155      return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6156
6157    if (N1CFP->isExactlyValue(-1.0) &&
6158        (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6159      SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6160      AddToWorkList(RHSNeg.getNode());
6161      return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6162    }
6163  }
6164
6165  // (fma x, c, x) -> (fmul x, (c+1))
6166  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) {
6167    return DAG.getNode(ISD::FMUL, dl, VT,
6168                       N0,
6169                       DAG.getNode(ISD::FADD, dl, VT,
6170                                   N1, DAG.getConstantFP(1.0, VT)));
6171  }
6172
6173  // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6174  if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6175      N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
6176    return DAG.getNode(ISD::FMUL, dl, VT,
6177                       N0,
6178                       DAG.getNode(ISD::FADD, dl, VT,
6179                                   N1, DAG.getConstantFP(-1.0, VT)));
6180  }
6181
6182
6183  return SDValue();
6184}
6185
6186SDValue DAGCombiner::visitFDIV(SDNode *N) {
6187  SDValue N0 = N->getOperand(0);
6188  SDValue N1 = N->getOperand(1);
6189  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6190  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6191  EVT VT = N->getValueType(0);
6192  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6193
6194  // fold vector ops
6195  if (VT.isVector()) {
6196    SDValue FoldedVOp = SimplifyVBinOp(N);
6197    if (FoldedVOp.getNode()) return FoldedVOp;
6198  }
6199
6200  // fold (fdiv c1, c2) -> c1/c2
6201  if (N0CFP && N1CFP)
6202    return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
6203
6204  // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6205  if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6206    // Compute the reciprocal 1.0 / c2.
6207    APFloat N1APF = N1CFP->getValueAPF();
6208    APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6209    APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6210    // Only do the transform if the reciprocal is a legal fp immediate that
6211    // isn't too nasty (eg NaN, denormal, ...).
6212    if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6213        (!LegalOperations ||
6214         // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6215         // backend)... we should handle this gracefully after Legalize.
6216         // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6217         TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6218         TLI.isFPImmLegal(Recip, VT)))
6219      return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0,
6220                         DAG.getConstantFP(Recip, VT));
6221  }
6222
6223  // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6224  if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6225                                       &DAG.getTarget().Options)) {
6226    if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6227                                         &DAG.getTarget().Options)) {
6228      // Both can be negated for free, check to see if at least one is cheaper
6229      // negated.
6230      if (LHSNeg == 2 || RHSNeg == 2)
6231        return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
6232                           GetNegatedExpression(N0, DAG, LegalOperations),
6233                           GetNegatedExpression(N1, DAG, LegalOperations));
6234    }
6235  }
6236
6237  return SDValue();
6238}
6239
6240SDValue DAGCombiner::visitFREM(SDNode *N) {
6241  SDValue N0 = N->getOperand(0);
6242  SDValue N1 = N->getOperand(1);
6243  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6244  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6245  EVT VT = N->getValueType(0);
6246
6247  // fold (frem c1, c2) -> fmod(c1,c2)
6248  if (N0CFP && N1CFP)
6249    return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
6250
6251  return SDValue();
6252}
6253
6254SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6255  SDValue N0 = N->getOperand(0);
6256  SDValue N1 = N->getOperand(1);
6257  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6258  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6259  EVT VT = N->getValueType(0);
6260
6261  if (N0CFP && N1CFP)  // Constant fold
6262    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
6263
6264  if (N1CFP) {
6265    const APFloat& V = N1CFP->getValueAPF();
6266    // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6267    // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6268    if (!V.isNegative()) {
6269      if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6270        return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6271    } else {
6272      if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6273        return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
6274                           DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
6275    }
6276  }
6277
6278  // copysign(fabs(x), y) -> copysign(x, y)
6279  // copysign(fneg(x), y) -> copysign(x, y)
6280  // copysign(copysign(x,z), y) -> copysign(x, y)
6281  if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6282      N0.getOpcode() == ISD::FCOPYSIGN)
6283    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6284                       N0.getOperand(0), N1);
6285
6286  // copysign(x, abs(y)) -> abs(x)
6287  if (N1.getOpcode() == ISD::FABS)
6288    return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6289
6290  // copysign(x, copysign(y,z)) -> copysign(x, z)
6291  if (N1.getOpcode() == ISD::FCOPYSIGN)
6292    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6293                       N0, N1.getOperand(1));
6294
6295  // copysign(x, fp_extend(y)) -> copysign(x, y)
6296  // copysign(x, fp_round(y)) -> copysign(x, y)
6297  if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6298    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6299                       N0, N1.getOperand(0));
6300
6301  return SDValue();
6302}
6303
6304SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6305  SDValue N0 = N->getOperand(0);
6306  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6307  EVT VT = N->getValueType(0);
6308  EVT OpVT = N0.getValueType();
6309
6310  // fold (sint_to_fp c1) -> c1fp
6311  if (N0C &&
6312      // ...but only if the target supports immediate floating-point values
6313      (!LegalOperations ||
6314       TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6315    return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6316
6317  // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6318  // but UINT_TO_FP is legal on this target, try to convert.
6319  if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6320      TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6321    // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6322    if (DAG.SignBitIsZero(N0))
6323      return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6324  }
6325
6326  // The next optimizations are desireable only if SELECT_CC can be lowered.
6327  // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6328  // having to say they don't support SELECT_CC on every type the DAG knows
6329  // about, since there is no way to mark an opcode illegal at all value types
6330  // (See also visitSELECT)
6331  if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6332    // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6333    if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6334        !VT.isVector() &&
6335        (!LegalOperations ||
6336         TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6337      SDValue Ops[] =
6338        { N0.getOperand(0), N0.getOperand(1),
6339          DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6340          N0.getOperand(2) };
6341      return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6342    }
6343
6344    // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6345    //      (select_cc x, y, 1.0, 0.0,, cc)
6346    if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6347        N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6348        (!LegalOperations ||
6349         TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6350      SDValue Ops[] =
6351        { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6352          DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6353          N0.getOperand(0).getOperand(2) };
6354      return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6355    }
6356  }
6357
6358  return SDValue();
6359}
6360
6361SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6362  SDValue N0 = N->getOperand(0);
6363  ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6364  EVT VT = N->getValueType(0);
6365  EVT OpVT = N0.getValueType();
6366
6367  // fold (uint_to_fp c1) -> c1fp
6368  if (N0C &&
6369      // ...but only if the target supports immediate floating-point values
6370      (!LegalOperations ||
6371       TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6372    return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6373
6374  // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6375  // but SINT_TO_FP is legal on this target, try to convert.
6376  if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6377      TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6378    // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6379    if (DAG.SignBitIsZero(N0))
6380      return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6381  }
6382
6383  // The next optimizations are desireable only if SELECT_CC can be lowered.
6384  // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6385  // having to say they don't support SELECT_CC on every type the DAG knows
6386  // about, since there is no way to mark an opcode illegal at all value types
6387  // (See also visitSELECT)
6388  if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6389    // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6390
6391    if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6392        (!LegalOperations ||
6393         TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6394      SDValue Ops[] =
6395        { N0.getOperand(0), N0.getOperand(1),
6396          DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6397          N0.getOperand(2) };
6398      return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6399    }
6400  }
6401
6402  return SDValue();
6403}
6404
6405SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6406  SDValue N0 = N->getOperand(0);
6407  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6408  EVT VT = N->getValueType(0);
6409
6410  // fold (fp_to_sint c1fp) -> c1
6411  if (N0CFP)
6412    return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
6413
6414  return SDValue();
6415}
6416
6417SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6418  SDValue N0 = N->getOperand(0);
6419  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6420  EVT VT = N->getValueType(0);
6421
6422  // fold (fp_to_uint c1fp) -> c1
6423  if (N0CFP)
6424    return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
6425
6426  return SDValue();
6427}
6428
6429SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6430  SDValue N0 = N->getOperand(0);
6431  SDValue N1 = N->getOperand(1);
6432  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6433  EVT VT = N->getValueType(0);
6434
6435  // fold (fp_round c1fp) -> c1fp
6436  if (N0CFP)
6437    return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
6438
6439  // fold (fp_round (fp_extend x)) -> x
6440  if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6441    return N0.getOperand(0);
6442
6443  // fold (fp_round (fp_round x)) -> (fp_round x)
6444  if (N0.getOpcode() == ISD::FP_ROUND) {
6445    // This is a value preserving truncation if both round's are.
6446    bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6447                   N0.getNode()->getConstantOperandVal(1) == 1;
6448    return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
6449                       DAG.getIntPtrConstant(IsTrunc));
6450  }
6451
6452  // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6453  if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6454    SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
6455                              N0.getOperand(0), N1);
6456    AddToWorkList(Tmp.getNode());
6457    return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6458                       Tmp, N0.getOperand(1));
6459  }
6460
6461  return SDValue();
6462}
6463
6464SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6465  SDValue N0 = N->getOperand(0);
6466  EVT VT = N->getValueType(0);
6467  EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6468  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6469
6470  // fold (fp_round_inreg c1fp) -> c1fp
6471  if (N0CFP && isTypeLegal(EVT)) {
6472    SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6473    return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
6474  }
6475
6476  return SDValue();
6477}
6478
6479SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6480  SDValue N0 = N->getOperand(0);
6481  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6482  EVT VT = N->getValueType(0);
6483
6484  // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6485  if (N->hasOneUse() &&
6486      N->use_begin()->getOpcode() == ISD::FP_ROUND)
6487    return SDValue();
6488
6489  // fold (fp_extend c1fp) -> c1fp
6490  if (N0CFP)
6491    return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
6492
6493  // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6494  // value of X.
6495  if (N0.getOpcode() == ISD::FP_ROUND
6496      && N0.getNode()->getConstantOperandVal(1) == 1) {
6497    SDValue In = N0.getOperand(0);
6498    if (In.getValueType() == VT) return In;
6499    if (VT.bitsLT(In.getValueType()))
6500      return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
6501                         In, N0.getOperand(1));
6502    return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
6503  }
6504
6505  // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6506  if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6507      ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6508       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6509    LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6510    SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
6511                                     LN0->getChain(),
6512                                     LN0->getBasePtr(), LN0->getPointerInfo(),
6513                                     N0.getValueType(),
6514                                     LN0->isVolatile(), LN0->isNonTemporal(),
6515                                     LN0->getAlignment());
6516    CombineTo(N, ExtLoad);
6517    CombineTo(N0.getNode(),
6518              DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
6519                          N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6520              ExtLoad.getValue(1));
6521    return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6522  }
6523
6524  return SDValue();
6525}
6526
6527SDValue DAGCombiner::visitFNEG(SDNode *N) {
6528  SDValue N0 = N->getOperand(0);
6529  EVT VT = N->getValueType(0);
6530
6531  if (VT.isVector()) {
6532    SDValue FoldedVOp = SimplifyVUnaryOp(N);
6533    if (FoldedVOp.getNode()) return FoldedVOp;
6534  }
6535
6536  if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6537                         &DAG.getTarget().Options))
6538    return GetNegatedExpression(N0, DAG, LegalOperations);
6539
6540  // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6541  // constant pool values.
6542  if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6543      !VT.isVector() &&
6544      N0.getNode()->hasOneUse() &&
6545      N0.getOperand(0).getValueType().isInteger()) {
6546    SDValue Int = N0.getOperand(0);
6547    EVT IntVT = Int.getValueType();
6548    if (IntVT.isInteger() && !IntVT.isVector()) {
6549      Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
6550              DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6551      AddToWorkList(Int.getNode());
6552      return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6553                         VT, Int);
6554    }
6555  }
6556
6557  // (fneg (fmul c, x)) -> (fmul -c, x)
6558  if (N0.getOpcode() == ISD::FMUL) {
6559    ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6560    if (CFP1) {
6561      return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6562                         N0.getOperand(0),
6563                         DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
6564                                     N0.getOperand(1)));
6565    }
6566  }
6567
6568  return SDValue();
6569}
6570
6571SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6572  SDValue N0 = N->getOperand(0);
6573  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6574  EVT VT = N->getValueType(0);
6575
6576  // fold (fceil c1) -> fceil(c1)
6577  if (N0CFP)
6578    return DAG.getNode(ISD::FCEIL, N->getDebugLoc(), VT, N0);
6579
6580  return SDValue();
6581}
6582
6583SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6584  SDValue N0 = N->getOperand(0);
6585  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6586  EVT VT = N->getValueType(0);
6587
6588  // fold (ftrunc c1) -> ftrunc(c1)
6589  if (N0CFP)
6590    return DAG.getNode(ISD::FTRUNC, N->getDebugLoc(), VT, N0);
6591
6592  return SDValue();
6593}
6594
6595SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6596  SDValue N0 = N->getOperand(0);
6597  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6598  EVT VT = N->getValueType(0);
6599
6600  // fold (ffloor c1) -> ffloor(c1)
6601  if (N0CFP)
6602    return DAG.getNode(ISD::FFLOOR, N->getDebugLoc(), VT, N0);
6603
6604  return SDValue();
6605}
6606
6607SDValue DAGCombiner::visitFABS(SDNode *N) {
6608  SDValue N0 = N->getOperand(0);
6609  ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6610  EVT VT = N->getValueType(0);
6611
6612  if (VT.isVector()) {
6613    SDValue FoldedVOp = SimplifyVUnaryOp(N);
6614    if (FoldedVOp.getNode()) return FoldedVOp;
6615  }
6616
6617  // fold (fabs c1) -> fabs(c1)
6618  if (N0CFP)
6619    return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6620  // fold (fabs (fabs x)) -> (fabs x)
6621  if (N0.getOpcode() == ISD::FABS)
6622    return N->getOperand(0);
6623  // fold (fabs (fneg x)) -> (fabs x)
6624  // fold (fabs (fcopysign x, y)) -> (fabs x)
6625  if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6626    return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
6627
6628  // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6629  // constant pool values.
6630  if (!TLI.isFAbsFree(VT) &&
6631      N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6632      N0.getOperand(0).getValueType().isInteger() &&
6633      !N0.getOperand(0).getValueType().isVector()) {
6634    SDValue Int = N0.getOperand(0);
6635    EVT IntVT = Int.getValueType();
6636    if (IntVT.isInteger() && !IntVT.isVector()) {
6637      Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
6638             DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6639      AddToWorkList(Int.getNode());
6640      return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6641                         N->getValueType(0), Int);
6642    }
6643  }
6644
6645  return SDValue();
6646}
6647
6648SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6649  SDValue Chain = N->getOperand(0);
6650  SDValue N1 = N->getOperand(1);
6651  SDValue N2 = N->getOperand(2);
6652
6653  // If N is a constant we could fold this into a fallthrough or unconditional
6654  // branch. However that doesn't happen very often in normal code, because
6655  // Instcombine/SimplifyCFG should have handled the available opportunities.
6656  // If we did this folding here, it would be necessary to update the
6657  // MachineBasicBlock CFG, which is awkward.
6658
6659  // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6660  // on the target.
6661  if (N1.getOpcode() == ISD::SETCC &&
6662      TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
6663    return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6664                       Chain, N1.getOperand(2),
6665                       N1.getOperand(0), N1.getOperand(1), N2);
6666  }
6667
6668  if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6669      ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6670       (N1.getOperand(0).hasOneUse() &&
6671        N1.getOperand(0).getOpcode() == ISD::SRL))) {
6672    SDNode *Trunc = 0;
6673    if (N1.getOpcode() == ISD::TRUNCATE) {
6674      // Look pass the truncate.
6675      Trunc = N1.getNode();
6676      N1 = N1.getOperand(0);
6677    }
6678
6679    // Match this pattern so that we can generate simpler code:
6680    //
6681    //   %a = ...
6682    //   %b = and i32 %a, 2
6683    //   %c = srl i32 %b, 1
6684    //   brcond i32 %c ...
6685    //
6686    // into
6687    //
6688    //   %a = ...
6689    //   %b = and i32 %a, 2
6690    //   %c = setcc eq %b, 0
6691    //   brcond %c ...
6692    //
6693    // This applies only when the AND constant value has one bit set and the
6694    // SRL constant is equal to the log2 of the AND constant. The back-end is
6695    // smart enough to convert the result into a TEST/JMP sequence.
6696    SDValue Op0 = N1.getOperand(0);
6697    SDValue Op1 = N1.getOperand(1);
6698
6699    if (Op0.getOpcode() == ISD::AND &&
6700        Op1.getOpcode() == ISD::Constant) {
6701      SDValue AndOp1 = Op0.getOperand(1);
6702
6703      if (AndOp1.getOpcode() == ISD::Constant) {
6704        const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6705
6706        if (AndConst.isPowerOf2() &&
6707            cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6708          SDValue SetCC =
6709            DAG.getSetCC(N->getDebugLoc(),
6710                         TLI.getSetCCResultType(Op0.getValueType()),
6711                         Op0, DAG.getConstant(0, Op0.getValueType()),
6712                         ISD::SETNE);
6713
6714          SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6715                                          MVT::Other, Chain, SetCC, N2);
6716          // Don't add the new BRCond into the worklist or else SimplifySelectCC
6717          // will convert it back to (X & C1) >> C2.
6718          CombineTo(N, NewBRCond, false);
6719          // Truncate is dead.
6720          if (Trunc) {
6721            removeFromWorkList(Trunc);
6722            DAG.DeleteNode(Trunc);
6723          }
6724          // Replace the uses of SRL with SETCC
6725          WorkListRemover DeadNodes(*this);
6726          DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6727          removeFromWorkList(N1.getNode());
6728          DAG.DeleteNode(N1.getNode());
6729          return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6730        }
6731      }
6732    }
6733
6734    if (Trunc)
6735      // Restore N1 if the above transformation doesn't match.
6736      N1 = N->getOperand(1);
6737  }
6738
6739  // Transform br(xor(x, y)) -> br(x != y)
6740  // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6741  if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6742    SDNode *TheXor = N1.getNode();
6743    SDValue Op0 = TheXor->getOperand(0);
6744    SDValue Op1 = TheXor->getOperand(1);
6745    if (Op0.getOpcode() == Op1.getOpcode()) {
6746      // Avoid missing important xor optimizations.
6747      SDValue Tmp = visitXOR(TheXor);
6748      if (Tmp.getNode()) {
6749        if (Tmp.getNode() != TheXor) {
6750          DEBUG(dbgs() << "\nReplacing.8 ";
6751                TheXor->dump(&DAG);
6752                dbgs() << "\nWith: ";
6753                Tmp.getNode()->dump(&DAG);
6754                dbgs() << '\n');
6755          WorkListRemover DeadNodes(*this);
6756          DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6757          removeFromWorkList(TheXor);
6758          DAG.DeleteNode(TheXor);
6759          return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6760                             MVT::Other, Chain, Tmp, N2);
6761        }
6762
6763        // visitXOR has changed XOR's operands.
6764        Op0 = TheXor->getOperand(0);
6765        Op1 = TheXor->getOperand(1);
6766      }
6767    }
6768
6769    if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6770      bool Equal = false;
6771      if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6772        if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6773            Op0.getOpcode() == ISD::XOR) {
6774          TheXor = Op0.getNode();
6775          Equal = true;
6776        }
6777
6778      EVT SetCCVT = N1.getValueType();
6779      if (LegalTypes)
6780        SetCCVT = TLI.getSetCCResultType(SetCCVT);
6781      SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
6782                                   SetCCVT,
6783                                   Op0, Op1,
6784                                   Equal ? ISD::SETEQ : ISD::SETNE);
6785      // Replace the uses of XOR with SETCC
6786      WorkListRemover DeadNodes(*this);
6787      DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6788      removeFromWorkList(N1.getNode());
6789      DAG.DeleteNode(N1.getNode());
6790      return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6791                         MVT::Other, Chain, SetCC, N2);
6792    }
6793  }
6794
6795  return SDValue();
6796}
6797
6798// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6799//
6800SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6801  CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6802  SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6803
6804  // If N is a constant we could fold this into a fallthrough or unconditional
6805  // branch. However that doesn't happen very often in normal code, because
6806  // Instcombine/SimplifyCFG should have handled the available opportunities.
6807  // If we did this folding here, it would be necessary to update the
6808  // MachineBasicBlock CFG, which is awkward.
6809
6810  // Use SimplifySetCC to simplify SETCC's.
6811  SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
6812                               CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
6813                               false);
6814  if (Simp.getNode()) AddToWorkList(Simp.getNode());
6815
6816  // fold to a simpler setcc
6817  if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6818    return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6819                       N->getOperand(0), Simp.getOperand(2),
6820                       Simp.getOperand(0), Simp.getOperand(1),
6821                       N->getOperand(4));
6822
6823  return SDValue();
6824}
6825
6826/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6827/// uses N as its base pointer and that N may be folded in the load / store
6828/// addressing mode.
6829static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6830                                    SelectionDAG &DAG,
6831                                    const TargetLowering &TLI) {
6832  EVT VT;
6833  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
6834    if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6835      return false;
6836    VT = Use->getValueType(0);
6837  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
6838    if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6839      return false;
6840    VT = ST->getValue().getValueType();
6841  } else
6842    return false;
6843
6844  TargetLowering::AddrMode AM;
6845  if (N->getOpcode() == ISD::ADD) {
6846    ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6847    if (Offset)
6848      // [reg +/- imm]
6849      AM.BaseOffs = Offset->getSExtValue();
6850    else
6851      // [reg +/- reg]
6852      AM.Scale = 1;
6853  } else if (N->getOpcode() == ISD::SUB) {
6854    ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6855    if (Offset)
6856      // [reg +/- imm]
6857      AM.BaseOffs = -Offset->getSExtValue();
6858    else
6859      // [reg +/- reg]
6860      AM.Scale = 1;
6861  } else
6862    return false;
6863
6864  return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
6865}
6866
6867/// CombineToPreIndexedLoadStore - Try turning a load / store into a
6868/// pre-indexed load / store when the base pointer is an add or subtract
6869/// and it has other uses besides the load / store. After the
6870/// transformation, the new indexed load / store has effectively folded
6871/// the add / subtract in and all of its other uses are redirected to the
6872/// new load / store.
6873bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
6874  if (Level < AfterLegalizeDAG)
6875    return false;
6876
6877  bool isLoad = true;
6878  SDValue Ptr;
6879  EVT VT;
6880  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
6881    if (LD->isIndexed())
6882      return false;
6883    VT = LD->getMemoryVT();
6884    if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
6885        !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
6886      return false;
6887    Ptr = LD->getBasePtr();
6888  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
6889    if (ST->isIndexed())
6890      return false;
6891    VT = ST->getMemoryVT();
6892    if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
6893        !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
6894      return false;
6895    Ptr = ST->getBasePtr();
6896    isLoad = false;
6897  } else {
6898    return false;
6899  }
6900
6901  // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
6902  // out.  There is no reason to make this a preinc/predec.
6903  if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
6904      Ptr.getNode()->hasOneUse())
6905    return false;
6906
6907  // Ask the target to do addressing mode selection.
6908  SDValue BasePtr;
6909  SDValue Offset;
6910  ISD::MemIndexedMode AM = ISD::UNINDEXED;
6911  if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
6912    return false;
6913  // Don't create a indexed load / store with zero offset.
6914  if (isa<ConstantSDNode>(Offset) &&
6915      cast<ConstantSDNode>(Offset)->isNullValue())
6916    return false;
6917
6918  // Try turning it into a pre-indexed load / store except when:
6919  // 1) The new base ptr is a frame index.
6920  // 2) If N is a store and the new base ptr is either the same as or is a
6921  //    predecessor of the value being stored.
6922  // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
6923  //    that would create a cycle.
6924  // 4) All uses are load / store ops that use it as old base ptr.
6925
6926  // Check #1.  Preinc'ing a frame index would require copying the stack pointer
6927  // (plus the implicit offset) to a register to preinc anyway.
6928  if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
6929    return false;
6930
6931  // Check #2.
6932  if (!isLoad) {
6933    SDValue Val = cast<StoreSDNode>(N)->getValue();
6934    if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
6935      return false;
6936  }
6937
6938  // Now check for #3 and #4.
6939  bool RealUse = false;
6940
6941  // Caches for hasPredecessorHelper
6942  SmallPtrSet<const SDNode *, 32> Visited;
6943  SmallVector<const SDNode *, 16> Worklist;
6944
6945  for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
6946         E = Ptr.getNode()->use_end(); I != E; ++I) {
6947    SDNode *Use = *I;
6948    if (Use == N)
6949      continue;
6950    if (N->hasPredecessorHelper(Use, Visited, Worklist))
6951      return false;
6952
6953    // If Ptr may be folded in addressing mode of other use, then it's
6954    // not profitable to do this transformation.
6955    if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
6956      RealUse = true;
6957  }
6958
6959  if (!RealUse)
6960    return false;
6961
6962  SDValue Result;
6963  if (isLoad)
6964    Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
6965                                BasePtr, Offset, AM);
6966  else
6967    Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
6968                                 BasePtr, Offset, AM);
6969  ++PreIndexedNodes;
6970  ++NodesCombined;
6971  DEBUG(dbgs() << "\nReplacing.4 ";
6972        N->dump(&DAG);
6973        dbgs() << "\nWith: ";
6974        Result.getNode()->dump(&DAG);
6975        dbgs() << '\n');
6976  WorkListRemover DeadNodes(*this);
6977  if (isLoad) {
6978    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
6979    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
6980  } else {
6981    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
6982  }
6983
6984  // Finally, since the node is now dead, remove it from the graph.
6985  DAG.DeleteNode(N);
6986
6987  // Replace the uses of Ptr with uses of the updated base value.
6988  DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
6989  removeFromWorkList(Ptr.getNode());
6990  DAG.DeleteNode(Ptr.getNode());
6991
6992  return true;
6993}
6994
6995/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
6996/// add / sub of the base pointer node into a post-indexed load / store.
6997/// The transformation folded the add / subtract into the new indexed
6998/// load / store effectively and all of its uses are redirected to the
6999/// new load / store.
7000bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7001  if (Level < AfterLegalizeDAG)
7002    return false;
7003
7004  bool isLoad = true;
7005  SDValue Ptr;
7006  EVT VT;
7007  if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7008    if (LD->isIndexed())
7009      return false;
7010    VT = LD->getMemoryVT();
7011    if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7012        !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7013      return false;
7014    Ptr = LD->getBasePtr();
7015  } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7016    if (ST->isIndexed())
7017      return false;
7018    VT = ST->getMemoryVT();
7019    if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7020        !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7021      return false;
7022    Ptr = ST->getBasePtr();
7023    isLoad = false;
7024  } else {
7025    return false;
7026  }
7027
7028  if (Ptr.getNode()->hasOneUse())
7029    return false;
7030
7031  for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7032         E = Ptr.getNode()->use_end(); I != E; ++I) {
7033    SDNode *Op = *I;
7034    if (Op == N ||
7035        (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7036      continue;
7037
7038    SDValue BasePtr;
7039    SDValue Offset;
7040    ISD::MemIndexedMode AM = ISD::UNINDEXED;
7041    if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7042      // Don't create a indexed load / store with zero offset.
7043      if (isa<ConstantSDNode>(Offset) &&
7044          cast<ConstantSDNode>(Offset)->isNullValue())
7045        continue;
7046
7047      // Try turning it into a post-indexed load / store except when
7048      // 1) All uses are load / store ops that use it as base ptr (and
7049      //    it may be folded as addressing mmode).
7050      // 2) Op must be independent of N, i.e. Op is neither a predecessor
7051      //    nor a successor of N. Otherwise, if Op is folded that would
7052      //    create a cycle.
7053
7054      if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7055        continue;
7056
7057      // Check for #1.
7058      bool TryNext = false;
7059      for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7060             EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7061        SDNode *Use = *II;
7062        if (Use == Ptr.getNode())
7063          continue;
7064
7065        // If all the uses are load / store addresses, then don't do the
7066        // transformation.
7067        if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7068          bool RealUse = false;
7069          for (SDNode::use_iterator III = Use->use_begin(),
7070                 EEE = Use->use_end(); III != EEE; ++III) {
7071            SDNode *UseUse = *III;
7072            if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7073              RealUse = true;
7074          }
7075
7076          if (!RealUse) {
7077            TryNext = true;
7078            break;
7079          }
7080        }
7081      }
7082
7083      if (TryNext)
7084        continue;
7085
7086      // Check for #2
7087      if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7088        SDValue Result = isLoad
7089          ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
7090                               BasePtr, Offset, AM)
7091          : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
7092                                BasePtr, Offset, AM);
7093        ++PostIndexedNodes;
7094        ++NodesCombined;
7095        DEBUG(dbgs() << "\nReplacing.5 ";
7096              N->dump(&DAG);
7097              dbgs() << "\nWith: ";
7098              Result.getNode()->dump(&DAG);
7099              dbgs() << '\n');
7100        WorkListRemover DeadNodes(*this);
7101        if (isLoad) {
7102          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7103          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7104        } else {
7105          DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7106        }
7107
7108        // Finally, since the node is now dead, remove it from the graph.
7109        DAG.DeleteNode(N);
7110
7111        // Replace the uses of Use with uses of the updated base value.
7112        DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7113                                      Result.getValue(isLoad ? 1 : 0));
7114        removeFromWorkList(Op);
7115        DAG.DeleteNode(Op);
7116        return true;
7117      }
7118    }
7119  }
7120
7121  return false;
7122}
7123
7124SDValue DAGCombiner::visitLOAD(SDNode *N) {
7125  LoadSDNode *LD  = cast<LoadSDNode>(N);
7126  SDValue Chain = LD->getChain();
7127  SDValue Ptr   = LD->getBasePtr();
7128
7129  // If load is not volatile and there are no uses of the loaded value (and
7130  // the updated indexed value in case of indexed loads), change uses of the
7131  // chain value into uses of the chain input (i.e. delete the dead load).
7132  if (!LD->isVolatile()) {
7133    if (N->getValueType(1) == MVT::Other) {
7134      // Unindexed loads.
7135      if (!N->hasAnyUseOfValue(0)) {
7136        // It's not safe to use the two value CombineTo variant here. e.g.
7137        // v1, chain2 = load chain1, loc
7138        // v2, chain3 = load chain2, loc
7139        // v3         = add v2, c
7140        // Now we replace use of chain2 with chain1.  This makes the second load
7141        // isomorphic to the one we are deleting, and thus makes this load live.
7142        DEBUG(dbgs() << "\nReplacing.6 ";
7143              N->dump(&DAG);
7144              dbgs() << "\nWith chain: ";
7145              Chain.getNode()->dump(&DAG);
7146              dbgs() << "\n");
7147        WorkListRemover DeadNodes(*this);
7148        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7149
7150        if (N->use_empty()) {
7151          removeFromWorkList(N);
7152          DAG.DeleteNode(N);
7153        }
7154
7155        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7156      }
7157    } else {
7158      // Indexed loads.
7159      assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7160      if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7161        SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7162        DEBUG(dbgs() << "\nReplacing.7 ";
7163              N->dump(&DAG);
7164              dbgs() << "\nWith: ";
7165              Undef.getNode()->dump(&DAG);
7166              dbgs() << " and 2 other values\n");
7167        WorkListRemover DeadNodes(*this);
7168        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7169        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7170                                      DAG.getUNDEF(N->getValueType(1)));
7171        DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7172        removeFromWorkList(N);
7173        DAG.DeleteNode(N);
7174        return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7175      }
7176    }
7177  }
7178
7179  // If this load is directly stored, replace the load value with the stored
7180  // value.
7181  // TODO: Handle store large -> read small portion.
7182  // TODO: Handle TRUNCSTORE/LOADEXT
7183  if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7184    if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7185      StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7186      if (PrevST->getBasePtr() == Ptr &&
7187          PrevST->getValue().getValueType() == N->getValueType(0))
7188      return CombineTo(N, Chain.getOperand(1), Chain);
7189    }
7190  }
7191
7192  // Try to infer better alignment information than the load already has.
7193  if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7194    if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7195      if (Align > LD->getAlignment())
7196        return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
7197                              LD->getValueType(0),
7198                              Chain, Ptr, LD->getPointerInfo(),
7199                              LD->getMemoryVT(),
7200                              LD->isVolatile(), LD->isNonTemporal(), Align);
7201    }
7202  }
7203
7204  if (CombinerAA) {
7205    // Walk up chain skipping non-aliasing memory nodes.
7206    SDValue BetterChain = FindBetterChain(N, Chain);
7207
7208    // If there is a better chain.
7209    if (Chain != BetterChain) {
7210      SDValue ReplLoad;
7211
7212      // Replace the chain to void dependency.
7213      if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7214        ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
7215                               BetterChain, Ptr, LD->getPointerInfo(),
7216                               LD->isVolatile(), LD->isNonTemporal(),
7217                               LD->isInvariant(), LD->getAlignment());
7218      } else {
7219        ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
7220                                  LD->getValueType(0),
7221                                  BetterChain, Ptr, LD->getPointerInfo(),
7222                                  LD->getMemoryVT(),
7223                                  LD->isVolatile(),
7224                                  LD->isNonTemporal(),
7225                                  LD->getAlignment());
7226      }
7227
7228      // Create token factor to keep old chain connected.
7229      SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
7230                                  MVT::Other, Chain, ReplLoad.getValue(1));
7231
7232      // Make sure the new and old chains are cleaned up.
7233      AddToWorkList(Token.getNode());
7234
7235      // Replace uses with load result and token factor. Don't add users
7236      // to work list.
7237      return CombineTo(N, ReplLoad.getValue(0), Token, false);
7238    }
7239  }
7240
7241  // Try transforming N to an indexed load.
7242  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7243    return SDValue(N, 0);
7244
7245  return SDValue();
7246}
7247
7248/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7249/// load is having specific bytes cleared out.  If so, return the byte size
7250/// being masked out and the shift amount.
7251static std::pair<unsigned, unsigned>
7252CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7253  std::pair<unsigned, unsigned> Result(0, 0);
7254
7255  // Check for the structure we're looking for.
7256  if (V->getOpcode() != ISD::AND ||
7257      !isa<ConstantSDNode>(V->getOperand(1)) ||
7258      !ISD::isNormalLoad(V->getOperand(0).getNode()))
7259    return Result;
7260
7261  // Check the chain and pointer.
7262  LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7263  if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
7264
7265  // The store should be chained directly to the load or be an operand of a
7266  // tokenfactor.
7267  if (LD == Chain.getNode())
7268    ; // ok.
7269  else if (Chain->getOpcode() != ISD::TokenFactor)
7270    return Result; // Fail.
7271  else {
7272    bool isOk = false;
7273    for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7274      if (Chain->getOperand(i).getNode() == LD) {
7275        isOk = true;
7276        break;
7277      }
7278    if (!isOk) return Result;
7279  }
7280
7281  // This only handles simple types.
7282  if (V.getValueType() != MVT::i16 &&
7283      V.getValueType() != MVT::i32 &&
7284      V.getValueType() != MVT::i64)
7285    return Result;
7286
7287  // Check the constant mask.  Invert it so that the bits being masked out are
7288  // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
7289  // follow the sign bit for uniformity.
7290  uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7291  unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
7292  if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
7293  unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
7294  if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
7295  if (NotMaskLZ == 64) return Result;  // All zero mask.
7296
7297  // See if we have a continuous run of bits.  If so, we have 0*1+0*
7298  if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7299    return Result;
7300
7301  // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7302  if (V.getValueType() != MVT::i64 && NotMaskLZ)
7303    NotMaskLZ -= 64-V.getValueSizeInBits();
7304
7305  unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7306  switch (MaskedBytes) {
7307  case 1:
7308  case 2:
7309  case 4: break;
7310  default: return Result; // All one mask, or 5-byte mask.
7311  }
7312
7313  // Verify that the first bit starts at a multiple of mask so that the access
7314  // is aligned the same as the access width.
7315  if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7316
7317  Result.first = MaskedBytes;
7318  Result.second = NotMaskTZ/8;
7319  return Result;
7320}
7321
7322
7323/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7324/// provides a value as specified by MaskInfo.  If so, replace the specified
7325/// store with a narrower store of truncated IVal.
7326static SDNode *
7327ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7328                                SDValue IVal, StoreSDNode *St,
7329                                DAGCombiner *DC) {
7330  unsigned NumBytes = MaskInfo.first;
7331  unsigned ByteShift = MaskInfo.second;
7332  SelectionDAG &DAG = DC->getDAG();
7333
7334  // Check to see if IVal is all zeros in the part being masked in by the 'or'
7335  // that uses this.  If not, this is not a replacement.
7336  APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7337                                  ByteShift*8, (ByteShift+NumBytes)*8);
7338  if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7339
7340  // Check that it is legal on the target to do this.  It is legal if the new
7341  // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7342  // legalization.
7343  MVT VT = MVT::getIntegerVT(NumBytes*8);
7344  if (!DC->isTypeLegal(VT))
7345    return 0;
7346
7347  // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
7348  // shifted by ByteShift and truncated down to NumBytes.
7349  if (ByteShift)
7350    IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
7351                       DAG.getConstant(ByteShift*8,
7352                                    DC->getShiftAmountTy(IVal.getValueType())));
7353
7354  // Figure out the offset for the store and the alignment of the access.
7355  unsigned StOffset;
7356  unsigned NewAlign = St->getAlignment();
7357
7358  if (DAG.getTargetLoweringInfo().isLittleEndian())
7359    StOffset = ByteShift;
7360  else
7361    StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7362
7363  SDValue Ptr = St->getBasePtr();
7364  if (StOffset) {
7365    Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
7366                      Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7367    NewAlign = MinAlign(NewAlign, StOffset);
7368  }
7369
7370  // Truncate down to the new size.
7371  IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
7372
7373  ++OpsNarrowed;
7374  return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
7375                      St->getPointerInfo().getWithOffset(StOffset),
7376                      false, false, NewAlign).getNode();
7377}
7378
7379
7380/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7381/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7382/// of the loaded bits, try narrowing the load and store if it would end up
7383/// being a win for performance or code size.
7384SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7385  StoreSDNode *ST  = cast<StoreSDNode>(N);
7386  if (ST->isVolatile())
7387    return SDValue();
7388
7389  SDValue Chain = ST->getChain();
7390  SDValue Value = ST->getValue();
7391  SDValue Ptr   = ST->getBasePtr();
7392  EVT VT = Value.getValueType();
7393
7394  if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7395    return SDValue();
7396
7397  unsigned Opc = Value.getOpcode();
7398
7399  // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7400  // is a byte mask indicating a consecutive number of bytes, check to see if
7401  // Y is known to provide just those bytes.  If so, we try to replace the
7402  // load + replace + store sequence with a single (narrower) store, which makes
7403  // the load dead.
7404  if (Opc == ISD::OR) {
7405    std::pair<unsigned, unsigned> MaskedLoad;
7406    MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7407    if (MaskedLoad.first)
7408      if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7409                                                  Value.getOperand(1), ST,this))
7410        return SDValue(NewST, 0);
7411
7412    // Or is commutative, so try swapping X and Y.
7413    MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7414    if (MaskedLoad.first)
7415      if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7416                                                  Value.getOperand(0), ST,this))
7417        return SDValue(NewST, 0);
7418  }
7419
7420  if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7421      Value.getOperand(1).getOpcode() != ISD::Constant)
7422    return SDValue();
7423
7424  SDValue N0 = Value.getOperand(0);
7425  if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7426      Chain == SDValue(N0.getNode(), 1)) {
7427    LoadSDNode *LD = cast<LoadSDNode>(N0);
7428    if (LD->getBasePtr() != Ptr ||
7429        LD->getPointerInfo().getAddrSpace() !=
7430        ST->getPointerInfo().getAddrSpace())
7431      return SDValue();
7432
7433    // Find the type to narrow it the load / op / store to.
7434    SDValue N1 = Value.getOperand(1);
7435    unsigned BitWidth = N1.getValueSizeInBits();
7436    APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7437    if (Opc == ISD::AND)
7438      Imm ^= APInt::getAllOnesValue(BitWidth);
7439    if (Imm == 0 || Imm.isAllOnesValue())
7440      return SDValue();
7441    unsigned ShAmt = Imm.countTrailingZeros();
7442    unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7443    unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7444    EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7445    while (NewBW < BitWidth &&
7446           !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7447             TLI.isNarrowingProfitable(VT, NewVT))) {
7448      NewBW = NextPowerOf2(NewBW);
7449      NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7450    }
7451    if (NewBW >= BitWidth)
7452      return SDValue();
7453
7454    // If the lsb changed does not start at the type bitwidth boundary,
7455    // start at the previous one.
7456    if (ShAmt % NewBW)
7457      ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7458    APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7459                                   std::min(BitWidth, ShAmt + NewBW));
7460    if ((Imm & Mask) == Imm) {
7461      APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7462      if (Opc == ISD::AND)
7463        NewImm ^= APInt::getAllOnesValue(NewBW);
7464      uint64_t PtrOff = ShAmt / 8;
7465      // For big endian targets, we need to adjust the offset to the pointer to
7466      // load the correct bytes.
7467      if (TLI.isBigEndian())
7468        PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7469
7470      unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7471      Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7472      if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7473        return SDValue();
7474
7475      SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
7476                                   Ptr.getValueType(), Ptr,
7477                                   DAG.getConstant(PtrOff, Ptr.getValueType()));
7478      SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
7479                                  LD->getChain(), NewPtr,
7480                                  LD->getPointerInfo().getWithOffset(PtrOff),
7481                                  LD->isVolatile(), LD->isNonTemporal(),
7482                                  LD->isInvariant(), NewAlign);
7483      SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
7484                                   DAG.getConstant(NewImm, NewVT));
7485      SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
7486                                   NewVal, NewPtr,
7487                                   ST->getPointerInfo().getWithOffset(PtrOff),
7488                                   false, false, NewAlign);
7489
7490      AddToWorkList(NewPtr.getNode());
7491      AddToWorkList(NewLD.getNode());
7492      AddToWorkList(NewVal.getNode());
7493      WorkListRemover DeadNodes(*this);
7494      DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7495      ++OpsNarrowed;
7496      return NewST;
7497    }
7498  }
7499
7500  return SDValue();
7501}
7502
7503/// TransformFPLoadStorePair - For a given floating point load / store pair,
7504/// if the load value isn't used by any other operations, then consider
7505/// transforming the pair to integer load / store operations if the target
7506/// deems the transformation profitable.
7507SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7508  StoreSDNode *ST  = cast<StoreSDNode>(N);
7509  SDValue Chain = ST->getChain();
7510  SDValue Value = ST->getValue();
7511  if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7512      Value.hasOneUse() &&
7513      Chain == SDValue(Value.getNode(), 1)) {
7514    LoadSDNode *LD = cast<LoadSDNode>(Value);
7515    EVT VT = LD->getMemoryVT();
7516    if (!VT.isFloatingPoint() ||
7517        VT != ST->getMemoryVT() ||
7518        LD->isNonTemporal() ||
7519        ST->isNonTemporal() ||
7520        LD->getPointerInfo().getAddrSpace() != 0 ||
7521        ST->getPointerInfo().getAddrSpace() != 0)
7522      return SDValue();
7523
7524    EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7525    if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7526        !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7527        !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7528        !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7529      return SDValue();
7530
7531    unsigned LDAlign = LD->getAlignment();
7532    unsigned STAlign = ST->getAlignment();
7533    Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7534    unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7535    if (LDAlign < ABIAlign || STAlign < ABIAlign)
7536      return SDValue();
7537
7538    SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
7539                                LD->getChain(), LD->getBasePtr(),
7540                                LD->getPointerInfo(),
7541                                false, false, false, LDAlign);
7542
7543    SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
7544                                 NewLD, ST->getBasePtr(),
7545                                 ST->getPointerInfo(),
7546                                 false, false, STAlign);
7547
7548    AddToWorkList(NewLD.getNode());
7549    AddToWorkList(NewST.getNode());
7550    WorkListRemover DeadNodes(*this);
7551    DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7552    ++LdStFP2Int;
7553    return NewST;
7554  }
7555
7556  return SDValue();
7557}
7558
7559/// Returns the base pointer and an integer offset from that object.
7560static std::pair<SDValue, int64_t> GetPointerBaseAndOffset(SDValue Ptr) {
7561  if (Ptr->getOpcode() == ISD::ADD && isa<ConstantSDNode>(Ptr->getOperand(1))) {
7562    int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7563    SDValue Base = Ptr->getOperand(0);
7564    return std::make_pair(Base, Offset);
7565  }
7566
7567  return std::make_pair(Ptr, 0);
7568}
7569
7570/// Holds a pointer to an LSBaseSDNode as well as information on where it
7571/// is located in a sequence of memory operations connected by a chain.
7572struct MemOpLink {
7573  MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7574    MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7575  // Ptr to the mem node.
7576  LSBaseSDNode *MemNode;
7577  // Offset from the base ptr.
7578  int64_t OffsetFromBase;
7579  // What is the sequence number of this mem node.
7580  // Lowest mem operand in the DAG starts at zero.
7581  unsigned SequenceNum;
7582};
7583
7584/// Sorts store nodes in a link according to their offset from a shared
7585// base ptr.
7586struct ConsecutiveMemoryChainSorter {
7587  bool operator()(MemOpLink LHS, MemOpLink RHS) {
7588    return LHS.OffsetFromBase < RHS.OffsetFromBase;
7589  }
7590};
7591
7592bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7593  EVT MemVT = St->getMemoryVT();
7594  int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7595
7596  // Don't merge vectors into wider inputs.
7597  if (MemVT.isVector() || !MemVT.isSimple())
7598    return false;
7599
7600  // Perform an early exit check. Do not bother looking at stored values that
7601  // are not constants or loads.
7602  SDValue StoredVal = St->getValue();
7603  bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7604  if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7605      !IsLoadSrc)
7606    return false;
7607
7608  // Only look at ends of store sequences.
7609  SDValue Chain = SDValue(St, 1);
7610  if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7611    return false;
7612
7613  // This holds the base pointer and the offset in bytes from the base pointer.
7614  std::pair<SDValue, int64_t> BasePtr =
7615      GetPointerBaseAndOffset(St->getBasePtr());
7616
7617  // We must have a base and an offset.
7618  if (!BasePtr.first.getNode())
7619    return false;
7620
7621  // Do not handle stores to undef base pointers.
7622  if (BasePtr.first.getOpcode() == ISD::UNDEF)
7623    return false;
7624
7625  // Save the LoadSDNodes that we find in the chain.
7626  // We need to make sure that these nodes do not interfere with
7627  // any of the store nodes.
7628  SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
7629
7630  // Save the StoreSDNodes that we find in the chain.
7631  SmallVector<MemOpLink, 8> StoreNodes;
7632
7633  // Walk up the chain and look for nodes with offsets from the same
7634  // base pointer. Stop when reaching an instruction with a different kind
7635  // or instruction which has a different base pointer.
7636  unsigned Seq = 0;
7637  StoreSDNode *Index = St;
7638  while (Index) {
7639    // If the chain has more than one use, then we can't reorder the mem ops.
7640    if (Index != St && !SDValue(Index, 1)->hasOneUse())
7641      break;
7642
7643    // Find the base pointer and offset for this memory node.
7644    std::pair<SDValue, int64_t> Ptr =
7645      GetPointerBaseAndOffset(Index->getBasePtr());
7646
7647    // Check that the base pointer is the same as the original one.
7648    if (Ptr.first.getNode() != BasePtr.first.getNode())
7649      break;
7650
7651    // Check that the alignment is the same.
7652    if (Index->getAlignment() != St->getAlignment())
7653      break;
7654
7655    // The memory operands must not be volatile.
7656    if (Index->isVolatile() || Index->isIndexed())
7657      break;
7658
7659    // No truncation.
7660    if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
7661      if (St->isTruncatingStore())
7662        break;
7663
7664    // The stored memory type must be the same.
7665    if (Index->getMemoryVT() != MemVT)
7666      break;
7667
7668    // We do not allow unaligned stores because we want to prevent overriding
7669    // stores.
7670    if (Index->getAlignment()*8 != MemVT.getSizeInBits())
7671      break;
7672
7673    // We found a potential memory operand to merge.
7674    StoreNodes.push_back(MemOpLink(Index, Ptr.second, Seq++));
7675
7676    // Find the next memory operand in the chain. If the next operand in the
7677    // chain is a store then move up and continue the scan with the next
7678    // memory operand. If the next operand is a load save it and use alias
7679    // information to check if it interferes with anything.
7680    SDNode *NextInChain = Index->getChain().getNode();
7681    while (1) {
7682      if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
7683        // We found a store node. Use it for the next iteration.
7684        Index = STn;
7685        break;
7686      } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
7687        // Save the load node for later. Continue the scan.
7688        AliasLoadNodes.push_back(Ldn);
7689        NextInChain = Ldn->getChain().getNode();
7690        continue;
7691      } else {
7692        Index = NULL;
7693        break;
7694      }
7695    }
7696  }
7697
7698  // Check if there is anything to merge.
7699  if (StoreNodes.size() < 2)
7700    return false;
7701
7702  // Sort the memory operands according to their distance from the base pointer.
7703  std::sort(StoreNodes.begin(), StoreNodes.end(),
7704            ConsecutiveMemoryChainSorter());
7705
7706  // Scan the memory operations on the chain and find the first non-consecutive
7707  // store memory address.
7708  unsigned LastConsecutiveStore = 0;
7709  int64_t StartAddress = StoreNodes[0].OffsetFromBase;
7710  for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
7711
7712    // Check that the addresses are consecutive starting from the second
7713    // element in the list of stores.
7714    if (i > 0) {
7715      int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
7716      if (CurrAddress - StartAddress != (ElementSizeBytes * i))
7717        break;
7718    }
7719
7720    bool Alias = false;
7721    // Check if this store interferes with any of the loads that we found.
7722    for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
7723      if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
7724        Alias = true;
7725        break;
7726      }
7727    // We found a load that alias with this store. Stop the sequence.
7728    if (Alias)
7729      break;
7730
7731    // Mark this node as useful.
7732    LastConsecutiveStore = i;
7733  }
7734
7735  // The node with the lowest store address.
7736  LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
7737
7738  // Store the constants into memory as one consecutive store.
7739  if (!IsLoadSrc) {
7740    unsigned LastLegalType = 0;
7741    unsigned LastLegalVectorType = 0;
7742    bool NonZero = false;
7743    for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
7744      StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
7745      SDValue StoredVal = St->getValue();
7746
7747      if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
7748        NonZero |= !C->isNullValue();
7749      } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
7750        NonZero |= !C->getConstantFPValue()->isNullValue();
7751      } else {
7752        // Non constant.
7753        break;
7754      }
7755
7756      // Find a legal type for the constant store.
7757      unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
7758      EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
7759      if (TLI.isTypeLegal(StoreTy))
7760        LastLegalType = i+1;
7761
7762      // Find a legal type for the vector store.
7763      EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
7764      if (TLI.isTypeLegal(Ty))
7765        LastLegalVectorType = i + 1;
7766    }
7767
7768    // We only use vectors if the constant is known to be zero and the
7769    // function is not marked with the noimplicitfloat attribute.
7770    if (NonZero || (DAG.getMachineFunction().getFunction()->getAttributes().
7771                    hasAttribute(AttributeSet::FunctionIndex,
7772                                 Attribute::NoImplicitFloat)))
7773      LastLegalVectorType = 0;
7774
7775    // Check if we found a legal integer type to store.
7776    if (LastLegalType == 0 && LastLegalVectorType == 0)
7777      return false;
7778
7779    bool UseVector = LastLegalVectorType > LastLegalType;
7780    unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
7781
7782    // Make sure we have something to merge.
7783    if (NumElem < 2)
7784      return false;
7785
7786    unsigned EarliestNodeUsed = 0;
7787    for (unsigned i=0; i < NumElem; ++i) {
7788      // Find a chain for the new wide-store operand. Notice that some
7789      // of the store nodes that we found may not be selected for inclusion
7790      // in the wide store. The chain we use needs to be the chain of the
7791      // earliest store node which is *used* and replaced by the wide store.
7792      if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
7793        EarliestNodeUsed = i;
7794    }
7795
7796    // The earliest Node in the DAG.
7797    LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
7798    DebugLoc DL = StoreNodes[0].MemNode->getDebugLoc();
7799
7800    SDValue StoredVal;
7801    if (UseVector) {
7802      // Find a legal type for the vector store.
7803      EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
7804      assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
7805      StoredVal = DAG.getConstant(0, Ty);
7806    } else {
7807      unsigned StoreBW = NumElem * ElementSizeBytes * 8;
7808      APInt StoreInt(StoreBW, 0);
7809
7810      // Construct a single integer constant which is made of the smaller
7811      // constant inputs.
7812      bool IsLE = TLI.isLittleEndian();
7813      for (unsigned i = 0; i < NumElem ; ++i) {
7814        unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
7815        StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
7816        SDValue Val = St->getValue();
7817        StoreInt<<=ElementSizeBytes*8;
7818        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
7819          StoreInt|=C->getAPIntValue().zext(StoreBW);
7820        } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
7821          StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
7822        } else {
7823          assert(false && "Invalid constant element type");
7824        }
7825      }
7826
7827      // Create the new Load and Store operations.
7828      EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
7829      StoredVal = DAG.getConstant(StoreInt, StoreTy);
7830    }
7831
7832    SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
7833                                    FirstInChain->getBasePtr(),
7834                                    FirstInChain->getPointerInfo(),
7835                                    false, false,
7836                                    FirstInChain->getAlignment());
7837
7838    // Replace the first store with the new store
7839    CombineTo(EarliestOp, NewStore);
7840    // Erase all other stores.
7841    for (unsigned i = 0; i < NumElem ; ++i) {
7842      if (StoreNodes[i].MemNode == EarliestOp)
7843        continue;
7844      StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
7845      // ReplaceAllUsesWith will replace all uses that existed when it was
7846      // called, but graph optimizations may cause new ones to appear. For
7847      // example, the case in pr14333 looks like
7848      //
7849      //  St's chain -> St -> another store -> X
7850      //
7851      // And the only difference from St to the other store is the chain.
7852      // When we change it's chain to be St's chain they become identical,
7853      // get CSEed and the net result is that X is now a use of St.
7854      // Since we know that St is redundant, just iterate.
7855      while (!St->use_empty())
7856        DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
7857      removeFromWorkList(St);
7858      DAG.DeleteNode(St);
7859    }
7860
7861    return true;
7862  }
7863
7864  // Below we handle the case of multiple consecutive stores that
7865  // come from multiple consecutive loads. We merge them into a single
7866  // wide load and a single wide store.
7867
7868  // Look for load nodes which are used by the stored values.
7869  SmallVector<MemOpLink, 8> LoadNodes;
7870
7871  // Find acceptable loads. Loads need to have the same chain (token factor),
7872  // must not be zext, volatile, indexed, and they must be consecutive.
7873  SDValue LdBasePtr;
7874  for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
7875    StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
7876    LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
7877    if (!Ld) break;
7878
7879    // Loads must only have one use.
7880    if (!Ld->hasNUsesOfValue(1, 0))
7881      break;
7882
7883    // Check that the alignment is the same as the stores.
7884    if (Ld->getAlignment() != St->getAlignment())
7885      break;
7886
7887    // The memory operands must not be volatile.
7888    if (Ld->isVolatile() || Ld->isIndexed())
7889      break;
7890
7891    // We do not accept ext loads.
7892    if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
7893      break;
7894
7895    // The stored memory type must be the same.
7896    if (Ld->getMemoryVT() != MemVT)
7897      break;
7898
7899    std::pair<SDValue, int64_t> LdPtr =
7900    GetPointerBaseAndOffset(Ld->getBasePtr());
7901
7902    // If this is not the first ptr that we check.
7903    if (LdBasePtr.getNode()) {
7904      // The base ptr must be the same.
7905      if (LdPtr.first != LdBasePtr)
7906        break;
7907    } else {
7908      // Check that all other base pointers are the same as this one.
7909      LdBasePtr = LdPtr.first;
7910    }
7911
7912    // We found a potential memory operand to merge.
7913    LoadNodes.push_back(MemOpLink(Ld, LdPtr.second, 0));
7914  }
7915
7916  if (LoadNodes.size() < 2)
7917    return false;
7918
7919  // Scan the memory operations on the chain and find the first non-consecutive
7920  // load memory address. These variables hold the index in the store node
7921  // array.
7922  unsigned LastConsecutiveLoad = 0;
7923  // This variable refers to the size and not index in the array.
7924  unsigned LastLegalVectorType = 0;
7925  unsigned LastLegalIntegerType = 0;
7926  StartAddress = LoadNodes[0].OffsetFromBase;
7927  SDValue FirstChain = LoadNodes[0].MemNode->getChain();
7928  for (unsigned i = 1; i < LoadNodes.size(); ++i) {
7929    // All loads much share the same chain.
7930    if (LoadNodes[i].MemNode->getChain() != FirstChain)
7931      break;
7932
7933    int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
7934    if (CurrAddress - StartAddress != (ElementSizeBytes * i))
7935      break;
7936    LastConsecutiveLoad = i;
7937
7938    // Find a legal type for the vector store.
7939    EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
7940    if (TLI.isTypeLegal(StoreTy))
7941      LastLegalVectorType = i + 1;
7942
7943    // Find a legal type for the integer store.
7944    unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
7945    StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
7946    if (TLI.isTypeLegal(StoreTy))
7947      LastLegalIntegerType = i + 1;
7948  }
7949
7950  // Only use vector types if the vector type is larger than the integer type.
7951  // If they are the same, use integers.
7952  bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType;
7953  unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
7954
7955  // We add +1 here because the LastXXX variables refer to location while
7956  // the NumElem refers to array/index size.
7957  unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
7958  NumElem = std::min(LastLegalType, NumElem);
7959
7960  if (NumElem < 2)
7961    return false;
7962
7963  // The earliest Node in the DAG.
7964  unsigned EarliestNodeUsed = 0;
7965  LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
7966  for (unsigned i=1; i<NumElem; ++i) {
7967    // Find a chain for the new wide-store operand. Notice that some
7968    // of the store nodes that we found may not be selected for inclusion
7969    // in the wide store. The chain we use needs to be the chain of the
7970    // earliest store node which is *used* and replaced by the wide store.
7971    if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
7972      EarliestNodeUsed = i;
7973  }
7974
7975  // Find if it is better to use vectors or integers to load and store
7976  // to memory.
7977  EVT JointMemOpVT;
7978  if (UseVectorTy) {
7979    JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
7980  } else {
7981    unsigned StoreBW = NumElem * ElementSizeBytes * 8;
7982    JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
7983  }
7984
7985  DebugLoc LoadDL = LoadNodes[0].MemNode->getDebugLoc();
7986  DebugLoc StoreDL = StoreNodes[0].MemNode->getDebugLoc();
7987
7988  LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
7989  SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
7990                                FirstLoad->getChain(),
7991                                FirstLoad->getBasePtr(),
7992                                FirstLoad->getPointerInfo(),
7993                                false, false, false,
7994                                FirstLoad->getAlignment());
7995
7996  SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
7997                                  FirstInChain->getBasePtr(),
7998                                  FirstInChain->getPointerInfo(), false, false,
7999                                  FirstInChain->getAlignment());
8000
8001  // Replace one of the loads with the new load.
8002  LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8003  DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8004                                SDValue(NewLoad.getNode(), 1));
8005
8006  // Remove the rest of the load chains.
8007  for (unsigned i = 1; i < NumElem ; ++i) {
8008    // Replace all chain users of the old load nodes with the chain of the new
8009    // load node.
8010    LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8011    DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8012  }
8013
8014  // Replace the first store with the new store.
8015  CombineTo(EarliestOp, NewStore);
8016  // Erase all other stores.
8017  for (unsigned i = 0; i < NumElem ; ++i) {
8018    // Remove all Store nodes.
8019    if (StoreNodes[i].MemNode == EarliestOp)
8020      continue;
8021    StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8022    DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8023    removeFromWorkList(St);
8024    DAG.DeleteNode(St);
8025  }
8026
8027  return true;
8028}
8029
8030SDValue DAGCombiner::visitSTORE(SDNode *N) {
8031  StoreSDNode *ST  = cast<StoreSDNode>(N);
8032  SDValue Chain = ST->getChain();
8033  SDValue Value = ST->getValue();
8034  SDValue Ptr   = ST->getBasePtr();
8035
8036  // If this is a store of a bit convert, store the input value if the
8037  // resultant store does not need a higher alignment than the original.
8038  if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8039      ST->isUnindexed()) {
8040    unsigned OrigAlign = ST->getAlignment();
8041    EVT SVT = Value.getOperand(0).getValueType();
8042    unsigned Align = TLI.getDataLayout()->
8043      getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8044    if (Align <= OrigAlign &&
8045        ((!LegalOperations && !ST->isVolatile()) ||
8046         TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8047      return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
8048                          Ptr, ST->getPointerInfo(), ST->isVolatile(),
8049                          ST->isNonTemporal(), OrigAlign);
8050  }
8051
8052  // Turn 'store undef, Ptr' -> nothing.
8053  if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8054    return Chain;
8055
8056  // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8057  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8058    // NOTE: If the original store is volatile, this transform must not increase
8059    // the number of stores.  For example, on x86-32 an f64 can be stored in one
8060    // processor operation but an i64 (which is not legal) requires two.  So the
8061    // transform should not be done in this case.
8062    if (Value.getOpcode() != ISD::TargetConstantFP) {
8063      SDValue Tmp;
8064      switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
8065      default: llvm_unreachable("Unknown FP type");
8066      case MVT::f16:    // We don't do this for these yet.
8067      case MVT::f80:
8068      case MVT::f128:
8069      case MVT::ppcf128:
8070        break;
8071      case MVT::f32:
8072        if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8073            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8074          Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8075                              bitcastToAPInt().getZExtValue(), MVT::i32);
8076          return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
8077                              Ptr, ST->getPointerInfo(), ST->isVolatile(),
8078                              ST->isNonTemporal(), ST->getAlignment());
8079        }
8080        break;
8081      case MVT::f64:
8082        if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8083             !ST->isVolatile()) ||
8084            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8085          Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8086                                getZExtValue(), MVT::i64);
8087          return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
8088                              Ptr, ST->getPointerInfo(), ST->isVolatile(),
8089                              ST->isNonTemporal(), ST->getAlignment());
8090        }
8091
8092        if (!ST->isVolatile() &&
8093            TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8094          // Many FP stores are not made apparent until after legalize, e.g. for
8095          // argument passing.  Since this is so common, custom legalize the
8096          // 64-bit integer store into two 32-bit stores.
8097          uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8098          SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8099          SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8100          if (TLI.isBigEndian()) std::swap(Lo, Hi);
8101
8102          unsigned Alignment = ST->getAlignment();
8103          bool isVolatile = ST->isVolatile();
8104          bool isNonTemporal = ST->isNonTemporal();
8105
8106          SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
8107                                     Ptr, ST->getPointerInfo(),
8108                                     isVolatile, isNonTemporal,
8109                                     ST->getAlignment());
8110          Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
8111                            DAG.getConstant(4, Ptr.getValueType()));
8112          Alignment = MinAlign(Alignment, 4U);
8113          SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
8114                                     Ptr, ST->getPointerInfo().getWithOffset(4),
8115                                     isVolatile, isNonTemporal,
8116                                     Alignment);
8117          return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
8118                             St0, St1);
8119        }
8120
8121        break;
8122      }
8123    }
8124  }
8125
8126  // Try to infer better alignment information than the store already has.
8127  if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8128    if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8129      if (Align > ST->getAlignment())
8130        return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
8131                                 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8132                                 ST->isVolatile(), ST->isNonTemporal(), Align);
8133    }
8134  }
8135
8136  // Try transforming a pair floating point load / store ops to integer
8137  // load / store ops.
8138  SDValue NewST = TransformFPLoadStorePair(N);
8139  if (NewST.getNode())
8140    return NewST;
8141
8142  if (CombinerAA) {
8143    // Walk up chain skipping non-aliasing memory nodes.
8144    SDValue BetterChain = FindBetterChain(N, Chain);
8145
8146    // If there is a better chain.
8147    if (Chain != BetterChain) {
8148      SDValue ReplStore;
8149
8150      // Replace the chain to avoid dependency.
8151      if (ST->isTruncatingStore()) {
8152        ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
8153                                      ST->getPointerInfo(),
8154                                      ST->getMemoryVT(), ST->isVolatile(),
8155                                      ST->isNonTemporal(), ST->getAlignment());
8156      } else {
8157        ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
8158                                 ST->getPointerInfo(),
8159                                 ST->isVolatile(), ST->isNonTemporal(),
8160                                 ST->getAlignment());
8161      }
8162
8163      // Create token to keep both nodes around.
8164      SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
8165                                  MVT::Other, Chain, ReplStore);
8166
8167      // Make sure the new and old chains are cleaned up.
8168      AddToWorkList(Token.getNode());
8169
8170      // Don't add users to work list.
8171      return CombineTo(N, Token, false);
8172    }
8173  }
8174
8175  // Try transforming N to an indexed store.
8176  if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8177    return SDValue(N, 0);
8178
8179  // FIXME: is there such a thing as a truncating indexed store?
8180  if (ST->isTruncatingStore() && ST->isUnindexed() &&
8181      Value.getValueType().isInteger()) {
8182    // See if we can simplify the input to this truncstore with knowledge that
8183    // only the low bits are being used.  For example:
8184    // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
8185    SDValue Shorter =
8186      GetDemandedBits(Value,
8187                      APInt::getLowBitsSet(
8188                        Value.getValueType().getScalarType().getSizeInBits(),
8189                        ST->getMemoryVT().getScalarType().getSizeInBits()));
8190    AddToWorkList(Value.getNode());
8191    if (Shorter.getNode())
8192      return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
8193                               Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8194                               ST->isVolatile(), ST->isNonTemporal(),
8195                               ST->getAlignment());
8196
8197    // Otherwise, see if we can simplify the operation with
8198    // SimplifyDemandedBits, which only works if the value has a single use.
8199    if (SimplifyDemandedBits(Value,
8200                        APInt::getLowBitsSet(
8201                          Value.getValueType().getScalarType().getSizeInBits(),
8202                          ST->getMemoryVT().getScalarType().getSizeInBits())))
8203      return SDValue(N, 0);
8204  }
8205
8206  // If this is a load followed by a store to the same location, then the store
8207  // is dead/noop.
8208  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8209    if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8210        ST->isUnindexed() && !ST->isVolatile() &&
8211        // There can't be any side effects between the load and store, such as
8212        // a call or store.
8213        Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8214      // The store is dead, remove it.
8215      return Chain;
8216    }
8217  }
8218
8219  // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8220  // truncating store.  We can do this even if this is already a truncstore.
8221  if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8222      && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8223      TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8224                            ST->getMemoryVT())) {
8225    return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
8226                             Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8227                             ST->isVolatile(), ST->isNonTemporal(),
8228                             ST->getAlignment());
8229  }
8230
8231  // Only perform this optimization before the types are legal, because we
8232  // don't want to perform this optimization on every DAGCombine invocation.
8233  if (!LegalTypes) {
8234    bool EverChanged = false;
8235
8236    do {
8237      // There can be multiple store sequences on the same chain.
8238      // Keep trying to merge store sequences until we are unable to do so
8239      // or until we merge the last store on the chain.
8240      bool Changed = MergeConsecutiveStores(ST);
8241      EverChanged |= Changed;
8242      if (!Changed) break;
8243    } while (ST->getOpcode() != ISD::DELETED_NODE);
8244
8245    if (EverChanged)
8246      return SDValue(N, 0);
8247  }
8248
8249  return ReduceLoadOpStoreWidth(N);
8250}
8251
8252SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8253  SDValue InVec = N->getOperand(0);
8254  SDValue InVal = N->getOperand(1);
8255  SDValue EltNo = N->getOperand(2);
8256  DebugLoc dl = N->getDebugLoc();
8257
8258  // If the inserted element is an UNDEF, just use the input vector.
8259  if (InVal.getOpcode() == ISD::UNDEF)
8260    return InVec;
8261
8262  EVT VT = InVec.getValueType();
8263
8264  // If we can't generate a legal BUILD_VECTOR, exit
8265  if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8266    return SDValue();
8267
8268  // Check that we know which element is being inserted
8269  if (!isa<ConstantSDNode>(EltNo))
8270    return SDValue();
8271  unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8272
8273  // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8274  // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
8275  // vector elements.
8276  SmallVector<SDValue, 8> Ops;
8277  if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8278    Ops.append(InVec.getNode()->op_begin(),
8279               InVec.getNode()->op_end());
8280  } else if (InVec.getOpcode() == ISD::UNDEF) {
8281    unsigned NElts = VT.getVectorNumElements();
8282    Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8283  } else {
8284    return SDValue();
8285  }
8286
8287  // Insert the element
8288  if (Elt < Ops.size()) {
8289    // All the operands of BUILD_VECTOR must have the same type;
8290    // we enforce that here.
8291    EVT OpVT = Ops[0].getValueType();
8292    if (InVal.getValueType() != OpVT)
8293      InVal = OpVT.bitsGT(InVal.getValueType()) ?
8294                DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8295                DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8296    Ops[Elt] = InVal;
8297  }
8298
8299  // Return the new vector
8300  return DAG.getNode(ISD::BUILD_VECTOR, dl,
8301                     VT, &Ops[0], Ops.size());
8302}
8303
8304SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8305  // (vextract (scalar_to_vector val, 0) -> val
8306  SDValue InVec = N->getOperand(0);
8307  EVT VT = InVec.getValueType();
8308  EVT NVT = N->getValueType(0);
8309
8310  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8311    // Check if the result type doesn't match the inserted element type. A
8312    // SCALAR_TO_VECTOR may truncate the inserted element and the
8313    // EXTRACT_VECTOR_ELT may widen the extracted vector.
8314    SDValue InOp = InVec.getOperand(0);
8315    if (InOp.getValueType() != NVT) {
8316      assert(InOp.getValueType().isInteger() && NVT.isInteger());
8317      return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
8318    }
8319    return InOp;
8320  }
8321
8322  SDValue EltNo = N->getOperand(1);
8323  bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8324
8325  // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8326  // We only perform this optimization before the op legalization phase because
8327  // we may introduce new vector instructions which are not backed by TD
8328  // patterns. For example on AVX, extracting elements from a wide vector
8329  // without using extract_subvector.
8330  if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8331      && ConstEltNo && !LegalOperations) {
8332    int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8333    int NumElem = VT.getVectorNumElements();
8334    ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8335    // Find the new index to extract from.
8336    int OrigElt = SVOp->getMaskElt(Elt);
8337
8338    // Extracting an undef index is undef.
8339    if (OrigElt == -1)
8340      return DAG.getUNDEF(NVT);
8341
8342    // Select the right vector half to extract from.
8343    if (OrigElt < NumElem) {
8344      InVec = InVec->getOperand(0);
8345    } else {
8346      InVec = InVec->getOperand(1);
8347      OrigElt -= NumElem;
8348    }
8349
8350    EVT IndexTy = N->getOperand(1).getValueType();
8351    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT,
8352                       InVec, DAG.getConstant(OrigElt, IndexTy));
8353  }
8354
8355  // Perform only after legalization to ensure build_vector / vector_shuffle
8356  // optimizations have already been done.
8357  if (!LegalOperations) return SDValue();
8358
8359  // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8360  // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8361  // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8362
8363  if (ConstEltNo) {
8364    int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8365    bool NewLoad = false;
8366    bool BCNumEltsChanged = false;
8367    EVT ExtVT = VT.getVectorElementType();
8368    EVT LVT = ExtVT;
8369
8370    // If the result of load has to be truncated, then it's not necessarily
8371    // profitable.
8372    if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8373      return SDValue();
8374
8375    if (InVec.getOpcode() == ISD::BITCAST) {
8376      // Don't duplicate a load with other uses.
8377      if (!InVec.hasOneUse())
8378        return SDValue();
8379
8380      EVT BCVT = InVec.getOperand(0).getValueType();
8381      if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8382        return SDValue();
8383      if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8384        BCNumEltsChanged = true;
8385      InVec = InVec.getOperand(0);
8386      ExtVT = BCVT.getVectorElementType();
8387      NewLoad = true;
8388    }
8389
8390    LoadSDNode *LN0 = NULL;
8391    const ShuffleVectorSDNode *SVN = NULL;
8392    if (ISD::isNormalLoad(InVec.getNode())) {
8393      LN0 = cast<LoadSDNode>(InVec);
8394    } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8395               InVec.getOperand(0).getValueType() == ExtVT &&
8396               ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8397      // Don't duplicate a load with other uses.
8398      if (!InVec.hasOneUse())
8399        return SDValue();
8400
8401      LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8402    } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8403      // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8404      // =>
8405      // (load $addr+1*size)
8406
8407      // Don't duplicate a load with other uses.
8408      if (!InVec.hasOneUse())
8409        return SDValue();
8410
8411      // If the bit convert changed the number of elements, it is unsafe
8412      // to examine the mask.
8413      if (BCNumEltsChanged)
8414        return SDValue();
8415
8416      // Select the input vector, guarding against out of range extract vector.
8417      unsigned NumElems = VT.getVectorNumElements();
8418      int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8419      InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8420
8421      if (InVec.getOpcode() == ISD::BITCAST) {
8422        // Don't duplicate a load with other uses.
8423        if (!InVec.hasOneUse())
8424          return SDValue();
8425
8426        InVec = InVec.getOperand(0);
8427      }
8428      if (ISD::isNormalLoad(InVec.getNode())) {
8429        LN0 = cast<LoadSDNode>(InVec);
8430        Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8431      }
8432    }
8433
8434    // Make sure we found a non-volatile load and the extractelement is
8435    // the only use.
8436    if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8437      return SDValue();
8438
8439    // If Idx was -1 above, Elt is going to be -1, so just return undef.
8440    if (Elt == -1)
8441      return DAG.getUNDEF(LVT);
8442
8443    unsigned Align = LN0->getAlignment();
8444    if (NewLoad) {
8445      // Check the resultant load doesn't need a higher alignment than the
8446      // original load.
8447      unsigned NewAlign =
8448        TLI.getDataLayout()
8449            ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8450
8451      if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8452        return SDValue();
8453
8454      Align = NewAlign;
8455    }
8456
8457    SDValue NewPtr = LN0->getBasePtr();
8458    unsigned PtrOff = 0;
8459
8460    if (Elt) {
8461      PtrOff = LVT.getSizeInBits() * Elt / 8;
8462      EVT PtrType = NewPtr.getValueType();
8463      if (TLI.isBigEndian())
8464        PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8465      NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
8466                           DAG.getConstant(PtrOff, PtrType));
8467    }
8468
8469    // The replacement we need to do here is a little tricky: we need to
8470    // replace an extractelement of a load with a load.
8471    // Use ReplaceAllUsesOfValuesWith to do the replacement.
8472    // Note that this replacement assumes that the extractvalue is the only
8473    // use of the load; that's okay because we don't want to perform this
8474    // transformation in other cases anyway.
8475    SDValue Load;
8476    SDValue Chain;
8477    if (NVT.bitsGT(LVT)) {
8478      // If the result type of vextract is wider than the load, then issue an
8479      // extending load instead.
8480      ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8481        ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8482      Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(),
8483                            NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8484                            LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8485      Chain = Load.getValue(1);
8486    } else {
8487      Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
8488                         LN0->getPointerInfo().getWithOffset(PtrOff),
8489                         LN0->isVolatile(), LN0->isNonTemporal(),
8490                         LN0->isInvariant(), Align);
8491      Chain = Load.getValue(1);
8492      if (NVT.bitsLT(LVT))
8493        Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load);
8494      else
8495        Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load);
8496    }
8497    WorkListRemover DeadNodes(*this);
8498    SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8499    SDValue To[] = { Load, Chain };
8500    DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8501    // Since we're explcitly calling ReplaceAllUses, add the new node to the
8502    // worklist explicitly as well.
8503    AddToWorkList(Load.getNode());
8504    AddUsersToWorkList(Load.getNode()); // Add users too
8505    // Make sure to revisit this node to clean it up; it will usually be dead.
8506    AddToWorkList(N);
8507    return SDValue(N, 0);
8508  }
8509
8510  return SDValue();
8511}
8512
8513// Simplify (build_vec (ext )) to (bitcast (build_vec ))
8514SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8515  // We perform this optimization post type-legalization because
8516  // the type-legalizer often scalarizes integer-promoted vectors.
8517  // Performing this optimization before may create bit-casts which
8518  // will be type-legalized to complex code sequences.
8519  // We perform this optimization only before the operation legalizer because we
8520  // may introduce illegal operations.
8521  if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8522    return SDValue();
8523
8524  unsigned NumInScalars = N->getNumOperands();
8525  DebugLoc dl = N->getDebugLoc();
8526  EVT VT = N->getValueType(0);
8527
8528  // Check to see if this is a BUILD_VECTOR of a bunch of values
8529  // which come from any_extend or zero_extend nodes. If so, we can create
8530  // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8531  // optimizations. We do not handle sign-extend because we can't fill the sign
8532  // using shuffles.
8533  EVT SourceType = MVT::Other;
8534  bool AllAnyExt = true;
8535
8536  for (unsigned i = 0; i != NumInScalars; ++i) {
8537    SDValue In = N->getOperand(i);
8538    // Ignore undef inputs.
8539    if (In.getOpcode() == ISD::UNDEF) continue;
8540
8541    bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
8542    bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8543
8544    // Abort if the element is not an extension.
8545    if (!ZeroExt && !AnyExt) {
8546      SourceType = MVT::Other;
8547      break;
8548    }
8549
8550    // The input is a ZeroExt or AnyExt. Check the original type.
8551    EVT InTy = In.getOperand(0).getValueType();
8552
8553    // Check that all of the widened source types are the same.
8554    if (SourceType == MVT::Other)
8555      // First time.
8556      SourceType = InTy;
8557    else if (InTy != SourceType) {
8558      // Multiple income types. Abort.
8559      SourceType = MVT::Other;
8560      break;
8561    }
8562
8563    // Check if all of the extends are ANY_EXTENDs.
8564    AllAnyExt &= AnyExt;
8565  }
8566
8567  // In order to have valid types, all of the inputs must be extended from the
8568  // same source type and all of the inputs must be any or zero extend.
8569  // Scalar sizes must be a power of two.
8570  EVT OutScalarTy = VT.getScalarType();
8571  bool ValidTypes = SourceType != MVT::Other &&
8572                 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8573                 isPowerOf2_32(SourceType.getSizeInBits());
8574
8575  // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8576  // turn into a single shuffle instruction.
8577  if (!ValidTypes)
8578    return SDValue();
8579
8580  bool isLE = TLI.isLittleEndian();
8581  unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8582  assert(ElemRatio > 1 && "Invalid element size ratio");
8583  SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8584                               DAG.getConstant(0, SourceType);
8585
8586  unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
8587  SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8588
8589  // Populate the new build_vector
8590  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8591    SDValue Cast = N->getOperand(i);
8592    assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8593            Cast.getOpcode() == ISD::ZERO_EXTEND ||
8594            Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
8595    SDValue In;
8596    if (Cast.getOpcode() == ISD::UNDEF)
8597      In = DAG.getUNDEF(SourceType);
8598    else
8599      In = Cast->getOperand(0);
8600    unsigned Index = isLE ? (i * ElemRatio) :
8601                            (i * ElemRatio + (ElemRatio - 1));
8602
8603    assert(Index < Ops.size() && "Invalid index");
8604    Ops[Index] = In;
8605  }
8606
8607  // The type of the new BUILD_VECTOR node.
8608  EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
8609  assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
8610         "Invalid vector size");
8611  // Check if the new vector type is legal.
8612  if (!isTypeLegal(VecVT)) return SDValue();
8613
8614  // Make the new BUILD_VECTOR.
8615  SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
8616
8617  // The new BUILD_VECTOR node has the potential to be further optimized.
8618  AddToWorkList(BV.getNode());
8619  // Bitcast to the desired type.
8620  return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8621}
8622
8623SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
8624  EVT VT = N->getValueType(0);
8625
8626  unsigned NumInScalars = N->getNumOperands();
8627  DebugLoc dl = N->getDebugLoc();
8628
8629  EVT SrcVT = MVT::Other;
8630  unsigned Opcode = ISD::DELETED_NODE;
8631  unsigned NumDefs = 0;
8632
8633  for (unsigned i = 0; i != NumInScalars; ++i) {
8634    SDValue In = N->getOperand(i);
8635    unsigned Opc = In.getOpcode();
8636
8637    if (Opc == ISD::UNDEF)
8638      continue;
8639
8640    // If all scalar values are floats and converted from integers.
8641    if (Opcode == ISD::DELETED_NODE &&
8642        (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
8643      Opcode = Opc;
8644    }
8645
8646    if (Opc != Opcode)
8647      return SDValue();
8648
8649    EVT InVT = In.getOperand(0).getValueType();
8650
8651    // If all scalar values are typed differently, bail out. It's chosen to
8652    // simplify BUILD_VECTOR of integer types.
8653    if (SrcVT == MVT::Other)
8654      SrcVT = InVT;
8655    if (SrcVT != InVT)
8656      return SDValue();
8657    NumDefs++;
8658  }
8659
8660  // If the vector has just one element defined, it's not worth to fold it into
8661  // a vectorized one.
8662  if (NumDefs < 2)
8663    return SDValue();
8664
8665  assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
8666         && "Should only handle conversion from integer to float.");
8667  assert(SrcVT != MVT::Other && "Cannot determine source type!");
8668
8669  EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
8670
8671  if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
8672    return SDValue();
8673
8674  SmallVector<SDValue, 8> Opnds;
8675  for (unsigned i = 0; i != NumInScalars; ++i) {
8676    SDValue In = N->getOperand(i);
8677
8678    if (In.getOpcode() == ISD::UNDEF)
8679      Opnds.push_back(DAG.getUNDEF(SrcVT));
8680    else
8681      Opnds.push_back(In.getOperand(0));
8682  }
8683  SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
8684                           &Opnds[0], Opnds.size());
8685  AddToWorkList(BV.getNode());
8686
8687  return DAG.getNode(Opcode, dl, VT, BV);
8688}
8689
8690SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
8691  unsigned NumInScalars = N->getNumOperands();
8692  DebugLoc dl = N->getDebugLoc();
8693  EVT VT = N->getValueType(0);
8694
8695  // A vector built entirely of undefs is undef.
8696  if (ISD::allOperandsUndef(N))
8697    return DAG.getUNDEF(VT);
8698
8699  SDValue V = reduceBuildVecExtToExtBuildVec(N);
8700  if (V.getNode())
8701    return V;
8702
8703  V = reduceBuildVecConvertToConvertBuildVec(N);
8704  if (V.getNode())
8705    return V;
8706
8707  // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
8708  // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
8709  // at most two distinct vectors, turn this into a shuffle node.
8710
8711  // May only combine to shuffle after legalize if shuffle is legal.
8712  if (LegalOperations &&
8713      !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
8714    return SDValue();
8715
8716  SDValue VecIn1, VecIn2;
8717  for (unsigned i = 0; i != NumInScalars; ++i) {
8718    // Ignore undef inputs.
8719    if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
8720
8721    // If this input is something other than a EXTRACT_VECTOR_ELT with a
8722    // constant index, bail out.
8723    if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8724        !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
8725      VecIn1 = VecIn2 = SDValue(0, 0);
8726      break;
8727    }
8728
8729    // We allow up to two distinct input vectors.
8730    SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
8731    if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
8732      continue;
8733
8734    if (VecIn1.getNode() == 0) {
8735      VecIn1 = ExtractedFromVec;
8736    } else if (VecIn2.getNode() == 0) {
8737      VecIn2 = ExtractedFromVec;
8738    } else {
8739      // Too many inputs.
8740      VecIn1 = VecIn2 = SDValue(0, 0);
8741      break;
8742    }
8743  }
8744
8745    // If everything is good, we can make a shuffle operation.
8746  if (VecIn1.getNode()) {
8747    SmallVector<int, 8> Mask;
8748    for (unsigned i = 0; i != NumInScalars; ++i) {
8749      if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
8750        Mask.push_back(-1);
8751        continue;
8752      }
8753
8754      // If extracting from the first vector, just use the index directly.
8755      SDValue Extract = N->getOperand(i);
8756      SDValue ExtVal = Extract.getOperand(1);
8757      if (Extract.getOperand(0) == VecIn1) {
8758        unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
8759        if (ExtIndex > VT.getVectorNumElements())
8760          return SDValue();
8761
8762        Mask.push_back(ExtIndex);
8763        continue;
8764      }
8765
8766      // Otherwise, use InIdx + VecSize
8767      unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
8768      Mask.push_back(Idx+NumInScalars);
8769    }
8770
8771    // We can't generate a shuffle node with mismatched input and output types.
8772    // Attempt to transform a single input vector to the correct type.
8773    if ((VT != VecIn1.getValueType())) {
8774      // We don't support shuffeling between TWO values of different types.
8775      if (VecIn2.getNode() != 0)
8776        return SDValue();
8777
8778      // We only support widening of vectors which are half the size of the
8779      // output registers. For example XMM->YMM widening on X86 with AVX.
8780      if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
8781        return SDValue();
8782
8783      // If the input vector type has a different base type to the output
8784      // vector type, bail out.
8785      if (VecIn1.getValueType().getVectorElementType() !=
8786          VT.getVectorElementType())
8787        return SDValue();
8788
8789      // Widen the input vector by adding undef values.
8790      VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8791                           VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
8792    }
8793
8794    // If VecIn2 is unused then change it to undef.
8795    VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
8796
8797    // Check that we were able to transform all incoming values to the same
8798    // type.
8799    if (VecIn2.getValueType() != VecIn1.getValueType() ||
8800        VecIn1.getValueType() != VT)
8801          return SDValue();
8802
8803    // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
8804    if (!isTypeLegal(VT))
8805      return SDValue();
8806
8807    // Return the new VECTOR_SHUFFLE node.
8808    SDValue Ops[2];
8809    Ops[0] = VecIn1;
8810    Ops[1] = VecIn2;
8811    return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
8812  }
8813
8814  return SDValue();
8815}
8816
8817SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
8818  // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
8819  // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
8820  // inputs come from at most two distinct vectors, turn this into a shuffle
8821  // node.
8822
8823  // If we only have one input vector, we don't need to do any concatenation.
8824  if (N->getNumOperands() == 1)
8825    return N->getOperand(0);
8826
8827  // Check if all of the operands are undefs.
8828  if (ISD::allOperandsUndef(N))
8829    return DAG.getUNDEF(N->getValueType(0));
8830
8831  return SDValue();
8832}
8833
8834SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
8835  EVT NVT = N->getValueType(0);
8836  SDValue V = N->getOperand(0);
8837
8838  if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
8839    // Handle only simple case where vector being inserted and vector
8840    // being extracted are of same type, and are half size of larger vectors.
8841    EVT BigVT = V->getOperand(0).getValueType();
8842    EVT SmallVT = V->getOperand(1).getValueType();
8843    if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
8844      return SDValue();
8845
8846    // Only handle cases where both indexes are constants with the same type.
8847    ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
8848    ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
8849
8850    if (InsIdx && ExtIdx &&
8851        InsIdx->getValueType(0).getSizeInBits() <= 64 &&
8852        ExtIdx->getValueType(0).getSizeInBits() <= 64) {
8853      // Combine:
8854      //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
8855      // Into:
8856      //    indices are equal => V1
8857      //    otherwise => (extract_subvec V1, ExtIdx)
8858      if (InsIdx->getZExtValue() == ExtIdx->getZExtValue())
8859        return V->getOperand(1);
8860      return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT,
8861                         V->getOperand(0), N->getOperand(1));
8862    }
8863  }
8864
8865  if (V->getOpcode() == ISD::CONCAT_VECTORS) {
8866    // Combine:
8867    //    (extract_subvec (concat V1, V2, ...), i)
8868    // Into:
8869    //    Vi if possible
8870    // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
8871    if (V->getOperand(0).getValueType() != NVT)
8872      return SDValue();
8873    unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8874    unsigned NumElems = NVT.getVectorNumElements();
8875    assert((Idx % NumElems) == 0 &&
8876           "IDX in concat is not a multiple of the result vector length.");
8877    return V->getOperand(Idx / NumElems);
8878  }
8879
8880  return SDValue();
8881}
8882
8883SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
8884  EVT VT = N->getValueType(0);
8885  unsigned NumElts = VT.getVectorNumElements();
8886
8887  SDValue N0 = N->getOperand(0);
8888  SDValue N1 = N->getOperand(1);
8889
8890  assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
8891
8892  // Canonicalize shuffle undef, undef -> undef
8893  if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
8894    return DAG.getUNDEF(VT);
8895
8896  ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8897
8898  // Canonicalize shuffle v, v -> v, undef
8899  if (N0 == N1) {
8900    SmallVector<int, 8> NewMask;
8901    for (unsigned i = 0; i != NumElts; ++i) {
8902      int Idx = SVN->getMaskElt(i);
8903      if (Idx >= (int)NumElts) Idx -= NumElts;
8904      NewMask.push_back(Idx);
8905    }
8906    return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT),
8907                                &NewMask[0]);
8908  }
8909
8910  // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
8911  if (N0.getOpcode() == ISD::UNDEF) {
8912    SmallVector<int, 8> NewMask;
8913    for (unsigned i = 0; i != NumElts; ++i) {
8914      int Idx = SVN->getMaskElt(i);
8915      if (Idx >= 0) {
8916        if (Idx < (int)NumElts)
8917          Idx += NumElts;
8918        else
8919          Idx -= NumElts;
8920      }
8921      NewMask.push_back(Idx);
8922    }
8923    return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT),
8924                                &NewMask[0]);
8925  }
8926
8927  // Remove references to rhs if it is undef
8928  if (N1.getOpcode() == ISD::UNDEF) {
8929    bool Changed = false;
8930    SmallVector<int, 8> NewMask;
8931    for (unsigned i = 0; i != NumElts; ++i) {
8932      int Idx = SVN->getMaskElt(i);
8933      if (Idx >= (int)NumElts) {
8934        Idx = -1;
8935        Changed = true;
8936      }
8937      NewMask.push_back(Idx);
8938    }
8939    if (Changed)
8940      return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]);
8941  }
8942
8943  // If it is a splat, check if the argument vector is another splat or a
8944  // build_vector with all scalar elements the same.
8945  if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
8946    SDNode *V = N0.getNode();
8947
8948    // If this is a bit convert that changes the element type of the vector but
8949    // not the number of vector elements, look through it.  Be careful not to
8950    // look though conversions that change things like v4f32 to v2f64.
8951    if (V->getOpcode() == ISD::BITCAST) {
8952      SDValue ConvInput = V->getOperand(0);
8953      if (ConvInput.getValueType().isVector() &&
8954          ConvInput.getValueType().getVectorNumElements() == NumElts)
8955        V = ConvInput.getNode();
8956    }
8957
8958    if (V->getOpcode() == ISD::BUILD_VECTOR) {
8959      assert(V->getNumOperands() == NumElts &&
8960             "BUILD_VECTOR has wrong number of operands");
8961      SDValue Base;
8962      bool AllSame = true;
8963      for (unsigned i = 0; i != NumElts; ++i) {
8964        if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
8965          Base = V->getOperand(i);
8966          break;
8967        }
8968      }
8969      // Splat of <u, u, u, u>, return <u, u, u, u>
8970      if (!Base.getNode())
8971        return N0;
8972      for (unsigned i = 0; i != NumElts; ++i) {
8973        if (V->getOperand(i) != Base) {
8974          AllSame = false;
8975          break;
8976        }
8977      }
8978      // Splat of <x, x, x, x>, return <x, x, x, x>
8979      if (AllSame)
8980        return N0;
8981    }
8982  }
8983
8984  // If this shuffle node is simply a swizzle of another shuffle node,
8985  // and it reverses the swizzle of the previous shuffle then we can
8986  // optimize shuffle(shuffle(x, undef), undef) -> x.
8987  if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
8988      N1.getOpcode() == ISD::UNDEF) {
8989
8990    ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
8991
8992    // Shuffle nodes can only reverse shuffles with a single non-undef value.
8993    if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
8994      return SDValue();
8995
8996    // The incoming shuffle must be of the same type as the result of the
8997    // current shuffle.
8998    assert(OtherSV->getOperand(0).getValueType() == VT &&
8999           "Shuffle types don't match");
9000
9001    for (unsigned i = 0; i != NumElts; ++i) {
9002      int Idx = SVN->getMaskElt(i);
9003      assert(Idx < (int)NumElts && "Index references undef operand");
9004      // Next, this index comes from the first value, which is the incoming
9005      // shuffle. Adopt the incoming index.
9006      if (Idx >= 0)
9007        Idx = OtherSV->getMaskElt(Idx);
9008
9009      // The combined shuffle must map each index to itself.
9010      if (Idx >= 0 && (unsigned)Idx != i)
9011        return SDValue();
9012    }
9013
9014    return OtherSV->getOperand(0);
9015  }
9016
9017  return SDValue();
9018}
9019
9020SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
9021  if (!TLI.getShouldFoldAtomicFences())
9022    return SDValue();
9023
9024  SDValue atomic = N->getOperand(0);
9025  switch (atomic.getOpcode()) {
9026    case ISD::ATOMIC_CMP_SWAP:
9027    case ISD::ATOMIC_SWAP:
9028    case ISD::ATOMIC_LOAD_ADD:
9029    case ISD::ATOMIC_LOAD_SUB:
9030    case ISD::ATOMIC_LOAD_AND:
9031    case ISD::ATOMIC_LOAD_OR:
9032    case ISD::ATOMIC_LOAD_XOR:
9033    case ISD::ATOMIC_LOAD_NAND:
9034    case ISD::ATOMIC_LOAD_MIN:
9035    case ISD::ATOMIC_LOAD_MAX:
9036    case ISD::ATOMIC_LOAD_UMIN:
9037    case ISD::ATOMIC_LOAD_UMAX:
9038      break;
9039    default:
9040      return SDValue();
9041  }
9042
9043  SDValue fence = atomic.getOperand(0);
9044  if (fence.getOpcode() != ISD::MEMBARRIER)
9045    return SDValue();
9046
9047  switch (atomic.getOpcode()) {
9048    case ISD::ATOMIC_CMP_SWAP:
9049      return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
9050                                    fence.getOperand(0),
9051                                    atomic.getOperand(1), atomic.getOperand(2),
9052                                    atomic.getOperand(3)), atomic.getResNo());
9053    case ISD::ATOMIC_SWAP:
9054    case ISD::ATOMIC_LOAD_ADD:
9055    case ISD::ATOMIC_LOAD_SUB:
9056    case ISD::ATOMIC_LOAD_AND:
9057    case ISD::ATOMIC_LOAD_OR:
9058    case ISD::ATOMIC_LOAD_XOR:
9059    case ISD::ATOMIC_LOAD_NAND:
9060    case ISD::ATOMIC_LOAD_MIN:
9061    case ISD::ATOMIC_LOAD_MAX:
9062    case ISD::ATOMIC_LOAD_UMIN:
9063    case ISD::ATOMIC_LOAD_UMAX:
9064      return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
9065                                    fence.getOperand(0),
9066                                    atomic.getOperand(1), atomic.getOperand(2)),
9067                     atomic.getResNo());
9068    default:
9069      return SDValue();
9070  }
9071}
9072
9073/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9074/// an AND to a vector_shuffle with the destination vector and a zero vector.
9075/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9076///      vector_shuffle V, Zero, <0, 4, 2, 4>
9077SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9078  EVT VT = N->getValueType(0);
9079  DebugLoc dl = N->getDebugLoc();
9080  SDValue LHS = N->getOperand(0);
9081  SDValue RHS = N->getOperand(1);
9082  if (N->getOpcode() == ISD::AND) {
9083    if (RHS.getOpcode() == ISD::BITCAST)
9084      RHS = RHS.getOperand(0);
9085    if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9086      SmallVector<int, 8> Indices;
9087      unsigned NumElts = RHS.getNumOperands();
9088      for (unsigned i = 0; i != NumElts; ++i) {
9089        SDValue Elt = RHS.getOperand(i);
9090        if (!isa<ConstantSDNode>(Elt))
9091          return SDValue();
9092
9093        if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9094          Indices.push_back(i);
9095        else if (cast<ConstantSDNode>(Elt)->isNullValue())
9096          Indices.push_back(NumElts);
9097        else
9098          return SDValue();
9099      }
9100
9101      // Let's see if the target supports this vector_shuffle.
9102      EVT RVT = RHS.getValueType();
9103      if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9104        return SDValue();
9105
9106      // Return the new VECTOR_SHUFFLE node.
9107      EVT EltVT = RVT.getVectorElementType();
9108      SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9109                                     DAG.getConstant(0, EltVT));
9110      SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9111                                 RVT, &ZeroOps[0], ZeroOps.size());
9112      LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9113      SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9114      return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9115    }
9116  }
9117
9118  return SDValue();
9119}
9120
9121/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9122SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9123  // After legalize, the target may be depending on adds and other
9124  // binary ops to provide legal ways to construct constants or other
9125  // things. Simplifying them may result in a loss of legality.
9126  if (LegalOperations) return SDValue();
9127
9128  assert(N->getValueType(0).isVector() &&
9129         "SimplifyVBinOp only works on vectors!");
9130
9131  SDValue LHS = N->getOperand(0);
9132  SDValue RHS = N->getOperand(1);
9133  SDValue Shuffle = XformToShuffleWithZero(N);
9134  if (Shuffle.getNode()) return Shuffle;
9135
9136  // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9137  // this operation.
9138  if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9139      RHS.getOpcode() == ISD::BUILD_VECTOR) {
9140    SmallVector<SDValue, 8> Ops;
9141    for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9142      SDValue LHSOp = LHS.getOperand(i);
9143      SDValue RHSOp = RHS.getOperand(i);
9144      // If these two elements can't be folded, bail out.
9145      if ((LHSOp.getOpcode() != ISD::UNDEF &&
9146           LHSOp.getOpcode() != ISD::Constant &&
9147           LHSOp.getOpcode() != ISD::ConstantFP) ||
9148          (RHSOp.getOpcode() != ISD::UNDEF &&
9149           RHSOp.getOpcode() != ISD::Constant &&
9150           RHSOp.getOpcode() != ISD::ConstantFP))
9151        break;
9152
9153      // Can't fold divide by zero.
9154      if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9155          N->getOpcode() == ISD::FDIV) {
9156        if ((RHSOp.getOpcode() == ISD::Constant &&
9157             cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9158            (RHSOp.getOpcode() == ISD::ConstantFP &&
9159             cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9160          break;
9161      }
9162
9163      EVT VT = LHSOp.getValueType();
9164      EVT RVT = RHSOp.getValueType();
9165      if (RVT != VT) {
9166        // Integer BUILD_VECTOR operands may have types larger than the element
9167        // size (e.g., when the element type is not legal).  Prior to type
9168        // legalization, the types may not match between the two BUILD_VECTORS.
9169        // Truncate one of the operands to make them match.
9170        if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9171          RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
9172        } else {
9173          LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
9174          VT = RVT;
9175        }
9176      }
9177      SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
9178                                   LHSOp, RHSOp);
9179      if (FoldOp.getOpcode() != ISD::UNDEF &&
9180          FoldOp.getOpcode() != ISD::Constant &&
9181          FoldOp.getOpcode() != ISD::ConstantFP)
9182        break;
9183      Ops.push_back(FoldOp);
9184      AddToWorkList(FoldOp.getNode());
9185    }
9186
9187    if (Ops.size() == LHS.getNumOperands())
9188      return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9189                         LHS.getValueType(), &Ops[0], Ops.size());
9190  }
9191
9192  return SDValue();
9193}
9194
9195/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9196SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9197  // After legalize, the target may be depending on adds and other
9198  // binary ops to provide legal ways to construct constants or other
9199  // things. Simplifying them may result in a loss of legality.
9200  if (LegalOperations) return SDValue();
9201
9202  assert(N->getValueType(0).isVector() &&
9203         "SimplifyVUnaryOp only works on vectors!");
9204
9205  SDValue N0 = N->getOperand(0);
9206
9207  if (N0.getOpcode() != ISD::BUILD_VECTOR)
9208    return SDValue();
9209
9210  // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9211  SmallVector<SDValue, 8> Ops;
9212  for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9213    SDValue Op = N0.getOperand(i);
9214    if (Op.getOpcode() != ISD::UNDEF &&
9215        Op.getOpcode() != ISD::ConstantFP)
9216      break;
9217    EVT EltVT = Op.getValueType();
9218    SDValue FoldOp = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), EltVT, Op);
9219    if (FoldOp.getOpcode() != ISD::UNDEF &&
9220        FoldOp.getOpcode() != ISD::ConstantFP)
9221      break;
9222    Ops.push_back(FoldOp);
9223    AddToWorkList(FoldOp.getNode());
9224  }
9225
9226  if (Ops.size() != N0.getNumOperands())
9227    return SDValue();
9228
9229  return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9230                     N0.getValueType(), &Ops[0], Ops.size());
9231}
9232
9233SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
9234                                    SDValue N1, SDValue N2){
9235  assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9236
9237  SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9238                                 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9239
9240  // If we got a simplified select_cc node back from SimplifySelectCC, then
9241  // break it down into a new SETCC node, and a new SELECT node, and then return
9242  // the SELECT node, since we were called with a SELECT node.
9243  if (SCC.getNode()) {
9244    // Check to see if we got a select_cc back (to turn into setcc/select).
9245    // Otherwise, just return whatever node we got back, like fabs.
9246    if (SCC.getOpcode() == ISD::SELECT_CC) {
9247      SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
9248                                  N0.getValueType(),
9249                                  SCC.getOperand(0), SCC.getOperand(1),
9250                                  SCC.getOperand(4));
9251      AddToWorkList(SETCC.getNode());
9252      return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
9253                         SCC.getOperand(2), SCC.getOperand(3), SETCC);
9254    }
9255
9256    return SCC;
9257  }
9258  return SDValue();
9259}
9260
9261/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9262/// are the two values being selected between, see if we can simplify the
9263/// select.  Callers of this should assume that TheSelect is deleted if this
9264/// returns true.  As such, they should return the appropriate thing (e.g. the
9265/// node) back to the top-level of the DAG combiner loop to avoid it being
9266/// looked at.
9267bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9268                                    SDValue RHS) {
9269
9270  // Cannot simplify select with vector condition
9271  if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9272
9273  // If this is a select from two identical things, try to pull the operation
9274  // through the select.
9275  if (LHS.getOpcode() != RHS.getOpcode() ||
9276      !LHS.hasOneUse() || !RHS.hasOneUse())
9277    return false;
9278
9279  // If this is a load and the token chain is identical, replace the select
9280  // of two loads with a load through a select of the address to load from.
9281  // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9282  // constants have been dropped into the constant pool.
9283  if (LHS.getOpcode() == ISD::LOAD) {
9284    LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9285    LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9286
9287    // Token chains must be identical.
9288    if (LHS.getOperand(0) != RHS.getOperand(0) ||
9289        // Do not let this transformation reduce the number of volatile loads.
9290        LLD->isVolatile() || RLD->isVolatile() ||
9291        // If this is an EXTLOAD, the VT's must match.
9292        LLD->getMemoryVT() != RLD->getMemoryVT() ||
9293        // If this is an EXTLOAD, the kind of extension must match.
9294        (LLD->getExtensionType() != RLD->getExtensionType() &&
9295         // The only exception is if one of the extensions is anyext.
9296         LLD->getExtensionType() != ISD::EXTLOAD &&
9297         RLD->getExtensionType() != ISD::EXTLOAD) ||
9298        // FIXME: this discards src value information.  This is
9299        // over-conservative. It would be beneficial to be able to remember
9300        // both potential memory locations.  Since we are discarding
9301        // src value info, don't do the transformation if the memory
9302        // locations are not in the default address space.
9303        LLD->getPointerInfo().getAddrSpace() != 0 ||
9304        RLD->getPointerInfo().getAddrSpace() != 0)
9305      return false;
9306
9307    // Check that the select condition doesn't reach either load.  If so,
9308    // folding this will induce a cycle into the DAG.  If not, this is safe to
9309    // xform, so create a select of the addresses.
9310    SDValue Addr;
9311    if (TheSelect->getOpcode() == ISD::SELECT) {
9312      SDNode *CondNode = TheSelect->getOperand(0).getNode();
9313      if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9314          (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9315        return false;
9316      // The loads must not depend on one another.
9317      if (LLD->isPredecessorOf(RLD) ||
9318          RLD->isPredecessorOf(LLD))
9319        return false;
9320      Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
9321                         LLD->getBasePtr().getValueType(),
9322                         TheSelect->getOperand(0), LLD->getBasePtr(),
9323                         RLD->getBasePtr());
9324    } else {  // Otherwise SELECT_CC
9325      SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9326      SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9327
9328      if ((LLD->hasAnyUseOfValue(1) &&
9329           (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9330          (RLD->hasAnyUseOfValue(1) &&
9331           (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9332        return false;
9333
9334      Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
9335                         LLD->getBasePtr().getValueType(),
9336                         TheSelect->getOperand(0),
9337                         TheSelect->getOperand(1),
9338                         LLD->getBasePtr(), RLD->getBasePtr(),
9339                         TheSelect->getOperand(4));
9340    }
9341
9342    SDValue Load;
9343    if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9344      Load = DAG.getLoad(TheSelect->getValueType(0),
9345                         TheSelect->getDebugLoc(),
9346                         // FIXME: Discards pointer info.
9347                         LLD->getChain(), Addr, MachinePointerInfo(),
9348                         LLD->isVolatile(), LLD->isNonTemporal(),
9349                         LLD->isInvariant(), LLD->getAlignment());
9350    } else {
9351      Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9352                            RLD->getExtensionType() : LLD->getExtensionType(),
9353                            TheSelect->getDebugLoc(),
9354                            TheSelect->getValueType(0),
9355                            // FIXME: Discards pointer info.
9356                            LLD->getChain(), Addr, MachinePointerInfo(),
9357                            LLD->getMemoryVT(), LLD->isVolatile(),
9358                            LLD->isNonTemporal(), LLD->getAlignment());
9359    }
9360
9361    // Users of the select now use the result of the load.
9362    CombineTo(TheSelect, Load);
9363
9364    // Users of the old loads now use the new load's chain.  We know the
9365    // old-load value is dead now.
9366    CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9367    CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9368    return true;
9369  }
9370
9371  return false;
9372}
9373
9374/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9375/// where 'cond' is the comparison specified by CC.
9376SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
9377                                      SDValue N2, SDValue N3,
9378                                      ISD::CondCode CC, bool NotExtCompare) {
9379  // (x ? y : y) -> y.
9380  if (N2 == N3) return N2;
9381
9382  EVT VT = N2.getValueType();
9383  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9384  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9385  ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9386
9387  // Determine if the condition we're dealing with is constant
9388  SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
9389                              N0, N1, CC, DL, false);
9390  if (SCC.getNode()) AddToWorkList(SCC.getNode());
9391  ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9392
9393  // fold select_cc true, x, y -> x
9394  if (SCCC && !SCCC->isNullValue())
9395    return N2;
9396  // fold select_cc false, x, y -> y
9397  if (SCCC && SCCC->isNullValue())
9398    return N3;
9399
9400  // Check to see if we can simplify the select into an fabs node
9401  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9402    // Allow either -0.0 or 0.0
9403    if (CFP->getValueAPF().isZero()) {
9404      // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9405      if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9406          N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9407          N2 == N3.getOperand(0))
9408        return DAG.getNode(ISD::FABS, DL, VT, N0);
9409
9410      // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9411      if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9412          N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9413          N2.getOperand(0) == N3)
9414        return DAG.getNode(ISD::FABS, DL, VT, N3);
9415    }
9416  }
9417
9418  // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9419  // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9420  // in it.  This is a win when the constant is not otherwise available because
9421  // it replaces two constant pool loads with one.  We only do this if the FP
9422  // type is known to be legal, because if it isn't, then we are before legalize
9423  // types an we want the other legalization to happen first (e.g. to avoid
9424  // messing with soft float) and if the ConstantFP is not legal, because if
9425  // it is legal, we may not need to store the FP constant in a constant pool.
9426  if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9427    if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9428      if (TLI.isTypeLegal(N2.getValueType()) &&
9429          (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9430           TargetLowering::Legal) &&
9431          // If both constants have multiple uses, then we won't need to do an
9432          // extra load, they are likely around in registers for other users.
9433          (TV->hasOneUse() || FV->hasOneUse())) {
9434        Constant *Elts[] = {
9435          const_cast<ConstantFP*>(FV->getConstantFPValue()),
9436          const_cast<ConstantFP*>(TV->getConstantFPValue())
9437        };
9438        Type *FPTy = Elts[0]->getType();
9439        const DataLayout &TD = *TLI.getDataLayout();
9440
9441        // Create a ConstantArray of the two constants.
9442        Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9443        SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9444                                            TD.getPrefTypeAlignment(FPTy));
9445        unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9446
9447        // Get the offsets to the 0 and 1 element of the array so that we can
9448        // select between them.
9449        SDValue Zero = DAG.getIntPtrConstant(0);
9450        unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9451        SDValue One = DAG.getIntPtrConstant(EltSize);
9452
9453        SDValue Cond = DAG.getSetCC(DL,
9454                                    TLI.getSetCCResultType(N0.getValueType()),
9455                                    N0, N1, CC);
9456        AddToWorkList(Cond.getNode());
9457        SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
9458                                        Cond, One, Zero);
9459        AddToWorkList(CstOffset.getNode());
9460        CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
9461                            CstOffset);
9462        AddToWorkList(CPIdx.getNode());
9463        return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9464                           MachinePointerInfo::getConstantPool(), false,
9465                           false, false, Alignment);
9466
9467      }
9468    }
9469
9470  // Check to see if we can perform the "gzip trick", transforming
9471  // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9472  if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9473      (N1C->isNullValue() ||                         // (a < 0) ? b : 0
9474       (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
9475    EVT XType = N0.getValueType();
9476    EVT AType = N2.getValueType();
9477    if (XType.bitsGE(AType)) {
9478      // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9479      // single-bit constant.
9480      if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9481        unsigned ShCtV = N2C->getAPIntValue().logBase2();
9482        ShCtV = XType.getSizeInBits()-ShCtV-1;
9483        SDValue ShCt = DAG.getConstant(ShCtV,
9484                                       getShiftAmountTy(N0.getValueType()));
9485        SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
9486                                    XType, N0, ShCt);
9487        AddToWorkList(Shift.getNode());
9488
9489        if (XType.bitsGT(AType)) {
9490          Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9491          AddToWorkList(Shift.getNode());
9492        }
9493
9494        return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9495      }
9496
9497      SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
9498                                  XType, N0,
9499                                  DAG.getConstant(XType.getSizeInBits()-1,
9500                                         getShiftAmountTy(N0.getValueType())));
9501      AddToWorkList(Shift.getNode());
9502
9503      if (XType.bitsGT(AType)) {
9504        Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9505        AddToWorkList(Shift.getNode());
9506      }
9507
9508      return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9509    }
9510  }
9511
9512  // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9513  // where y is has a single bit set.
9514  // A plaintext description would be, we can turn the SELECT_CC into an AND
9515  // when the condition can be materialized as an all-ones register.  Any
9516  // single bit-test can be materialized as an all-ones register with
9517  // shift-left and shift-right-arith.
9518  if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9519      N0->getValueType(0) == VT &&
9520      N1C && N1C->isNullValue() &&
9521      N2C && N2C->isNullValue()) {
9522    SDValue AndLHS = N0->getOperand(0);
9523    ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9524    if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9525      // Shift the tested bit over the sign bit.
9526      APInt AndMask = ConstAndRHS->getAPIntValue();
9527      SDValue ShlAmt =
9528        DAG.getConstant(AndMask.countLeadingZeros(),
9529                        getShiftAmountTy(AndLHS.getValueType()));
9530      SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
9531
9532      // Now arithmetic right shift it all the way over, so the result is either
9533      // all-ones, or zero.
9534      SDValue ShrAmt =
9535        DAG.getConstant(AndMask.getBitWidth()-1,
9536                        getShiftAmountTy(Shl.getValueType()));
9537      SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
9538
9539      return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
9540    }
9541  }
9542
9543  // fold select C, 16, 0 -> shl C, 4
9544  if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
9545    TLI.getBooleanContents(N0.getValueType().isVector()) ==
9546      TargetLowering::ZeroOrOneBooleanContent) {
9547
9548    // If the caller doesn't want us to simplify this into a zext of a compare,
9549    // don't do it.
9550    if (NotExtCompare && N2C->getAPIntValue() == 1)
9551      return SDValue();
9552
9553    // Get a SetCC of the condition
9554    // NOTE: Don't create a SETCC if it's not legal on this target.
9555    if (!LegalOperations ||
9556        TLI.isOperationLegal(ISD::SETCC,
9557          LegalTypes ? TLI.getSetCCResultType(N0.getValueType()) : MVT::i1)) {
9558      SDValue Temp, SCC;
9559      // cast from setcc result type to select result type
9560      if (LegalTypes) {
9561        SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
9562                            N0, N1, CC);
9563        if (N2.getValueType().bitsLT(SCC.getValueType()))
9564          Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(),
9565                                        N2.getValueType());
9566        else
9567          Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
9568                             N2.getValueType(), SCC);
9569      } else {
9570        SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
9571        Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
9572                           N2.getValueType(), SCC);
9573      }
9574
9575      AddToWorkList(SCC.getNode());
9576      AddToWorkList(Temp.getNode());
9577
9578      if (N2C->getAPIntValue() == 1)
9579        return Temp;
9580
9581      // shl setcc result by log2 n2c
9582      return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
9583                         DAG.getConstant(N2C->getAPIntValue().logBase2(),
9584                                         getShiftAmountTy(Temp.getValueType())));
9585    }
9586  }
9587
9588  // Check to see if this is the equivalent of setcc
9589  // FIXME: Turn all of these into setcc if setcc if setcc is legal
9590  // otherwise, go ahead with the folds.
9591  if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
9592    EVT XType = N0.getValueType();
9593    if (!LegalOperations ||
9594        TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
9595      SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
9596      if (Res.getValueType() != VT)
9597        Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
9598      return Res;
9599    }
9600
9601    // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
9602    if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
9603        (!LegalOperations ||
9604         TLI.isOperationLegal(ISD::CTLZ, XType))) {
9605      SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
9606      return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
9607                         DAG.getConstant(Log2_32(XType.getSizeInBits()),
9608                                       getShiftAmountTy(Ctlz.getValueType())));
9609    }
9610    // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
9611    if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
9612      SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
9613                                  XType, DAG.getConstant(0, XType), N0);
9614      SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
9615      return DAG.getNode(ISD::SRL, DL, XType,
9616                         DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
9617                         DAG.getConstant(XType.getSizeInBits()-1,
9618                                         getShiftAmountTy(XType)));
9619    }
9620    // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
9621    if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
9622      SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
9623                                 DAG.getConstant(XType.getSizeInBits()-1,
9624                                         getShiftAmountTy(N0.getValueType())));
9625      return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
9626    }
9627  }
9628
9629  // Check to see if this is an integer abs.
9630  // select_cc setg[te] X,  0,  X, -X ->
9631  // select_cc setgt    X, -1,  X, -X ->
9632  // select_cc setl[te] X,  0, -X,  X ->
9633  // select_cc setlt    X,  1, -X,  X ->
9634  // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
9635  if (N1C) {
9636    ConstantSDNode *SubC = NULL;
9637    if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
9638         (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
9639        N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
9640      SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
9641    else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
9642              (N1C->isOne() && CC == ISD::SETLT)) &&
9643             N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
9644      SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
9645
9646    EVT XType = N0.getValueType();
9647    if (SubC && SubC->isNullValue() && XType.isInteger()) {
9648      SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
9649                                  N0,
9650                                  DAG.getConstant(XType.getSizeInBits()-1,
9651                                         getShiftAmountTy(N0.getValueType())));
9652      SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
9653                                XType, N0, Shift);
9654      AddToWorkList(Shift.getNode());
9655      AddToWorkList(Add.getNode());
9656      return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
9657    }
9658  }
9659
9660  return SDValue();
9661}
9662
9663/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
9664SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
9665                                   SDValue N1, ISD::CondCode Cond,
9666                                   DebugLoc DL, bool foldBooleans) {
9667  TargetLowering::DAGCombinerInfo
9668    DagCombineInfo(DAG, Level, false, this);
9669  return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
9670}
9671
9672/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
9673/// return a DAG expression to select that will generate the same value by
9674/// multiplying by a magic number.  See:
9675/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
9676SDValue DAGCombiner::BuildSDIV(SDNode *N) {
9677  std::vector<SDNode*> Built;
9678  SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
9679
9680  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
9681       ii != ee; ++ii)
9682    AddToWorkList(*ii);
9683  return S;
9684}
9685
9686/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
9687/// return a DAG expression to select that will generate the same value by
9688/// multiplying by a magic number.  See:
9689/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
9690SDValue DAGCombiner::BuildUDIV(SDNode *N) {
9691  std::vector<SDNode*> Built;
9692  SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
9693
9694  for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
9695       ii != ee; ++ii)
9696    AddToWorkList(*ii);
9697  return S;
9698}
9699
9700/// FindBaseOffset - Return true if base is a frame index, which is known not
9701// to alias with anything but itself.  Provides base object and offset as
9702// results.
9703static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
9704                           const GlobalValue *&GV, const void *&CV) {
9705  // Assume it is a primitive operation.
9706  Base = Ptr; Offset = 0; GV = 0; CV = 0;
9707
9708  // If it's an adding a simple constant then integrate the offset.
9709  if (Base.getOpcode() == ISD::ADD) {
9710    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
9711      Base = Base.getOperand(0);
9712      Offset += C->getZExtValue();
9713    }
9714  }
9715
9716  // Return the underlying GlobalValue, and update the Offset.  Return false
9717  // for GlobalAddressSDNode since the same GlobalAddress may be represented
9718  // by multiple nodes with different offsets.
9719  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
9720    GV = G->getGlobal();
9721    Offset += G->getOffset();
9722    return false;
9723  }
9724
9725  // Return the underlying Constant value, and update the Offset.  Return false
9726  // for ConstantSDNodes since the same constant pool entry may be represented
9727  // by multiple nodes with different offsets.
9728  if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
9729    CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
9730                                         : (const void *)C->getConstVal();
9731    Offset += C->getOffset();
9732    return false;
9733  }
9734  // If it's any of the following then it can't alias with anything but itself.
9735  return isa<FrameIndexSDNode>(Base);
9736}
9737
9738/// isAlias - Return true if there is any possibility that the two addresses
9739/// overlap.
9740bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
9741                          const Value *SrcValue1, int SrcValueOffset1,
9742                          unsigned SrcValueAlign1,
9743                          const MDNode *TBAAInfo1,
9744                          SDValue Ptr2, int64_t Size2,
9745                          const Value *SrcValue2, int SrcValueOffset2,
9746                          unsigned SrcValueAlign2,
9747                          const MDNode *TBAAInfo2) const {
9748  // If they are the same then they must be aliases.
9749  if (Ptr1 == Ptr2) return true;
9750
9751  // Gather base node and offset information.
9752  SDValue Base1, Base2;
9753  int64_t Offset1, Offset2;
9754  const GlobalValue *GV1, *GV2;
9755  const void *CV1, *CV2;
9756  bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
9757  bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
9758
9759  // If they have a same base address then check to see if they overlap.
9760  if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
9761    return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
9762
9763  // It is possible for different frame indices to alias each other, mostly
9764  // when tail call optimization reuses return address slots for arguments.
9765  // To catch this case, look up the actual index of frame indices to compute
9766  // the real alias relationship.
9767  if (isFrameIndex1 && isFrameIndex2) {
9768    MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9769    Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
9770    Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
9771    return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
9772  }
9773
9774  // Otherwise, if we know what the bases are, and they aren't identical, then
9775  // we know they cannot alias.
9776  if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
9777    return false;
9778
9779  // If we know required SrcValue1 and SrcValue2 have relatively large alignment
9780  // compared to the size and offset of the access, we may be able to prove they
9781  // do not alias.  This check is conservative for now to catch cases created by
9782  // splitting vector types.
9783  if ((SrcValueAlign1 == SrcValueAlign2) &&
9784      (SrcValueOffset1 != SrcValueOffset2) &&
9785      (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
9786    int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
9787    int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
9788
9789    // There is no overlap between these relatively aligned accesses of similar
9790    // size, return no alias.
9791    if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
9792      return false;
9793  }
9794
9795  if (CombinerGlobalAA) {
9796    // Use alias analysis information.
9797    int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
9798    int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
9799    int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
9800    AliasAnalysis::AliasResult AAResult =
9801      AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
9802               AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
9803    if (AAResult == AliasAnalysis::NoAlias)
9804      return false;
9805  }
9806
9807  // Otherwise we have to assume they alias.
9808  return true;
9809}
9810
9811bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
9812  SDValue Ptr0, Ptr1;
9813  int64_t Size0, Size1;
9814  const Value *SrcValue0, *SrcValue1;
9815  int SrcValueOffset0, SrcValueOffset1;
9816  unsigned SrcValueAlign0, SrcValueAlign1;
9817  const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
9818  FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
9819                SrcValueAlign0, SrcTBAAInfo0);
9820  FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
9821                SrcValueAlign1, SrcTBAAInfo1);
9822  return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
9823                 SrcValueAlign0, SrcTBAAInfo0,
9824                 Ptr1, Size1, SrcValue1, SrcValueOffset1,
9825                 SrcValueAlign1, SrcTBAAInfo1);
9826}
9827
9828/// FindAliasInfo - Extracts the relevant alias information from the memory
9829/// node.  Returns true if the operand was a load.
9830bool DAGCombiner::FindAliasInfo(SDNode *N,
9831                                SDValue &Ptr, int64_t &Size,
9832                                const Value *&SrcValue,
9833                                int &SrcValueOffset,
9834                                unsigned &SrcValueAlign,
9835                                const MDNode *&TBAAInfo) const {
9836  LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
9837
9838  Ptr = LS->getBasePtr();
9839  Size = LS->getMemoryVT().getSizeInBits() >> 3;
9840  SrcValue = LS->getSrcValue();
9841  SrcValueOffset = LS->getSrcValueOffset();
9842  SrcValueAlign = LS->getOriginalAlignment();
9843  TBAAInfo = LS->getTBAAInfo();
9844  return isa<LoadSDNode>(LS);
9845}
9846
9847/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
9848/// looking for aliasing nodes and adding them to the Aliases vector.
9849void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
9850                                   SmallVector<SDValue, 8> &Aliases) {
9851  SmallVector<SDValue, 8> Chains;     // List of chains to visit.
9852  SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
9853
9854  // Get alias information for node.
9855  SDValue Ptr;
9856  int64_t Size;
9857  const Value *SrcValue;
9858  int SrcValueOffset;
9859  unsigned SrcValueAlign;
9860  const MDNode *SrcTBAAInfo;
9861  bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
9862                              SrcValueAlign, SrcTBAAInfo);
9863
9864  // Starting off.
9865  Chains.push_back(OriginalChain);
9866  unsigned Depth = 0;
9867
9868  // Look at each chain and determine if it is an alias.  If so, add it to the
9869  // aliases list.  If not, then continue up the chain looking for the next
9870  // candidate.
9871  while (!Chains.empty()) {
9872    SDValue Chain = Chains.back();
9873    Chains.pop_back();
9874
9875    // For TokenFactor nodes, look at each operand and only continue up the
9876    // chain until we find two aliases.  If we've seen two aliases, assume we'll
9877    // find more and revert to original chain since the xform is unlikely to be
9878    // profitable.
9879    //
9880    // FIXME: The depth check could be made to return the last non-aliasing
9881    // chain we found before we hit a tokenfactor rather than the original
9882    // chain.
9883    if (Depth > 6 || Aliases.size() == 2) {
9884      Aliases.clear();
9885      Aliases.push_back(OriginalChain);
9886      break;
9887    }
9888
9889    // Don't bother if we've been before.
9890    if (!Visited.insert(Chain.getNode()))
9891      continue;
9892
9893    switch (Chain.getOpcode()) {
9894    case ISD::EntryToken:
9895      // Entry token is ideal chain operand, but handled in FindBetterChain.
9896      break;
9897
9898    case ISD::LOAD:
9899    case ISD::STORE: {
9900      // Get alias information for Chain.
9901      SDValue OpPtr;
9902      int64_t OpSize;
9903      const Value *OpSrcValue;
9904      int OpSrcValueOffset;
9905      unsigned OpSrcValueAlign;
9906      const MDNode *OpSrcTBAAInfo;
9907      bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
9908                                    OpSrcValue, OpSrcValueOffset,
9909                                    OpSrcValueAlign,
9910                                    OpSrcTBAAInfo);
9911
9912      // If chain is alias then stop here.
9913      if (!(IsLoad && IsOpLoad) &&
9914          isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
9915                  SrcTBAAInfo,
9916                  OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
9917                  OpSrcValueAlign, OpSrcTBAAInfo)) {
9918        Aliases.push_back(Chain);
9919      } else {
9920        // Look further up the chain.
9921        Chains.push_back(Chain.getOperand(0));
9922        ++Depth;
9923      }
9924      break;
9925    }
9926
9927    case ISD::TokenFactor:
9928      // We have to check each of the operands of the token factor for "small"
9929      // token factors, so we queue them up.  Adding the operands to the queue
9930      // (stack) in reverse order maintains the original order and increases the
9931      // likelihood that getNode will find a matching token factor (CSE.)
9932      if (Chain.getNumOperands() > 16) {
9933        Aliases.push_back(Chain);
9934        break;
9935      }
9936      for (unsigned n = Chain.getNumOperands(); n;)
9937        Chains.push_back(Chain.getOperand(--n));
9938      ++Depth;
9939      break;
9940
9941    default:
9942      // For all other instructions we will just have to take what we can get.
9943      Aliases.push_back(Chain);
9944      break;
9945    }
9946  }
9947}
9948
9949/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
9950/// for a better chain (aliasing node.)
9951SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
9952  SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
9953
9954  // Accumulate all the aliases to this node.
9955  GatherAllAliases(N, OldChain, Aliases);
9956
9957  // If no operands then chain to entry token.
9958  if (Aliases.size() == 0)
9959    return DAG.getEntryNode();
9960
9961  // If a single operand then chain to it.  We don't need to revisit it.
9962  if (Aliases.size() == 1)
9963    return Aliases[0];
9964
9965  // Construct a custom tailored token factor.
9966  return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
9967                     &Aliases[0], Aliases.size());
9968}
9969
9970// SelectionDAG::Combine - This is the entry point for the file.
9971//
9972void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
9973                           CodeGenOpt::Level OptLevel) {
9974  /// run - This is the main entry point to this class.
9975  ///
9976  DAGCombiner(*this, AA, OptLevel).Run(Level);
9977}
9978