blob: 69e2ce198e0c8f4c75d4ef4c109ecbe73be57239 [file] [log] [blame]
Nate Begeman2504fe22005-09-01 23:24:04 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
Nate Begeman21158fc2005-09-01 00:19:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman21158fc2005-09-01 00:19:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11// both before and after the DAG is legalized.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012//
Dan Gohman45399872009-04-25 17:09:45 +000013// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14// primarily intended to handle simplification opportunities that are implicit
15// in the LLVM IR and exposed by the various codegen lowering phases.
16//
Nate Begeman21158fc2005-09-01 00:19:25 +000017//===----------------------------------------------------------------------===//
18
19#define DEBUG_TYPE "dagcombine"
Nate Begeman21158fc2005-09-01 00:19:25 +000020#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000030#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000031#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000038#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000039#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000040#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000041using namespace llvm;
42
Chris Lattneraee775a2006-12-19 22:41:21 +000043STATISTIC(NodesCombined , "Number of dag nodes combined");
44STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000046STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000047STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000048STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000049
Nate Begeman21158fc2005-09-01 00:19:25 +000050namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000051 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000052 CombinerAA("combiner-alias-analysis", cl::Hidden,
Jim Laskeye7d2c242006-10-17 19:33:52 +000053 cl::desc("Turn on alias analysis during testing"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000054
Jim Laskey55e4dca2006-10-18 19:08:31 +000055 static cl::opt<bool>
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57 cl::desc("Include global information in alias analysis"));
58
Quentin Colombetde0e0622013-10-11 18:29:42 +000059 /// Hidden option to stress test load slicing, i.e., when this option
60 /// is enabled, load slicing bypasses most of its profitability guards.
61 static cl::opt<bool>
62 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
63 cl::desc("Bypass the profitability model of load "
64 "slicing"),
65 cl::init(false));
66
Jim Laskey6549d222006-10-05 15:07:25 +000067//------------------------------ DAGCombiner ---------------------------------//
68
Nick Lewycky02d5f772009-10-25 06:33:48 +000069 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000070 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000071 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000072 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000073 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000074 bool LegalOperations;
75 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000076 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000077
78 // Worklist of all of the nodes that need to be simplified.
James Molloy67b6b112012-02-16 09:17:04 +000079 //
80 // This has the semantics that when adding to the worklist,
81 // the item added must be next to be processed. It should
82 // also only appear once. The naive approach to this takes
83 // linear time.
84 //
85 // To reduce the insert/remove time to logarithmic, we use
86 // a set and a vector to maintain our worklist.
87 //
88 // The set contains the items on the worklist, but does not
89 // maintain the order they should be visited.
90 //
91 // The vector maintains the order nodes should be visited, but may
92 // contain duplicate or removed nodes. When choosing a node to
93 // visit, we pop off the order stack until we find an item that is
94 // also in the contents set. All operations are O(log N).
95 SmallPtrSet<SDNode*, 64> WorkListContents;
Benjamin Kramere1e549d2012-03-10 00:23:58 +000096 SmallVector<SDNode*, 64> WorkListOrder;
Nate Begeman21158fc2005-09-01 00:19:25 +000097
Jim Laskeydcb2b832006-10-16 20:52:31 +000098 // AA - Used for DAG load/store alias analysis.
99 AliasAnalysis &AA;
100
Nate Begeman21158fc2005-09-01 00:19:25 +0000101 /// AddUsersToWorkList - When an instruction is simplified, add all users of
102 /// the instruction to the work lists because they might get more simplified
103 /// now.
104 ///
105 void AddUsersToWorkList(SDNode *N) {
106 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
Nate Begeman2504fe22005-09-01 23:24:04 +0000107 UI != UE; ++UI)
Dan Gohman91e5dcb2008-07-27 20:43:25 +0000108 AddToWorkList(*UI);
Nate Begeman21158fc2005-09-01 00:19:25 +0000109 }
110
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000111 /// visit - call the node-specific routine that knows how to fold each
112 /// particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000113 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000114
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000115 public:
James Molloy920ae8c2012-02-16 09:48:07 +0000116 /// AddToWorkList - Add to the work list making sure its instance is at the
James Molloy67b6b112012-02-16 09:17:04 +0000117 /// back (next to be processed.)
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000118 void AddToWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000119 WorkListContents.insert(N);
120 WorkListOrder.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000121 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000122
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000123 /// removeFromWorkList - remove all instances of N from the worklist.
124 ///
125 void removeFromWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000126 WorkListContents.erase(N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000127 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000128
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000129 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000130 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000131
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000132 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000133 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000134 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000135
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000136 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000137 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000138 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000139 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000140 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000141
142 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000143
144 private:
145
Chris Lattner375e1a72006-02-17 21:58:01 +0000146 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattner232024e2006-03-01 19:55:35 +0000147 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner375e1a72006-02-17 21:58:01 +0000148 /// propagation. If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000149 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000150 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
151 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000152 return SimplifyDemandedBits(Op, Demanded);
153 }
154
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000155 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000156
Chris Lattnerffad2162006-11-11 00:39:41 +0000157 bool CombineToPreIndexedLoadStore(SDNode *N);
158 bool CombineToPostIndexedLoadStore(SDNode *N);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000159 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000160
Evan Cheng0abb54d2010-04-24 04:43:44 +0000161 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
162 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
163 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
164 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000165 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000166 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000167 SDValue PromoteExtend(SDValue Op);
168 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000169
Craig Toppere0b71182013-07-13 07:43:40 +0000170 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000171 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000172 ISD::NodeType ExtType);
173
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000174 /// combine - call the node-specific routine that knows how to fold each
175 /// particular type of node. If that doesn't do anything, try the
176 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000177 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000178
179 // Visitation implementation - Implement dag node combining for different
180 // node types. The semantics are as follows:
181 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000182 // SDValue.getNode() == 0 - No change was made
183 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
184 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000185 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000186 SDValue visitTokenFactor(SDNode *N);
187 SDValue visitMERGE_VALUES(SDNode *N);
188 SDValue visitADD(SDNode *N);
189 SDValue visitSUB(SDNode *N);
190 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000191 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000192 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000193 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000194 SDValue visitMUL(SDNode *N);
195 SDValue visitSDIV(SDNode *N);
196 SDValue visitUDIV(SDNode *N);
197 SDValue visitSREM(SDNode *N);
198 SDValue visitUREM(SDNode *N);
199 SDValue visitMULHU(SDNode *N);
200 SDValue visitMULHS(SDNode *N);
201 SDValue visitSMUL_LOHI(SDNode *N);
202 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000203 SDValue visitSMULO(SDNode *N);
204 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000205 SDValue visitSDIVREM(SDNode *N);
206 SDValue visitUDIVREM(SDNode *N);
207 SDValue visitAND(SDNode *N);
208 SDValue visitOR(SDNode *N);
209 SDValue visitXOR(SDNode *N);
210 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000211 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000212 SDValue visitSHL(SDNode *N);
213 SDValue visitSRA(SDNode *N);
214 SDValue visitSRL(SDNode *N);
215 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000216 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000217 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000218 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000219 SDValue visitCTPOP(SDNode *N);
220 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000221 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000222 SDValue visitSELECT_CC(SDNode *N);
223 SDValue visitSETCC(SDNode *N);
224 SDValue visitSIGN_EXTEND(SDNode *N);
225 SDValue visitZERO_EXTEND(SDNode *N);
226 SDValue visitANY_EXTEND(SDNode *N);
227 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
228 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000229 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000230 SDValue visitBUILD_PAIR(SDNode *N);
231 SDValue visitFADD(SDNode *N);
232 SDValue visitFSUB(SDNode *N);
233 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000234 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000235 SDValue visitFDIV(SDNode *N);
236 SDValue visitFREM(SDNode *N);
237 SDValue visitFCOPYSIGN(SDNode *N);
238 SDValue visitSINT_TO_FP(SDNode *N);
239 SDValue visitUINT_TO_FP(SDNode *N);
240 SDValue visitFP_TO_SINT(SDNode *N);
241 SDValue visitFP_TO_UINT(SDNode *N);
242 SDValue visitFP_ROUND(SDNode *N);
243 SDValue visitFP_ROUND_INREG(SDNode *N);
244 SDValue visitFP_EXTEND(SDNode *N);
245 SDValue visitFNEG(SDNode *N);
246 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000247 SDValue visitFCEIL(SDNode *N);
248 SDValue visitFTRUNC(SDNode *N);
249 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000250 SDValue visitBRCOND(SDNode *N);
251 SDValue visitBR_CC(SDNode *N);
252 SDValue visitLOAD(SDNode *N);
253 SDValue visitSTORE(SDNode *N);
254 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
255 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
256 SDValue visitBUILD_VECTOR(SDNode *N);
257 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000258 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000259 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000260
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000261 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000262 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000263
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000264 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000265
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000266 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
267 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000268 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
269 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000270 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000271 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000272 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000273 SDLoc DL, bool foldBooleans = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000274 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000275 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000276 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000277 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000278 SDValue BuildSDIV(SDNode *N);
279 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000280 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
281 bool DemandHighBits = true);
282 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000283 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
284 SDValue InnerPos, SDValue InnerNeg,
285 unsigned PosOpcode, unsigned NegOpcode,
286 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000287 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000288 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000289 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000290 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000291 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000292 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000293
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000294 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000295
Jim Laskey708d0db2006-10-04 16:53:27 +0000296 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
297 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000298 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000299 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000300
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000301 /// isAlias - Return true if there is any possibility that the two addresses
302 /// overlap.
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000303 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000304 const Value *SrcValue1, int SrcValueOffset1,
Nate Begeman879d8f12009-09-15 00:18:30 +0000305 unsigned SrcValueAlign1,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000306 const MDNode *TBAAInfo1,
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000307 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begeman879d8f12009-09-15 00:18:30 +0000308 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000309 unsigned SrcValueAlign2,
310 const MDNode *TBAAInfo2) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000311
Nadav Rotem307d7672012-11-29 00:00:08 +0000312 /// isAlias - Return true if there is any possibility that the two addresses
313 /// overlap.
314 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
315
Jim Laskey08edf332006-10-11 13:47:09 +0000316 /// FindAliasInfo - Extracts the relevant alias information from the memory
317 /// node. Returns true if the operand was a load.
318 bool FindAliasInfo(SDNode *N,
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000319 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Nate Begeman879d8f12009-09-15 00:18:30 +0000320 const Value *&SrcValue, int &SrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000321 unsigned &SrcValueAlignment,
322 const MDNode *&TBAAInfo) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000323
Jim Laskeyd07be232006-09-25 16:29:54 +0000324 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000325 /// looking for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000326 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000327
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000328 /// Merge consecutive store operations into a wide store.
329 /// This optimization uses wide integers or vectors when possible.
330 /// \return True if some memory operations were changed.
331 bool MergeConsecutiveStores(StoreSDNode *N);
332
Chris Lattner4041ab62010-04-15 04:48:01 +0000333 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000334 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000335 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
336 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
337 AttributeSet FnAttrs =
338 DAG.getMachineFunction().getFunction()->getAttributes();
339 ForCodeSize =
340 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
341 Attribute::OptimizeForSize) ||
342 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
343 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000344
Nate Begeman21158fc2005-09-01 00:19:25 +0000345 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000346 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000347
Chris Lattner4041ab62010-04-15 04:48:01 +0000348 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000349
Chris Lattner4041ab62010-04-15 04:48:01 +0000350 /// getShiftAmountTy - Returns a type large enough to hold any valid
351 /// shift amount - before type legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000352 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000353 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
354 if (LHSTy.isVector())
355 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000356 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
357 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000358 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000359
Chris Lattner4041ab62010-04-15 04:48:01 +0000360 /// isTypeLegal - This method returns true if we are running before type
361 /// legalization or if the specified VT is legal.
362 bool isTypeLegal(const EVT &VT) {
363 if (!LegalTypes) return true;
364 return TLI.isTypeLegal(VT);
365 }
Matt Arsenault758659232013-05-18 00:21:46 +0000366
367 /// getSetCCResultType - Convenience wrapper around
368 /// TargetLowering::getSetCCResultType
369 EVT getSetCCResultType(EVT VT) const {
370 return TLI.getSetCCResultType(*DAG.getContext(), VT);
371 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000372 };
373}
374
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000375
376namespace {
377/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
378/// nodes from the worklist.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000379class WorkListRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000380 DAGCombiner &DC;
381public:
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000382 explicit WorkListRemover(DAGCombiner &dc)
383 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000384
Duncan Sandsbf170802008-06-11 11:42:12 +0000385 virtual void NodeDeleted(SDNode *N, SDNode *E) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000386 DC.removeFromWorkList(N);
387 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000388};
389}
390
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000391//===----------------------------------------------------------------------===//
392// TargetLowering::DAGCombinerInfo implementation
393//===----------------------------------------------------------------------===//
394
395void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
396 ((DAGCombiner*)DC)->AddToWorkList(N);
397}
398
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000399void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
400 ((DAGCombiner*)DC)->removeFromWorkList(N);
401}
402
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000403SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000404CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
405 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000406}
407
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000408SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000409CombineTo(SDNode *N, SDValue Res, bool AddTo) {
410 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000411}
412
413
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000414SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000415CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
416 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000417}
418
Dan Gohmane58ab792009-01-29 01:59:02 +0000419void TargetLowering::DAGCombinerInfo::
420CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
421 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
422}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000423
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000424//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000425// Helper Functions
426//===----------------------------------------------------------------------===//
427
428/// isNegatibleForFree - Return 1 if we can compute the negated form of the
429/// specified expression for the same cost as the expression itself, or 2 if we
430/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000431static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000432 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000433 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000434 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000435 // fneg is removable even if it has multiple uses.
436 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000437
Chris Lattnere49c9742007-05-14 22:04:50 +0000438 // Don't allow anything with multiple uses.
439 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000440
Chris Lattner46980832007-05-25 02:19:06 +0000441 // Don't recurse exponentially.
442 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000443
Chris Lattnere49c9742007-05-14 22:04:50 +0000444 switch (Op.getOpcode()) {
445 default: return false;
446 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000447 // Don't invert constant FP values after legalize. The negated constant
448 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000449 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000450 case ISD::FADD:
451 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000452 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000453
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000454 // After operation legalization, it might not be legal to create new FSUBs.
455 if (LegalOperations &&
456 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
457 return 0;
458
Craig Topper03f39772012-09-09 22:58:45 +0000459 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000460 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
461 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000462 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000463 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000464 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000465 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000466 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000467 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000468 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000469
Bill Wendling6fbf5492009-01-30 23:10:18 +0000470 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000471 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000472
Chris Lattnere49c9742007-05-14 22:04:50 +0000473 case ISD::FMUL:
474 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000475 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000476
Bill Wendling6fbf5492009-01-30 23:10:18 +0000477 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000478 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
479 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000480 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000481
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000482 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000483 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000484
Chris Lattnere49c9742007-05-14 22:04:50 +0000485 case ISD::FP_EXTEND:
486 case ISD::FP_ROUND:
487 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000488 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000489 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000490 }
491}
492
493/// GetNegatedExpression - If isNegatibleForFree returns true, this function
494/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000495static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000496 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000497 // fneg is removable even if it has multiple uses.
498 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000499
Chris Lattnere49c9742007-05-14 22:04:50 +0000500 // Don't allow anything with multiple uses.
501 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000502
Chris Lattner46980832007-05-25 02:19:06 +0000503 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000504 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000505 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000506 case ISD::ConstantFP: {
507 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
508 V.changeSign();
509 return DAG.getConstantFP(V, Op.getValueType());
510 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000511 case ISD::FADD:
512 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000513 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000514
Bill Wendling6fbf5492009-01-30 23:10:18 +0000515 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000516 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000517 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000518 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000519 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000520 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000521 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000522 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000523 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000524 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000525 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000526 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000527 Op.getOperand(0));
528 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000529 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000530 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000531
Bill Wendling6fbf5492009-01-30 23:10:18 +0000532 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000533 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000534 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000535 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000536
Bill Wendling6fbf5492009-01-30 23:10:18 +0000537 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000538 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000539 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000540
Chris Lattnere49c9742007-05-14 22:04:50 +0000541 case ISD::FMUL:
542 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000543 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000544
Bill Wendling6fbf5492009-01-30 23:10:18 +0000545 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000546 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000547 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000548 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000549 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000550 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000551 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000552 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000553
Bill Wendling6fbf5492009-01-30 23:10:18 +0000554 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000555 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000556 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000557 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000558 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000559
Chris Lattnere49c9742007-05-14 22:04:50 +0000560 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000561 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000562 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000563 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000564 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000565 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000566 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000567 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000568 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000569 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000570 }
571}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000572
573
Nate Begeman2504fe22005-09-01 23:24:04 +0000574// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
575// that selects between the values 1 and 0, making it equivalent to a setcc.
Scott Michelcf0da6c2009-02-17 22:15:04 +0000576// Also, set the incoming LHS, RHS, and CC references to the appropriate
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000577// nodes based on the type of node we are checking. This simplifies life a
578// bit for the callers.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000579static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
580 SDValue &CC) {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000581 if (N.getOpcode() == ISD::SETCC) {
582 LHS = N.getOperand(0);
583 RHS = N.getOperand(1);
584 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000585 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000586 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000587 if (N.getOpcode() == ISD::SELECT_CC &&
Nate Begeman21158fc2005-09-01 00:19:25 +0000588 N.getOperand(2).getOpcode() == ISD::Constant &&
589 N.getOperand(3).getOpcode() == ISD::Constant &&
Dan Gohmanb72127a2008-03-13 22:13:53 +0000590 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000591 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
592 LHS = N.getOperand(0);
593 RHS = N.getOperand(1);
594 CC = N.getOperand(4);
Nate Begeman21158fc2005-09-01 00:19:25 +0000595 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000596 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000597 return false;
598}
599
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000600// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
601// one use. If this is true, it allows the users to invert the operation for
602// free when it is profitable to do so.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000603static bool isOneUseSetCC(SDValue N) {
604 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000605 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000606 return true;
607 return false;
608}
609
Juergen Ributzka68402822014-01-13 21:49:25 +0000610// \brief Returns the SDNode if it is a constant BuildVector or constant int.
611static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
612 if (isa<ConstantSDNode>(N))
613 return N.getNode();
614 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
615 if(BV && BV->isConstant())
616 return BV;
617 return NULL;
618}
619
Andrew Trickef9de2a2013-05-25 02:42:55 +0000620SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000621 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000622 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000623 if (N0.getOpcode() == Opc) {
624 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
625 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
626 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
627 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
628 if (!OpNode.getNode())
629 return SDValue();
630 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000631 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000632 if (N0.hasOneUse()) {
633 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
634 // use
635 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
636 if (!OpNode.getNode())
637 return SDValue();
638 AddToWorkList(OpNode.getNode());
639 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000640 }
641 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000642 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000643
Juergen Ributzka68402822014-01-13 21:49:25 +0000644 if (N1.getOpcode() == Opc) {
645 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
646 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
647 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
648 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
649 if (!OpNode.getNode())
650 return SDValue();
651 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
652 }
653 if (N1.hasOneUse()) {
654 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
655 // use
656 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
657 if (!OpNode.getNode())
658 return SDValue();
659 AddToWorkList(OpNode.getNode());
660 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
661 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000662 }
663 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000664
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000665 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000666}
667
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000668SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
669 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000670 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
671 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000672 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000673 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000674 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000675 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000676 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000677 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000678 assert((!To[i].getNode() ||
679 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000680 "Cannot combine value to value of different type!"));
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000681 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000682 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000683 if (AddTo) {
684 // Push the new nodes and any users onto the worklist
685 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000686 if (To[i].getNode()) {
687 AddToWorkList(To[i].getNode());
688 AddUsersToWorkList(To[i].getNode());
689 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000690 }
691 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000692
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000693 // Finally, if the node is now dead, remove it from the graph. The node
694 // may not be dead if the replacement process recursively simplified to
695 // something else needing this node.
696 if (N->use_empty()) {
697 // Nodes can be reintroduced into the worklist. Make sure we do not
698 // process a node that has been replaced.
699 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000700
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000701 // Finally, since the node is now dead, remove it from the graph.
702 DAG.DeleteNode(N);
703 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000704 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000705}
706
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000707void DAGCombiner::
708CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000709 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000710 // are deleted, make sure to remove them from our worklist.
711 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000712 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000713
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000714 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000715 AddToWorkList(TLO.New.getNode());
716 AddUsersToWorkList(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000717
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000718 // Finally, if the node is now dead, remove it from the graph. The node
719 // may not be dead if the replacement process recursively simplified to
720 // something else needing this node.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000721 if (TLO.Old.getNode()->use_empty()) {
722 removeFromWorkList(TLO.Old.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000723
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000724 // If the operands of this node are only used by the node, they will now
725 // be dead. Make sure to visit them first to delete dead nodes early.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000726 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
727 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
728 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000729
Gabor Greiff304a7a2008-08-28 21:40:38 +0000730 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000731 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000732}
733
734/// SimplifyDemandedBits - Check the specified integer node value to see if
735/// it can be simplified or if things it uses can be simplified by bit
736/// propagation. If so, return true.
737bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000738 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000739 APInt KnownZero, KnownOne;
740 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
741 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000742
Dan Gohmane58ab792009-01-29 01:59:02 +0000743 // Revisit the node.
744 AddToWorkList(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000745
Dan Gohmane58ab792009-01-29 01:59:02 +0000746 // Replace the old value with the new one.
747 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000748 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000749 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000750 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000751 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000752 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000753
Dan Gohmane58ab792009-01-29 01:59:02 +0000754 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000755 return true;
756}
757
Evan Cheng0abb54d2010-04-24 04:43:44 +0000758void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000759 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000760 EVT VT = Load->getValueType(0);
761 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000762
Evan Cheng0abb54d2010-04-24 04:43:44 +0000763 DEBUG(dbgs() << "\nReplacing.9 ";
764 Load->dump(&DAG);
765 dbgs() << "\nWith: ";
766 Trunc.getNode()->dump(&DAG);
767 dbgs() << '\n');
768 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000769 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
770 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng0abb54d2010-04-24 04:43:44 +0000771 removeFromWorkList(Load);
772 DAG.DeleteNode(Load);
Evan Chenge8136902010-04-27 19:48:13 +0000773 AddToWorkList(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000774}
775
776SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
777 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000778 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000779 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000780 EVT MemVT = LD->getMemoryVT();
781 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000782 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000783 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000784 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000785 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000786 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000787 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000788 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000789 }
790
Evan Chenge19aa5c2010-04-19 19:29:22 +0000791 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000792 switch (Opc) {
793 default: break;
794 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000795 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000796 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000797 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000798 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000799 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000800 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000801 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000802 case ISD::Constant: {
803 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000804 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000805 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000806 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000807 }
808
809 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000810 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000811 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000812}
813
Evan Cheng0abb54d2010-04-24 04:43:44 +0000814SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000815 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
816 return SDValue();
817 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000818 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000819 bool Replace = false;
820 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
821 if (NewOp.getNode() == 0)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000822 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000823 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000824
825 if (Replace)
826 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
827 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000828 DAG.getValueType(OldVT));
829}
830
Evan Cheng0abb54d2010-04-24 04:43:44 +0000831SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000832 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000833 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000834 bool Replace = false;
835 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
836 if (NewOp.getNode() == 0)
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000837 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000838 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000839
840 if (Replace)
841 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
842 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000843}
844
Evan Chengaf56fac2010-04-16 06:14:10 +0000845/// PromoteIntBinOp - Promote the specified integer binary operation if the
846/// target indicates it is beneficial. e.g. On x86, it's usually better to
847/// promote i16 operations to i32 since i16 instructions are longer.
848SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
849 if (!LegalOperations)
850 return SDValue();
851
852 EVT VT = Op.getValueType();
853 if (VT.isVector() || !VT.isInteger())
854 return SDValue();
855
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000856 // If operation type is 'undesirable', e.g. i16 on x86, consider
857 // promoting it.
858 unsigned Opc = Op.getOpcode();
859 if (TLI.isTypeDesirableForOp(Opc, VT))
860 return SDValue();
861
Evan Chengaf56fac2010-04-16 06:14:10 +0000862 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000863 // Consult target whether it is a good idea to promote this operation and
864 // what's the right type to promote it to.
865 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000866 assert(PVT != VT && "Don't know what type to promote to!");
867
Evan Cheng0abb54d2010-04-24 04:43:44 +0000868 bool Replace0 = false;
869 SDValue N0 = Op.getOperand(0);
870 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
871 if (NN0.getNode() == 0)
Evan Chengf1223bd2010-04-22 20:19:46 +0000872 return SDValue();
873
Evan Cheng0abb54d2010-04-24 04:43:44 +0000874 bool Replace1 = false;
875 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000876 SDValue NN1;
877 if (N0 == N1)
878 NN1 = NN0;
879 else {
880 NN1 = PromoteOperand(N1, PVT, Replace1);
881 if (NN1.getNode() == 0)
882 return SDValue();
883 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000884
Evan Cheng0abb54d2010-04-24 04:43:44 +0000885 AddToWorkList(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000886 if (NN1.getNode())
887 AddToWorkList(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000888
889 if (Replace0)
890 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
891 if (Replace1)
892 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000893
Evan Chenge8136902010-04-27 19:48:13 +0000894 DEBUG(dbgs() << "\nPromoting ";
895 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000896 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000897 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000898 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000899 }
900 return SDValue();
901}
902
903/// PromoteIntShiftOp - Promote the specified integer shift operation if the
904/// target indicates it is beneficial. e.g. On x86, it's usually better to
905/// promote i16 operations to i32 since i16 instructions are longer.
906SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
907 if (!LegalOperations)
908 return SDValue();
909
910 EVT VT = Op.getValueType();
911 if (VT.isVector() || !VT.isInteger())
912 return SDValue();
913
914 // If operation type is 'undesirable', e.g. i16 on x86, consider
915 // promoting it.
916 unsigned Opc = Op.getOpcode();
917 if (TLI.isTypeDesirableForOp(Opc, VT))
918 return SDValue();
919
920 EVT PVT = VT;
921 // Consult target whether it is a good idea to promote this operation and
922 // what's the right type to promote it to.
923 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
924 assert(PVT != VT && "Don't know what type to promote to!");
925
Evan Cheng0abb54d2010-04-24 04:43:44 +0000926 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000927 SDValue N0 = Op.getOperand(0);
928 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000929 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000930 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000931 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000932 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000933 N0 = PromoteOperand(N0, PVT, Replace);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000934 if (N0.getNode() == 0)
935 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000936
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000937 AddToWorkList(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000938 if (Replace)
939 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000940
Evan Chenge8136902010-04-27 19:48:13 +0000941 DEBUG(dbgs() << "\nPromoting ";
942 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000943 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000944 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +0000945 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +0000946 }
947 return SDValue();
948}
949
Evan Chenge19aa5c2010-04-19 19:29:22 +0000950SDValue DAGCombiner::PromoteExtend(SDValue Op) {
951 if (!LegalOperations)
952 return SDValue();
953
954 EVT VT = Op.getValueType();
955 if (VT.isVector() || !VT.isInteger())
956 return SDValue();
957
958 // If operation type is 'undesirable', e.g. i16 on x86, consider
959 // promoting it.
960 unsigned Opc = Op.getOpcode();
961 if (TLI.isTypeDesirableForOp(Opc, VT))
962 return SDValue();
963
964 EVT PVT = VT;
965 // Consult target whether it is a good idea to promote this operation and
966 // what's the right type to promote it to.
967 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
968 assert(PVT != VT && "Don't know what type to promote to!");
969 // fold (aext (aext x)) -> (aext x)
970 // fold (aext (zext x)) -> (zext x)
971 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +0000972 DEBUG(dbgs() << "\nPromoting ";
973 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000974 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000975 }
976 return SDValue();
977}
978
979bool DAGCombiner::PromoteLoad(SDValue Op) {
980 if (!LegalOperations)
981 return false;
982
983 EVT VT = Op.getValueType();
984 if (VT.isVector() || !VT.isInteger())
985 return false;
986
987 // If operation type is 'undesirable', e.g. i16 on x86, consider
988 // promoting it.
989 unsigned Opc = Op.getOpcode();
990 if (TLI.isTypeDesirableForOp(Opc, VT))
991 return false;
992
993 EVT PVT = VT;
994 // Consult target whether it is a good idea to promote this operation and
995 // what's the right type to promote it to.
996 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
997 assert(PVT != VT && "Don't know what type to promote to!");
998
Andrew Trickef9de2a2013-05-25 02:42:55 +0000999 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001000 SDNode *N = Op.getNode();
1001 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001002 EVT MemVT = LD->getMemoryVT();
1003 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001004 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001005 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001006 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001007 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001008 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001009 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001010 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1011
Evan Cheng0abb54d2010-04-24 04:43:44 +00001012 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001013 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001014 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001015 Result.getNode()->dump(&DAG);
1016 dbgs() << '\n');
1017 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001018 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1019 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001020 removeFromWorkList(N);
1021 DAG.DeleteNode(N);
Evan Chenge8136902010-04-27 19:48:13 +00001022 AddToWorkList(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001023 return true;
1024 }
1025 return false;
1026}
1027
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001028
Chris Lattnere49c9742007-05-14 22:04:50 +00001029//===----------------------------------------------------------------------===//
1030// Main DAG Combiner implementation
1031//===----------------------------------------------------------------------===//
1032
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001033void DAGCombiner::Run(CombineLevel AtLevel) {
1034 // set the instance variables, so that the various visit routines may use it.
1035 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001036 LegalOperations = Level >= AfterLegalizeVectorOps;
1037 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001038
Evan Cheng5e7658c2008-08-29 22:21:44 +00001039 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001040 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1041 E = DAG.allnodes_end(); I != E; ++I)
James Molloy67b6b112012-02-16 09:17:04 +00001042 AddToWorkList(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001043
Evan Cheng5e7658c2008-08-29 22:21:44 +00001044 // Create a dummy node (which is not added to allnodes), that adds a reference
1045 // to the root node, preventing it from being deleted, and tracking any
1046 // changes of the root.
1047 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001048
Jim Laskeye7d2c242006-10-17 19:33:52 +00001049 // The root of the dag may dangle to deleted nodes until the dag combiner is
1050 // done. Set it to null to avoid confusion.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001051 DAG.setRoot(SDValue());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001052
James Molloy67b6b112012-02-16 09:17:04 +00001053 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001054 // try and combine it.
James Molloy67b6b112012-02-16 09:17:04 +00001055 while (!WorkListContents.empty()) {
1056 SDNode *N;
Jack Carterd4e96152013-10-17 01:34:33 +00001057 // The WorkListOrder holds the SDNodes in order, but it may contain
1058 // duplicates.
James Molloy67b6b112012-02-16 09:17:04 +00001059 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1060 // worklist *should* contain, and check the node we want to visit is should
1061 // actually be visited.
1062 do {
Benjamin Kramere1e549d2012-03-10 00:23:58 +00001063 N = WorkListOrder.pop_back_val();
James Molloy67b6b112012-02-16 09:17:04 +00001064 } while (!WorkListContents.erase(N));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001065
Evan Cheng5e7658c2008-08-29 22:21:44 +00001066 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1067 // N is deleted from the DAG, since they too may now be dead or may have a
1068 // reduced number of uses, allowing other xforms.
1069 if (N->use_empty() && N != &Dummy) {
1070 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1071 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001072
Evan Cheng5e7658c2008-08-29 22:21:44 +00001073 DAG.DeleteNode(N);
1074 continue;
Nate Begeman21158fc2005-09-01 00:19:25 +00001075 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001076
Evan Cheng5e7658c2008-08-29 22:21:44 +00001077 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001078
Evan Cheng5e7658c2008-08-29 22:21:44 +00001079 if (RV.getNode() == 0)
1080 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001081
Evan Cheng5e7658c2008-08-29 22:21:44 +00001082 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001083
Evan Cheng5e7658c2008-08-29 22:21:44 +00001084 // If we get back the same node we passed in, rather than a new node or
1085 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001086 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001087 // mechanics for us, we have no work to do in this case.
1088 if (RV.getNode() == N)
1089 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001090
Evan Cheng5e7658c2008-08-29 22:21:44 +00001091 assert(N->getOpcode() != ISD::DELETED_NODE &&
1092 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1093 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001094
Wesley Peck527da1b2010-11-23 03:31:01 +00001095 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001096 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001097 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001098 RV.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001099 dbgs() << '\n');
Eric Christopherd6300d22011-07-14 01:12:15 +00001100
Devang Patelefec7712011-05-23 22:04:42 +00001101 // Transfer debug value.
1102 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001103 WorkListRemover DeadNodes(*this);
1104 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001105 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001106 else {
1107 assert(N->getValueType(0) == RV.getValueType() &&
1108 N->getNumValues() == 1 && "Type mismatch");
1109 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001110 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001111 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001112
Evan Cheng5e7658c2008-08-29 22:21:44 +00001113 // Push the new node and any users onto the worklist
1114 AddToWorkList(RV.getNode());
1115 AddUsersToWorkList(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001116
Evan Cheng5e7658c2008-08-29 22:21:44 +00001117 // Add any uses of the old node to the worklist in case this node is the
1118 // last one that uses them. They may become dead after this node is
1119 // deleted.
1120 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1121 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001122
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001123 // Finally, if the node is now dead, remove it from the graph. The node
1124 // may not be dead if the replacement process recursively simplified to
1125 // something else needing this node.
1126 if (N->use_empty()) {
1127 // Nodes can be reintroduced into the worklist. Make sure we do not
1128 // process a node that has been replaced.
1129 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001130
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001131 // Finally, since the node is now dead, remove it from the graph.
1132 DAG.DeleteNode(N);
1133 }
Evan Cheng5e7658c2008-08-29 22:21:44 +00001134 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001135
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001136 // If the root changed (e.g. it was a dead load, update the root).
1137 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001138 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001139}
1140
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001141SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001142 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001143 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001144 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001145 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001146 case ISD::ADD: return visitADD(N);
1147 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001148 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001149 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001150 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001151 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001152 case ISD::MUL: return visitMUL(N);
1153 case ISD::SDIV: return visitSDIV(N);
1154 case ISD::UDIV: return visitUDIV(N);
1155 case ISD::SREM: return visitSREM(N);
1156 case ISD::UREM: return visitUREM(N);
1157 case ISD::MULHU: return visitMULHU(N);
1158 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001159 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1160 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001161 case ISD::SMULO: return visitSMULO(N);
1162 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001163 case ISD::SDIVREM: return visitSDIVREM(N);
1164 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001165 case ISD::AND: return visitAND(N);
1166 case ISD::OR: return visitOR(N);
1167 case ISD::XOR: return visitXOR(N);
1168 case ISD::SHL: return visitSHL(N);
1169 case ISD::SRA: return visitSRA(N);
1170 case ISD::SRL: return visitSRL(N);
1171 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001172 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001173 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001174 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001175 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001176 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001177 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001178 case ISD::SELECT_CC: return visitSELECT_CC(N);
1179 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001180 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1181 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001182 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001183 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1184 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001185 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001186 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001187 case ISD::FADD: return visitFADD(N);
1188 case ISD::FSUB: return visitFSUB(N);
1189 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001190 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001191 case ISD::FDIV: return visitFDIV(N);
1192 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001193 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001194 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1195 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1196 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1197 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1198 case ISD::FP_ROUND: return visitFP_ROUND(N);
1199 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1200 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1201 case ISD::FNEG: return visitFNEG(N);
1202 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001203 case ISD::FFLOOR: return visitFFLOOR(N);
1204 case ISD::FCEIL: return visitFCEIL(N);
1205 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001206 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001207 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001208 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001209 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001210 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001211 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001212 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1213 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001214 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001215 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001216 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001217 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001218}
1219
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001220SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001221 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001222
1223 // If nothing happened, try a target-specific DAG combine.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001224 if (RV.getNode() == 0) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001225 assert(N->getOpcode() != ISD::DELETED_NODE &&
1226 "Node was deleted but visit returned NULL!");
1227
1228 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1229 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1230
1231 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001232 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001233 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001234
1235 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1236 }
1237 }
1238
Evan Chengf1005572010-04-28 07:10:39 +00001239 // If nothing happened still, try promoting the operation.
1240 if (RV.getNode() == 0) {
1241 switch (N->getOpcode()) {
1242 default: break;
1243 case ISD::ADD:
1244 case ISD::SUB:
1245 case ISD::MUL:
1246 case ISD::AND:
1247 case ISD::OR:
1248 case ISD::XOR:
1249 RV = PromoteIntBinOp(SDValue(N, 0));
1250 break;
1251 case ISD::SHL:
1252 case ISD::SRA:
1253 case ISD::SRL:
1254 RV = PromoteIntShiftOp(SDValue(N, 0));
1255 break;
1256 case ISD::SIGN_EXTEND:
1257 case ISD::ZERO_EXTEND:
1258 case ISD::ANY_EXTEND:
1259 RV = PromoteExtend(SDValue(N, 0));
1260 break;
1261 case ISD::LOAD:
1262 if (PromoteLoad(SDValue(N, 0)))
1263 RV = SDValue(N, 0);
1264 break;
1265 }
1266 }
1267
Scott Michelcf0da6c2009-02-17 22:15:04 +00001268 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001269 // sdisel CSE.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001270 if (RV.getNode() == 0 &&
Evan Cheng31604a62008-03-22 01:55:50 +00001271 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1272 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001273 SDValue N0 = N->getOperand(0);
1274 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001275
Evan Cheng31604a62008-03-22 01:55:50 +00001276 // Constant operands are canonicalized to RHS.
1277 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001278 SDValue Ops[] = { N1, N0 };
Evan Cheng31604a62008-03-22 01:55:50 +00001279 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1280 Ops, 2);
Evan Chengfe7610f2008-03-24 23:55:16 +00001281 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001282 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001283 }
1284 }
1285
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001286 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001287}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001288
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001289/// getInputChainForNode - Given a node, return its input chain if it has one,
1290/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001291static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001292 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001293 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001294 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001295 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001296 return N->getOperand(NumOps-1);
1297 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001298 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001299 return N->getOperand(i);
1300 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001301 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001302}
1303
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001304SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001305 // If N has two operands, where one has an input chain equal to the other,
1306 // the 'other' chain is redundant.
1307 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001308 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001309 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001310 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001311 return N->getOperand(1);
1312 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001313
Chris Lattner48fb92f2007-05-16 06:37:59 +00001314 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001315 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001316 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001317 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001318
Jim Laskey708d0db2006-10-04 16:53:27 +00001319 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001320 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001321
Jim Laskey0463e082006-10-07 23:37:56 +00001322 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001323 // encountered.
1324 for (unsigned i = 0; i < TFs.size(); ++i) {
1325 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001326
Jim Laskey708d0db2006-10-04 16:53:27 +00001327 // Check each of the operands.
1328 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001329 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001330
Jim Laskey708d0db2006-10-04 16:53:27 +00001331 switch (Op.getOpcode()) {
1332 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001333 // Entry tokens don't need to be added to the list. They are
1334 // rededundant.
1335 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001336 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001337
Jim Laskey708d0db2006-10-04 16:53:27 +00001338 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001339 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001340 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001341 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001342 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001343 // Clean up in case the token factor is removed.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001344 AddToWorkList(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001345 Changed = true;
1346 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001347 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001348 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001349
Jim Laskey708d0db2006-10-04 16:53:27 +00001350 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001351 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001352 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001353 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001354 else
1355 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001356 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001357 }
1358 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001359 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001360
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001361 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001362
1363 // If we've change things around then replace token factor.
1364 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001365 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001366 // The entry token is the only possible outcome.
1367 Result = DAG.getEntryNode();
1368 } else {
1369 // New and improved token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001370 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00001371 MVT::Other, &Ops[0], Ops.size());
Nate Begeman02b23c62005-10-13 03:11:28 +00001372 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001373
Jim Laskeydcf983c2006-10-13 23:32:28 +00001374 // Don't add users to work list.
1375 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001376 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001377
Jim Laskey708d0db2006-10-04 16:53:27 +00001378 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001379}
1380
Chris Lattneree322b42008-02-13 07:25:05 +00001381/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001382SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattneree322b42008-02-13 07:25:05 +00001383 WorkListRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001384 // Replacing results may cause a different MERGE_VALUES to suddenly
1385 // be CSE'd with N, and carry its uses with it. Iterate until no
1386 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001387 // First add the users of this node to the work list so that they
1388 // can be tried again once they have new operands.
1389 AddUsersToWorkList(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001390 do {
1391 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001392 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001393 } while (!N->use_empty());
Chris Lattneree322b42008-02-13 07:25:05 +00001394 removeFromWorkList(N);
1395 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001396 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001397}
1398
Evan Cheng92011002007-01-19 17:51:44 +00001399static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001400SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001401 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001402 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001403 SDValue N00 = N0.getOperand(0);
1404 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001405 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001406
Gabor Greiff304a7a2008-08-28 21:40:38 +00001407 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001408 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001409 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001410 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1411 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001412 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001413 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001414 N00.getOperand(1), N01));
1415 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001416 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001417
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001418 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001419}
1420
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001421SDValue DAGCombiner::visitADD(SDNode *N) {
1422 SDValue N0 = N->getOperand(0);
1423 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001424 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1425 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001426 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001427
1428 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001429 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001430 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001431 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001432
1433 // fold (add x, 0) -> x, vector edition
1434 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1435 return N0;
1436 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1437 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001438 }
Bill Wendling0864a752008-12-10 22:36:00 +00001439
Dan Gohman06563a82007-07-03 14:03:57 +00001440 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001441 if (N0.getOpcode() == ISD::UNDEF)
1442 return N0;
1443 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001444 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001445 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001446 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001447 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001448 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001449 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001450 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001451 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001452 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001453 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001454 // fold (add Sym, c) -> Sym+c
1455 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001456 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001457 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001458 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001459 GA->getOffset() +
1460 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001461 // fold ((c1-A)+c2) -> (c1+c2)-A
1462 if (N1C && N0.getOpcode() == ISD::SUB)
1463 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001464 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001465 DAG.getConstant(N1C->getAPIntValue()+
1466 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001467 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001468 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001469 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001470 if (RADD.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00001471 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001472 // fold ((0-A) + B) -> B-A
1473 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1474 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001475 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001476 // fold (A + (0-B)) -> A-B
1477 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1478 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001479 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001480 // fold (A+(B-A)) -> B
1481 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001482 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001483 // fold ((B-A)+A) -> B
1484 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1485 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001486 // fold (A+(B-(A+C))) to (B-C)
1487 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001488 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001489 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001490 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001491 // fold (A+(B-(C+A))) to (B-C)
1492 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001493 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001494 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001495 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001496 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001497 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1498 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001499 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001500 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001501 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001502
Dale Johannesen8c766702008-12-02 01:30:54 +00001503 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1504 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1505 SDValue N00 = N0.getOperand(0);
1506 SDValue N01 = N0.getOperand(1);
1507 SDValue N10 = N1.getOperand(0);
1508 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001509
1510 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001511 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1512 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1513 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001514 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001515
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001516 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1517 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001518
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001519 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001520 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001521 APInt LHSZero, LHSOne;
1522 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001523 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001524
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001525 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001526 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001527
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001528 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1529 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001530 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001531 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001532 }
1533 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001534
Evan Cheng92011002007-01-19 17:51:44 +00001535 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001536 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001537 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001538 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001539 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001540 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001541 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001542 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001543 }
1544
Dan Gohman954f4902010-01-19 23:30:49 +00001545 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1546 if (N1.getOpcode() == ISD::SHL &&
1547 N1.getOperand(0).getOpcode() == ISD::SUB)
1548 if (ConstantSDNode *C =
1549 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1550 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001551 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1552 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001553 N1.getOperand(0).getOperand(1),
1554 N1.getOperand(1)));
1555 if (N0.getOpcode() == ISD::SHL &&
1556 N0.getOperand(0).getOpcode() == ISD::SUB)
1557 if (ConstantSDNode *C =
1558 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1559 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001560 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1561 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001562 N0.getOperand(0).getOperand(1),
1563 N0.getOperand(1)));
1564
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001565 if (N1.getOpcode() == ISD::AND) {
1566 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001567 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001568 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1569 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001570
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001571 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1572 // and similar xforms where the inner op is either ~0 or 0.
1573 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001574 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001575 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1576 }
1577 }
1578
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001579 // add (sext i1), X -> sub X, (zext i1)
1580 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1581 N0.getOperand(0).getValueType() == MVT::i1 &&
1582 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001583 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001584 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1585 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1586 }
1587
Evan Chengf1005572010-04-28 07:10:39 +00001588 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001589}
1590
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001591SDValue DAGCombiner::visitADDC(SDNode *N) {
1592 SDValue N0 = N->getOperand(0);
1593 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001594 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1595 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001596 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001597
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001598 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001599 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001600 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001601 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001602 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001603
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001604 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001605 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001606 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001607
Chris Lattner47206662007-03-04 20:40:38 +00001608 // fold (addc x, 0) -> x + no carry out
1609 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001610 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001611 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001612
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001613 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001614 APInt LHSZero, LHSOne;
1615 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001616 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001617
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001618 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001619 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001620
Chris Lattner47206662007-03-04 20:40:38 +00001621 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1622 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001623 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001624 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001625 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001626 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001627 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001628
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001629 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001630}
1631
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001632SDValue DAGCombiner::visitADDE(SDNode *N) {
1633 SDValue N0 = N->getOperand(0);
1634 SDValue N1 = N->getOperand(1);
1635 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001636 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1637 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001638
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001639 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001640 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001641 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001642 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001643
Chris Lattner47206662007-03-04 20:40:38 +00001644 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001645 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001646 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001647
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001648 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001649}
1650
Eric Christophere5ca1e02011-02-16 04:50:12 +00001651// Since it may not be valid to emit a fold to zero for vector initializers
1652// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001653static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001654 SelectionDAG &DAG,
1655 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001656 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001657 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001658 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1659 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001660 return SDValue();
1661}
1662
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001663SDValue DAGCombiner::visitSUB(SDNode *N) {
1664 SDValue N0 = N->getOperand(0);
1665 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001666 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1667 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Eric Christopherd6300d22011-07-14 01:12:15 +00001668 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1669 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001670 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001671
Dan Gohmana8665142007-06-25 16:23:39 +00001672 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001673 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001674 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001675 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001676
1677 // fold (sub x, 0) -> x, vector edition
1678 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1679 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001680 }
Bill Wendling0864a752008-12-10 22:36:00 +00001681
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001682 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001683 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001684 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001685 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001686 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001687 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001688 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001689 // fold (sub x, c) -> (add x, -c)
1690 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001691 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001692 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001693 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1694 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001695 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001696 // fold A-(A-B) -> B
1697 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1698 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001699 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001700 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001701 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001702 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001703 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001704 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001705 // fold C2-(A+C1) -> (C2-C1)-A
1706 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001707 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1708 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001709 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001710 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001711 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001712 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001713 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001714 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1715 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001716 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001717 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001718 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001719 // fold ((A+(C+B))-B) -> A+C
1720 if (N0.getOpcode() == ISD::ADD &&
1721 N0.getOperand(1).getOpcode() == ISD::ADD &&
1722 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001723 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001724 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001725 // fold ((A-(B-C))-C) -> A-B
1726 if (N0.getOpcode() == ISD::SUB &&
1727 N0.getOperand(1).getOpcode() == ISD::SUB &&
1728 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001729 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001730 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001731
Dan Gohman06563a82007-07-03 14:03:57 +00001732 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001733 if (N0.getOpcode() == ISD::UNDEF)
1734 return N0;
1735 if (N1.getOpcode() == ISD::UNDEF)
1736 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001737
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001738 // If the relocation model supports it, consider symbol offsets.
1739 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001740 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001741 // fold (sub Sym, c) -> Sym-c
1742 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001743 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001744 GA->getOffset() -
1745 (uint64_t)N1C->getSExtValue());
1746 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1747 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1748 if (GA->getGlobal() == GB->getGlobal())
1749 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1750 VT);
1751 }
1752
Evan Chengf1005572010-04-28 07:10:39 +00001753 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001754}
1755
Craig Topper43a1bd62012-01-07 09:06:39 +00001756SDValue DAGCombiner::visitSUBC(SDNode *N) {
1757 SDValue N0 = N->getOperand(0);
1758 SDValue N1 = N->getOperand(1);
1759 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1760 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1761 EVT VT = N0.getValueType();
1762
1763 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001764 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001765 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1766 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001767 MVT::Glue));
1768
1769 // fold (subc x, x) -> 0 + no borrow
1770 if (N0 == N1)
1771 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001772 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001773 MVT::Glue));
1774
1775 // fold (subc x, 0) -> x + no borrow
1776 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001777 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001778 MVT::Glue));
1779
1780 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1781 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001782 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1783 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001784 MVT::Glue));
1785
1786 return SDValue();
1787}
1788
1789SDValue DAGCombiner::visitSUBE(SDNode *N) {
1790 SDValue N0 = N->getOperand(0);
1791 SDValue N1 = N->getOperand(1);
1792 SDValue CarryIn = N->getOperand(2);
1793
1794 // fold (sube x, y, false) -> (subc x, y)
1795 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001796 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001797
1798 return SDValue();
1799}
1800
Jack Carterd4e96152013-10-17 01:34:33 +00001801/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1802/// elements are all the same constant or undefined.
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001803static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1804 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1805 if (!C)
1806 return false;
1807
1808 APInt SplatUndef;
1809 unsigned SplatBitSize;
1810 bool HasAnyUndefs;
1811 EVT EltVT = N->getValueType(0).getVectorElementType();
1812 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1813 HasAnyUndefs) &&
1814 EltVT.getSizeInBits() >= SplatBitSize);
1815}
1816
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001817SDValue DAGCombiner::visitMUL(SDNode *N) {
1818 SDValue N0 = N->getOperand(0);
1819 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001820 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001821
Dan Gohman06563a82007-07-03 14:03:57 +00001822 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001823 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001824 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001825
1826 bool N0IsConst = false;
1827 bool N1IsConst = false;
1828 APInt ConstValue0, ConstValue1;
1829 // fold vector ops
1830 if (VT.isVector()) {
1831 SDValue FoldedVOp = SimplifyVBinOp(N);
1832 if (FoldedVOp.getNode()) return FoldedVOp;
1833
1834 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1835 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1836 } else {
1837 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
Jack Carterd4e96152013-10-17 01:34:33 +00001838 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1839 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001840 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
Jack Carterd4e96152013-10-17 01:34:33 +00001841 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1842 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001843 }
1844
Nate Begeman21158fc2005-09-01 00:19:25 +00001845 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001846 if (N0IsConst && N1IsConst)
1847 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1848
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001849 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001850 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001851 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001852 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001853 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001854 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001855 // We require a splat of the entire scalar bit width for non-contiguous
1856 // bit patterns.
1857 bool IsFullSplat =
1858 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001859 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001860 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001861 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001862 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001863 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001864 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001865 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001866 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001867 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001868 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001869 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001870 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001871 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001872 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001873 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001874 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001875 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001876 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001877 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001878 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001879 DAG.getConstant(Log2Val,
1880 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001881 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001882
1883 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001884 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001885 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001886 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1887 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001888 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001889 N1, N0.getOperand(1));
Gabor Greiff304a7a2008-08-28 21:40:38 +00001890 AddToWorkList(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001891 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001892 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001893 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001894
Chris Lattner324871e2006-03-01 03:44:24 +00001895 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1896 // use.
1897 {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001898 SDValue Sh(0,0), Y(0,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001899 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001900 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001901 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1902 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001903 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001904 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001905 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001906 isa<ConstantSDNode>(N1.getOperand(1)) &&
1907 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001908 Sh = N1; Y = N0;
1909 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001910
Gabor Greiff304a7a2008-08-28 21:40:38 +00001911 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001912 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001913 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001914 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001915 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001916 }
1917 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001918
Chris Lattnerf29f5202006-03-04 23:33:26 +00001919 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001920 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1921 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1922 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001923 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1924 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001925 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001926 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001927 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001928
Nate Begeman22e251a2006-02-03 06:46:56 +00001929 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001930 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001931 if (RMUL.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00001932 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001933
Evan Chengf1005572010-04-28 07:10:39 +00001934 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001935}
1936
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001937SDValue DAGCombiner::visitSDIV(SDNode *N) {
1938 SDValue N0 = N->getOperand(0);
1939 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001940 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1941 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001942 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001943
Dan Gohmana8665142007-06-25 16:23:39 +00001944 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001945 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001946 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001947 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00001948 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001949
Nate Begeman21158fc2005-09-01 00:19:25 +00001950 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001951 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00001952 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00001953 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00001954 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00001955 return N0;
1956 // fold (sdiv X, -1) -> 0-X
1957 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001958 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00001959 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00001960 // If we know the sign bits of both operands are zero, strength reduce to a
1961 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00001962 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00001963 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001964 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00001965 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00001966 }
Nate Begeman57b35672006-02-17 07:26:20 +00001967 // fold (sdiv X, pow2) -> simple ops after legalize
Eli Friedmanf9081a82011-12-07 03:55:52 +00001968 if (N1C && !N1C->isNullValue() &&
Eli Friedmane9e356a2011-10-27 02:06:39 +00001969 (N1C->getAPIntValue().isPowerOf2() ||
1970 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00001971 // If dividing by powers of two is cheap, then don't perform the following
1972 // fold.
1973 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001974 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00001975
Eli Friedmane9e356a2011-10-27 02:06:39 +00001976 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00001977
Chris Lattner471627c2006-02-16 08:02:36 +00001978 // Splat the sign bit into the register
Andrew Trickef9de2a2013-05-25 02:42:55 +00001979 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
Bill Wendling5b663e72009-01-30 02:52:17 +00001980 DAG.getConstant(VT.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001981 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00001982 AddToWorkList(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00001983
Chris Lattner471627c2006-02-16 08:02:36 +00001984 // Add (N0 < 0) ? abs2 - 1 : 0;
Andrew Trickef9de2a2013-05-25 02:42:55 +00001985 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
Bill Wendling5b663e72009-01-30 02:52:17 +00001986 DAG.getConstant(VT.getSizeInBits() - lg2,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001987 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001988 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001989 AddToWorkList(SRL.getNode());
1990 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00001991 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001992 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00001993
Nate Begeman4dd38312005-10-21 00:02:42 +00001994 // If we're dividing by a positive value, we're done. Otherwise, we must
1995 // negate the result.
Eli Friedmane9e356a2011-10-27 02:06:39 +00001996 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00001997 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00001998
Gabor Greiff304a7a2008-08-28 21:40:38 +00001999 AddToWorkList(SRA.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002000 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002001 DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002002 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002003
Nate Begemanc6f067a2005-10-20 02:15:44 +00002004 // if integer divide is expensive and we satisfy the requirements, emit an
2005 // alternate sequence.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002006 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002007 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002008 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002009 }
Dan Gohmana8665142007-06-25 16:23:39 +00002010
Dan Gohman06563a82007-07-03 14:03:57 +00002011 // undef / X -> 0
2012 if (N0.getOpcode() == ISD::UNDEF)
2013 return DAG.getConstant(0, VT);
2014 // X / undef -> undef
2015 if (N1.getOpcode() == ISD::UNDEF)
2016 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002017
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002018 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002019}
2020
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002021SDValue DAGCombiner::visitUDIV(SDNode *N) {
2022 SDValue N0 = N->getOperand(0);
2023 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002024 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2025 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00002026 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002027
Dan Gohmana8665142007-06-25 16:23:39 +00002028 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002029 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002030 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002031 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002032 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002033
Nate Begeman21158fc2005-09-01 00:19:25 +00002034 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002035 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002036 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002037 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002038 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002039 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002040 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002041 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002042 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002043 if (N1.getOpcode() == ISD::SHL) {
2044 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002045 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002046 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002047 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002048 N1.getOperand(1),
2049 DAG.getConstant(SHC->getAPIntValue()
2050 .logBase2(),
2051 ADDVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002052 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002053 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002054 }
2055 }
2056 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002057 // fold (udiv x, c) -> alternate
Dan Gohmanb72127a2008-03-13 22:13:53 +00002058 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002059 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002060 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002061 }
Dan Gohmana8665142007-06-25 16:23:39 +00002062
Dan Gohman06563a82007-07-03 14:03:57 +00002063 // undef / X -> 0
2064 if (N0.getOpcode() == ISD::UNDEF)
2065 return DAG.getConstant(0, VT);
2066 // X / undef -> undef
2067 if (N1.getOpcode() == ISD::UNDEF)
2068 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002069
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002070 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002071}
2072
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002073SDValue DAGCombiner::visitSREM(SDNode *N) {
2074 SDValue N0 = N->getOperand(0);
2075 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002076 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2077 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002078 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002079
Nate Begeman21158fc2005-09-01 00:19:25 +00002080 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002081 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002082 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002083 // If we know the sign bits of both operands are zero, strength reduce to a
2084 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002085 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002086 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002087 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002088 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002089
Dan Gohman9a693412007-11-26 23:46:11 +00002090 // If X/C can be simplified by the division-by-constant logic, lower
2091 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002092 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002093 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002094 AddToWorkList(Div.getNode());
2095 SDValue OptimizedDiv = combine(Div.getNode());
2096 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002097 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002098 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002099 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002100 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002101 return Sub;
2102 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002103 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002104
Dan Gohman06563a82007-07-03 14:03:57 +00002105 // undef % X -> 0
2106 if (N0.getOpcode() == ISD::UNDEF)
2107 return DAG.getConstant(0, VT);
2108 // X % undef -> undef
2109 if (N1.getOpcode() == ISD::UNDEF)
2110 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002111
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002112 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002113}
2114
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002115SDValue DAGCombiner::visitUREM(SDNode *N) {
2116 SDValue N0 = N->getOperand(0);
2117 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002118 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2119 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002120 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002121
Nate Begeman21158fc2005-09-01 00:19:25 +00002122 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002123 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002124 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002125 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002126 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002127 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002128 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002129 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2130 if (N1.getOpcode() == ISD::SHL) {
2131 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002132 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002133 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002134 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002135 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002136 VT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002137 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002138 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002139 }
2140 }
2141 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002142
Dan Gohman9a693412007-11-26 23:46:11 +00002143 // If X/C can be simplified by the division-by-constant logic, lower
2144 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002145 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002146 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman1df80f62008-09-08 16:59:01 +00002147 AddToWorkList(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002148 SDValue OptimizedDiv = combine(Div.getNode());
2149 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002150 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002151 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002152 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002153 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002154 return Sub;
2155 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002156 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002157
Dan Gohman06563a82007-07-03 14:03:57 +00002158 // undef % X -> 0
2159 if (N0.getOpcode() == ISD::UNDEF)
2160 return DAG.getConstant(0, VT);
2161 // X % undef -> undef
2162 if (N1.getOpcode() == ISD::UNDEF)
2163 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002164
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002165 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002166}
2167
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002168SDValue DAGCombiner::visitMULHS(SDNode *N) {
2169 SDValue N0 = N->getOperand(0);
2170 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002171 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002172 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002173 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002174
Nate Begeman21158fc2005-09-01 00:19:25 +00002175 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002176 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002177 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002178 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002179 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002180 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002181 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002182 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002183 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002184 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002185 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002186
Chris Lattner10bd29f2010-12-13 08:39:01 +00002187 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2188 // plus a shift.
2189 if (VT.isSimple() && !VT.isVector()) {
2190 MVT Simple = VT.getSimpleVT();
2191 unsigned SimpleSize = Simple.getSizeInBits();
2192 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2193 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2194 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2195 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2196 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002197 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002198 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002199 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2200 }
2201 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002202
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002203 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002204}
2205
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002206SDValue DAGCombiner::visitMULHU(SDNode *N) {
2207 SDValue N0 = N->getOperand(0);
2208 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002209 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002210 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002211 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002212
Nate Begeman21158fc2005-09-01 00:19:25 +00002213 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002214 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002215 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002216 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002217 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002218 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002219 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002220 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002221 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002222
Chris Lattner10bd29f2010-12-13 08:39:01 +00002223 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2224 // plus a shift.
2225 if (VT.isSimple() && !VT.isVector()) {
2226 MVT Simple = VT.getSimpleVT();
2227 unsigned SimpleSize = Simple.getSizeInBits();
2228 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2229 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2230 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2231 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2232 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2233 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002234 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002235 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2236 }
2237 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002238
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002239 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002240}
2241
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002242/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2243/// compute two values. LoOp and HiOp give the opcodes for the two computations
2244/// that are being performed. Return true if a simplification was made.
2245///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002246SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002247 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002248 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002249 bool HiExists = N->hasAnyUseOfValue(1);
2250 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002251 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002252 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002253 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002254 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002255 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002256 }
2257
2258 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002259 bool LoExists = N->hasAnyUseOfValue(0);
2260 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002261 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002262 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002263 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002264 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002265 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002266 }
2267
Evan Chengece4c682007-11-08 09:25:29 +00002268 // If both halves are used, return as it is.
2269 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002270 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002271
2272 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002273 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002274 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002275 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002276 AddToWorkList(Lo.getNode());
2277 SDValue LoOpt = combine(Lo.getNode());
2278 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002279 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002280 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002281 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002282 }
2283
Evan Chengece4c682007-11-08 09:25:29 +00002284 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002285 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002286 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002287 AddToWorkList(Hi.getNode());
2288 SDValue HiOpt = combine(Hi.getNode());
2289 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002290 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002291 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002292 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002293 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002294
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002295 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002296}
2297
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002298SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2299 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002300 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002301
Chris Lattner15090e12010-12-15 06:04:19 +00002302 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002303 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002304
2305 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2306 // plus a shift.
2307 if (VT.isSimple() && !VT.isVector()) {
2308 MVT Simple = VT.getSimpleVT();
2309 unsigned SimpleSize = Simple.getSizeInBits();
2310 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2311 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2312 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2313 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2314 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2315 // Compute the high part as N1.
2316 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002317 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002318 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2319 // Compute the low part as N0.
2320 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2321 return CombineTo(N, Lo, Hi);
2322 }
2323 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002324
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002325 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002326}
2327
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002328SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2329 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002330 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002331
Chris Lattner15090e12010-12-15 06:04:19 +00002332 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002333 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002334
Chris Lattner15090e12010-12-15 06:04:19 +00002335 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2336 // plus a shift.
2337 if (VT.isSimple() && !VT.isVector()) {
2338 MVT Simple = VT.getSimpleVT();
2339 unsigned SimpleSize = Simple.getSizeInBits();
2340 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2341 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2342 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2343 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2344 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2345 // Compute the high part as N1.
2346 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002347 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002348 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2349 // Compute the low part as N0.
2350 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2351 return CombineTo(N, Lo, Hi);
2352 }
2353 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002354
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002355 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002356}
2357
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002358SDValue DAGCombiner::visitSMULO(SDNode *N) {
2359 // (smulo x, 2) -> (saddo x, x)
2360 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2361 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002362 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002363 N->getOperand(0), N->getOperand(0));
2364
2365 return SDValue();
2366}
2367
2368SDValue DAGCombiner::visitUMULO(SDNode *N) {
2369 // (umulo x, 2) -> (uaddo x, x)
2370 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2371 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002372 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002373 N->getOperand(0), N->getOperand(0));
2374
2375 return SDValue();
2376}
2377
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002378SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2379 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002380 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002381
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002382 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002383}
2384
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002385SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2386 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002387 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002388
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002389 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002390}
2391
Chris Lattner8d6fc202006-05-05 05:51:50 +00002392/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2393/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002394SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2395 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002396 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002397 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002398
Dan Gohmandd5286d2010-01-14 03:08:49 +00002399 // Bail early if none of these transforms apply.
2400 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2401
Chris Lattner002ee912006-05-05 06:31:05 +00002402 // For each of OP in AND/OR/XOR:
2403 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2404 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2405 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002406 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002407 //
2408 // do not sink logical op inside of a vector extend, since it may combine
2409 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002410 EVT Op0VT = N0.getOperand(0).getValueType();
2411 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002412 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002413 // Avoid infinite looping with PromoteIntBinOp.
2414 (N0.getOpcode() == ISD::ANY_EXTEND &&
2415 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002416 (N0.getOpcode() == ISD::TRUNCATE &&
2417 (!TLI.isZExtFree(VT, Op0VT) ||
2418 !TLI.isTruncateFree(Op0VT, VT)) &&
2419 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002420 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002421 Op0VT == N1.getOperand(0).getValueType() &&
2422 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002423 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002424 N0.getOperand(0).getValueType(),
2425 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002426 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002427 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002428 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002429
Chris Lattner5ac42932006-05-05 06:10:43 +00002430 // For each of OP in SHL/SRL/SRA/AND...
2431 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2432 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2433 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002434 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002435 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002436 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002437 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002438 N0.getOperand(0).getValueType(),
2439 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002440 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002441 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002442 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002443 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002444
Nadav Rotemb0783502012-04-01 19:31:22 +00002445 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2446 // Only perform this optimization after type legalization and before
2447 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2448 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2449 // we don't want to undo this promotion.
2450 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2451 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002452 if ((N0.getOpcode() == ISD::BITCAST ||
2453 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2454 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002455 SDValue In0 = N0.getOperand(0);
2456 SDValue In1 = N1.getOperand(0);
2457 EVT In0Ty = In0.getValueType();
2458 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002459 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002460 // If both incoming values are integers, and the original types are the
2461 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002462 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002463 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2464 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotemb0783502012-04-01 19:31:22 +00002465 AddToWorkList(Op.getNode());
2466 return BC;
2467 }
2468 }
2469
2470 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2471 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2472 // If both shuffles use the same mask, and both shuffle within a single
2473 // vector, then it is worthwhile to move the swizzle after the operation.
2474 // The type-legalizer generates this pattern when loading illegal
2475 // vector types from memory. In many cases this allows additional shuffle
2476 // optimizations.
Craig Topper9c3da312012-04-09 07:19:09 +00002477 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2478 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2479 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002480 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2481 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002482
2483 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2484 "Inputs to shuffles are not the same type");
Nadav Rotemb0783502012-04-01 19:31:22 +00002485
2486 unsigned NumElts = VT.getVectorNumElements();
Nadav Rotemb0783502012-04-01 19:31:22 +00002487
2488 // Check that both shuffles use the same mask. The masks are known to be of
2489 // the same length because the result vector type is the same.
2490 bool SameMask = true;
2491 for (unsigned i = 0; i != NumElts; ++i) {
2492 int Idx0 = SVN0->getMaskElt(i);
2493 int Idx1 = SVN1->getMaskElt(i);
2494 if (Idx0 != Idx1) {
2495 SameMask = false;
2496 break;
2497 }
2498 }
2499
Craig Topper9c3da312012-04-09 07:19:09 +00002500 if (SameMask) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002501 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
Craig Topper9c3da312012-04-09 07:19:09 +00002502 N0.getOperand(0), N1.getOperand(0));
Nadav Rotemb0783502012-04-01 19:31:22 +00002503 AddToWorkList(Op.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002504 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
Craig Topper9c3da312012-04-09 07:19:09 +00002505 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
Nadav Rotemb0783502012-04-01 19:31:22 +00002506 }
2507 }
Craig Topper9c3da312012-04-09 07:19:09 +00002508
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002509 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002510}
2511
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002512SDValue DAGCombiner::visitAND(SDNode *N) {
2513 SDValue N0 = N->getOperand(0);
2514 SDValue N1 = N->getOperand(1);
2515 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002516 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2517 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002518 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002519 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002520
Dan Gohmana8665142007-06-25 16:23:39 +00002521 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002522 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002523 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002524 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002525
2526 // fold (and x, 0) -> 0, vector edition
2527 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2528 return N0;
2529 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2530 return N1;
2531
2532 // fold (and x, -1) -> x, vector edition
2533 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2534 return N1;
2535 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2536 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002537 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002538
Dan Gohman06563a82007-07-03 14:03:57 +00002539 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002540 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002541 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002542 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002543 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002544 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002545 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002546 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002547 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002548 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002549 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002550 return N0;
2551 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002552 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002553 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002554 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002555 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002556 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002557 if (RAND.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00002558 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002559 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002560 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002561 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002562 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002563 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002564 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2565 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002566 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002567 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002568 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002569 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002570 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002571 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002572
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002573 // Replace uses of the AND with uses of the Zero extend node.
2574 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002575
Chris Lattner49beaf42006-02-02 07:17:31 +00002576 // We actually want to replace all uses of the any_extend with the
2577 // zero_extend, to avoid duplicating things. This will later cause this
2578 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002579 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002580 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002581 }
2582 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002583 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002584 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2585 // already be zero by virtue of the width of the base type of the load.
2586 //
2587 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2588 // more cases.
2589 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2590 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2591 N0.getOpcode() == ISD::LOAD) {
2592 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2593 N0 : N0.getOperand(0) );
2594
2595 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2596 // This can be a pure constant or a vector splat, in which case we treat the
2597 // vector as a scalar and use the splat value.
2598 APInt Constant = APInt::getNullValue(1);
2599 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2600 Constant = C->getAPIntValue();
2601 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2602 APInt SplatValue, SplatUndef;
2603 unsigned SplatBitSize;
2604 bool HasAnyUndefs;
2605 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2606 SplatBitSize, HasAnyUndefs);
2607 if (IsSplat) {
2608 // Undef bits can contribute to a possible optimisation if set, so
2609 // set them.
2610 SplatValue |= SplatUndef;
2611
2612 // The splat value may be something like "0x00FFFFFF", which means 0 for
2613 // the first vector value and FF for the rest, repeating. We need a mask
2614 // that will apply equally to all members of the vector, so AND all the
2615 // lanes of the constant together.
2616 EVT VT = Vector->getValueType(0);
2617 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002618
2619 // If the splat value has been compressed to a bitlength lower
2620 // than the size of the vector lane, we need to re-expand it to
2621 // the lane size.
2622 if (BitWidth > SplatBitSize)
2623 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2624 SplatBitSize < BitWidth;
2625 SplatBitSize = SplatBitSize * 2)
2626 SplatValue |= SplatValue.shl(SplatBitSize);
2627
James Molloy862fe492012-02-20 12:02:38 +00002628 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002629 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002630 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2631 }
2632 }
2633
2634 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2635 // actually legal and isn't going to get expanded, else this is a false
2636 // optimisation.
2637 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2638 Load->getMemoryVT());
2639
2640 // Resize the constant to the same size as the original memory access before
2641 // extension. If it is still the AllOnesValue then this AND is completely
2642 // unneeded.
2643 Constant =
2644 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2645
2646 bool B;
2647 switch (Load->getExtensionType()) {
2648 default: B = false; break;
2649 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2650 case ISD::ZEXTLOAD:
2651 case ISD::NON_EXTLOAD: B = true; break;
2652 }
2653
2654 if (B && Constant.isAllOnesValue()) {
2655 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2656 // preserve semantics once we get rid of the AND.
2657 SDValue NewLoad(Load, 0);
2658 if (Load->getExtensionType() == ISD::EXTLOAD) {
2659 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002660 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002661 Load->getChain(), Load->getBasePtr(),
2662 Load->getOffset(), Load->getMemoryVT(),
2663 Load->getMemOperand());
2664 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002665 if (Load->getNumValues() == 3) {
2666 // PRE/POST_INC loads have 3 values.
2667 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2668 NewLoad.getValue(2) };
2669 CombineTo(Load, To, 3, true);
2670 } else {
2671 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2672 }
James Molloy862fe492012-02-20 12:02:38 +00002673 }
2674
2675 // Fold the AND away, taking care not to fold to the old load node if we
2676 // replaced it.
2677 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2678
2679 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2680 }
2681 }
Nate Begeman049b7482005-09-09 19:49:52 +00002682 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2683 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2684 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2685 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002686
Nate Begeman049b7482005-09-09 19:49:52 +00002687 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002688 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002689 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002690 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002691 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002692 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002693 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002694 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002695 }
Bill Wendling86171912009-01-30 20:43:18 +00002696 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002697 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002698 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002699 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002700 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002701 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002702 }
Bill Wendling86171912009-01-30 20:43:18 +00002703 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002704 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002705 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002706 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002707 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002708 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002709 }
2710 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002711 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2712 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2713 Op0 == Op1 && LL.getValueType().isInteger() &&
2714 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2715 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2716 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2717 cast<ConstantSDNode>(RR)->isNullValue()))) {
2718 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2719 LL, DAG.getConstant(1, LL.getValueType()));
2720 AddToWorkList(ADDNode.getNode());
2721 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2722 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2723 }
Nate Begeman049b7482005-09-09 19:49:52 +00002724 // canonicalize equivalent to ll == rl
2725 if (LL == RR && LR == RL) {
2726 Op1 = ISD::getSetCCSwappedOperands(Op1);
2727 std::swap(RL, RR);
2728 }
2729 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002730 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002731 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002732 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002733 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002734 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2735 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002736 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002737 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002738 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002739 }
2740 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002741
Bill Wendling86171912009-01-30 20:43:18 +00002742 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002743 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002744 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002745 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002746 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002747
Nate Begemandc7bba92006-02-03 22:24:05 +00002748 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2749 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002750 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002751 SimplifyDemandedBits(SDValue(N, 0)))
2752 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002753
Nate Begeman02b23c62005-10-13 03:11:28 +00002754 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002755 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002756 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002757 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002758 // If we zero all the possible extended bits, then we can turn this into
2759 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002760 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002761 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002762 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002763 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002764 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002765 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002766 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002767 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002768 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002769 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002770 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002771 }
2772 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002773 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002774 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002775 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002776 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002777 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002778 // If we zero all the possible extended bits, then we can turn this into
2779 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002780 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002781 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002782 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002783 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002784 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002785 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002786 LN0->getChain(), LN0->getBasePtr(),
2787 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002788 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002789 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002790 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002791 }
2792 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002793
Chris Lattnerf0032b32006-02-28 06:49:37 +00002794 // fold (and (load x), 255) -> (zextload x, i8)
2795 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002796 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2797 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2798 (N0.getOpcode() == ISD::ANY_EXTEND &&
2799 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2800 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2801 LoadSDNode *LN0 = HasAnyExt
2802 ? cast<LoadSDNode>(N0.getOperand(0))
2803 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002804 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002805 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002806 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002807 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2808 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2809 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002810
Evan Cheng166a4e62010-01-06 19:38:29 +00002811 if (ExtVT == LoadedVT &&
2812 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002813 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002814
2815 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002816 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002817 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2818 LN0->getMemOperand());
Chris Lattner88de3842010-01-07 21:53:27 +00002819 AddToWorkList(N);
2820 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2821 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2822 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002823
Chris Lattner88de3842010-01-07 21:53:27 +00002824 // Do not change the width of a volatile load.
2825 // Do not generate loads of non-round integer types since these can
2826 // be expensive (and would be wrong if the type is not byte sized).
2827 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2828 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2829 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002830
Chris Lattner88de3842010-01-07 21:53:27 +00002831 unsigned Alignment = LN0->getAlignment();
2832 SDValue NewPtr = LN0->getBasePtr();
2833
2834 // For big endian targets, we need to add an offset to the pointer
2835 // to load the correct bytes. For little endian systems, we merely
2836 // need to read fewer bytes from the same pointer.
2837 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002838 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2839 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2840 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002841 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002842 NewPtr, DAG.getConstant(PtrOff, PtrType));
2843 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002844 }
Chris Lattner88de3842010-01-07 21:53:27 +00002845
2846 AddToWorkList(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002847
Chris Lattner88de3842010-01-07 21:53:27 +00002848 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2849 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002850 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002851 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002852 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002853 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002854 Alignment, LN0->getTBAAInfo());
Chris Lattner88de3842010-01-07 21:53:27 +00002855 AddToWorkList(N);
2856 CombineTo(LN0, Load, Load.getValue(1));
2857 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002858 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002859 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002860 }
2861 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002862
Evan Chenge6a3b032012-07-17 18:54:11 +00002863 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2864 VT.getSizeInBits() <= 64) {
2865 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2866 APInt ADDC = ADDI->getAPIntValue();
2867 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2868 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2869 // immediate for an add, but it is legal if its top c2 bits are set,
2870 // transform the ADD so the immediate doesn't need to be materialized
2871 // in a register.
2872 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2873 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2874 SRLI->getZExtValue());
2875 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2876 ADDC |= Mask;
2877 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2878 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002879 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002880 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2881 CombineTo(N0.getNode(), NewAdd);
2882 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2883 }
2884 }
2885 }
2886 }
2887 }
2888 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002889
Tim Northover819bfb52013-08-27 13:46:45 +00002890 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2891 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2892 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2893 N0.getOperand(1), false);
2894 if (BSwap.getNode())
2895 return BSwap;
2896 }
2897
Evan Chengf1005572010-04-28 07:10:39 +00002898 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002899}
2900
Evan Cheng4c0bd962011-06-21 06:01:08 +00002901/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2902///
2903SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2904 bool DemandHighBits) {
2905 if (!LegalOperations)
2906 return SDValue();
2907
2908 EVT VT = N->getValueType(0);
2909 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2910 return SDValue();
2911 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2912 return SDValue();
2913
2914 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2915 bool LookPassAnd0 = false;
2916 bool LookPassAnd1 = false;
2917 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2918 std::swap(N0, N1);
2919 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2920 std::swap(N0, N1);
2921 if (N0.getOpcode() == ISD::AND) {
2922 if (!N0.getNode()->hasOneUse())
2923 return SDValue();
2924 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2925 if (!N01C || N01C->getZExtValue() != 0xFF00)
2926 return SDValue();
2927 N0 = N0.getOperand(0);
2928 LookPassAnd0 = true;
2929 }
2930
2931 if (N1.getOpcode() == ISD::AND) {
2932 if (!N1.getNode()->hasOneUse())
2933 return SDValue();
2934 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2935 if (!N11C || N11C->getZExtValue() != 0xFF)
2936 return SDValue();
2937 N1 = N1.getOperand(0);
2938 LookPassAnd1 = true;
2939 }
2940
2941 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2942 std::swap(N0, N1);
2943 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2944 return SDValue();
2945 if (!N0.getNode()->hasOneUse() ||
2946 !N1.getNode()->hasOneUse())
2947 return SDValue();
2948
2949 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2950 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2951 if (!N01C || !N11C)
2952 return SDValue();
2953 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2954 return SDValue();
2955
2956 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2957 SDValue N00 = N0->getOperand(0);
2958 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2959 if (!N00.getNode()->hasOneUse())
2960 return SDValue();
2961 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2962 if (!N001C || N001C->getZExtValue() != 0xFF)
2963 return SDValue();
2964 N00 = N00.getOperand(0);
2965 LookPassAnd0 = true;
2966 }
2967
2968 SDValue N10 = N1->getOperand(0);
2969 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2970 if (!N10.getNode()->hasOneUse())
2971 return SDValue();
2972 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2973 if (!N101C || N101C->getZExtValue() != 0xFF00)
2974 return SDValue();
2975 N10 = N10.getOperand(0);
2976 LookPassAnd1 = true;
2977 }
2978
2979 if (N00 != N10)
2980 return SDValue();
2981
Tim Northover819bfb52013-08-27 13:46:45 +00002982 // Make sure everything beyond the low halfword gets set to zero since the SRL
2983 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00002984 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00002985 if (DemandHighBits && OpSizeInBits > 16) {
2986 // If the left-shift isn't masked out then the only way this is a bswap is
2987 // if all bits beyond the low 8 are 0. In that case the entire pattern
2988 // reduces to a left shift anyway: leave it for other parts of the combiner.
2989 if (!LookPassAnd0)
2990 return SDValue();
2991
2992 // However, if the right shift isn't masked out then it might be because
2993 // it's not needed. See if we can spot that too.
2994 if (!LookPassAnd1 &&
2995 !DAG.MaskedValueIsZero(
2996 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2997 return SDValue();
2998 }
Eric Christopherd6300d22011-07-14 01:12:15 +00002999
Andrew Trickef9de2a2013-05-25 02:42:55 +00003000 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003001 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003002 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003003 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3004 return Res;
3005}
3006
3007/// isBSwapHWordElement - Return true if the specified node is an element
3008/// that makes up a 32-bit packed halfword byteswap. i.e.
3009/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003010static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003011 if (!N.getNode()->hasOneUse())
3012 return false;
3013
3014 unsigned Opc = N.getOpcode();
3015 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3016 return false;
3017
3018 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3019 if (!N1C)
3020 return false;
3021
3022 unsigned Num;
3023 switch (N1C->getZExtValue()) {
3024 default:
3025 return false;
3026 case 0xFF: Num = 0; break;
3027 case 0xFF00: Num = 1; break;
3028 case 0xFF0000: Num = 2; break;
3029 case 0xFF000000: Num = 3; break;
3030 }
3031
3032 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3033 SDValue N0 = N.getOperand(0);
3034 if (Opc == ISD::AND) {
3035 if (Num == 0 || Num == 2) {
3036 // (x >> 8) & 0xff
3037 // (x >> 8) & 0xff0000
3038 if (N0.getOpcode() != ISD::SRL)
3039 return false;
3040 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3041 if (!C || C->getZExtValue() != 8)
3042 return false;
3043 } else {
3044 // (x << 8) & 0xff00
3045 // (x << 8) & 0xff000000
3046 if (N0.getOpcode() != ISD::SHL)
3047 return false;
3048 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3049 if (!C || C->getZExtValue() != 8)
3050 return false;
3051 }
3052 } else if (Opc == ISD::SHL) {
3053 // (x & 0xff) << 8
3054 // (x & 0xff0000) << 8
3055 if (Num != 0 && Num != 2)
3056 return false;
3057 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3058 if (!C || C->getZExtValue() != 8)
3059 return false;
3060 } else { // Opc == ISD::SRL
3061 // (x & 0xff00) >> 8
3062 // (x & 0xff000000) >> 8
3063 if (Num != 1 && Num != 3)
3064 return false;
3065 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3066 if (!C || C->getZExtValue() != 8)
3067 return false;
3068 }
3069
3070 if (Parts[Num])
3071 return false;
3072
3073 Parts[Num] = N0.getOperand(0).getNode();
3074 return true;
3075}
3076
3077/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3078/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3079/// => (rotl (bswap x), 16)
3080SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3081 if (!LegalOperations)
3082 return SDValue();
3083
3084 EVT VT = N->getValueType(0);
3085 if (VT != MVT::i32)
3086 return SDValue();
3087 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3088 return SDValue();
3089
3090 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3091 // Look for either
3092 // (or (or (and), (and)), (or (and), (and)))
3093 // (or (or (or (and), (and)), (and)), (and))
3094 if (N0.getOpcode() != ISD::OR)
3095 return SDValue();
3096 SDValue N00 = N0.getOperand(0);
3097 SDValue N01 = N0.getOperand(1);
3098
Evan Chengbf0baa92012-12-13 01:34:32 +00003099 if (N1.getOpcode() == ISD::OR &&
3100 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003101 // (or (or (and), (and)), (or (and), (and)))
3102 SDValue N000 = N00.getOperand(0);
3103 if (!isBSwapHWordElement(N000, Parts))
3104 return SDValue();
3105
3106 SDValue N001 = N00.getOperand(1);
3107 if (!isBSwapHWordElement(N001, Parts))
3108 return SDValue();
3109 SDValue N010 = N01.getOperand(0);
3110 if (!isBSwapHWordElement(N010, Parts))
3111 return SDValue();
3112 SDValue N011 = N01.getOperand(1);
3113 if (!isBSwapHWordElement(N011, Parts))
3114 return SDValue();
3115 } else {
3116 // (or (or (or (and), (and)), (and)), (and))
3117 if (!isBSwapHWordElement(N1, Parts))
3118 return SDValue();
3119 if (!isBSwapHWordElement(N01, Parts))
3120 return SDValue();
3121 if (N00.getOpcode() != ISD::OR)
3122 return SDValue();
3123 SDValue N000 = N00.getOperand(0);
3124 if (!isBSwapHWordElement(N000, Parts))
3125 return SDValue();
3126 SDValue N001 = N00.getOperand(1);
3127 if (!isBSwapHWordElement(N001, Parts))
3128 return SDValue();
3129 }
3130
3131 // Make sure the parts are all coming from the same node.
3132 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3133 return SDValue();
3134
Andrew Trickef9de2a2013-05-25 02:42:55 +00003135 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003136 SDValue(Parts[0],0));
3137
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003138 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003139 // do (x << 16) | (x >> 16).
3140 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3141 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003142 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003143 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003144 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3145 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3146 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3147 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003148}
3149
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003150SDValue DAGCombiner::visitOR(SDNode *N) {
3151 SDValue N0 = N->getOperand(0);
3152 SDValue N1 = N->getOperand(1);
3153 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003154 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3155 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003156 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003157
Dan Gohmana8665142007-06-25 16:23:39 +00003158 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003159 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003160 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003161 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003162
3163 // fold (or x, 0) -> x, vector edition
3164 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3165 return N1;
3166 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3167 return N0;
3168
3169 // fold (or x, -1) -> -1, vector edition
3170 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3171 return N0;
3172 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3173 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00003174 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003175
Dan Gohman06563a82007-07-03 14:03:57 +00003176 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003177 if (!LegalOperations &&
3178 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003179 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3180 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3181 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003182 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003183 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003184 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003185 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003186 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003187 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003188 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003189 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003190 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003191 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003192 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003193 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003194 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003195 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003196 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003197
3198 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3199 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3200 if (BSwap.getNode() != 0)
3201 return BSwap;
3202 BSwap = MatchBSwapHWordLow(N, N0, N1);
3203 if (BSwap.getNode() != 0)
3204 return BSwap;
3205
Nate Begeman22e251a2006-02-03 06:46:56 +00003206 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003207 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003208 if (ROR.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00003209 return ROR;
3210 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003211 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003212 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003213 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003214 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzka50e7e802014-01-24 18:40:30 +00003215 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003216 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3217 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzka50e7e802014-01-24 18:40:30 +00003218 N0.getOperand(0), N1),
3219 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003220 }
Nate Begeman049b7482005-09-09 19:49:52 +00003221 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3222 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3223 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3224 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003225
Nate Begeman049b7482005-09-09 19:49:52 +00003226 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003227 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003228 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3229 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003230 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003231 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003232 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003233 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003234 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003235 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003236 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003237 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3238 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003239 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003240 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003241 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003242 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003243 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003244 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003245 }
3246 }
3247 // canonicalize equivalent to ll == rl
3248 if (LL == RR && LR == RL) {
3249 Op1 = ISD::getSetCCSwappedOperands(Op1);
3250 std::swap(RL, RR);
3251 }
3252 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003253 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003254 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003255 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003256 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003257 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3258 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003259 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003260 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003261 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003262 }
3263 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003264
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003265 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003266 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003267 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003268 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003269 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003270
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003271 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003272 if (N0.getOpcode() == ISD::AND &&
3273 N1.getOpcode() == ISD::AND &&
3274 N0.getOperand(1).getOpcode() == ISD::Constant &&
3275 N1.getOperand(1).getOpcode() == ISD::Constant &&
3276 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003277 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003278 // We can only do this xform if we know that bits from X that are set in C2
3279 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003280 const APInt &LHSMask =
3281 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3282 const APInt &RHSMask =
3283 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003284
Dan Gohman309d3d52007-06-22 14:59:07 +00003285 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3286 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003287 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003288 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003289 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003290 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003291 }
3292 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003293
Chris Lattner97614c82006-09-14 20:50:57 +00003294 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003295 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003296 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003297
Dan Gohman600f62b2010-06-24 14:30:44 +00003298 // Simplify the operands using demanded-bits information.
3299 if (!VT.isVector() &&
3300 SimplifyDemandedBits(SDValue(N, 0)))
3301 return SDValue(N, 0);
3302
Evan Chengf1005572010-04-28 07:10:39 +00003303 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003304}
3305
Chris Lattner97614c82006-09-14 20:50:57 +00003306/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003307static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003308 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003309 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003310 Mask = Op.getOperand(1);
3311 Op = Op.getOperand(0);
3312 } else {
3313 return false;
3314 }
3315 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003316
Chris Lattner97614c82006-09-14 20:50:57 +00003317 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3318 Shift = Op;
3319 return true;
3320 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003321
Scott Michelcf0da6c2009-02-17 22:15:04 +00003322 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003323}
3324
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003325// Return true if we can prove that, whenever Neg and Pos are both in the
3326// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003327// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3328//
3329// (or (shift1 X, Neg), (shift2 X, Pos))
3330//
3331// reduces to a rotate in direction shift2 by Pos and a rotate in direction
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003332// shift1 by Neg. The range [0, OpSize) means that we only need to consider
3333// shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003334static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003335 // If OpSize is a power of 2 then:
3336 //
3337 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3338 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3339 //
3340 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3341 // for the stronger condition:
3342 //
3343 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3344 //
3345 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3346 // we can just replace Neg with Neg' for the rest of the function.
3347 //
3348 // In other cases we check for the even stronger condition:
3349 //
3350 // Neg == OpSize - Pos [B]
3351 //
3352 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3353 // behavior if Pos == 0 (and consequently Neg == OpSize).
3354 //
3355 // We could actually use [A] whenever OpSize is a power of 2, but the
3356 // only extra cases that it would match are those uninteresting ones
3357 // where Neg and Pos are never in range at the same time. E.g. for
3358 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3359 // as well as (sub 32, Pos), but:
3360 //
3361 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3362 //
3363 // always invokes undefined behavior for 32-bit X.
3364 //
3365 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3366 unsigned LoBits = 0;
3367 if (Neg.getOpcode() == ISD::AND &&
3368 isPowerOf2_64(OpSize) &&
3369 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3370 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3371 Neg = Neg.getOperand(0);
3372 LoBits = Log2_64(OpSize);
3373 }
3374
Richard Sandiford0f264db2014-01-09 10:49:40 +00003375 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3376 if (Neg.getOpcode() != ISD::SUB)
3377 return 0;
3378 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3379 if (!NegC)
3380 return 0;
3381 SDValue NegOp1 = Neg.getOperand(1);
3382
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003383 // The condition we need is now:
3384 //
3385 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3386 //
3387 // If NegOp1 == Pos then we need:
3388 //
3389 // OpSize & Mask == NegC & Mask
3390 //
3391 // (because "x & Mask" is a truncation and distributes through subtraction).
3392 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003393 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003394 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003395 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3396 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003397 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003398 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3399 //
3400 // which, again because "x & Mask" is a truncation, becomes:
3401 //
3402 // NegC & Mask == (OpSize - PosC) & Mask
3403 // OpSize & Mask == (NegC + PosC) & Mask
3404 else if (Pos.getOpcode() == ISD::ADD &&
3405 Pos.getOperand(0) == NegOp1 &&
3406 Pos.getOperand(1).getOpcode() == ISD::Constant)
3407 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3408 NegC->getAPIntValue());
3409 else
3410 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003411
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003412 // Now we just need to check that OpSize & Mask == Width & Mask.
3413 if (LoBits)
3414 return Width.getLoBits(LoBits) == 0;
3415 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003416}
3417
Richard Sandiford95c864d2014-01-08 15:40:47 +00003418// A subroutine of MatchRotate used once we have found an OR of two opposite
3419// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3420// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3421// former being preferred if supported. InnerPos and InnerNeg are Pos and
3422// Neg with outer conversions stripped away.
3423SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3424 SDValue Neg, SDValue InnerPos,
3425 SDValue InnerNeg, unsigned PosOpcode,
3426 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003427 // fold (or (shl x, (*ext y)),
3428 // (srl x, (*ext (sub 32, y)))) ->
3429 // (rotl x, y) or (rotr x, (sub 32, y))
3430 //
3431 // fold (or (shl x, (*ext (sub 32, y))),
3432 // (srl x, (*ext y))) ->
3433 // (rotr x, y) or (rotl x, (sub 32, y))
3434 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003435 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003436 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3437 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3438 HasPos ? Pos : Neg).getNode();
3439 }
3440
3441 // fold (or (shl (*ext x), (*ext y)),
3442 // (srl (*ext x), (*ext (sub 32, y)))) ->
3443 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3444 //
3445 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3446 // (srl (*ext x), (*ext y))) ->
3447 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3448 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3449 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3450 SDValue InnerShifted = Shifted.getOperand(0);
3451 EVT InnerVT = InnerShifted.getValueType();
3452 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3453 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
Richard Sandiford0f264db2014-01-09 10:49:40 +00003454 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003455 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3456 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3457 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3458 }
3459 }
3460 }
3461
3462 return 0;
3463}
3464
Chris Lattner97614c82006-09-14 20:50:57 +00003465// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3466// idioms for rotate, and if the target supports rotation instructions, generate
3467// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003468SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003469 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003470 EVT VT = LHS.getValueType();
Chris Lattner97614c82006-09-14 20:50:57 +00003471 if (!TLI.isTypeLegal(VT)) return 0;
3472
3473 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003474 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3475 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Chris Lattner97614c82006-09-14 20:50:57 +00003476 if (!HasROTL && !HasROTR) return 0;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003477
Chris Lattner97614c82006-09-14 20:50:57 +00003478 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003479 SDValue LHSShift; // The shift.
3480 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003481 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3482 return 0; // Not part of a rotate.
3483
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003484 SDValue RHSShift; // The shift.
3485 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003486 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3487 return 0; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003488
Chris Lattner97614c82006-09-14 20:50:57 +00003489 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3490 return 0; // Not shifting the same value.
3491
3492 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3493 return 0; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003494
Chris Lattner97614c82006-09-14 20:50:57 +00003495 // Canonicalize shl to left side in a shl/srl pair.
3496 if (RHSShift.getOpcode() == ISD::SHL) {
3497 std::swap(LHS, RHS);
3498 std::swap(LHSShift, RHSShift);
3499 std::swap(LHSMask , RHSMask );
3500 }
3501
Duncan Sands13237ac2008-06-06 12:08:01 +00003502 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003503 SDValue LHSShiftArg = LHSShift.getOperand(0);
3504 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003505 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003506 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003507
3508 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3509 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003510 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3511 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003512 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3513 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003514 if ((LShVal + RShVal) != OpSizeInBits)
3515 return 0;
3516
Craig Topper65161fa2012-09-29 06:54:22 +00003517 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3518 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003519
Chris Lattner97614c82006-09-14 20:50:57 +00003520 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003521 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003522 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003523
Gabor Greiff304a7a2008-08-28 21:40:38 +00003524 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003525 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3526 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003527 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003528 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003529 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3530 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003531 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003532
Bill Wendling35972a92009-01-30 21:14:50 +00003533 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003534 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003535
Gabor Greiff304a7a2008-08-28 21:40:38 +00003536 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003537 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003538
Chris Lattner97614c82006-09-14 20:50:57 +00003539 // If there is a mask here, and we have a variable shift, we can't be sure
3540 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003541 if (LHSMask.getNode() || RHSMask.getNode())
Chris Lattner97614c82006-09-14 20:50:57 +00003542 return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003543
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003544 // If the shift amount is sign/zext/any-extended just peel it off.
3545 SDValue LExtOp0 = LHSShiftAmt;
3546 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003547 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3548 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3549 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3550 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3551 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3552 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3553 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3554 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003555 LExtOp0 = LHSShiftAmt.getOperand(0);
3556 RExtOp0 = RHSShiftAmt.getOperand(0);
3557 }
3558
Richard Sandiford95c864d2014-01-08 15:40:47 +00003559 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3560 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3561 if (TryL)
3562 return TryL;
3563
3564 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3565 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3566 if (TryR)
3567 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003568
Chris Lattner97614c82006-09-14 20:50:57 +00003569 return 0;
3570}
3571
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003572SDValue DAGCombiner::visitXOR(SDNode *N) {
3573 SDValue N0 = N->getOperand(0);
3574 SDValue N1 = N->getOperand(1);
3575 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003576 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3577 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003578 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003579
Dan Gohmana8665142007-06-25 16:23:39 +00003580 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003581 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003582 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003583 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003584
3585 // fold (xor x, 0) -> x, vector edition
3586 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3587 return N1;
3588 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3589 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003590 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003591
Evan Chengdf1690d2008-03-25 20:08:07 +00003592 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3593 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3594 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003595 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003596 if (N0.getOpcode() == ISD::UNDEF)
3597 return N0;
3598 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003599 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003600 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003601 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003602 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003603 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003604 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003605 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003606 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003607 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003608 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003609 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003610 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003611 if (RXOR.getNode() != 0)
Nate Begeman22e251a2006-02-03 06:46:56 +00003612 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003613
Nate Begeman21158fc2005-09-01 00:19:25 +00003614 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003615 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003616 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003617 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3618 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003619
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003620 if (!LegalOperations ||
3621 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003622 switch (N0.getOpcode()) {
3623 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003624 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003625 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003626 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003627 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003628 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003629 N0.getOperand(3), NotCC);
3630 }
3631 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003632 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003633
Chris Lattner58c227b2007-09-10 21:39:07 +00003634 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003635 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003636 N0.getNode()->hasOneUse() &&
3637 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003638 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003639 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003640 DAG.getConstant(1, V.getValueType()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00003641 AddToWorkList(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003642 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003643 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003644
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003645 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003646 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003647 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003648 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003649 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3650 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003651 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3652 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003653 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003654 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003655 }
3656 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003657 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003658 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003659 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003660 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003661 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3662 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003663 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3664 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003665 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003666 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003667 }
3668 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003669 // fold (xor (and x, y), y) -> (and (not x), y)
3670 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003671 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003672 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003673 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer386ab7f2013-05-08 06:44:42 +00003674 AddToWorkList(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003675 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003676 }
Bill Wendling35972a92009-01-30 21:14:50 +00003677 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003678 if (N1C && N0.getOpcode() == ISD::XOR) {
3679 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3680 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3681 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003682 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003683 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003684 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003685 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003686 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003687 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003688 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003689 }
3690 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003691 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003692 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003693
Chris Lattner8d6fc202006-05-05 05:51:50 +00003694 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3695 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003696 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003697 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003698 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003699
Chris Lattner098c01e2006-04-08 04:15:24 +00003700 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003701 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003702 SimplifyDemandedBits(SDValue(N, 0)))
3703 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003704
Evan Chengf1005572010-04-28 07:10:39 +00003705 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003706}
3707
Chris Lattner7c709a52007-12-06 07:33:36 +00003708/// visitShiftByConstant - Handle transforms common to the three shifts, when
3709/// the shift amount is a constant.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003710SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00003711 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003712 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003713
Chris Lattner7c709a52007-12-06 07:33:36 +00003714 // We want to pull some binops through shifts, so that we have (and (shift))
3715 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3716 // thing happens with address calculations, so it's important to canonicalize
3717 // it.
3718 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003719
Chris Lattner7c709a52007-12-06 07:33:36 +00003720 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003721 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003722 case ISD::OR:
3723 case ISD::XOR:
3724 HighBitSet = false; // We can only transform sra if the high bit is clear.
3725 break;
3726 case ISD::AND:
3727 HighBitSet = true; // We can only transform sra if the high bit is set.
3728 break;
3729 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003730 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003731 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003732 HighBitSet = false; // We can only transform sra if the high bit is clear.
3733 break;
3734 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003735
Chris Lattner7c709a52007-12-06 07:33:36 +00003736 // We require the RHS of the binop to be a constant as well.
3737 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003738 if (!BinOpCst) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003739
3740 // FIXME: disable this unless the input to the binop is a shift by a constant.
3741 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003742 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003743 // void foo(int *X, int i) { X[i & 1235] = 1; }
3744 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003745 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003746 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003747 BinOpLHSVal->getOpcode() != ISD::SRA &&
3748 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3749 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003750 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003751
Owen Anderson53aa7a92009-08-10 22:56:29 +00003752 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003753
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003754 // If this is a signed shift right, and the high bit is modified by the
3755 // logical operation, do not perform the transformation. The highBitSet
3756 // boolean indicates the value of the high bit of the constant which would
3757 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003758 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003759 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3760 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003761 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003762 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003763
Chris Lattner7c709a52007-12-06 07:33:36 +00003764 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003765 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003766 N->getValueType(0),
3767 LHS->getOperand(1), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003768
3769 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003770 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003771 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003772 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003773
3774 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003775 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003776}
3777
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003778SDValue DAGCombiner::visitSHL(SDNode *N) {
3779 SDValue N0 = N->getOperand(0);
3780 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003781 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3782 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003783 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00003784 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003785
Daniel Sandersa1840d22013-11-11 17:23:41 +00003786 // fold vector ops
3787 if (VT.isVector()) {
3788 SDValue FoldedVOp = SimplifyVBinOp(N);
3789 if (FoldedVOp.getNode()) return FoldedVOp;
3790 }
3791
Nate Begeman21158fc2005-09-01 00:19:25 +00003792 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003793 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003794 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003795 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003796 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003797 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003798 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00003799 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003800 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003801 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003802 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003803 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00003804 // fold (shl undef, x) -> 0
3805 if (N0.getOpcode() == ISD::UNDEF)
3806 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003807 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003808 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00003809 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00003810 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00003811 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003812 if (N1.getOpcode() == ISD::TRUNCATE &&
Evan Cheng13beeeb12008-09-22 18:19:24 +00003813 N1.getOperand(0).getOpcode() == ISD::AND &&
3814 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003815 SDValue N101 = N1.getOperand(0).getOperand(1);
Evan Cheng13beeeb12008-09-22 18:19:24 +00003816 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00003817 EVT TruncVT = N1.getValueType();
Evan Cheng13beeeb12008-09-22 18:19:24 +00003818 SDValue N100 = N1.getOperand(0).getOperand(0);
Duncan Sands3ed76882009-02-01 18:06:53 +00003819 APInt TruncC = N101C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00003820 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003821 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3822 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00003823 DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00003824 SDLoc(N),
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00003825 TruncVT, N100),
Dan Gohmanfb58faf2009-01-27 20:39:34 +00003826 DAG.getConstant(TruncC, TruncVT)));
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003827 }
3828 }
3829
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003830 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3831 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003832
3833 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Scott Michelcf0da6c2009-02-17 22:15:04 +00003834 if (N1C && N0.getOpcode() == ISD::SHL &&
Nate Begeman21158fc2005-09-01 00:19:25 +00003835 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003836 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3837 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00003838 if (c1 + c2 >= OpSizeInBits)
Nate Begemand23739d2005-09-06 04:43:02 +00003839 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003840 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
Nate Begemand23739d2005-09-06 04:43:02 +00003841 DAG.getConstant(c1 + c2, N1.getValueType()));
Nate Begeman21158fc2005-09-01 00:19:25 +00003842 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00003843
3844 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3845 // For this to be valid, the second form must not preserve any of the bits
3846 // that are shifted out by the inner shift in the first form. This means
3847 // the outer shift size must be >= the number of bits added by the ext.
3848 // As a corollary, we don't care what kind of ext it is.
3849 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3850 N0.getOpcode() == ISD::ANY_EXTEND ||
3851 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3852 N0.getOperand(0).getOpcode() == ISD::SHL &&
3853 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00003854 uint64_t c1 =
Dale Johannesena94e36b2010-12-21 21:55:50 +00003855 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3856 uint64_t c2 = N1C->getZExtValue();
3857 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3858 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3859 if (c2 >= OpSizeInBits - InnerShiftSize) {
3860 if (c1 + c2 >= OpSizeInBits)
3861 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003862 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3863 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
Dale Johannesena94e36b2010-12-21 21:55:50 +00003864 N0.getOperand(0)->getOperand(0)),
3865 DAG.getConstant(c1 + c2, N1.getValueType()));
3866 }
3867 }
3868
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00003869 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3870 // Only fold this if the inner zext has no other uses to avoid increasing
3871 // the total number of instructions.
3872 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
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 if (c1 < VT.getSizeInBits()) {
3878 uint64_t c2 = N1C->getZExtValue();
3879 if (c1 == c2) {
3880 SDValue NewOp0 = N0.getOperand(0);
3881 EVT CountVT = NewOp0.getOperand(1).getValueType();
3882 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3883 NewOp0, DAG.getConstant(c2, CountVT));
Andrea Di Biagio561badf2013-10-17 11:02:58 +00003884 AddToWorkList(NewSHL.getNode());
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00003885 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3886 }
3887 }
3888 }
3889
Eli Friedman1877ac92011-06-09 22:14:44 +00003890 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3891 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00003892 // Only fold this if the inner shift has no other uses -- if it does, folding
3893 // this will increase the total number of instructions.
3894 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
Nate Begeman21158fc2005-09-01 00:19:25 +00003895 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003896 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
Evan Chenga7bb55e2009-07-21 05:40:15 +00003897 if (c1 < VT.getSizeInBits()) {
3898 uint64_t c2 = N1C->getZExtValue();
Eli Friedman1877ac92011-06-09 22:14:44 +00003899 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3900 VT.getSizeInBits() - c1);
3901 SDValue Shift;
3902 if (c2 > c1) {
3903 Mask = Mask.shl(c2-c1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003904 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
Eli Friedman1877ac92011-06-09 22:14:44 +00003905 DAG.getConstant(c2-c1, N1.getValueType()));
3906 } else {
3907 Mask = Mask.lshr(c1-c2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003908 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
Eli Friedman1877ac92011-06-09 22:14:44 +00003909 DAG.getConstant(c1-c2, N1.getValueType()));
3910 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00003911 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
Eli Friedman1877ac92011-06-09 22:14:44 +00003912 DAG.getConstant(Mask, VT));
Evan Chenga7bb55e2009-07-21 05:40:15 +00003913 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003914 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003915 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00003916 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3917 SDValue HiBitsMask =
3918 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3919 VT.getSizeInBits() -
3920 N1C->getZExtValue()),
3921 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003922 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00003923 HiBitsMask);
3924 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003925
Evan Chengf1bd5fc2010-04-17 06:13:15 +00003926 if (N1C) {
3927 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3928 if (NewSHL.getNode())
3929 return NewSHL;
3930 }
3931
Evan Chengf1005572010-04-28 07:10:39 +00003932 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003933}
3934
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003935SDValue DAGCombiner::visitSRA(SDNode *N) {
3936 SDValue N0 = N->getOperand(0);
3937 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003938 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3939 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003940 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00003941 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003942
Daniel Sandersa1840d22013-11-11 17:23:41 +00003943 // fold vector ops
3944 if (VT.isVector()) {
3945 SDValue FoldedVOp = SimplifyVBinOp(N);
3946 if (FoldedVOp.getNode()) return FoldedVOp;
3947 }
3948
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003949 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003950 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003951 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003952 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003953 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003954 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003955 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003956 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003957 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003958 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00003959 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003960 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003961 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003962 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003963 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00003964 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3965 // sext_inreg.
3966 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00003967 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00003968 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3969 if (VT.isVector())
3970 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3971 ExtVT, VT.getVectorNumElements());
3972 if ((!LegalOperations ||
3973 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003974 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00003975 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00003976 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00003977
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003978 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00003979 if (N1C && N0.getOpcode() == ISD::SRA) {
3980 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003981 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Dan Gohman1d459e42009-12-11 21:31:27 +00003982 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003983 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0f8a7272006-02-28 06:23:04 +00003984 DAG.getConstant(Sum, N1C->getValueType(0)));
3985 }
3986 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00003987
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003988 // fold (sra (shl X, m), (sub result_size, n))
3989 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00003990 // result_size - n != m.
3991 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00003992 // code.
Christopher Lamb8fe91092008-03-19 08:30:06 +00003993 if (N0.getOpcode() == ISD::SHL) {
3994 // Get the two constanst of the shifts, CN0 = m, CN = n.
3995 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3996 if (N01C && N1C) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00003997 // Determine what the truncate's result bitsize and type would be.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003998 EVT TruncVT =
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003999 EVT::getIntegerVT(*DAG.getContext(),
4000 OpSizeInBits - N1C->getZExtValue());
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004001 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004002 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004003
Scott Michelcf0da6c2009-02-17 22:15:04 +00004004 // If the shift is not a no-op (in which case this should be just a sign
4005 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004006 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004007 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004008 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004009 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4010 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004011 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004012
Owen Andersonb2c80da2011-02-25 21:41:48 +00004013 SDValue Amt = DAG.getConstant(ShiftAmt,
4014 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004015 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004016 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004017 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004018 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004019 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004020 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004021 }
4022 }
4023 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004024
Duncan Sands3ed76882009-02-01 18:06:53 +00004025 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004026 if (N1.getOpcode() == ISD::TRUNCATE &&
Evan Cheng13beeeb12008-09-22 18:19:24 +00004027 N1.getOperand(0).getOpcode() == ISD::AND &&
4028 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004029 SDValue N101 = N1.getOperand(0).getOperand(1);
Evan Cheng13beeeb12008-09-22 18:19:24 +00004030 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00004031 EVT TruncVT = N1.getValueType();
Evan Cheng13beeeb12008-09-22 18:19:24 +00004032 SDValue N100 = N1.getOperand(0).getOperand(0);
Duncan Sands3ed76882009-02-01 18:06:53 +00004033 APInt TruncC = N101C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00004034 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004035 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
4036 DAG.getNode(ISD::AND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004037 TruncVT,
Bill Wendling3b585af2009-01-31 03:12:48 +00004038 DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004039 SDLoc(N),
Bill Wendling3b585af2009-01-31 03:12:48 +00004040 TruncVT, N100),
Dan Gohmanfb58faf2009-01-27 20:39:34 +00004041 DAG.getConstant(TruncC, TruncVT)));
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004042 }
4043 }
4044
Benjamin Kramer946e1522011-01-30 16:38:43 +00004045 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4046 // if c1 is equal to the number of bits the trunc removes
4047 if (N0.getOpcode() == ISD::TRUNCATE &&
4048 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4049 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4050 N0.getOperand(0).hasOneUse() &&
4051 N0.getOperand(0).getOperand(1).hasOneUse() &&
4052 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4053 EVT LargeVT = N0.getOperand(0).getValueType();
4054 ConstantSDNode *LargeShiftAmt =
4055 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4056
4057 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4058 LargeShiftAmt->getZExtValue()) {
4059 SDValue Amt =
4060 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00004061 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004062 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
Benjamin Kramer946e1522011-01-30 16:38:43 +00004063 N0.getOperand(0).getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004064 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
Benjamin Kramer946e1522011-01-30 16:38:43 +00004065 }
4066 }
4067
Scott Michelcf0da6c2009-02-17 22:15:04 +00004068 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004069 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4070 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004071
4072
Nate Begeman21158fc2005-09-01 00:19:25 +00004073 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004074 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004075 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004076
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004077 if (N1C) {
4078 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4079 if (NewSRA.getNode())
4080 return NewSRA;
4081 }
4082
Evan Chengf1005572010-04-28 07:10:39 +00004083 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004084}
4085
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004086SDValue DAGCombiner::visitSRL(SDNode *N) {
4087 SDValue N0 = N->getOperand(0);
4088 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004089 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4090 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004091 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004092 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004093
Daniel Sandersa1840d22013-11-11 17:23:41 +00004094 // fold vector ops
4095 if (VT.isVector()) {
4096 SDValue FoldedVOp = SimplifyVBinOp(N);
4097 if (FoldedVOp.getNode()) return FoldedVOp;
4098 }
4099
Nate Begeman21158fc2005-09-01 00:19:25 +00004100 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004101 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004102 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004103 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004104 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004105 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004106 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004107 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004108 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004109 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004110 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004111 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004112 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004113 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004114 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004115 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004116
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004117 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Scott Michelcf0da6c2009-02-17 22:15:04 +00004118 if (N1C && N0.getOpcode() == ISD::SRL &&
Nate Begeman21158fc2005-09-01 00:19:25 +00004119 N0.getOperand(1).getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004120 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4121 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004122 if (c1 + c2 >= OpSizeInBits)
Nate Begemand23739d2005-09-06 04:43:02 +00004123 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004124 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
Nate Begemand23739d2005-09-06 04:43:02 +00004125 DAG.getConstant(c1 + c2, N1.getValueType()));
Nate Begeman21158fc2005-09-01 00:19:25 +00004126 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004127
Dale Johannesencd538af2010-12-17 21:45:49 +00004128 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004129 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4130 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004131 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004132 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004133 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4134 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004135 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4136 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004137 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004138 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004139 if (c1 + OpSizeInBits == InnerShiftSize) {
4140 if (c1 + c2 >= InnerShiftSize)
4141 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004142 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4143 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004144 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004145 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004146 }
4147 }
4148
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004149 // fold (srl (shl x, c), c) -> (and x, cst2)
4150 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4151 N0.getValueSizeInBits() <= 64) {
4152 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004153 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004154 DAG.getConstant(~0ULL >> ShAmt, VT));
4155 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004156
Michael Liao62ebfd82013-06-21 18:45:27 +00004157 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004158 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4159 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004160 EVT SmallVT = N0.getOperand(0).getValueType();
Dan Gohmaneffb8942008-09-12 16:56:44 +00004161 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
Dale Johannesen84935752009-02-06 23:05:02 +00004162 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004163
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004164 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004165 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004166 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004167 N0.getOperand(0),
4168 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004169 AddToWorkList(SmallShift.getNode());
Michael Liao62ebfd82013-06-21 18:45:27 +00004170 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4171 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4172 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4173 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004174 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004175 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004176
Chris Lattner2e33fb42006-10-12 20:23:19 +00004177 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4178 // bit, which is unmodified by sra.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004179 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004180 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004181 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004182 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004183
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004184 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004185 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Duncan Sands13237ac2008-06-06 12:08:01 +00004186 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004187 APInt KnownZero, KnownOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004188 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004189
Chris Lattner49932492006-04-02 06:11:11 +00004190 // If any of the input bits are KnownOne, then the input couldn't be all
4191 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004192 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004193
Chris Lattner49932492006-04-02 06:11:11 +00004194 // If all of the bits input the to ctlz node are known to be zero, then
4195 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004196 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004197 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004198
Chris Lattner49932492006-04-02 06:11:11 +00004199 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004200 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004201 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004202 // could be set on input to the CTLZ node. If this bit is set, the SRL
4203 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4204 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004205 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004206 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004207
Chris Lattner49932492006-04-02 06:11:11 +00004208 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004209 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004210 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004211 AddToWorkList(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004212 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004213
Andrew Trickef9de2a2013-05-25 02:42:55 +00004214 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004215 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004216 }
4217 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004218
Duncan Sands3ed76882009-02-01 18:06:53 +00004219 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004220 if (N1.getOpcode() == ISD::TRUNCATE &&
Evan Cheng13beeeb12008-09-22 18:19:24 +00004221 N1.getOperand(0).getOpcode() == ISD::AND &&
4222 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004223 SDValue N101 = N1.getOperand(0).getOperand(1);
Evan Cheng13beeeb12008-09-22 18:19:24 +00004224 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00004225 EVT TruncVT = N1.getValueType();
Evan Cheng13beeeb12008-09-22 18:19:24 +00004226 SDValue N100 = N1.getOperand(0).getOperand(0);
Duncan Sands3ed76882009-02-01 18:06:53 +00004227 APInt TruncC = N101C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00004228 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004229 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4230 DAG.getNode(ISD::AND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004231 TruncVT,
Bill Wendling3b585af2009-01-31 03:12:48 +00004232 DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004233 SDLoc(N),
Bill Wendling3b585af2009-01-31 03:12:48 +00004234 TruncVT, N100),
Dan Gohmanfb58faf2009-01-27 20:39:34 +00004235 DAG.getConstant(TruncC, TruncVT)));
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004236 }
4237 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004238
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004239 // fold operands of srl based on knowledge that the low bits are not
4240 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004241 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4242 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004243
Evan Chengb175de62009-12-18 21:31:31 +00004244 if (N1C) {
4245 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4246 if (NewSRL.getNode())
4247 return NewSRL;
4248 }
4249
Dan Gohman600f62b2010-06-24 14:30:44 +00004250 // Attempt to convert a srl of a load into a narrower zero-extending load.
4251 SDValue NarrowLoad = ReduceLoadWidth(N);
4252 if (NarrowLoad.getNode())
4253 return NarrowLoad;
4254
Evan Chengb175de62009-12-18 21:31:31 +00004255 // Here is a common situation. We want to optimize:
4256 //
4257 // %a = ...
4258 // %b = and i32 %a, 2
4259 // %c = srl i32 %b, 1
4260 // brcond i32 %c ...
4261 //
4262 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004263 //
Evan Chengb175de62009-12-18 21:31:31 +00004264 // %a = ...
4265 // %b = and %a, 2
4266 // %c = setcc eq %b, 0
4267 // brcond %c ...
4268 //
4269 // However when after the source operand of SRL is optimized into AND, the SRL
4270 // itself may not be optimized further. Look for it and add the BRCOND into
4271 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004272 if (N->hasOneUse()) {
4273 SDNode *Use = *N->use_begin();
4274 if (Use->getOpcode() == ISD::BRCOND)
4275 AddToWorkList(Use);
4276 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4277 // Also look pass the truncate.
4278 Use = *Use->use_begin();
4279 if (Use->getOpcode() == ISD::BRCOND)
4280 AddToWorkList(Use);
4281 }
4282 }
Evan Chengb175de62009-12-18 21:31:31 +00004283
Evan Chengf1005572010-04-28 07:10:39 +00004284 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004285}
4286
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004287SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4288 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004289 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004290
4291 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004292 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004293 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004294 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004295}
4296
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004297SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4298 SDValue N0 = N->getOperand(0);
4299 EVT VT = N->getValueType(0);
4300
4301 // fold (ctlz_zero_undef c1) -> c2
4302 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004303 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004304 return SDValue();
4305}
4306
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004307SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4308 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004309 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004310
Nate Begeman21158fc2005-09-01 00:19:25 +00004311 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004312 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004313 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004314 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004315}
4316
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004317SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4318 SDValue N0 = N->getOperand(0);
4319 EVT VT = N->getValueType(0);
4320
4321 // fold (cttz_zero_undef c1) -> c2
4322 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004323 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004324 return SDValue();
4325}
4326
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004327SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4328 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004329 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004330
Nate Begeman21158fc2005-09-01 00:19:25 +00004331 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004332 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004333 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004334 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004335}
4336
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004337SDValue DAGCombiner::visitSELECT(SDNode *N) {
4338 SDValue N0 = N->getOperand(0);
4339 SDValue N1 = N->getOperand(1);
4340 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004341 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4342 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4343 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004344 EVT VT = N->getValueType(0);
4345 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004346
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004347 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004348 if (N1 == N2)
4349 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004350 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004351 if (N0C && !N0C->isNullValue())
4352 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004353 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004354 if (N0C && N0C->isNullValue())
4355 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004356 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004357 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004358 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004359 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004360 if (VT.isInteger() &&
Owen Anderson9f944592009-08-11 20:47:22 +00004361 (VT0 == MVT::i1 ||
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004362 (VT0.isInteger() &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00004363 TLI.getBooleanContents(false) ==
4364 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004365 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004366 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004367 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004368 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004369 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004370 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004371 N0, DAG.getConstant(1, VT0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004372 AddToWorkList(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004373 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004374 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4375 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004376 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004377 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004378 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004379 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004380 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004381 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004382 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004383 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004384 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004385 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004386 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004387 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004388 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004389 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004390 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004391 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004392 // fold (select X, X, Y) -> (or X, Y)
4393 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004394 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004395 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004396 // fold (select X, Y, X) -> (and X, Y)
4397 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004398 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004399 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004400
Chris Lattner6c14c352005-10-18 06:04:22 +00004401 // If we can fold this based on the true/false value, do so.
4402 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004403 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004404
Nate Begemanc760f802005-09-19 22:34:01 +00004405 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004406 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman7e7f4392006-02-01 07:19:44 +00004407 // FIXME:
Owen Anderson9f944592009-08-11 20:47:22 +00004408 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman7e7f4392006-02-01 07:19:44 +00004409 // having to say they don't support SELECT_CC on every type the DAG knows
4410 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson9f944592009-08-11 20:47:22 +00004411 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman3f323842009-08-02 16:19:38 +00004412 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004413 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004414 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004415 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004416 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004417 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004418
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004419 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004420}
4421
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004422static
4423std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4424 SDLoc DL(N);
4425 EVT LoVT, HiVT;
4426 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4427
4428 // Split the inputs.
4429 SDValue Lo, Hi, LL, LH, RL, RH;
4430 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4431 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4432
4433 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4434 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4435
4436 return std::make_pair(Lo, Hi);
4437}
4438
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004439SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4440 SDValue N0 = N->getOperand(0);
4441 SDValue N1 = N->getOperand(1);
4442 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004443 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004444
4445 // Canonicalize integer abs.
4446 // vselect (setg[te] X, 0), X, -X ->
4447 // vselect (setgt X, -1), X, -X ->
4448 // vselect (setl[te] X, 0), -X, X ->
4449 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4450 if (N0.getOpcode() == ISD::SETCC) {
4451 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4452 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4453 bool isAbs = false;
4454 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4455
4456 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4457 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4458 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4459 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4460 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4461 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4462 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4463
4464 if (isAbs) {
4465 EVT VT = LHS.getValueType();
4466 SDValue Shift = DAG.getNode(
4467 ISD::SRA, DL, VT, LHS,
4468 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4469 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4470 AddToWorkList(Shift.getNode());
4471 AddToWorkList(Add.getNode());
4472 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4473 }
4474 }
4475
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004476 // If the VSELECT result requires splitting and the mask is provided by a
4477 // SETCC, then split both nodes and its operands before legalization. This
4478 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4479 // and enables future optimizations (e.g. min/max pattern matching on X86).
4480 if (N0.getOpcode() == ISD::SETCC) {
4481 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004482
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004483 // Check if any splitting is required.
4484 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4485 TargetLowering::TypeSplitVector)
4486 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004487
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004488 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4489 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4490 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4491 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004492
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004493 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4494 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004495
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004496 // Add the new VSELECT nodes to the work list in case they need to be split
4497 // again.
4498 AddToWorkList(Lo.getNode());
4499 AddToWorkList(Hi.getNode());
4500
4501 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004502 }
4503
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004504 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4505 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4506 return N1;
4507 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4508 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4509 return N2;
4510
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004511 return SDValue();
4512}
4513
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004514SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4515 SDValue N0 = N->getOperand(0);
4516 SDValue N1 = N->getOperand(1);
4517 SDValue N2 = N->getOperand(2);
4518 SDValue N3 = N->getOperand(3);
4519 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004520 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004521
Nate Begemanc760f802005-09-19 22:34:01 +00004522 // fold select_cc lhs, rhs, x, x, cc -> x
4523 if (N2 == N3)
4524 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004525
Chris Lattner8b68dec2006-09-20 06:19:26 +00004526 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004527 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004528 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004529 if (SCC.getNode()) {
4530 AddToWorkList(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004531
Stephen Lin605207f2013-06-15 04:03:33 +00004532 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4533 if (!SCCC->isNullValue())
4534 return N2; // cond always true -> true val
4535 else
4536 return N3; // cond always false -> false val
4537 }
4538
4539 // Fold to a simpler select_cc
4540 if (SCC.getOpcode() == ISD::SETCC)
4541 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4542 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4543 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004544 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004545
Chris Lattner6c14c352005-10-18 06:04:22 +00004546 // If we can fold this based on the true/false value, do so.
4547 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004548 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004549
Nate Begemanc760f802005-09-19 22:34:01 +00004550 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004551 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004552}
4553
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004554SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004555 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004556 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004557 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004558}
4559
Evan Chenge106e2f2007-10-29 19:58:20 +00004560// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004561// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004562// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004563// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004564static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004565 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004566 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004567 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004568 bool HasCopyToRegUses = false;
4569 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004570 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4571 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004572 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004573 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004574 if (User == N)
4575 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004576 if (UI.getUse().getResNo() != N0.getResNo())
4577 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004578 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004579 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004580 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4581 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4582 // Sign bits will be lost after a zext.
4583 return false;
4584 bool Add = false;
4585 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004586 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004587 if (UseOp == N0)
4588 continue;
4589 if (!isa<ConstantSDNode>(UseOp))
4590 return false;
4591 Add = true;
4592 }
4593 if (Add)
4594 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004595 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004596 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004597 // If truncates aren't free and there are users we can't
4598 // extend, it isn't worthwhile.
4599 if (!isTruncFree)
4600 return false;
4601 // Remember if this value is live-out.
4602 if (User->getOpcode() == ISD::CopyToReg)
4603 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004604 }
4605
4606 if (HasCopyToRegUses) {
4607 bool BothLiveOut = false;
4608 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4609 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004610 SDUse &Use = UI.getUse();
4611 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4612 BothLiveOut = true;
4613 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004614 }
4615 }
4616 if (BothLiveOut)
4617 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004618 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004619 return ExtendNodes.size();
4620 }
4621 return true;
4622}
4623
Craig Toppere0b71182013-07-13 07:43:40 +00004624void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004625 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004626 ISD::NodeType ExtType) {
4627 // Extend SetCC uses if necessary.
4628 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4629 SDNode *SetCC = SetCCs[i];
4630 SmallVector<SDValue, 4> Ops;
4631
4632 for (unsigned j = 0; j != 2; ++j) {
4633 SDValue SOp = SetCC->getOperand(j);
4634 if (SOp == Trunc)
4635 Ops.push_back(ExtLoad);
4636 else
4637 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4638 }
4639
4640 Ops.push_back(SetCC->getOperand(2));
4641 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4642 &Ops[0], Ops.size()));
4643 }
4644}
4645
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004646SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4647 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004648 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004649
Nate Begeman21158fc2005-09-01 00:19:25 +00004650 // fold (sext c1) -> c1
Reid Spencerde46e482006-11-02 20:25:50 +00004651 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004652 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004653
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004654 // fold (sext (sext x)) -> (sext x)
4655 // fold (sext (aext x)) -> (sext x)
4656 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004657 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004658 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004659
Chris Lattnerfce448f2007-02-26 03:13:59 +00004660 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004661 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4662 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004663 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4664 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004665 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4666 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004667 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004668 // CombineTo deleted the truncate, if needed, but not what's under it.
4669 AddToWorkList(oye);
4670 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004671 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004672 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004673
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004674 // See if the value being truncated is already sign extended. If so, just
4675 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004676 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004677 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4678 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4679 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004680 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004681
Chris Lattnerfce448f2007-02-26 03:13:59 +00004682 if (OpBits == DestBits) {
4683 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4684 // bits, it is already ready.
4685 if (NumSignBits > DestBits-MidBits)
4686 return Op;
4687 } else if (OpBits < DestBits) {
4688 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4689 // bits, just sext from i32.
4690 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004691 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00004692 } else {
4693 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4694 // bits, just truncate to i32.
4695 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004696 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00004697 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004698
Chris Lattnerfce448f2007-02-26 03:13:59 +00004699 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004700 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4701 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004702 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004703 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004704 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004705 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4706 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004707 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00004708 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00004709 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004710
Evan Chengbce7c472005-12-14 02:19:23 +00004711 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00004712 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00004713 // on vectors in one instruction. We only perform this transformation on
4714 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00004715 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004716 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00004717 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004718 bool DoXform = true;
4719 SmallVector<SDNode*, 4> SetCCs;
4720 if (!N0.hasOneUse())
4721 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4722 if (DoXform) {
4723 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004724 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00004725 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004726 LN0->getBasePtr(), N0.getValueType(),
4727 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00004728 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004729 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004730 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004731 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004732 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004733 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004734 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00004735 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00004736 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004737
4738 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4739 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004740 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4741 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00004742 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00004743 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004744 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00004745 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004746 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00004747 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004748 LN0->getBasePtr(), MemVT,
4749 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00004750 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00004751 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004752 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004753 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00004754 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004755 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00004756 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004757 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004758
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004759 // fold (sext (and/or/xor (load x), cst)) ->
4760 // (and/or/xor (sextload x), (sext cst))
4761 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4762 N0.getOpcode() == ISD::XOR) &&
4763 isa<LoadSDNode>(N0.getOperand(0)) &&
4764 N0.getOperand(1).getOpcode() == ISD::Constant &&
4765 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4766 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4767 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4768 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4769 bool DoXform = true;
4770 SmallVector<SDNode*, 4> SetCCs;
4771 if (!N0.hasOneUse())
4772 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4773 SetCCs, TLI);
4774 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004775 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004776 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004777 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004778 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004779 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4780 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004781 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004782 ExtLoad, DAG.getConstant(Mask, VT));
4783 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004784 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004785 N0.getOperand(0).getValueType(), ExtLoad);
4786 CombineTo(N, And);
4787 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004788 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004789 ISD::SIGN_EXTEND);
4790 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4791 }
4792 }
4793 }
4794
Chris Lattner65786b02007-04-11 05:32:27 +00004795 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner4ac60732009-07-08 00:31:33 +00004796 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00004797 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00004798 if (VT.isVector() && !LegalOperations &&
Stephen Lincfe7f352013-07-08 00:37:03 +00004799 TLI.getBooleanContents(true) ==
Owen Anderson2d4cca32013-04-23 18:09:28 +00004800 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohmane82c25e2010-04-30 17:19:19 +00004801 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem9d376b62012-04-11 08:26:11 +00004802 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4803 // of the same size as the compared operands. Only optimize sext(setcc())
4804 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00004805 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00004806
4807 // We know that the # elements of the results is the same as the
4808 // # elements of the compare (and the # elements of the compare result
4809 // for that matter). Check to see that they are the same size. If so,
4810 // we know that the element size of the sext'd result matches the
4811 // element size of the compare operands.
4812 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004813 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00004814 N0.getOperand(1),
4815 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00004816
Dan Gohmane82c25e2010-04-30 17:19:19 +00004817 // If the desired elements are smaller or larger than the source
4818 // elements we can use a matching integer vector type and then
4819 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00004820 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00004821 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004822 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00004823 N0.getOperand(0), N0.getOperand(1),
4824 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004825 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00004826 }
Chris Lattner4ac60732009-07-08 00:31:33 +00004827 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00004828
Chris Lattner4ac60732009-07-08 00:31:33 +00004829 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
Dan Gohman5544b0c2010-04-24 01:17:30 +00004830 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004831 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00004832 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004833 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00004834 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004835 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00004836 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004837 if (SCC.getNode()) return SCC;
Matt Arsenaultd2f03322013-06-14 22:04:37 +00004838 if (!VT.isVector() &&
4839 (!LegalOperations ||
4840 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4841 return DAG.getSelect(SDLoc(N), VT,
4842 DAG.getSetCC(SDLoc(N),
Jack Carterd4e96152013-10-17 01:34:33 +00004843 getSetCCResultType(VT),
4844 N0.getOperand(0), N0.getOperand(1),
4845 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Matt Arsenaultd2f03322013-06-14 22:04:37 +00004846 NegOne, DAG.getConstant(0, VT));
4847 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004848 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004849
Dan Gohman3eb10f72008-04-28 16:58:24 +00004850 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004851 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00004852 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004853 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004854
Evan Chengf1005572010-04-28 07:10:39 +00004855 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004856}
4857
Rafael Espindola8f62b322012-04-09 16:06:03 +00004858// isTruncateOf - If N is a truncate of some other value, return true, record
4859// the value being truncated in Op and which of Op's bits are zero in KnownZero.
4860// This function computes KnownZero to avoid a duplicated call to
4861// ComputeMaskedBits in the caller.
4862static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4863 APInt &KnownZero) {
4864 APInt KnownOne;
4865 if (N->getOpcode() == ISD::TRUNCATE) {
4866 Op = N->getOperand(0);
4867 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4868 return true;
4869 }
4870
4871 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4872 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4873 return false;
4874
4875 SDValue Op0 = N->getOperand(0);
4876 SDValue Op1 = N->getOperand(1);
4877 assert(Op0.getValueType() == Op1.getValueType());
4878
4879 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4880 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00004881 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00004882 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00004883 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00004884 Op = Op0;
4885 else
4886 return false;
4887
4888 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4889
4890 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4891 return false;
4892
4893 return true;
4894}
4895
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004896SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4897 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004898 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004899
Nate Begeman21158fc2005-09-01 00:19:25 +00004900 // fold (zext c1) -> c1
Reid Spencerde46e482006-11-02 20:25:50 +00004901 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004902 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004903 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004904 // fold (zext (aext x)) -> (zext x)
4905 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004906 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00004907 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00004908
Chandler Carruth55b2cde2012-01-11 08:41:08 +00004909 // fold (zext (truncate x)) -> (zext x) or
4910 // (zext (truncate x)) -> (truncate x)
4911 // This is valid when the truncated bits of x are already zero.
4912 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00004913 SDValue Op;
4914 APInt KnownZero;
4915 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4916 APInt TruncatedBits =
4917 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4918 APInt(Op.getValueSizeInBits(), 0) :
4919 APInt::getBitsSet(Op.getValueSizeInBits(),
4920 N0.getValueSizeInBits(),
4921 std::min(Op.getValueSizeInBits(),
4922 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004923 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00004924 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004925 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00004926 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004927 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00004928
4929 return Op;
4930 }
4931 }
4932
Evan Cheng464dc9b2007-03-22 01:54:19 +00004933 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4934 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00004935 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004936 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4937 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004938 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4939 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004940 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004941 // CombineTo deleted the truncate, if needed, but not what's under it.
4942 AddToWorkList(oye);
4943 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00004944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004945 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004946 }
4947
Chris Lattnera31f0a62006-09-21 06:00:20 +00004948 // fold (zext (truncate x)) -> (and x, mask)
4949 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00004950 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00004951
4952 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4953 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4954 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4955 if (NarrowLoad.getNode()) {
4956 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4957 if (NarrowLoad.getNode() != N0.getNode()) {
4958 CombineTo(N0.getNode(), NarrowLoad);
4959 // CombineTo deleted the truncate, if needed, but not what's under it.
4960 AddToWorkList(oye);
4961 }
4962 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4963 }
4964
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004965 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00004966 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004967 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00004968 AddToWorkList(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004969 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004970 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00004971 AddToWorkList(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00004972 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00004973 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00004974 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00004975 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004976
Dan Gohmanad3e5492009-04-08 00:15:30 +00004977 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4978 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00004979 if (N0.getOpcode() == ISD::AND &&
4980 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00004981 N0.getOperand(1).getOpcode() == ISD::Constant &&
4982 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4983 N0.getValueType()) ||
4984 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004985 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00004986 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004987 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00004988 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004989 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00004990 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00004991 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00004992 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004993 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00004994 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00004995 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004996
Evan Chengbce7c472005-12-14 02:19:23 +00004997 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00004998 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00004999 // on vectors in one instruction. We only perform this transformation on
5000 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005001 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005002 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005003 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005004 bool DoXform = true;
5005 SmallVector<SDNode*, 4> SetCCs;
5006 if (!N0.hasOneUse())
5007 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5008 if (DoXform) {
5009 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005010 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005011 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005012 LN0->getBasePtr(), N0.getValueType(),
5013 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005014 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005015 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005016 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005017 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005018
Andrew Trickef9de2a2013-05-25 02:42:55 +00005019 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005020 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005021 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005022 }
Evan Chengbce7c472005-12-14 02:19:23 +00005023 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005024
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005025 // fold (zext (and/or/xor (load x), cst)) ->
5026 // (and/or/xor (zextload x), (zext cst))
5027 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5028 N0.getOpcode() == ISD::XOR) &&
5029 isa<LoadSDNode>(N0.getOperand(0)) &&
5030 N0.getOperand(1).getOpcode() == ISD::Constant &&
5031 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5032 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5033 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5034 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5035 bool DoXform = true;
5036 SmallVector<SDNode*, 4> SetCCs;
5037 if (!N0.hasOneUse())
5038 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5039 SetCCs, TLI);
5040 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005041 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005042 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005043 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005044 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005045 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5046 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005047 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005048 ExtLoad, DAG.getConstant(Mask, VT));
5049 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005050 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005051 N0.getOperand(0).getValueType(), ExtLoad);
5052 CombineTo(N, And);
5053 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005054 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005055 ISD::ZERO_EXTEND);
5056 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5057 }
5058 }
5059 }
5060
Chris Lattner7dac1082005-12-14 19:05:06 +00005061 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5062 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005063 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5064 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005065 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005066 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005067 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005068 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005069 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005070 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005071 LN0->getBasePtr(), MemVT,
5072 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005073 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005074 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005075 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005076 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005077 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005078 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005079 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005080 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005081
Chris Lattner65786b02007-04-11 05:32:27 +00005082 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005083 if (!LegalOperations && VT.isVector() &&
5084 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005085 EVT N0VT = N0.getOperand(0).getValueType();
5086 if (getSetCCResultType(N0VT) == N0.getValueType())
5087 return SDValue();
5088
Evan Chengabd0ad52010-05-19 01:08:17 +00005089 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5090 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005091 EVT EltVT = VT.getVectorElementType();
5092 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5093 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005094 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005095 // We know that the # elements of the results is the same as the
5096 // # elements of the compare (and the # elements of the compare result
5097 // for that matter). Check to see that they are the same size. If so,
5098 // we know that the element size of the sext'd result matches the
5099 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005100 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5101 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005102 N0.getOperand(1),
5103 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005104 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Evan Chengabd0ad52010-05-19 01:08:17 +00005105 &OneOps[0], OneOps.size()));
Dan Gohman4298df62011-05-17 22:20:36 +00005106
5107 // If the desired elements are smaller or larger than the source
5108 // elements we can use a matching integer vector type and then
5109 // truncate/sign extend
5110 EVT MatchingElementType =
5111 EVT::getIntegerVT(*DAG.getContext(),
5112 N0VT.getScalarType().getSizeInBits());
5113 EVT MatchingVectorType =
5114 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5115 N0VT.getVectorNumElements());
5116 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005117 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005118 N0.getOperand(1),
5119 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005120 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5121 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5122 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Dan Gohman4298df62011-05-17 22:20:36 +00005123 &OneOps[0], OneOps.size()));
Evan Chengabd0ad52010-05-19 01:08:17 +00005124 }
5125
5126 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005127 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005128 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005129 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005130 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005131 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005132 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005133
Evan Cheng852c4862009-12-15 03:00:32 +00005134 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005135 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005136 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005137 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5138 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005139 SDValue ShAmt = N0.getOperand(1);
5140 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005141 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005142 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005143 // If the original shl may be shifting out bits, do not perform this
5144 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005145 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5146 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5147 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005148 return SDValue();
5149 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005150
Andrew Trickef9de2a2013-05-25 02:42:55 +00005151 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005152
5153 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005154 if (VT.getSizeInBits() >= 256)
5155 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005156
Chris Lattnere95d1952011-02-13 19:09:16 +00005157 return DAG.getNode(N0.getOpcode(), DL, VT,
5158 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5159 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005160 }
5161
Evan Chengf1005572010-04-28 07:10:39 +00005162 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005163}
5164
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005165SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5166 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005167 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005168
Chris Lattner812646a2006-05-05 05:58:59 +00005169 // fold (aext c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005170 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005171 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
Chris Lattner812646a2006-05-05 05:58:59 +00005172 // fold (aext (aext x)) -> (aext x)
5173 // fold (aext (zext x)) -> (zext x)
5174 // fold (aext (sext x)) -> (sext x)
5175 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5176 N0.getOpcode() == ISD::ZERO_EXTEND ||
5177 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005178 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005179
Evan Cheng464dc9b2007-03-22 01:54:19 +00005180 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5181 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5182 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005183 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5184 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005185 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5186 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005187 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005188 // CombineTo deleted the truncate, if needed, but not what's under it.
5189 AddToWorkList(oye);
5190 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005191 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005192 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005193 }
5194
Chris Lattner8746e2c2006-09-20 06:29:17 +00005195 // fold (aext (truncate x))
5196 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005197 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005198 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005199 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005200 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005201 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5202 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005203 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005204
Dan Gohmanad3e5492009-04-08 00:15:30 +00005205 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5206 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005207 if (N0.getOpcode() == ISD::AND &&
5208 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005209 N0.getOperand(1).getOpcode() == ISD::Constant &&
5210 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5211 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005212 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005213 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005214 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005215 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005216 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005217 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005218 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005219 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005220 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005221 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005222 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005223
Chris Lattner812646a2006-05-05 05:58:59 +00005224 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005225 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005226 // on vectors in one instruction. We only perform this transformation on
5227 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005228 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005229 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005230 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005231 bool DoXform = true;
5232 SmallVector<SDNode*, 4> SetCCs;
5233 if (!N0.hasOneUse())
5234 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5235 if (DoXform) {
5236 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005237 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005238 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005239 LN0->getBasePtr(), N0.getValueType(),
5240 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005241 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005242 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005243 N0.getValueType(), ExtLoad);
5244 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005245 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005246 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005247 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5248 }
Chris Lattner812646a2006-05-05 05:58:59 +00005249 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005250
Chris Lattner812646a2006-05-05 05:58:59 +00005251 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5252 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5253 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005254 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005255 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005256 N0.hasOneUse()) {
5257 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005258 EVT MemVT = LN0->getMemoryVT();
Andrew Trickef9de2a2013-05-25 02:42:55 +00005259 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
Stuart Hastings81c43062011-02-16 16:23:55 +00005260 VT, LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005261 MemVT, LN0->getMemOperand());
Chris Lattner812646a2006-05-05 05:58:59 +00005262 CombineTo(N, ExtLoad);
Evan Cheng894be332008-08-29 23:20:46 +00005263 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005264 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005265 N0.getValueType(), ExtLoad),
Chris Lattner812646a2006-05-05 05:58:59 +00005266 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005267 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner812646a2006-05-05 05:58:59 +00005268 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005269
Chris Lattner65786b02007-04-11 05:32:27 +00005270 if (N0.getOpcode() == ISD::SETCC) {
Evan Chengabd0ad52010-05-19 01:08:17 +00005271 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5272 // Only do this before legalize for now.
5273 if (VT.isVector() && !LegalOperations) {
5274 EVT N0VT = N0.getOperand(0).getValueType();
5275 // We know that the # elements of the results is the same as the
5276 // # elements of the compare (and the # elements of the compare result
5277 // for that matter). Check to see that they are the same size. If so,
5278 // we know that the element size of the sext'd result matches the
5279 // element size of the compare operands.
5280 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005281 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005282 N0.getOperand(1),
5283 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005284 // If the desired elements are smaller or larger than the source
5285 // elements we can use a matching integer vector type and then
5286 // truncate/sign extend
5287 else {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005288 EVT MatchingElementType =
5289 EVT::getIntegerVT(*DAG.getContext(),
5290 N0VT.getScalarType().getSizeInBits());
5291 EVT MatchingVectorType =
5292 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5293 N0VT.getVectorNumElements());
5294 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005295 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005296 N0.getOperand(1),
5297 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005298 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005299 }
5300 }
5301
5302 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005303 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005304 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005305 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005306 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005307 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005308 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005309 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005310
Evan Chengf1005572010-04-28 07:10:39 +00005311 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005312}
5313
Chris Lattner5e6fe052007-10-13 06:35:54 +00005314/// GetDemandedBits - See if the specified operand can be simplified with the
5315/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005316/// simpler operand, otherwise return a null SDValue.
5317SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005318 switch (V.getOpcode()) {
5319 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005320 case ISD::Constant: {
5321 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5322 assert(CV != 0 && "Const value should be ConstSDNode.");
5323 const APInt &CVal = CV->getAPIntValue();
5324 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005325 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005326 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005327 break;
5328 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005329 case ISD::OR:
5330 case ISD::XOR:
5331 // If the LHS or RHS don't contribute bits to the or, drop them.
5332 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5333 return V.getOperand(1);
5334 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5335 return V.getOperand(0);
5336 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005337 case ISD::SRL:
5338 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005339 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005340 break;
5341 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5342 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005343 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005344
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005345 // Watch out for shift count overflow though.
5346 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005347 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005348 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005349 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005350 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005351 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005352 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005353 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005354 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005355}
5356
Evan Cheng464dc9b2007-03-22 01:54:19 +00005357/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5358/// bits and then truncated to a narrower type and where N is a multiple
5359/// of number of bits of the narrower type, transform it to a narrower load
5360/// from address + N / num of bits of new type. If the result is to be
5361/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005362SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005363 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005364
Evan Cheng464dc9b2007-03-22 01:54:19 +00005365 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005366 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005367 EVT VT = N->getValueType(0);
5368 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005369
Dan Gohman550c9af2008-08-14 20:04:46 +00005370 // This transformation isn't valid for vector loads.
5371 if (VT.isVector())
5372 return SDValue();
5373
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005374 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005375 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005376 if (Opc == ISD::SIGN_EXTEND_INREG) {
5377 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005378 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005379 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005380 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005381 ExtType = ISD::ZEXTLOAD;
5382 N0 = SDValue(N, 0);
5383 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5384 if (!N01) return SDValue();
5385 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5386 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005387 }
Richard Osborne272e0842011-01-31 17:41:44 +00005388 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5389 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005390
Owen Anderson53aa7a92009-08-10 22:56:29 +00005391 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005392
Chris Lattner9a499e92010-12-22 08:01:44 +00005393 // Do not generate loads of non-round integer types since these can
5394 // be expensive (and would be wrong if the type is not byte sized).
5395 if (!ExtVT.isRound())
5396 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005397
Evan Cheng464dc9b2007-03-22 01:54:19 +00005398 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005399 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005400 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005401 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005402 // Is the shift amount a multiple of size of VT?
5403 if ((ShAmt & (EVTBits-1)) == 0) {
5404 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005405 // Is the load width a multiple of size of VT?
5406 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005407 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005408 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005409
Chris Lattnercafc1e62010-12-22 08:02:57 +00005410 // At this point, we must have a load or else we can't do the transform.
5411 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005412
Chandler Carruthb27041c2012-12-11 00:36:57 +00005413 // Because a SRL must be assumed to *need* to zero-extend the high bits
5414 // (as opposed to anyext the high bits), we can't combine the zextload
5415 // lowering of SRL and an sextload.
5416 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5417 return SDValue();
5418
Chris Lattnera2050552010-10-01 05:36:09 +00005419 // If the shift amount is larger than the input type then we're not
5420 // accessing any of the loaded bytes. If the load was a zextload/extload
5421 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005422 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005423 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005424 }
5425 }
5426
Dan Gohman68fb0042010-11-03 01:47:46 +00005427 // If the load is shifted left (and the result isn't shifted back right),
5428 // we can fold the truncate through the shift.
5429 unsigned ShLeftAmt = 0;
5430 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005431 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005432 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5433 ShLeftAmt = N01->getZExtValue();
5434 N0 = N0.getOperand(0);
5435 }
5436 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005437
Chris Lattner222374d2010-12-22 07:36:50 +00005438 // If we haven't found a load, we can't narrow it. Don't transform one with
5439 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005440 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5441 return SDValue();
5442
5443 // Don't change the width of a volatile load.
5444 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5445 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005446 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005447
Chris Lattner9a499e92010-12-22 08:01:44 +00005448 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005449 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005450 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005451
Bill Schmidtd006c692013-01-14 22:04:38 +00005452 // For the transform to be legal, the load must produce only two values
5453 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005454 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005455 // transformation is not equivalent, and the downstream logic to replace
5456 // uses gets things wrong.
5457 if (LN0->getNumValues() > 2)
5458 return SDValue();
5459
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005460 // If the load that we're shrinking is an extload and we're not just
5461 // discarding the extension we can't simply shrink the load. Bail.
5462 // TODO: It would be possible to merge the extensions in some cases.
5463 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5464 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5465 return SDValue();
5466
Chris Lattner222374d2010-12-22 07:36:50 +00005467 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005468
Evan Cheng4c6f9172012-06-26 01:19:33 +00005469 if (PtrType == MVT::Untyped || PtrType.isExtended())
5470 // It's not possible to generate a constant of extended or untyped type.
5471 return SDValue();
5472
Chris Lattner222374d2010-12-22 07:36:50 +00005473 // For big endian targets, we need to adjust the offset to the pointer to
5474 // load the correct bytes.
5475 if (TLI.isBigEndian()) {
5476 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5477 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5478 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005479 }
5480
Chris Lattner222374d2010-12-22 07:36:50 +00005481 uint64_t PtrOff = ShAmt / 8;
5482 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005483 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005484 PtrType, LN0->getBasePtr(),
5485 DAG.getConstant(PtrOff, PtrType));
5486 AddToWorkList(NewPtr.getNode());
5487
Chris Lattner9a499e92010-12-22 08:01:44 +00005488 SDValue Load;
5489 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005490 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005491 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005492 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005493 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005494 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005495 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005496 LN0->getPointerInfo().getWithOffset(PtrOff),
5497 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005498 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005499
5500 // Replace the old load's chain with the new load's chain.
5501 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005502 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005503
5504 // Shift the result left, if we've swallowed a left shift.
5505 SDValue Result = Load;
5506 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005507 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005508 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5509 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005510 // If the shift amount is as large as the result size (but, presumably,
5511 // no larger than the source) then the useful bits of the result are
5512 // zero; we can't simply return the shortened shift, because the result
5513 // of that operation is undefined.
5514 if (ShLeftAmt >= VT.getSizeInBits())
5515 Result = DAG.getConstant(0, VT);
5516 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005517 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005518 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005519 }
5520
5521 // Return the new loaded value.
5522 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005523}
5524
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005525SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5526 SDValue N0 = N->getOperand(0);
5527 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005528 EVT VT = N->getValueType(0);
5529 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005530 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005531 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005532
Nate Begeman21158fc2005-09-01 00:19:25 +00005533 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005534 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005535 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005536
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005537 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005538 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005539 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005540
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005541 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5542 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005543 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005544 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005545 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005546
Dan Gohman345d63c2008-07-31 00:50:31 +00005547 // fold (sext_in_reg (sext x)) -> (sext x)
5548 // fold (sext_in_reg (aext x)) -> (sext x)
5549 // if x is small enough.
5550 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5551 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005552 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5553 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005554 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005555 }
5556
Chris Lattner9ad59152007-04-17 19:03:21 +00005557 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005558 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005559 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005560
Chris Lattner9ad59152007-04-17 19:03:21 +00005561 // fold operands of sext_in_reg based on knowledge that the top bits are not
5562 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005563 if (SimplifyDemandedBits(SDValue(N, 0)))
5564 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005565
Evan Cheng464dc9b2007-03-22 01:54:19 +00005566 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5567 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005568 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005569 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005570 return NarrowLoad;
5571
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005572 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005573 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005574 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5575 if (N0.getOpcode() == ISD::SRL) {
5576 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005577 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005578 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005579 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005580 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005581 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005582 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005583 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005584 }
5585 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005586
Nate Begeman02b23c62005-10-13 03:11:28 +00005587 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005588 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005589 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005590 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005591 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005592 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005593 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005594 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005595 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005596 LN0->getBasePtr(), EVT,
5597 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005598 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005599 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky14a4af02012-12-19 07:50:20 +00005600 AddToWorkList(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005601 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005602 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005603 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005604 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005605 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005606 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005607 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005608 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005609 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005610 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005611 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005612 LN0->getBasePtr(), EVT,
5613 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005614 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005615 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005616 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005617 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005618
5619 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5620 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5621 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5622 N0.getOperand(1), false);
5623 if (BSwap.getNode() != 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005624 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005625 BSwap, N1);
5626 }
5627
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005628 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5629 // into a build_vector.
5630 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5631 SmallVector<SDValue, 8> Elts;
5632 unsigned NumElts = N0->getNumOperands();
5633 unsigned ShAmt = VTBits - EVTBits;
5634
5635 for (unsigned i = 0; i != NumElts; ++i) {
5636 SDValue Op = N0->getOperand(i);
5637 if (Op->getOpcode() == ISD::UNDEF) {
5638 Elts.push_back(Op);
5639 continue;
5640 }
5641
5642 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005643 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5644 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005645 Op.getValueType()));
5646 }
5647
5648 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5649 }
5650
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005651 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005652}
5653
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005654SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5655 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005656 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005657 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005658
5659 // noop truncate
5660 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005661 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005662 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005663 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005664 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005665 // fold (truncate (truncate x)) -> (truncate x)
5666 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005667 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005668 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005669 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5670 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005671 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005672 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005673 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005674 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005675 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005676 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005677 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00005678 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005679 // if the source and dest are the same type, we can drop both the extend
5680 // and the truncate.
5681 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005682 }
Evan Chengd63baea2007-03-21 20:14:05 +00005683
Nadav Rotem4f4546b2012-02-05 11:39:23 +00005684 // Fold extract-and-trunc into a narrow extract. For example:
5685 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5686 // i32 y = TRUNCATE(i64 x)
5687 // -- becomes --
5688 // v16i8 b = BITCAST (v2i64 val)
5689 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5690 //
5691 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005692 // creates this pattern) and before operation legalization after which
5693 // we need to be more careful about the vector instructions that we generate.
5694 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5695 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5696
5697 EVT VecTy = N0.getOperand(0).getValueType();
5698 EVT ExTy = N0.getValueType();
5699 EVT TrTy = N->getValueType(0);
5700
5701 unsigned NumElem = VecTy.getVectorNumElements();
5702 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5703
5704 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5705 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5706
5707 SDValue EltNo = N0->getOperand(1);
5708 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5709 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00005710 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005711 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5712
Andrew Trickef9de2a2013-05-25 02:42:55 +00005713 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005714 NVT, N0.getOperand(0));
5715
5716 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005717 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00005718 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005719 }
5720 }
5721
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005722 // Fold a series of buildvector, bitcast, and truncate if possible.
5723 // For example fold
5724 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5725 // (2xi32 (buildvector x, y)).
5726 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5727 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5728 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5729 N0.getOperand(0).hasOneUse()) {
5730
5731 SDValue BuildVect = N0.getOperand(0);
5732 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5733 EVT TruncVecEltTy = VT.getVectorElementType();
5734
5735 // Check that the element types match.
5736 if (BuildVectEltTy == TruncVecEltTy) {
5737 // Now we only need to compute the offset of the truncated elements.
5738 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5739 unsigned TruncVecNumElts = VT.getVectorNumElements();
5740 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5741
5742 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5743 "Invalid number of elements");
5744
5745 SmallVector<SDValue, 8> Opnds;
5746 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5747 Opnds.push_back(BuildVect.getOperand(i));
5748
Andrew Trickef9de2a2013-05-25 02:42:55 +00005749 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005750 Opnds.size());
5751 }
5752 }
5753
Chris Lattner5e6fe052007-10-13 06:35:54 +00005754 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00005755 // only the low bits are being used.
5756 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00005757 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00005758 // may have different active low bits.
5759 if (!VT.isVector()) {
5760 SDValue Shorter =
5761 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5762 VT.getSizeInBits()));
5763 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005764 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00005765 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005766 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00005767 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00005768 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5769 SDValue Reduced = ReduceLoadWidth(N);
5770 if (Reduced.getNode())
5771 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00005772 // Handle the case where the load remains an extending load even
5773 // after truncation.
5774 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5775 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5776 if (!LN0->isVolatile() &&
5777 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5778 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5779 VT, LN0->getChain(), LN0->getBasePtr(),
5780 LN0->getMemoryVT(),
5781 LN0->getMemOperand());
5782 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5783 return NewLoad;
5784 }
5785 }
Dan Gohman600f62b2010-06-24 14:30:44 +00005786 }
Michael Liao3ac82012012-10-17 23:45:54 +00005787 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5788 // where ... are all 'undef'.
5789 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5790 SmallVector<EVT, 8> VTs;
5791 SDValue V;
5792 unsigned Idx = 0;
5793 unsigned NumDefs = 0;
5794
5795 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5796 SDValue X = N0.getOperand(i);
5797 if (X.getOpcode() != ISD::UNDEF) {
5798 V = X;
5799 Idx = i;
5800 NumDefs++;
5801 }
5802 // Stop if more than one members are non-undef.
5803 if (NumDefs > 1)
5804 break;
5805 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5806 VT.getVectorElementType(),
5807 X.getValueType().getVectorNumElements()));
5808 }
5809
5810 if (NumDefs == 0)
5811 return DAG.getUNDEF(VT);
5812
5813 if (NumDefs == 1) {
5814 assert(V.getNode() && "The single defined operand is empty!");
5815 SmallVector<SDValue, 8> Opnds;
5816 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5817 if (i != Idx) {
5818 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5819 continue;
5820 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005821 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao3ac82012012-10-17 23:45:54 +00005822 AddToWorkList(NV.getNode());
5823 Opnds.push_back(NV);
5824 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005825 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
Michael Liao3ac82012012-10-17 23:45:54 +00005826 &Opnds[0], Opnds.size());
5827 }
5828 }
Dan Gohman600f62b2010-06-24 14:30:44 +00005829
5830 // Simplify the operands using demanded-bits information.
5831 if (!VT.isVector() &&
5832 SimplifyDemandedBits(SDValue(N, 0)))
5833 return SDValue(N, 0);
5834
Evan Chengf1bd5fc2010-04-17 06:13:15 +00005835 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005836}
5837
Evan Chengb980f6f2008-05-12 23:04:07 +00005838static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005839 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00005840 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00005841 return Elt.getNode();
5842 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00005843}
5844
5845/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00005846/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00005847SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00005848 assert(N->getOpcode() == ISD::BUILD_PAIR);
5849
Nate Begeman624690c2009-06-05 21:37:30 +00005850 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5851 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00005852 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5853 LD1->getPointerInfo().getAddrSpace() !=
5854 LD2->getPointerInfo().getAddrSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005855 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00005856 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00005857
Evan Chengb980f6f2008-05-12 23:04:07 +00005858 if (ISD::isNON_EXTLoad(LD2) &&
5859 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00005860 // If both are volatile this would reduce the number of volatile loads.
5861 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00005862 !LD1->isVolatile() &&
5863 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00005864 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00005865 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00005866 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00005867 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00005868
Duncan Sands8651e9c2008-06-13 19:07:40 +00005869 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005870 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005871 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00005872 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005873 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00005874 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00005875
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005876 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00005877}
5878
Wesley Peck527da1b2010-11-23 03:31:01 +00005879SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005880 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005881 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00005882
Dan Gohmana8665142007-06-25 16:23:39 +00005883 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5884 // Only do this before legalize, since afterward the target may be depending
5885 // on the bitconvert.
5886 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005887 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005888 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00005889 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00005890 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005891
Owen Anderson53aa7a92009-08-10 22:56:29 +00005892 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00005893 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00005894 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00005895 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00005896 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00005897 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005898
Dan Gohman921ddd62008-09-05 01:58:21 +00005899 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00005900 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005901 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00005902 if (Res.getNode() != N) {
5903 if (!LegalOperations ||
5904 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5905 return Res;
5906
5907 // Folding it resulted in an illegal node, and it's too late to
5908 // do that. Clean up the old node and forego the transformation.
5909 // Ideally this won't happen very often, because instcombine
5910 // and the earlier dagcombine runs (where illegal nodes are
5911 // permitted) should have folded most of them already.
5912 DAG.DeleteNode(Res.getNode());
5913 }
Chris Lattnera1874602005-12-23 05:30:37 +00005914 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005915
Bill Wendling4e0a6152009-01-30 22:44:24 +00005916 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00005917 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005918 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005919 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00005920
Chris Lattner54560f62005-12-23 05:44:41 +00005921 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00005922 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00005923 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00005924 // Do not change the width of a volatile load.
5925 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00005926 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5927 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005928 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00005929 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00005930 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00005931 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00005932
Evan Chenga4cf58a2007-05-07 21:27:48 +00005933 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005934 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00005935 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00005936 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005937 LN0->isInvariant(), OrigAlign,
5938 LN0->getTBAAInfo());
Evan Chenga4cf58a2007-05-07 21:27:48 +00005939 AddToWorkList(N);
Gabor Greife12264b2008-08-30 19:29:20 +00005940 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005941 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00005942 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00005943 Load.getValue(1));
5944 return Load;
5945 }
Chris Lattner54560f62005-12-23 05:44:41 +00005946 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00005947
Bill Wendling4e0a6152009-01-30 22:44:24 +00005948 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5949 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00005950 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00005951 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5952 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00005953 N0.getNode()->hasOneUse() && VT.isInteger() &&
5954 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005955 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005956 N0.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00005957 AddToWorkList(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00005958
Duncan Sands13237ac2008-06-06 12:08:01 +00005959 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00005960 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005961 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005962 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00005963 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005964 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005965 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00005966 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005967
Bill Wendling4e0a6152009-01-30 22:44:24 +00005968 // fold (bitconvert (fcopysign cst, x)) ->
5969 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5970 // Note that we don't handle (copysign x, cst) because this can always be
5971 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005972 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00005973 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00005974 VT.isInteger() && !VT.isVector()) {
5975 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00005976 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00005977 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005978 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00005979 IntXVT, N0.getOperand(1));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005980 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00005981
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005982 // If X has a different width than the result/lhs, sext it or truncate it.
5983 unsigned VTWidth = VT.getSizeInBits();
5984 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005985 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005986 AddToWorkList(X.getNode());
5987 } else if (OrigXWidth > VTWidth) {
5988 // To get the sign bit in the right place, we have to shift it right
5989 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005990 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00005991 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005992 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5993 AddToWorkList(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005994 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005995 AddToWorkList(X.getNode());
5996 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005997
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005998 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005999 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006000 X, DAG.getConstant(SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006001 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006002
Andrew Trickef9de2a2013-05-25 02:42:55 +00006003 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006004 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006005 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006006 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006007 AddToWorkList(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006008
Andrew Trickef9de2a2013-05-25 02:42:55 +00006009 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006010 }
Chris Lattner888560d2008-01-27 17:42:27 +00006011 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006012
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006013 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006014 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006015 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6016 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006017 return CombineLD;
6018 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006019
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006020 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006021}
6022
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006023SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006024 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006025 return CombineConsecutiveLoads(N, VT);
6026}
6027
Wesley Peck527da1b2010-11-23 03:31:01 +00006028/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006029/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006030/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006031SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006032ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006033 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006034
Chris Lattnere4e64b62006-04-02 02:53:43 +00006035 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006036 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006037
Duncan Sands13237ac2008-06-06 12:08:01 +00006038 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6039 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006040
Chris Lattnere4e64b62006-04-02 02:53:43 +00006041 // If this is a conversion of N elements of one type to N elements of another
6042 // type, convert each element. This handles FP<->INT cases.
6043 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006044 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6045 BV->getValueType(0).getVectorNumElements());
6046
6047 // Due to the FP element handling below calling this routine recursively,
6048 // we can end up with a scalar-to-vector node here.
6049 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006050 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6051 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006052 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006053
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006054 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006055 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006056 SDValue Op = BV->getOperand(i);
6057 // If the vector element type is not legal, the BUILD_VECTOR operands
6058 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006059 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006060 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6061 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006062 DstEltVT, Op));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006063 AddToWorkList(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006064 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006065 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006066 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006067 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006068
Chris Lattnere4e64b62006-04-02 02:53:43 +00006069 // Otherwise, we're growing or shrinking the elements. To avoid having to
6070 // handle annoying details of growing/shrinking FP values, we convert them to
6071 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006072 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006073 // Convert the input float vector to a int vector where the elements are the
6074 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006075 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006076 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006077 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006078 SrcEltVT = IntVT;
6079 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006080
Chris Lattnere4e64b62006-04-02 02:53:43 +00006081 // Now we know the input is an integer vector. If the output is a FP type,
6082 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006083 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006084 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006085 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006086 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006087
Chris Lattnere4e64b62006-04-02 02:53:43 +00006088 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006089 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006090 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006091
Chris Lattnere4e64b62006-04-02 02:53:43 +00006092 // Okay, we know the src/dst types are both integers of differing types.
6093 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006094 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006095 if (SrcBitSize < DstBitSize) {
6096 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006097
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006098 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006099 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006100 i += NumInputsPerOutput) {
6101 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006102 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006103 bool EltIsUndef = true;
6104 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6105 // Shift the previously computed bits over.
6106 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006107 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006108 if (Op.getOpcode() == ISD::UNDEF) continue;
6109 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006110
Jay Foad583abbc2010-12-07 08:25:19 +00006111 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006112 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006113 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006114
Chris Lattnere4e64b62006-04-02 02:53:43 +00006115 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006116 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006117 else
6118 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6119 }
6120
Owen Anderson117c9e82009-08-12 00:36:31 +00006121 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006122 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006123 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006124 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006125
Chris Lattnere4e64b62006-04-02 02:53:43 +00006126 // Finally, this must be the case where we are shrinking elements: each input
6127 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006128 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006129 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006130 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6131 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006132 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006133
Dan Gohmana8665142007-06-25 16:23:39 +00006134 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006135 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6136 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006137 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006138 continue;
6139 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006140
Jay Foad583abbc2010-12-07 08:25:19 +00006141 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6142 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006143
Chris Lattnere4e64b62006-04-02 02:53:43 +00006144 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006145 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006146 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006147 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006148 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006149 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006150 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006151 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006152 }
6153
6154 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006155 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006156 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6157 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006158
Andrew Trickef9de2a2013-05-25 02:42:55 +00006159 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006160 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006161}
6162
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006163SDValue DAGCombiner::visitFADD(SDNode *N) {
6164 SDValue N0 = N->getOperand(0);
6165 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006166 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6167 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006168 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006169
Dan Gohmana8665142007-06-25 16:23:39 +00006170 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006171 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006172 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006173 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006174 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006175
Lang Hamesa33db652012-06-14 20:37:15 +00006176 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006177 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006178 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006179 // canonicalize constant to RHS
6180 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006181 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006182 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006183 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6184 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006185 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006186 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006187 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006188 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006189 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006190 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006191 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006192 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006193 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006194 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006195 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006196
Chris Lattner0199fd62007-01-08 23:04:05 +00006197 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006198 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6199 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6200 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006201 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6202 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006203 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006204
Shuxin Yang93b1f122013-03-25 22:52:29 +00006205 // No FP constant should be created after legalization as Instruction
6206 // Selection pass has hard time in dealing with FP constant.
6207 //
6208 // We don't need test this condition for transformation like following, as
6209 // the DAG being transformed implies it is legal to take FP constant as
6210 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006211 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006212 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006213 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006214 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6215
Owen Andersonb351c8d2012-11-01 02:00:53 +00006216 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006217 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006218 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006219 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006220
6221 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006222 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006223 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006224 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006225
Owen Andersoncc61f872012-08-30 23:35:16 +00006226 // In unsafe math mode, we can fold chains of FADD's of the same value
6227 // into multiplications. This transform is not safe in general because
6228 // we are reducing the number of rounding steps.
6229 if (DAG.getTarget().Options.UnsafeFPMath &&
6230 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6231 !N0CFP && !N1CFP) {
6232 if (N0.getOpcode() == ISD::FMUL) {
6233 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6234 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6235
Stephen Line31f2d22013-06-14 18:17:35 +00006236 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006237 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006238 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006239 SDValue(CFP00, 0),
6240 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006241 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006242 N1, NewCFP);
6243 }
6244
Stephen Line31f2d22013-06-14 18:17:35 +00006245 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006246 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006247 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006248 SDValue(CFP01, 0),
6249 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006250 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006251 N1, NewCFP);
6252 }
6253
Stephen Line31f2d22013-06-14 18:17:35 +00006254 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006255 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6256 N1.getOperand(0) == N1.getOperand(1) &&
6257 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006258 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006259 SDValue(CFP00, 0),
6260 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006261 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006262 N0.getOperand(1), NewCFP);
6263 }
6264
Stephen Line31f2d22013-06-14 18:17:35 +00006265 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006266 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6267 N1.getOperand(0) == N1.getOperand(1) &&
6268 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006269 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006270 SDValue(CFP01, 0),
6271 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006272 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006273 N0.getOperand(0), NewCFP);
6274 }
6275 }
6276
6277 if (N1.getOpcode() == ISD::FMUL) {
6278 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6279 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6280
Stephen Line31f2d22013-06-14 18:17:35 +00006281 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006282 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006283 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006284 SDValue(CFP10, 0),
6285 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006286 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006287 N0, NewCFP);
6288 }
6289
Stephen Line31f2d22013-06-14 18:17:35 +00006290 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006291 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006292 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006293 SDValue(CFP11, 0),
6294 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006295 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006296 N0, NewCFP);
6297 }
6298
Owen Andersoncc61f872012-08-30 23:35:16 +00006299
Stephen Line31f2d22013-06-14 18:17:35 +00006300 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6301 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6302 N0.getOperand(0) == N0.getOperand(1) &&
6303 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006304 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006305 SDValue(CFP10, 0),
6306 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006307 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006308 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006309 }
6310
Stephen Line31f2d22013-06-14 18:17:35 +00006311 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6312 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6313 N0.getOperand(0) == N0.getOperand(1) &&
6314 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006315 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006316 SDValue(CFP11, 0),
6317 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006318 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006319 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006320 }
6321 }
6322
Shuxin Yang93b1f122013-03-25 22:52:29 +00006323 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006324 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006325 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006326 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006327 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006328 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006329 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006330 }
6331
Shuxin Yang93b1f122013-03-25 22:52:29 +00006332 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006333 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006334 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006335 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006336 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006337 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006338 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006339 }
6340
Stephen Lin4e69d012013-06-14 21:33:58 +00006341 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006342 if (AllowNewFpConst &&
6343 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006344 N0.getOperand(0) == N0.getOperand(1) &&
6345 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006346 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006347 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006348 N0.getOperand(0),
6349 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006350 }
6351
Lang Hames39fb1d02012-06-19 22:51:23 +00006352 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006353 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006354 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006355 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6356 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006357
6358 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006359 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006360 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006361 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006362
Michael Liaoec3850122012-09-01 04:09:16 +00006363 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006364 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006365 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006366 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006367 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006368 }
6369
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006370 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006371}
6372
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006373SDValue DAGCombiner::visitFSUB(SDNode *N) {
6374 SDValue N0 = N->getOperand(0);
6375 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006376 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6377 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006378 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006379 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006380
Dan Gohmana8665142007-06-25 16:23:39 +00006381 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006382 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006383 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006384 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006385 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006386
Nate Begeman418c6e42005-10-18 00:28:13 +00006387 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006388 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006389 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006390 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006391 if (DAG.getTarget().Options.UnsafeFPMath &&
6392 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006393 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006394 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006395 if (DAG.getTarget().Options.UnsafeFPMath &&
6396 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006397 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006398 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006399 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006400 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006401 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006402 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006403 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006404 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006405 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006406
Bill Wendlingdf170db2012-03-15 05:12:00 +00006407 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006408 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006409 // (fsub x, (fadd x, y)) -> (fneg y) &
6410 // (fsub x, (fadd y, x)) -> (fneg y)
6411 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006412 if (N0 == N1)
6413 return DAG.getConstantFP(0.0f, VT);
6414
Bill Wendlingdf170db2012-03-15 05:12:00 +00006415 if (N1.getOpcode() == ISD::FADD) {
6416 SDValue N10 = N1->getOperand(0);
6417 SDValue N11 = N1->getOperand(1);
6418
6419 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6420 &DAG.getTarget().Options))
6421 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006422
Stephen Lin8e8424e2013-07-09 00:44:49 +00006423 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6424 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006425 return GetNegatedExpression(N10, DAG, LegalOperations);
6426 }
6427 }
6428
Lang Hames39fb1d02012-06-19 22:51:23 +00006429 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006430 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006431 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006432 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6433 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006434
6435 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006436 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006437 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006438 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006439 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006440
6441 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6442 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006443 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006444 return DAG.getNode(ISD::FMA, dl, VT,
6445 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006446 N1.getOperand(0)),
6447 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006448
Stephen Lin8e8424e2013-07-09 00:44:49 +00006449 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006450 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006451 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6452 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6453 SDValue N00 = N0.getOperand(0).getOperand(0);
6454 SDValue N01 = N0.getOperand(0).getOperand(1);
6455 return DAG.getNode(ISD::FMA, dl, VT,
6456 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6457 DAG.getNode(ISD::FNEG, dl, VT, N1));
6458 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006459 }
6460
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006461 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006462}
6463
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006464SDValue DAGCombiner::visitFMUL(SDNode *N) {
6465 SDValue N0 = N->getOperand(0);
6466 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006467 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6468 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006469 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006470 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006471
Dan Gohmana8665142007-06-25 16:23:39 +00006472 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006473 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006474 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006475 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006476 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006477
Nate Begemanec48a1b2005-10-17 20:40:11 +00006478 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006479 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006480 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006481 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006482 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006483 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006484 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006485 if (DAG.getTarget().Options.UnsafeFPMath &&
6486 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006487 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006488 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006489 if (DAG.getTarget().Options.UnsafeFPMath &&
6490 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006491 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006492 // fold (fmul A, 1.0) -> A
6493 if (N1CFP && N1CFP->isExactlyValue(1.0))
6494 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006495 // fold (fmul X, 2.0) -> (fadd X, X)
6496 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006497 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006498 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006499 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006500 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006501 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006502
Bill Wendling3dc5d242009-01-30 22:57:07 +00006503 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006504 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006505 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006506 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006507 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006508 // Both can be negated for free, check to see if at least one is cheaper
6509 // negated.
6510 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006511 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006512 GetNegatedExpression(N0, DAG, LegalOperations),
6513 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006514 }
6515 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006516
Chris Lattner0199fd62007-01-08 23:04:05 +00006517 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006518 if (DAG.getTarget().Options.UnsafeFPMath &&
6519 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006520 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006521 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6522 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006523 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006524
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006525 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006526}
6527
Owen Anderson41b06652012-05-02 22:17:40 +00006528SDValue DAGCombiner::visitFMA(SDNode *N) {
6529 SDValue N0 = N->getOperand(0);
6530 SDValue N1 = N->getOperand(1);
6531 SDValue N2 = N->getOperand(2);
6532 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6533 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6534 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006535 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006536
Owen Andersonb351c8d2012-11-01 02:00:53 +00006537 if (DAG.getTarget().Options.UnsafeFPMath) {
6538 if (N0CFP && N0CFP->isZero())
6539 return N2;
6540 if (N1CFP && N1CFP->isZero())
6541 return N2;
6542 }
Owen Anderson41b06652012-05-02 22:17:40 +00006543 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006544 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006545 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006546 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006547
Owen Andersonc7aaf522012-05-30 18:50:39 +00006548 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006549 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006550 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006551
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006552 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6553 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6554 N2.getOpcode() == ISD::FMUL &&
6555 N0 == N2.getOperand(0) &&
6556 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6557 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6558 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6559 }
6560
6561
6562 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6563 if (DAG.getTarget().Options.UnsafeFPMath &&
6564 N0.getOpcode() == ISD::FMUL && N1CFP &&
6565 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6566 return DAG.getNode(ISD::FMA, dl, VT,
6567 N0.getOperand(0),
6568 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6569 N2);
6570 }
6571
6572 // (fma x, 1, y) -> (fadd x, y)
6573 // (fma x, -1, y) -> (fadd (fneg x), y)
6574 if (N1CFP) {
6575 if (N1CFP->isExactlyValue(1.0))
6576 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6577
6578 if (N1CFP->isExactlyValue(-1.0) &&
6579 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6580 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6581 AddToWorkList(RHSNeg.getNode());
6582 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6583 }
6584 }
6585
6586 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006587 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6588 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006589 DAG.getNode(ISD::FADD, dl, VT,
6590 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006591
6592 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6593 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006594 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6595 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006596 DAG.getNode(ISD::FADD, dl, VT,
6597 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006598
6599
Owen Anderson41b06652012-05-02 22:17:40 +00006600 return SDValue();
6601}
6602
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006603SDValue DAGCombiner::visitFDIV(SDNode *N) {
6604 SDValue N0 = N->getOperand(0);
6605 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006606 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6607 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006608 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006609 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006610
Dan Gohmana8665142007-06-25 16:23:39 +00006611 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006612 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006613 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006614 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006615 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006616
Nate Begeman569c4392006-01-18 22:35:16 +00006617 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006618 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006619 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006620
Duncan Sands2f1dc382012-04-08 18:08:12 +00006621 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006622 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006623 // Compute the reciprocal 1.0 / c2.
6624 APFloat N1APF = N1CFP->getValueAPF();
6625 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6626 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006627 // Only do the transform if the reciprocal is a legal fp immediate that
6628 // isn't too nasty (eg NaN, denormal, ...).
6629 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006630 (!LegalOperations ||
6631 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6632 // backend)... we should handle this gracefully after Legalize.
6633 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6634 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6635 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006636 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006637 DAG.getConstantFP(Recip, VT));
6638 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006639
Bill Wendling3dc5d242009-01-30 22:57:07 +00006640 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006641 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006642 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006643 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006644 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006645 // Both can be negated for free, check to see if at least one is cheaper
6646 // negated.
6647 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006648 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006649 GetNegatedExpression(N0, DAG, LegalOperations),
6650 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006651 }
6652 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006653
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006654 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006655}
6656
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006657SDValue DAGCombiner::visitFREM(SDNode *N) {
6658 SDValue N0 = N->getOperand(0);
6659 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006660 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6661 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006662 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006663
Nate Begeman569c4392006-01-18 22:35:16 +00006664 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006665 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006666 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00006667
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006668 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006669}
6670
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006671SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6672 SDValue N0 = N->getOperand(0);
6673 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006674 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6675 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006676 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00006677
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006678 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00006679 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006680
Chris Lattner3bc40502006-03-05 05:30:57 +00006681 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00006682 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006683 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6684 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00006685 if (!V.isNegative()) {
6686 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006687 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006688 } else {
6689 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006690 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6691 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00006692 }
Chris Lattner3bc40502006-03-05 05:30:57 +00006693 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006694
Chris Lattner3bc40502006-03-05 05:30:57 +00006695 // copysign(fabs(x), y) -> copysign(x, y)
6696 // copysign(fneg(x), y) -> copysign(x, y)
6697 // copysign(copysign(x,z), y) -> copysign(x, y)
6698 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6699 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006700 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006701 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006702
6703 // copysign(x, abs(y)) -> abs(x)
6704 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006705 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006706
Chris Lattner3bc40502006-03-05 05:30:57 +00006707 // copysign(x, copysign(y,z)) -> copysign(x, z)
6708 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006709 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006710 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006711
Chris Lattner3bc40502006-03-05 05:30:57 +00006712 // copysign(x, fp_extend(y)) -> copysign(x, y)
6713 // copysign(x, fp_round(y)) -> copysign(x, y)
6714 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006715 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006716 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006717
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006718 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00006719}
6720
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006721SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6722 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006723 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006724 EVT VT = N->getValueType(0);
6725 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006726
Nate Begeman21158fc2005-09-01 00:19:25 +00006727 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006728 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006729 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006730 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006731 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006732 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006733
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006734 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6735 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006736 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6737 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006738 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006739 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006740 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006741 }
Bill Wendling0bd29742009-01-30 23:15:49 +00006742
Alp Tokercb402912014-01-24 17:20:08 +00006743 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006744 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6745 // having to say they don't support SELECT_CC on every type the DAG knows
6746 // about, since there is no way to mark an opcode illegal at all value types
6747 // (See also visitSELECT)
6748 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6749 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6750 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6751 !VT.isVector() &&
6752 (!LegalOperations ||
6753 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6754 SDValue Ops[] =
6755 { N0.getOperand(0), N0.getOperand(1),
6756 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6757 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006758 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006759 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006760
Nadav Rotem90560762012-07-23 07:59:50 +00006761 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6762 // (select_cc x, y, 1.0, 0.0,, cc)
6763 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6764 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6765 (!LegalOperations ||
6766 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6767 SDValue Ops[] =
6768 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6769 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6770 N0.getOperand(0).getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006771 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006772 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006773 }
6774
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006775 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006776}
6777
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006778SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6779 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006780 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006781 EVT VT = N->getValueType(0);
6782 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00006783
Nate Begeman21158fc2005-09-01 00:19:25 +00006784 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006785 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006786 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006787 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006788 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006789 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006790
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006791 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6792 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006793 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6794 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006795 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006796 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006797 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006798 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006799
Alp Tokercb402912014-01-24 17:20:08 +00006800 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006801 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6802 // having to say they don't support SELECT_CC on every type the DAG knows
6803 // about, since there is no way to mark an opcode illegal at all value types
6804 // (See also visitSELECT)
6805 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6806 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00006807
Nadav Rotem90560762012-07-23 07:59:50 +00006808 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6809 (!LegalOperations ||
6810 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6811 SDValue Ops[] =
6812 { N0.getOperand(0), N0.getOperand(1),
6813 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6814 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00006815 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00006816 }
6817 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006818
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006819 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006820}
6821
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006822SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6823 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00006824 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006825 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006826
Nate Begeman21158fc2005-09-01 00:19:25 +00006827 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006828 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006829 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00006830
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006831 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006832}
6833
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006834SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6835 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00006836 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006837 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006838
Nate Begeman21158fc2005-09-01 00:19:25 +00006839 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006840 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006841 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00006842
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006843 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006844}
6845
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006846SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6847 SDValue N0 = N->getOperand(0);
6848 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006849 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006850 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006851
Nate Begeman21158fc2005-09-01 00:19:25 +00006852 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006853 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006854 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006855
Chris Lattner8bb6cb72006-03-13 06:26:26 +00006856 // fold (fp_round (fp_extend x)) -> x
6857 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6858 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006859
Chris Lattner0feb1b02008-01-24 06:45:35 +00006860 // fold (fp_round (fp_round x)) -> (fp_round x)
6861 if (N0.getOpcode() == ISD::FP_ROUND) {
6862 // This is a value preserving truncation if both round's are.
6863 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006864 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00006865 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00006866 DAG.getIntPtrConstant(IsTrunc));
6867 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006868
Chris Lattner8bb6cb72006-03-13 06:26:26 +00006869 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006870 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006871 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006872 N0.getOperand(0), N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006873 AddToWorkList(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006874 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006875 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00006876 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006877
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006878 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006879}
6880
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006881SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6882 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006883 EVT VT = N->getValueType(0);
6884 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006885 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006886
Nate Begeman21158fc2005-09-01 00:19:25 +00006887 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00006888 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00006889 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006890 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00006891 }
Bill Wendling0bd29742009-01-30 23:15:49 +00006892
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006893 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006894}
6895
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006896SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6897 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00006898 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006899 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006900
Chris Lattner5919b482007-12-29 06:55:23 +00006901 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00006902 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00006903 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006904 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00006905
Nate Begeman21158fc2005-09-01 00:19:25 +00006906 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006907 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006908 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00006909
6910 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6911 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00006912 if (N0.getOpcode() == ISD::FP_ROUND
6913 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006914 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00006915 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00006916 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006917 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006918 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006919 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00006920 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006921
Chris Lattner72733e52008-01-17 07:00:52 +00006922 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00006923 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006924 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00006925 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006926 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006927 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006928 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006929 LN0->getBasePtr(), N0.getValueType(),
6930 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00006931 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00006932 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006933 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00006934 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00006935 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006936 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00006937 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006938
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006939 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006940}
6941
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006942SDValue DAGCombiner::visitFNEG(SDNode *N) {
6943 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00006944 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00006945
Craig Topper82384612012-09-11 01:45:21 +00006946 if (VT.isVector()) {
6947 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6948 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00006949 }
6950
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006951 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6952 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006953 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00006954
Chris Lattner888560d2008-01-27 17:42:27 +00006955 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6956 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00006957 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00006958 !VT.isVector() &&
6959 N0.getNode()->hasOneUse() &&
6960 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006961 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006962 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006963 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006964 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00006965 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006966 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006967 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00006968 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00006969 }
6970 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006971
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006972 // (fneg (fmul c, x)) -> (fmul -c, x)
6973 if (N0.getOpcode() == ISD::FMUL) {
6974 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Stephen Lin8e8424e2013-07-09 00:44:49 +00006975 if (CFP1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006976 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006977 N0.getOperand(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006978 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006979 N0.getOperand(1)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006980 }
6981
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006982 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006983}
6984
Owen Andersona40319b2012-08-13 23:32:49 +00006985SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6986 SDValue N0 = N->getOperand(0);
6987 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6988 EVT VT = N->getValueType(0);
6989
6990 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006991 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006992 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00006993
6994 return SDValue();
6995}
6996
6997SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6998 SDValue N0 = N->getOperand(0);
6999 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7000 EVT VT = N->getValueType(0);
7001
7002 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007003 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007004 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007005
7006 return SDValue();
7007}
7008
7009SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7010 SDValue N0 = N->getOperand(0);
7011 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7012 EVT VT = N->getValueType(0);
7013
7014 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007015 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007016 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007017
7018 return SDValue();
7019}
7020
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007021SDValue DAGCombiner::visitFABS(SDNode *N) {
7022 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007023 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007024 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007025
Craig Topper82384612012-09-11 01:45:21 +00007026 if (VT.isVector()) {
7027 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7028 if (FoldedVOp.getNode()) return FoldedVOp;
7029 }
7030
Nate Begeman21158fc2005-09-01 00:19:25 +00007031 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007032 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007033 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007034 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007035 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007036 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007037 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007038 // fold (fabs (fcopysign x, y)) -> (fabs x)
7039 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007040 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007041
Chris Lattner888560d2008-01-27 17:42:27 +00007042 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7043 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007044 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007045 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007046 N0.getOperand(0).getValueType().isInteger() &&
7047 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007048 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007049 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007050 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007051 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007052 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007053 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007054 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007055 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007056 }
7057 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007058
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007059 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007060}
7061
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007062SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7063 SDValue Chain = N->getOperand(0);
7064 SDValue N1 = N->getOperand(1);
7065 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007066
Dan Gohman82e80012009-11-17 00:47:23 +00007067 // If N is a constant we could fold this into a fallthrough or unconditional
7068 // branch. However that doesn't happen very often in normal code, because
7069 // Instcombine/SimplifyCFG should have handled the available opportunities.
7070 // If we did this folding here, it would be necessary to update the
7071 // MachineBasicBlock CFG, which is awkward.
7072
Nate Begeman7e7f4392006-02-01 07:19:44 +00007073 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7074 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007075 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007076 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7077 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007078 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007079 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007080 N1.getOperand(0), N1.getOperand(1), N2);
7081 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007082
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007083 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7084 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7085 (N1.getOperand(0).hasOneUse() &&
7086 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7087 SDNode *Trunc = 0;
7088 if (N1.getOpcode() == ISD::TRUNCATE) {
7089 // Look pass the truncate.
7090 Trunc = N1.getNode();
7091 N1 = N1.getOperand(0);
7092 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007093
Bill Wendlingaa28be62009-03-26 06:14:09 +00007094 // Match this pattern so that we can generate simpler code:
7095 //
7096 // %a = ...
7097 // %b = and i32 %a, 2
7098 // %c = srl i32 %b, 1
7099 // brcond i32 %c ...
7100 //
7101 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007102 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007103 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007104 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007105 // %c = setcc eq %b, 0
7106 // brcond %c ...
7107 //
7108 // This applies only when the AND constant value has one bit set and the
7109 // SRL constant is equal to the log2 of the AND constant. The back-end is
7110 // smart enough to convert the result into a TEST/JMP sequence.
7111 SDValue Op0 = N1.getOperand(0);
7112 SDValue Op1 = N1.getOperand(1);
7113
7114 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007115 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007116 SDValue AndOp1 = Op0.getOperand(1);
7117
7118 if (AndOp1.getOpcode() == ISD::Constant) {
7119 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7120
7121 if (AndConst.isPowerOf2() &&
7122 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7123 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007124 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007125 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007126 Op0, DAG.getConstant(0, Op0.getValueType()),
7127 ISD::SETNE);
7128
Andrew Trickef9de2a2013-05-25 02:42:55 +00007129 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007130 MVT::Other, Chain, SetCC, N2);
7131 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7132 // will convert it back to (X & C1) >> C2.
7133 CombineTo(N, NewBRCond, false);
7134 // Truncate is dead.
7135 if (Trunc) {
7136 removeFromWorkList(Trunc);
7137 DAG.DeleteNode(Trunc);
7138 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007139 // Replace the uses of SRL with SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00007140 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007141 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007142 removeFromWorkList(N1.getNode());
7143 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007144 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007145 }
7146 }
7147 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007148
7149 if (Trunc)
7150 // Restore N1 if the above transformation doesn't match.
7151 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007152 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007153
Evan Cheng228c31f2010-02-27 07:36:59 +00007154 // Transform br(xor(x, y)) -> br(x != y)
7155 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7156 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7157 SDNode *TheXor = N1.getNode();
7158 SDValue Op0 = TheXor->getOperand(0);
7159 SDValue Op1 = TheXor->getOperand(1);
7160 if (Op0.getOpcode() == Op1.getOpcode()) {
7161 // Avoid missing important xor optimizations.
7162 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007163 if (Tmp.getNode()) {
7164 if (Tmp.getNode() != TheXor) {
7165 DEBUG(dbgs() << "\nReplacing.8 ";
7166 TheXor->dump(&DAG);
7167 dbgs() << "\nWith: ";
7168 Tmp.getNode()->dump(&DAG);
7169 dbgs() << '\n');
7170 WorkListRemover DeadNodes(*this);
7171 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7172 removeFromWorkList(TheXor);
7173 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007174 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007175 MVT::Other, Chain, Tmp, N2);
7176 }
7177
Benjamin Kramer93354432013-03-30 21:28:18 +00007178 // visitXOR has changed XOR's operands or replaced the XOR completely,
7179 // bail out.
7180 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007181 }
7182 }
7183
7184 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7185 bool Equal = false;
7186 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7187 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7188 Op0.getOpcode() == ISD::XOR) {
7189 TheXor = Op0.getNode();
7190 Equal = true;
7191 }
7192
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007193 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007194 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007195 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007196 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007197 SetCCVT,
7198 Op0, Op1,
7199 Equal ? ISD::SETEQ : ISD::SETNE);
7200 // Replace the uses of XOR with SETCC
7201 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007202 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007203 removeFromWorkList(N1.getNode());
7204 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007205 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007206 MVT::Other, Chain, SetCC, N2);
7207 }
7208 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007209
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007210 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007211}
7212
Chris Lattnera49e16f2005-10-05 06:47:48 +00007213// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7214//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007215SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007216 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007217 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007218
Dan Gohman82e80012009-11-17 00:47:23 +00007219 // If N is a constant we could fold this into a fallthrough or unconditional
7220 // branch. However that doesn't happen very often in normal code, because
7221 // Instcombine/SimplifyCFG should have handled the available opportunities.
7222 // If we did this folding here, it would be necessary to update the
7223 // MachineBasicBlock CFG, which is awkward.
7224
Duncan Sands93b66092008-06-09 11:32:28 +00007225 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007226 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007227 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007228 false);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007229 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007230
Nate Begemanbd7df032005-10-05 21:43:42 +00007231 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007232 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007233 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007234 N->getOperand(0), Simp.getOperand(2),
7235 Simp.getOperand(0), Simp.getOperand(1),
7236 N->getOperand(4));
7237
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007238 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007239}
7240
Evan Chengfa832632012-01-13 01:37:24 +00007241/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7242/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007243/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007244static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7245 SelectionDAG &DAG,
7246 const TargetLowering &TLI) {
7247 EVT VT;
7248 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7249 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7250 return false;
7251 VT = Use->getValueType(0);
7252 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7253 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7254 return false;
7255 VT = ST->getValue().getValueType();
7256 } else
7257 return false;
7258
Chandler Carruth95f83e02013-01-07 15:14:13 +00007259 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007260 if (N->getOpcode() == ISD::ADD) {
7261 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7262 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007263 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007264 AM.BaseOffs = Offset->getSExtValue();
7265 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007266 // [reg +/- reg]
7267 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007268 } else if (N->getOpcode() == ISD::SUB) {
7269 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7270 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007271 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007272 AM.BaseOffs = -Offset->getSExtValue();
7273 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007274 // [reg +/- reg]
7275 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007276 } else
7277 return false;
7278
7279 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7280}
7281
Duncan Sands075293f2008-06-15 20:12:31 +00007282/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7283/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007284/// and it has other uses besides the load / store. After the
7285/// transformation, the new indexed load / store has effectively folded
7286/// the add / subtract in and all of its other uses are redirected to the
7287/// new load / store.
7288bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007289 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007290 return false;
7291
7292 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007293 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007294 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007295 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007296 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007297 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007298 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007299 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007300 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7301 return false;
7302 Ptr = LD->getBasePtr();
7303 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007304 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007305 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007306 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007307 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7308 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7309 return false;
7310 Ptr = ST->getBasePtr();
7311 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007312 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007313 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007314 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007315
Chris Lattnereabc15c2006-11-11 00:56:29 +00007316 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7317 // out. There is no reason to make this a preinc/predec.
7318 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007319 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007320 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007321
Chris Lattnereabc15c2006-11-11 00:56:29 +00007322 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007323 SDValue BasePtr;
7324 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007325 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7326 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7327 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007328
7329 // Backends without true r+i pre-indexed forms may need to pass a
7330 // constant base with a variable offset so that constant coercion
7331 // will work with the patterns in canonical form.
7332 bool Swapped = false;
7333 if (isa<ConstantSDNode>(BasePtr)) {
7334 std::swap(BasePtr, Offset);
7335 Swapped = true;
7336 }
7337
Evan Cheng044a0a82007-05-03 23:52:19 +00007338 // Don't create a indexed load / store with zero offset.
7339 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007340 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007341 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007342
Chris Lattnera0a80032006-11-11 01:00:15 +00007343 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007344 // 1) The new base ptr is a frame index.
7345 // 2) If N is a store and the new base ptr is either the same as or is a
Chris Lattnereabc15c2006-11-11 00:56:29 +00007346 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007347 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007348 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007349 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007350
Chris Lattnera0a80032006-11-11 01:00:15 +00007351 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7352 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007353 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007354 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007355
Chris Lattnera0a80032006-11-11 01:00:15 +00007356 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007357 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007358 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007359 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007360 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007361 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007362
Hal Finkel25819052013-02-08 21:35:47 +00007363 // If the offset is a constant, there may be other adds of constants that
7364 // can be folded with this one. We should do this to avoid having to keep
7365 // a copy of the original base pointer.
7366 SmallVector<SDNode *, 16> OtherUses;
7367 if (isa<ConstantSDNode>(Offset))
7368 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7369 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7370 SDNode *Use = *I;
7371 if (Use == Ptr.getNode())
7372 continue;
7373
7374 if (Use->isPredecessorOf(N))
7375 continue;
7376
7377 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7378 OtherUses.clear();
7379 break;
7380 }
7381
7382 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7383 if (Op1.getNode() == BasePtr.getNode())
7384 std::swap(Op0, Op1);
7385 assert(Op0.getNode() == BasePtr.getNode() &&
7386 "Use of ADD/SUB but not an operand");
7387
7388 if (!isa<ConstantSDNode>(Op1)) {
7389 OtherUses.clear();
7390 break;
7391 }
7392
7393 // FIXME: In some cases, we can be smarter about this.
7394 if (Op1.getValueType() != Offset.getValueType()) {
7395 OtherUses.clear();
7396 break;
7397 }
7398
7399 OtherUses.push_back(Use);
7400 }
7401
7402 if (Swapped)
7403 std::swap(BasePtr, Offset);
7404
Evan Chenga4d187b2007-05-24 02:35:39 +00007405 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007406 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007407
7408 // Caches for hasPredecessorHelper
7409 SmallPtrSet<const SDNode *, 32> Visited;
7410 SmallVector<const SDNode *, 16> Worklist;
7411
Gabor Greiff304a7a2008-08-28 21:40:38 +00007412 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7413 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007414 SDNode *Use = *I;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007415 if (Use == N)
7416 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007417 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007418 return false;
7419
Evan Chengfa832632012-01-13 01:37:24 +00007420 // If Ptr may be folded in addressing mode of other use, then it's
7421 // not profitable to do this transformation.
7422 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007423 RealUse = true;
7424 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007425
Chris Lattnereabc15c2006-11-11 00:56:29 +00007426 if (!RealUse)
7427 return false;
7428
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007429 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007430 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007431 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007432 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007433 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007434 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007435 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007436 ++PreIndexedNodes;
7437 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007438 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007439 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007440 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007441 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007442 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007443 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007444 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007445 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7446 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007447 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007448 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007449 }
7450
Chris Lattnereabc15c2006-11-11 00:56:29 +00007451 // Finally, since the node is now dead, remove it from the graph.
7452 DAG.DeleteNode(N);
7453
Hal Finkel25819052013-02-08 21:35:47 +00007454 if (Swapped)
7455 std::swap(BasePtr, Offset);
7456
7457 // Replace other uses of BasePtr that can be updated to use Ptr
7458 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7459 unsigned OffsetIdx = 1;
7460 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7461 OffsetIdx = 0;
7462 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7463 BasePtr.getNode() && "Expected BasePtr operand");
7464
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007465 // We need to replace ptr0 in the following expression:
7466 // x0 * offset0 + y0 * ptr0 = t0
7467 // knowing that
7468 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007469 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007470 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7471 // indexed load/store and the expresion that needs to be re-written.
7472 //
7473 // Therefore, we have:
7474 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007475
7476 ConstantSDNode *CN =
7477 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007478 int X0, X1, Y0, Y1;
7479 APInt Offset0 = CN->getAPIntValue();
7480 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007481
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007482 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7483 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7484 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7485 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007486
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007487 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7488
7489 APInt CNV = Offset0;
7490 if (X0 < 0) CNV = -CNV;
7491 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7492 else CNV = CNV - Offset1;
7493
7494 // We can now generate the new expression.
7495 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7496 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7497
7498 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007499 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007500 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7501 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7502 removeFromWorkList(OtherUses[i]);
7503 DAG.DeleteNode(OtherUses[i]);
7504 }
7505
Chris Lattnereabc15c2006-11-11 00:56:29 +00007506 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007507 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007508 removeFromWorkList(Ptr.getNode());
7509 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007510
7511 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007512}
7513
Duncan Sands075293f2008-06-15 20:12:31 +00007514/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007515/// add / sub of the base pointer node into a post-indexed load / store.
7516/// The transformation folded the add / subtract into the new indexed
7517/// load / store effectively and all of its uses are redirected to the
7518/// new load / store.
7519bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007520 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007521 return false;
7522
7523 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007524 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007525 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007526 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007527 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007528 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007529 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007530 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7531 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7532 return false;
7533 Ptr = LD->getBasePtr();
7534 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007535 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007536 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007537 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007538 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7539 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7540 return false;
7541 Ptr = ST->getBasePtr();
7542 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007543 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007544 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007545 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007546
Gabor Greiff304a7a2008-08-28 21:40:38 +00007547 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007548 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007549
Gabor Greiff304a7a2008-08-28 21:40:38 +00007550 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7551 E = Ptr.getNode()->use_end(); I != E; ++I) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007552 SDNode *Op = *I;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007553 if (Op == N ||
7554 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7555 continue;
7556
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007557 SDValue BasePtr;
7558 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007559 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7560 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007561 // Don't create a indexed load / store with zero offset.
7562 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007563 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007564 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007565
Chris Lattnereabc15c2006-11-11 00:56:29 +00007566 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007567 // 1) All uses are load / store ops that use it as base ptr (and
7568 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007569 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7570 // nor a successor of N. Otherwise, if Op is folded that would
7571 // create a cycle.
7572
Evan Chengcfc05132009-05-06 18:25:01 +00007573 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7574 continue;
7575
Chris Lattnereabc15c2006-11-11 00:56:29 +00007576 // Check for #1.
7577 bool TryNext = false;
Gabor Greiff304a7a2008-08-28 21:40:38 +00007578 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7579 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007580 SDNode *Use = *II;
Gabor Greiff304a7a2008-08-28 21:40:38 +00007581 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007582 continue;
7583
Chris Lattnereabc15c2006-11-11 00:56:29 +00007584 // If all the uses are load / store addresses, then don't do the
7585 // transformation.
7586 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7587 bool RealUse = false;
7588 for (SDNode::use_iterator III = Use->use_begin(),
7589 EEE = Use->use_end(); III != EEE; ++III) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00007590 SDNode *UseUse = *III;
Stephen Lincfe7f352013-07-08 00:37:03 +00007591 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007592 RealUse = true;
7593 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007594
Chris Lattnereabc15c2006-11-11 00:56:29 +00007595 if (!RealUse) {
7596 TryNext = true;
7597 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007598 }
7599 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007600 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007601
Chris Lattnereabc15c2006-11-11 00:56:29 +00007602 if (TryNext)
7603 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007604
Chris Lattnereabc15c2006-11-11 00:56:29 +00007605 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007606 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007607 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007608 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007609 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007610 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007611 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007612 ++PostIndexedNodes;
7613 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007614 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007615 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007616 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007617 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007618 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007619 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007620 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007621 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7622 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007623 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007624 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007625 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007626
Chris Lattnereabc15c2006-11-11 00:56:29 +00007627 // Finally, since the node is now dead, remove it from the graph.
7628 DAG.DeleteNode(N);
7629
7630 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007631 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007632 Result.getValue(isLoad ? 1 : 0));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007633 removeFromWorkList(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007634 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007635 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007636 }
7637 }
7638 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007639
Chris Lattnerffad2162006-11-11 00:39:41 +00007640 return false;
7641}
7642
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007643SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007644 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007645 SDValue Chain = LD->getChain();
7646 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007647
Evan Chenga684cd22007-05-01 00:38:21 +00007648 // If load is not volatile and there are no uses of the loaded value (and
7649 // the updated indexed value in case of indexed loads), change uses of the
7650 // chain value into uses of the chain input (i.e. delete the dead load).
7651 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007652 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007653 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007654 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007655 // It's not safe to use the two value CombineTo variant here. e.g.
7656 // v1, chain2 = load chain1, loc
7657 // v2, chain3 = load chain2, loc
7658 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007659 // Now we replace use of chain2 with chain1. This makes the second load
7660 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007661 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007662 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007663 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007664 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007665 dbgs() << "\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007666 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007667 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007668
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007669 if (N->use_empty()) {
7670 removeFromWorkList(N);
7671 DAG.DeleteNode(N);
7672 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007673
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007674 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007675 }
Evan Chengb68343c2007-05-01 08:53:39 +00007676 } else {
7677 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007678 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Craig Topper0515cd42012-01-07 18:31:09 +00007679 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00007680 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00007681 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007682 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007683 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007684 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007685 dbgs() << " and 2 other values\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007686 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007687 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007688 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007689 DAG.getUNDEF(N->getValueType(1)));
7690 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng7be15282008-01-16 23:11:54 +00007691 removeFromWorkList(N);
Evan Cheng7be15282008-01-16 23:11:54 +00007692 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007693 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00007694 }
Evan Chenga684cd22007-05-01 00:38:21 +00007695 }
7696 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007697
Chris Lattnere260ed82005-10-10 22:04:48 +00007698 // If this load is directly stored, replace the load value with the stored
7699 // value.
7700 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007701 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00007702 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007703 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00007704 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7705 if (PrevST->getBasePtr() == Ptr &&
7706 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00007707 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00007708 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00007709 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007710
Evan Cheng43cd9e32010-04-01 06:04:33 +00007711 // Try to infer better alignment information than the load already has.
7712 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00007713 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00007714 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7715 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007716 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00007717 LD->getValueType(0),
7718 Chain, Ptr, LD->getPointerInfo(),
7719 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007720 LD->isVolatile(), LD->isNonTemporal(), Align,
7721 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00007722 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7723 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00007724 }
7725 }
7726
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00007727 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7728 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkelccc18e12014-01-24 18:25:26 +00007729 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00007730 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007731 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007732
Jim Laskey708d0db2006-10-04 16:53:27 +00007733 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00007734 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007735 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00007736
Jim Laskeyd07be232006-09-25 16:29:54 +00007737 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007738 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007739 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007740 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007741 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007742 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00007743 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007744 BetterChain, Ptr, LD->getMemoryVT(),
7745 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007746 }
Jim Laskeyd07be232006-09-25 16:29:54 +00007747
Jim Laskey708d0db2006-10-04 16:53:27 +00007748 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00007749 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00007750 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00007751
Nate Begeman879d8f12009-09-15 00:18:30 +00007752 // Make sure the new and old chains are cleaned up.
7753 AddToWorkList(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00007754
Jim Laskeydcf983c2006-10-13 23:32:28 +00007755 // Replace uses with load result and token factor. Don't add users
7756 // to work list.
7757 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00007758 }
7759 }
7760
Evan Cheng357017f2006-11-03 03:06:21 +00007761 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00007762 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007763 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00007764
Quentin Colombetde0e0622013-10-11 18:29:42 +00007765 // Try to slice up N to more direct loads if the slices are mapped to
7766 // different register banks or pairing can take place.
7767 if (SliceUpLoad(N))
7768 return SDValue(N, 0);
7769
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007770 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00007771}
7772
Quentin Colombetde0e0622013-10-11 18:29:42 +00007773namespace {
7774/// \brief Helper structure used to slice a load in smaller loads.
7775/// Basically a slice is obtained from the following sequence:
7776/// Origin = load Ty1, Base
7777/// Shift = srl Ty1 Origin, CstTy Amount
7778/// Inst = trunc Shift to Ty2
7779///
7780/// Then, it will be rewriten into:
7781/// Slice = load SliceTy, Base + SliceOffset
7782/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7783///
7784/// SliceTy is deduced from the number of bits that are actually used to
7785/// build Inst.
7786struct LoadedSlice {
7787 /// \brief Helper structure used to compute the cost of a slice.
7788 struct Cost {
7789 /// Are we optimizing for code size.
7790 bool ForCodeSize;
7791 /// Various cost.
7792 unsigned Loads;
7793 unsigned Truncates;
7794 unsigned CrossRegisterBanksCopies;
7795 unsigned ZExts;
7796 unsigned Shift;
7797
7798 Cost(bool ForCodeSize = false)
7799 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7800 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7801
7802 /// \brief Get the cost of one isolated slice.
7803 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7804 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7805 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7806 EVT TruncType = LS.Inst->getValueType(0);
7807 EVT LoadedType = LS.getLoadedType();
7808 if (TruncType != LoadedType &&
7809 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7810 ZExts = 1;
7811 }
7812
7813 /// \brief Account for slicing gain in the current cost.
7814 /// Slicing provide a few gains like removing a shift or a
7815 /// truncate. This method allows to grow the cost of the original
7816 /// load with the gain from this slice.
7817 void addSliceGain(const LoadedSlice &LS) {
7818 // Each slice saves a truncate.
7819 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7820 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7821 LS.Inst->getOperand(0).getValueType()))
7822 ++Truncates;
7823 // If there is a shift amount, this slice gets rid of it.
7824 if (LS.Shift)
7825 ++Shift;
7826 // If this slice can merge a cross register bank copy, account for it.
7827 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7828 ++CrossRegisterBanksCopies;
7829 }
7830
7831 Cost &operator+=(const Cost &RHS) {
7832 Loads += RHS.Loads;
7833 Truncates += RHS.Truncates;
7834 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7835 ZExts += RHS.ZExts;
7836 Shift += RHS.Shift;
7837 return *this;
7838 }
7839
7840 bool operator==(const Cost &RHS) const {
7841 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7842 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7843 ZExts == RHS.ZExts && Shift == RHS.Shift;
7844 }
7845
7846 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7847
7848 bool operator<(const Cost &RHS) const {
7849 // Assume cross register banks copies are as expensive as loads.
7850 // FIXME: Do we want some more target hooks?
7851 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7852 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7853 // Unless we are optimizing for code size, consider the
7854 // expensive operation first.
7855 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7856 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7857 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7858 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7859 }
7860
7861 bool operator>(const Cost &RHS) const { return RHS < *this; }
7862
7863 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7864
7865 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7866 };
7867 // The last instruction that represent the slice. This should be a
7868 // truncate instruction.
7869 SDNode *Inst;
7870 // The original load instruction.
7871 LoadSDNode *Origin;
7872 // The right shift amount in bits from the original load.
7873 unsigned Shift;
7874 // The DAG from which Origin came from.
7875 // This is used to get some contextual information about legal types, etc.
7876 SelectionDAG *DAG;
7877
7878 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7879 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7880 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7881
7882 LoadedSlice(const LoadedSlice &LS)
7883 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7884
7885 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7886 /// \return Result is \p BitWidth and has used bits set to 1 and
7887 /// not used bits set to 0.
7888 APInt getUsedBits() const {
7889 // Reproduce the trunc(lshr) sequence:
7890 // - Start from the truncated value.
7891 // - Zero extend to the desired bit width.
7892 // - Shift left.
7893 assert(Origin && "No original load to compare against.");
7894 unsigned BitWidth = Origin->getValueSizeInBits(0);
7895 assert(Inst && "This slice is not bound to an instruction");
7896 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7897 "Extracted slice is bigger than the whole type!");
7898 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7899 UsedBits.setAllBits();
7900 UsedBits = UsedBits.zext(BitWidth);
7901 UsedBits <<= Shift;
7902 return UsedBits;
7903 }
7904
7905 /// \brief Get the size of the slice to be loaded in bytes.
7906 unsigned getLoadedSize() const {
7907 unsigned SliceSize = getUsedBits().countPopulation();
7908 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7909 return SliceSize / 8;
7910 }
7911
7912 /// \brief Get the type that will be loaded for this slice.
7913 /// Note: This may not be the final type for the slice.
7914 EVT getLoadedType() const {
7915 assert(DAG && "Missing context");
7916 LLVMContext &Ctxt = *DAG->getContext();
7917 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7918 }
7919
7920 /// \brief Get the alignment of the load used for this slice.
7921 unsigned getAlignment() const {
7922 unsigned Alignment = Origin->getAlignment();
7923 unsigned Offset = getOffsetFromBase();
7924 if (Offset != 0)
7925 Alignment = MinAlign(Alignment, Alignment + Offset);
7926 return Alignment;
7927 }
7928
7929 /// \brief Check if this slice can be rewritten with legal operations.
7930 bool isLegal() const {
7931 // An invalid slice is not legal.
7932 if (!Origin || !Inst || !DAG)
7933 return false;
7934
7935 // Offsets are for indexed load only, we do not handle that.
7936 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7937 return false;
7938
7939 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7940
7941 // Check that the type is legal.
7942 EVT SliceType = getLoadedType();
7943 if (!TLI.isTypeLegal(SliceType))
7944 return false;
7945
7946 // Check that the load is legal for this type.
7947 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7948 return false;
7949
7950 // Check that the offset can be computed.
7951 // 1. Check its type.
7952 EVT PtrType = Origin->getBasePtr().getValueType();
7953 if (PtrType == MVT::Untyped || PtrType.isExtended())
7954 return false;
7955
7956 // 2. Check that it fits in the immediate.
7957 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7958 return false;
7959
7960 // 3. Check that the computation is legal.
7961 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7962 return false;
7963
7964 // Check that the zext is legal if it needs one.
7965 EVT TruncateType = Inst->getValueType(0);
7966 if (TruncateType != SliceType &&
7967 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7968 return false;
7969
7970 return true;
7971 }
7972
7973 /// \brief Get the offset in bytes of this slice in the original chunk of
7974 /// bits.
7975 /// \pre DAG != NULL.
7976 uint64_t getOffsetFromBase() const {
7977 assert(DAG && "Missing context.");
7978 bool IsBigEndian =
7979 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7980 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7981 uint64_t Offset = Shift / 8;
7982 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7983 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7984 "The size of the original loaded type is not a multiple of a"
7985 " byte.");
7986 // If Offset is bigger than TySizeInBytes, it means we are loading all
7987 // zeros. This should have been optimized before in the process.
7988 assert(TySizeInBytes > Offset &&
7989 "Invalid shift amount for given loaded size");
7990 if (IsBigEndian)
7991 Offset = TySizeInBytes - Offset - getLoadedSize();
7992 return Offset;
7993 }
7994
7995 /// \brief Generate the sequence of instructions to load the slice
7996 /// represented by this object and redirect the uses of this slice to
7997 /// this new sequence of instructions.
7998 /// \pre this->Inst && this->Origin are valid Instructions and this
7999 /// object passed the legal check: LoadedSlice::isLegal returned true.
8000 /// \return The last instruction of the sequence used to load the slice.
8001 SDValue loadSlice() const {
8002 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8003 const SDValue &OldBaseAddr = Origin->getBasePtr();
8004 SDValue BaseAddr = OldBaseAddr;
8005 // Get the offset in that chunk of bytes w.r.t. the endianess.
8006 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8007 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8008 if (Offset) {
8009 // BaseAddr = BaseAddr + Offset.
8010 EVT ArithType = BaseAddr.getValueType();
8011 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8012 DAG->getConstant(Offset, ArithType));
8013 }
8014
8015 // Create the type of the loaded slice according to its size.
8016 EVT SliceType = getLoadedType();
8017
8018 // Create the load for the slice.
8019 SDValue LastInst = DAG->getLoad(
8020 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8021 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8022 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8023 // If the final type is not the same as the loaded type, this means that
8024 // we have to pad with zero. Create a zero extend for that.
8025 EVT FinalType = Inst->getValueType(0);
8026 if (SliceType != FinalType)
8027 LastInst =
8028 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8029 return LastInst;
8030 }
8031
8032 /// \brief Check if this slice can be merged with an expensive cross register
8033 /// bank copy. E.g.,
8034 /// i = load i32
8035 /// f = bitcast i32 i to float
8036 bool canMergeExpensiveCrossRegisterBankCopy() const {
8037 if (!Inst || !Inst->hasOneUse())
8038 return false;
8039 SDNode *Use = *Inst->use_begin();
8040 if (Use->getOpcode() != ISD::BITCAST)
8041 return false;
8042 assert(DAG && "Missing context");
8043 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8044 EVT ResVT = Use->getValueType(0);
8045 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8046 const TargetRegisterClass *ArgRC =
8047 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8048 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8049 return false;
8050
8051 // At this point, we know that we perform a cross-register-bank copy.
8052 // Check if it is expensive.
8053 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8054 // Assume bitcasts are cheap, unless both register classes do not
8055 // explicitly share a common sub class.
8056 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8057 return false;
8058
8059 // Check if it will be merged with the load.
8060 // 1. Check the alignment constraint.
8061 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8062 ResVT.getTypeForEVT(*DAG->getContext()));
8063
8064 if (RequiredAlignment > getAlignment())
8065 return false;
8066
8067 // 2. Check that the load is a legal operation for that type.
8068 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8069 return false;
8070
8071 // 3. Check that we do not have a zext in the way.
8072 if (Inst->getValueType(0) != getLoadedType())
8073 return false;
8074
8075 return true;
8076 }
8077};
8078}
8079
8080/// \brief Sorts LoadedSlice according to their offset.
8081struct LoadedSliceSorter {
8082 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
8083 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8084 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8085 }
8086};
8087
8088/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8089/// \p UsedBits looks like 0..0 1..1 0..0.
8090static bool areUsedBitsDense(const APInt &UsedBits) {
8091 // If all the bits are one, this is dense!
8092 if (UsedBits.isAllOnesValue())
8093 return true;
8094
8095 // Get rid of the unused bits on the right.
8096 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8097 // Get rid of the unused bits on the left.
8098 if (NarrowedUsedBits.countLeadingZeros())
8099 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8100 // Check that the chunk of bits is completely used.
8101 return NarrowedUsedBits.isAllOnesValue();
8102}
8103
8104/// \brief Check whether or not \p First and \p Second are next to each other
8105/// in memory. This means that there is no hole between the bits loaded
8106/// by \p First and the bits loaded by \p Second.
8107static bool areSlicesNextToEachOther(const LoadedSlice &First,
8108 const LoadedSlice &Second) {
8109 assert(First.Origin == Second.Origin && First.Origin &&
8110 "Unable to match different memory origins.");
8111 APInt UsedBits = First.getUsedBits();
8112 assert((UsedBits & Second.getUsedBits()) == 0 &&
8113 "Slices are not supposed to overlap.");
8114 UsedBits |= Second.getUsedBits();
8115 return areUsedBitsDense(UsedBits);
8116}
8117
8118/// \brief Adjust the \p GlobalLSCost according to the target
8119/// paring capabilities and the layout of the slices.
8120/// \pre \p GlobalLSCost should account for at least as many loads as
8121/// there is in the slices in \p LoadedSlices.
8122static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8123 LoadedSlice::Cost &GlobalLSCost) {
8124 unsigned NumberOfSlices = LoadedSlices.size();
8125 // If there is less than 2 elements, no pairing is possible.
8126 if (NumberOfSlices < 2)
8127 return;
8128
8129 // Sort the slices so that elements that are likely to be next to each
8130 // other in memory are next to each other in the list.
8131 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8132 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8133 // First (resp. Second) is the first (resp. Second) potentially candidate
8134 // to be placed in a paired load.
8135 const LoadedSlice *First = NULL;
8136 const LoadedSlice *Second = NULL;
8137 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8138 // Set the beginning of the pair.
8139 First = Second) {
8140
8141 Second = &LoadedSlices[CurrSlice];
8142
8143 // If First is NULL, it means we start a new pair.
8144 // Get to the next slice.
8145 if (!First)
8146 continue;
8147
8148 EVT LoadedType = First->getLoadedType();
8149
8150 // If the types of the slices are different, we cannot pair them.
8151 if (LoadedType != Second->getLoadedType())
8152 continue;
8153
8154 // Check if the target supplies paired loads for this type.
8155 unsigned RequiredAlignment = 0;
8156 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8157 // move to the next pair, this type is hopeless.
8158 Second = NULL;
8159 continue;
8160 }
8161 // Check if we meet the alignment requirement.
8162 if (RequiredAlignment > First->getAlignment())
8163 continue;
8164
8165 // Check that both loads are next to each other in memory.
8166 if (!areSlicesNextToEachOther(*First, *Second))
8167 continue;
8168
8169 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8170 --GlobalLSCost.Loads;
8171 // Move to the next pair.
8172 Second = NULL;
8173 }
8174}
8175
8176/// \brief Check the profitability of all involved LoadedSlice.
8177/// Currently, it is considered profitable if there is exactly two
8178/// involved slices (1) which are (2) next to each other in memory, and
8179/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8180///
8181/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8182/// the elements themselves.
8183///
8184/// FIXME: When the cost model will be mature enough, we can relax
8185/// constraints (1) and (2).
8186static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8187 const APInt &UsedBits, bool ForCodeSize) {
8188 unsigned NumberOfSlices = LoadedSlices.size();
8189 if (StressLoadSlicing)
8190 return NumberOfSlices > 1;
8191
8192 // Check (1).
8193 if (NumberOfSlices != 2)
8194 return false;
8195
8196 // Check (2).
8197 if (!areUsedBitsDense(UsedBits))
8198 return false;
8199
8200 // Check (3).
8201 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8202 // The original code has one big load.
8203 OrigCost.Loads = 1;
8204 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8205 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8206 // Accumulate the cost of all the slices.
8207 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8208 GlobalSlicingCost += SliceCost;
8209
8210 // Account as cost in the original configuration the gain obtained
8211 // with the current slices.
8212 OrigCost.addSliceGain(LS);
8213 }
8214
8215 // If the target supports paired load, adjust the cost accordingly.
8216 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8217 return OrigCost > GlobalSlicingCost;
8218}
8219
8220/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8221/// operations, split it in the various pieces being extracted.
8222///
8223/// This sort of thing is introduced by SROA.
8224/// This slicing takes care not to insert overlapping loads.
8225/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8226bool DAGCombiner::SliceUpLoad(SDNode *N) {
8227 if (Level < AfterLegalizeDAG)
8228 return false;
8229
8230 LoadSDNode *LD = cast<LoadSDNode>(N);
8231 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8232 !LD->getValueType(0).isInteger())
8233 return false;
8234
8235 // Keep track of already used bits to detect overlapping values.
8236 // In that case, we will just abort the transformation.
8237 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8238
8239 SmallVector<LoadedSlice, 4> LoadedSlices;
8240
8241 // Check if this load is used as several smaller chunks of bits.
8242 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8243 // of computation for each trunc.
8244 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8245 UI != UIEnd; ++UI) {
8246 // Skip the uses of the chain.
8247 if (UI.getUse().getResNo() != 0)
8248 continue;
8249
8250 SDNode *User = *UI;
8251 unsigned Shift = 0;
8252
8253 // Check if this is a trunc(lshr).
8254 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8255 isa<ConstantSDNode>(User->getOperand(1))) {
8256 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8257 User = *User->use_begin();
8258 }
8259
8260 // At this point, User is a Truncate, iff we encountered, trunc or
8261 // trunc(lshr).
8262 if (User->getOpcode() != ISD::TRUNCATE)
8263 return false;
8264
8265 // The width of the type must be a power of 2 and greater than 8-bits.
8266 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008267 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008268 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008269 unsigned Width = User->getValueSizeInBits(0);
8270 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8271 return 0;
8272
8273 // Build the slice for this chain of computations.
8274 LoadedSlice LS(User, LD, Shift, &DAG);
8275 APInt CurrentUsedBits = LS.getUsedBits();
8276
8277 // Check if this slice overlaps with another.
8278 if ((CurrentUsedBits & UsedBits) != 0)
8279 return false;
8280 // Update the bits used globally.
8281 UsedBits |= CurrentUsedBits;
8282
8283 // Check if the new slice would be legal.
8284 if (!LS.isLegal())
8285 return false;
8286
8287 // Record the slice.
8288 LoadedSlices.push_back(LS);
8289 }
8290
8291 // Abort slicing if it does not seem to be profitable.
8292 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8293 return false;
8294
8295 ++SlicedLoads;
8296
8297 // Rewrite each chain to use an independent load.
8298 // By construction, each chain can be represented by a unique load.
8299
8300 // Prepare the argument for the new token factor for all the slices.
8301 SmallVector<SDValue, 8> ArgChains;
8302 for (SmallVectorImpl<LoadedSlice>::const_iterator
8303 LSIt = LoadedSlices.begin(),
8304 LSItEnd = LoadedSlices.end();
8305 LSIt != LSItEnd; ++LSIt) {
8306 SDValue SliceInst = LSIt->loadSlice();
8307 CombineTo(LSIt->Inst, SliceInst, true);
8308 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8309 SliceInst = SliceInst.getOperand(0);
8310 assert(SliceInst->getOpcode() == ISD::LOAD &&
8311 "It takes more than a zext to get to the loaded slice!!");
8312 ArgChains.push_back(SliceInst.getValue(1));
8313 }
8314
8315 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8316 &ArgChains[0], ArgChains.size());
8317 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8318 return true;
8319}
8320
Chris Lattner4041ab62010-04-15 04:48:01 +00008321/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8322/// load is having specific bytes cleared out. If so, return the byte size
8323/// being masked out and the shift amount.
8324static std::pair<unsigned, unsigned>
8325CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8326 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008327
Chris Lattner4041ab62010-04-15 04:48:01 +00008328 // Check for the structure we're looking for.
8329 if (V->getOpcode() != ISD::AND ||
8330 !isa<ConstantSDNode>(V->getOperand(1)) ||
8331 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8332 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008333
Chris Lattner3245afd2010-04-15 06:10:49 +00008334 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008335 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008336 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008337
Chris Lattner3245afd2010-04-15 06:10:49 +00008338 // The store should be chained directly to the load or be an operand of a
8339 // tokenfactor.
8340 if (LD == Chain.getNode())
8341 ; // ok.
8342 else if (Chain->getOpcode() != ISD::TokenFactor)
8343 return Result; // Fail.
8344 else {
8345 bool isOk = false;
8346 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8347 if (Chain->getOperand(i).getNode() == LD) {
8348 isOk = true;
8349 break;
8350 }
8351 if (!isOk) return Result;
8352 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008353
Chris Lattner4041ab62010-04-15 04:48:01 +00008354 // This only handles simple types.
8355 if (V.getValueType() != MVT::i16 &&
8356 V.getValueType() != MVT::i32 &&
8357 V.getValueType() != MVT::i64)
8358 return Result;
8359
8360 // Check the constant mask. Invert it so that the bits being masked out are
8361 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8362 // follow the sign bit for uniformity.
8363 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008364 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008365 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008366 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008367 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8368 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008369
Chris Lattner4041ab62010-04-15 04:48:01 +00008370 // See if we have a continuous run of bits. If so, we have 0*1+0*
8371 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8372 return Result;
8373
8374 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8375 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8376 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008377
Chris Lattner4041ab62010-04-15 04:48:01 +00008378 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8379 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008380 case 1:
8381 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008382 case 4: break;
8383 default: return Result; // All one mask, or 5-byte mask.
8384 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008385
Chris Lattner4041ab62010-04-15 04:48:01 +00008386 // Verify that the first bit starts at a multiple of mask so that the access
8387 // is aligned the same as the access width.
8388 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008389
Chris Lattner4041ab62010-04-15 04:48:01 +00008390 Result.first = MaskedBytes;
8391 Result.second = NotMaskTZ/8;
8392 return Result;
8393}
8394
8395
8396/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8397/// provides a value as specified by MaskInfo. If so, replace the specified
8398/// store with a narrower store of truncated IVal.
8399static SDNode *
8400ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8401 SDValue IVal, StoreSDNode *St,
8402 DAGCombiner *DC) {
8403 unsigned NumBytes = MaskInfo.first;
8404 unsigned ByteShift = MaskInfo.second;
8405 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008406
Chris Lattner4041ab62010-04-15 04:48:01 +00008407 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8408 // that uses this. If not, this is not a replacement.
8409 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8410 ByteShift*8, (ByteShift+NumBytes)*8);
8411 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00008412
Chris Lattner4041ab62010-04-15 04:48:01 +00008413 // Check that it is legal on the target to do this. It is legal if the new
8414 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8415 // legalization.
8416 MVT VT = MVT::getIntegerVT(NumBytes*8);
8417 if (!DC->isTypeLegal(VT))
8418 return 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00008419
Chris Lattner4041ab62010-04-15 04:48:01 +00008420 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8421 // shifted by ByteShift and truncated down to NumBytes.
8422 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008423 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008424 DAG.getConstant(ByteShift*8,
8425 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008426
8427 // Figure out the offset for the store and the alignment of the access.
8428 unsigned StOffset;
8429 unsigned NewAlign = St->getAlignment();
8430
8431 if (DAG.getTargetLoweringInfo().isLittleEndian())
8432 StOffset = ByteShift;
8433 else
8434 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008435
Chris Lattner4041ab62010-04-15 04:48:01 +00008436 SDValue Ptr = St->getBasePtr();
8437 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008438 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008439 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8440 NewAlign = MinAlign(NewAlign, StOffset);
8441 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008442
Chris Lattner4041ab62010-04-15 04:48:01 +00008443 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008444 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008445
Chris Lattner4041ab62010-04-15 04:48:01 +00008446 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008447 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008448 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008449 false, false, NewAlign).getNode();
8450}
8451
Evan Chenga9cda8a2009-05-28 00:35:15 +00008452
8453/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8454/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8455/// of the loaded bits, try narrowing the load and store if it would end up
8456/// being a win for performance or code size.
8457SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8458 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008459 if (ST->isVolatile())
8460 return SDValue();
8461
Evan Chenga9cda8a2009-05-28 00:35:15 +00008462 SDValue Chain = ST->getChain();
8463 SDValue Value = ST->getValue();
8464 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008465 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008466
8467 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008468 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008469
8470 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008471
Chris Lattner4041ab62010-04-15 04:48:01 +00008472 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8473 // is a byte mask indicating a consecutive number of bytes, check to see if
8474 // Y is known to provide just those bytes. If so, we try to replace the
8475 // load + replace + store sequence with a single (narrower) store, which makes
8476 // the load dead.
8477 if (Opc == ISD::OR) {
8478 std::pair<unsigned, unsigned> MaskedLoad;
8479 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8480 if (MaskedLoad.first)
8481 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8482 Value.getOperand(1), ST,this))
8483 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008484
Chris Lattner4041ab62010-04-15 04:48:01 +00008485 // Or is commutative, so try swapping X and Y.
8486 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8487 if (MaskedLoad.first)
8488 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8489 Value.getOperand(0), ST,this))
8490 return SDValue(NewST, 0);
8491 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008492
Evan Chenga9cda8a2009-05-28 00:35:15 +00008493 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8494 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008495 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008496
8497 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008498 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8499 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008500 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008501 if (LD->getBasePtr() != Ptr ||
8502 LD->getPointerInfo().getAddrSpace() !=
8503 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008504 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008505
8506 // Find the type to narrow it the load / op / store to.
8507 SDValue N1 = Value.getOperand(1);
8508 unsigned BitWidth = N1.getValueSizeInBits();
8509 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8510 if (Opc == ISD::AND)
8511 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008512 if (Imm == 0 || Imm.isAllOnesValue())
8513 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008514 unsigned ShAmt = Imm.countTrailingZeros();
8515 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8516 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008517 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008518 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008519 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008520 TLI.isNarrowingProfitable(VT, NewVT))) {
8521 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008522 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008523 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008524 if (NewBW >= BitWidth)
8525 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008526
8527 // If the lsb changed does not start at the type bitwidth boundary,
8528 // start at the previous one.
8529 if (ShAmt % NewBW)
8530 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008531 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8532 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008533 if ((Imm & Mask) == Imm) {
8534 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8535 if (Opc == ISD::AND)
8536 NewImm ^= APInt::getAllOnesValue(NewBW);
8537 uint64_t PtrOff = ShAmt / 8;
8538 // For big endian targets, we need to adjust the offset to the pointer to
8539 // load the correct bytes.
8540 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008541 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008542
8543 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008544 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008545 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008546 return SDValue();
8547
Andrew Trickef9de2a2013-05-25 02:42:55 +00008548 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008549 Ptr.getValueType(), Ptr,
8550 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008551 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008552 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008553 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008554 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008555 LD->isInvariant(), NewAlign,
8556 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008557 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008558 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008559 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008560 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008561 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008562 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008563
8564 AddToWorkList(NewPtr.getNode());
8565 AddToWorkList(NewLD.getNode());
8566 AddToWorkList(NewVal.getNode());
8567 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008568 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008569 ++OpsNarrowed;
8570 return NewST;
8571 }
8572 }
8573
Evan Cheng6673ff02009-05-28 18:41:02 +00008574 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008575}
8576
Evan Chengd42641c2011-02-02 01:06:55 +00008577/// TransformFPLoadStorePair - For a given floating point load / store pair,
8578/// if the load value isn't used by any other operations, then consider
8579/// transforming the pair to integer load / store operations if the target
8580/// deems the transformation profitable.
8581SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8582 StoreSDNode *ST = cast<StoreSDNode>(N);
8583 SDValue Chain = ST->getChain();
8584 SDValue Value = ST->getValue();
8585 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8586 Value.hasOneUse() &&
8587 Chain == SDValue(Value.getNode(), 1)) {
8588 LoadSDNode *LD = cast<LoadSDNode>(Value);
8589 EVT VT = LD->getMemoryVT();
8590 if (!VT.isFloatingPoint() ||
8591 VT != ST->getMemoryVT() ||
8592 LD->isNonTemporal() ||
8593 ST->isNonTemporal() ||
8594 LD->getPointerInfo().getAddrSpace() != 0 ||
8595 ST->getPointerInfo().getAddrSpace() != 0)
8596 return SDValue();
8597
8598 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8599 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8600 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8601 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8602 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8603 return SDValue();
8604
8605 unsigned LDAlign = LD->getAlignment();
8606 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008607 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008608 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008609 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8610 return SDValue();
8611
Andrew Trickef9de2a2013-05-25 02:42:55 +00008612 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008613 LD->getChain(), LD->getBasePtr(),
8614 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008615 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008616
Andrew Trickef9de2a2013-05-25 02:42:55 +00008617 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008618 NewLD, ST->getBasePtr(),
8619 ST->getPointerInfo(),
8620 false, false, STAlign);
8621
8622 AddToWorkList(NewLD.getNode());
8623 AddToWorkList(NewST.getNode());
8624 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008625 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008626 ++LdStFP2Int;
8627 return NewST;
8628 }
8629
8630 return SDValue();
8631}
8632
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008633/// Helper struct to parse and store a memory address as base + index + offset.
8634/// We ignore sign extensions when it is safe to do so.
8635/// The following two expressions are not equivalent. To differentiate we need
8636/// to store whether there was a sign extension involved in the index
8637/// computation.
8638/// (load (i64 add (i64 copyfromreg %c)
8639/// (i64 signextend (add (i8 load %index)
8640/// (i8 1))))
8641/// vs
8642///
8643/// (load (i64 add (i64 copyfromreg %c)
8644/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8645/// (i32 1)))))
8646struct BaseIndexOffset {
8647 SDValue Base;
8648 SDValue Index;
8649 int64_t Offset;
8650 bool IsIndexSignExt;
8651
8652 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8653
8654 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8655 bool IsIndexSignExt) :
8656 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8657
8658 bool equalBaseIndex(const BaseIndexOffset &Other) {
8659 return Other.Base == Base && Other.Index == Index &&
8660 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008661 }
8662
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008663 /// Parses tree in Ptr for base, index, offset addresses.
8664 static BaseIndexOffset match(SDValue Ptr) {
8665 bool IsIndexSignExt = false;
8666
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008667 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8668 // instruction, then it could be just the BASE or everything else we don't
8669 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008670 if (Ptr->getOpcode() != ISD::ADD)
8671 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8672
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008673 // We know that we have at least an ADD instruction. Try to pattern match
8674 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008675 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8676 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8677 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8678 IsIndexSignExt);
8679 }
8680
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008681 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008682 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008683 // (i64 add (i64 %array_ptr)
8684 // (i64 mul (i64 %induction_var)
8685 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008686 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008687 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008688
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008689 // Look at Base + Index + Offset cases.
8690 SDValue Base = Ptr->getOperand(0);
8691 SDValue IndexOffset = Ptr->getOperand(1);
8692
8693 // Skip signextends.
8694 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8695 IndexOffset = IndexOffset->getOperand(0);
8696 IsIndexSignExt = true;
8697 }
8698
8699 // Either the case of Base + Index (no offset) or something else.
8700 if (IndexOffset->getOpcode() != ISD::ADD)
8701 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8702
8703 // Now we have the case of Base + Index + offset.
8704 SDValue Index = IndexOffset->getOperand(0);
8705 SDValue Offset = IndexOffset->getOperand(1);
8706
8707 if (!isa<ConstantSDNode>(Offset))
8708 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8709
8710 // Ignore signextends.
8711 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8712 Index = Index->getOperand(0);
8713 IsIndexSignExt = true;
8714 } else IsIndexSignExt = false;
8715
8716 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8717 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8718 }
8719};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008720
8721/// Holds a pointer to an LSBaseSDNode as well as information on where it
8722/// is located in a sequence of memory operations connected by a chain.
8723struct MemOpLink {
8724 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8725 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8726 // Ptr to the mem node.
8727 LSBaseSDNode *MemNode;
8728 // Offset from the base ptr.
8729 int64_t OffsetFromBase;
8730 // What is the sequence number of this mem node.
8731 // Lowest mem operand in the DAG starts at zero.
8732 unsigned SequenceNum;
8733};
8734
8735/// Sorts store nodes in a link according to their offset from a shared
8736// base ptr.
8737struct ConsecutiveMemoryChainSorter {
8738 bool operator()(MemOpLink LHS, MemOpLink RHS) {
8739 return LHS.OffsetFromBase < RHS.OffsetFromBase;
8740 }
8741};
8742
8743bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8744 EVT MemVT = St->getMemoryVT();
8745 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00008746 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8747 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008748
8749 // Don't merge vectors into wider inputs.
8750 if (MemVT.isVector() || !MemVT.isSimple())
8751 return false;
8752
8753 // Perform an early exit check. Do not bother looking at stored values that
8754 // are not constants or loads.
8755 SDValue StoredVal = St->getValue();
8756 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8757 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8758 !IsLoadSrc)
8759 return false;
8760
8761 // Only look at ends of store sequences.
8762 SDValue Chain = SDValue(St, 1);
8763 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8764 return false;
8765
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008766 // This holds the base pointer, index, and the offset in bytes from the base
8767 // pointer.
8768 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008769
8770 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008771 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008772 return false;
8773
8774 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008775 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008776 return false;
8777
Nadav Rotem307d7672012-11-29 00:00:08 +00008778 // Save the LoadSDNodes that we find in the chain.
8779 // We need to make sure that these nodes do not interfere with
8780 // any of the store nodes.
8781 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8782
8783 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008784 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00008785
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008786 // Walk up the chain and look for nodes with offsets from the same
8787 // base pointer. Stop when reaching an instruction with a different kind
8788 // or instruction which has a different base pointer.
8789 unsigned Seq = 0;
8790 StoreSDNode *Index = St;
8791 while (Index) {
8792 // If the chain has more than one use, then we can't reorder the mem ops.
8793 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8794 break;
8795
8796 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008797 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008798
8799 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008800 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008801 break;
8802
8803 // Check that the alignment is the same.
8804 if (Index->getAlignment() != St->getAlignment())
8805 break;
8806
8807 // The memory operands must not be volatile.
8808 if (Index->isVolatile() || Index->isIndexed())
8809 break;
8810
8811 // No truncation.
8812 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8813 if (St->isTruncatingStore())
8814 break;
8815
8816 // The stored memory type must be the same.
8817 if (Index->getMemoryVT() != MemVT)
8818 break;
8819
8820 // We do not allow unaligned stores because we want to prevent overriding
8821 // stores.
8822 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8823 break;
8824
8825 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008826 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008827
Nadav Rotem307d7672012-11-29 00:00:08 +00008828 // Find the next memory operand in the chain. If the next operand in the
8829 // chain is a store then move up and continue the scan with the next
8830 // memory operand. If the next operand is a load save it and use alias
8831 // information to check if it interferes with anything.
8832 SDNode *NextInChain = Index->getChain().getNode();
8833 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00008834 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00008835 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00008836 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00008837 break;
8838 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00008839 if (Ldn->isVolatile()) {
8840 Index = NULL;
8841 break;
8842 }
8843
Nadav Rotem307d7672012-11-29 00:00:08 +00008844 // Save the load node for later. Continue the scan.
8845 AliasLoadNodes.push_back(Ldn);
8846 NextInChain = Ldn->getChain().getNode();
8847 continue;
8848 } else {
8849 Index = NULL;
8850 break;
8851 }
8852 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008853 }
8854
8855 // Check if there is anything to merge.
8856 if (StoreNodes.size() < 2)
8857 return false;
8858
8859 // Sort the memory operands according to their distance from the base pointer.
8860 std::sort(StoreNodes.begin(), StoreNodes.end(),
8861 ConsecutiveMemoryChainSorter());
8862
8863 // Scan the memory operations on the chain and find the first non-consecutive
8864 // store memory address.
8865 unsigned LastConsecutiveStore = 0;
8866 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00008867 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8868
8869 // Check that the addresses are consecutive starting from the second
8870 // element in the list of stores.
8871 if (i > 0) {
8872 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8873 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8874 break;
8875 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008876
Nadav Rotem307d7672012-11-29 00:00:08 +00008877 bool Alias = false;
8878 // Check if this store interferes with any of the loads that we found.
8879 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8880 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8881 Alias = true;
8882 break;
8883 }
Nadav Rotem307d7672012-11-29 00:00:08 +00008884 // We found a load that alias with this store. Stop the sequence.
8885 if (Alias)
8886 break;
8887
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008888 // Mark this node as useful.
8889 LastConsecutiveStore = i;
8890 }
8891
8892 // The node with the lowest store address.
8893 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8894
8895 // Store the constants into memory as one consecutive store.
8896 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008897 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00008898 unsigned LastLegalVectorType = 0;
8899 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008900 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8901 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8902 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00008903
8904 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00008905 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00008906 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00008907 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00008908 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00008909 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008910 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00008911 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008912
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008913 // Find a legal type for the constant store.
8914 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8915 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8916 if (TLI.isTypeLegal(StoreTy))
8917 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00008918 // Or check whether a truncstore is legal.
8919 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8920 TargetLowering::TypePromoteInteger) {
8921 EVT LegalizedStoredValueTy =
8922 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8923 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8924 LastLegalType = i+1;
8925 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00008926
8927 // Find a legal type for the vector store.
8928 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8929 if (TLI.isTypeLegal(Ty))
8930 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008931 }
8932
Bob Wilson3365b802012-12-20 01:36:20 +00008933 // We only use vectors if the constant is known to be zero and the
8934 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00008935 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00008936 LastLegalVectorType = 0;
8937
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008938 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00008939 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008940 return false;
8941
Nadav Rotem495b1a42013-02-14 18:28:52 +00008942 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00008943 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8944
8945 // Make sure we have something to merge.
8946 if (NumElem < 2)
8947 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008948
8949 unsigned EarliestNodeUsed = 0;
8950 for (unsigned i=0; i < NumElem; ++i) {
8951 // Find a chain for the new wide-store operand. Notice that some
8952 // of the store nodes that we found may not be selected for inclusion
8953 // in the wide store. The chain we use needs to be the chain of the
8954 // earliest store node which is *used* and replaced by the wide store.
8955 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8956 EarliestNodeUsed = i;
8957 }
8958
8959 // The earliest Node in the DAG.
8960 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008961 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008962
Nadav Rotemb27777f2012-10-04 22:35:15 +00008963 SDValue StoredVal;
8964 if (UseVector) {
8965 // Find a legal type for the vector store.
8966 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8967 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8968 StoredVal = DAG.getConstant(0, Ty);
8969 } else {
8970 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8971 APInt StoreInt(StoreBW, 0);
8972
8973 // Construct a single integer constant which is made of the smaller
8974 // constant inputs.
8975 bool IsLE = TLI.isLittleEndian();
8976 for (unsigned i = 0; i < NumElem ; ++i) {
8977 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8978 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8979 SDValue Val = St->getValue();
8980 StoreInt<<=ElementSizeBytes*8;
8981 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8982 StoreInt|=C->getAPIntValue().zext(StoreBW);
8983 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8984 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8985 } else {
8986 assert(false && "Invalid constant element type");
8987 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008988 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00008989
8990 // Create the new Load and Store operations.
8991 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8992 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008993 }
8994
Nadav Rotemb27777f2012-10-04 22:35:15 +00008995 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008996 FirstInChain->getBasePtr(),
8997 FirstInChain->getPointerInfo(),
8998 false, false,
8999 FirstInChain->getAlignment());
9000
9001 // Replace the first store with the new store
9002 CombineTo(EarliestOp, NewStore);
9003 // Erase all other stores.
9004 for (unsigned i = 0; i < NumElem ; ++i) {
9005 if (StoreNodes[i].MemNode == EarliestOp)
9006 continue;
9007 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009008 // ReplaceAllUsesWith will replace all uses that existed when it was
9009 // called, but graph optimizations may cause new ones to appear. For
9010 // example, the case in pr14333 looks like
9011 //
9012 // St's chain -> St -> another store -> X
9013 //
9014 // And the only difference from St to the other store is the chain.
9015 // When we change it's chain to be St's chain they become identical,
9016 // get CSEed and the net result is that X is now a use of St.
9017 // Since we know that St is redundant, just iterate.
9018 while (!St->use_empty())
9019 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009020 removeFromWorkList(St);
9021 DAG.DeleteNode(St);
9022 }
9023
9024 return true;
9025 }
9026
9027 // Below we handle the case of multiple consecutive stores that
9028 // come from multiple consecutive loads. We merge them into a single
9029 // wide load and a single wide store.
9030
9031 // Look for load nodes which are used by the stored values.
9032 SmallVector<MemOpLink, 8> LoadNodes;
9033
9034 // Find acceptable loads. Loads need to have the same chain (token factor),
9035 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009036 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009037 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9038 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9039 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9040 if (!Ld) break;
9041
9042 // Loads must only have one use.
9043 if (!Ld->hasNUsesOfValue(1, 0))
9044 break;
9045
9046 // Check that the alignment is the same as the stores.
9047 if (Ld->getAlignment() != St->getAlignment())
9048 break;
9049
9050 // The memory operands must not be volatile.
9051 if (Ld->isVolatile() || Ld->isIndexed())
9052 break;
9053
9054 // We do not accept ext loads.
9055 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9056 break;
9057
9058 // The stored memory type must be the same.
9059 if (Ld->getMemoryVT() != MemVT)
9060 break;
9061
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009062 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009063 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009064 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009065 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009066 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009067 break;
9068 } else {
9069 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009070 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009071 }
9072
9073 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009074 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009075 }
9076
9077 if (LoadNodes.size() < 2)
9078 return false;
9079
9080 // Scan the memory operations on the chain and find the first non-consecutive
9081 // load memory address. These variables hold the index in the store node
9082 // array.
9083 unsigned LastConsecutiveLoad = 0;
9084 // This variable refers to the size and not index in the array.
9085 unsigned LastLegalVectorType = 0;
9086 unsigned LastLegalIntegerType = 0;
9087 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009088 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9089 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9090 // All loads much share the same chain.
9091 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9092 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009093
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009094 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9095 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9096 break;
9097 LastConsecutiveLoad = i;
9098
9099 // Find a legal type for the vector store.
9100 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9101 if (TLI.isTypeLegal(StoreTy))
9102 LastLegalVectorType = i + 1;
9103
9104 // Find a legal type for the integer store.
9105 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9106 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9107 if (TLI.isTypeLegal(StoreTy))
9108 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009109 // Or check whether a truncstore and extload is legal.
9110 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9111 TargetLowering::TypePromoteInteger) {
9112 EVT LegalizedStoredValueTy =
9113 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9114 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9115 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9116 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9117 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9118 LastLegalIntegerType = i+1;
9119 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009120 }
9121
9122 // Only use vector types if the vector type is larger than the integer type.
9123 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009124 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009125 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9126
9127 // We add +1 here because the LastXXX variables refer to location while
9128 // the NumElem refers to array/index size.
9129 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9130 NumElem = std::min(LastLegalType, NumElem);
9131
9132 if (NumElem < 2)
9133 return false;
9134
9135 // The earliest Node in the DAG.
9136 unsigned EarliestNodeUsed = 0;
9137 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9138 for (unsigned i=1; i<NumElem; ++i) {
9139 // Find a chain for the new wide-store operand. Notice that some
9140 // of the store nodes that we found may not be selected for inclusion
9141 // in the wide store. The chain we use needs to be the chain of the
9142 // earliest store node which is *used* and replaced by the wide store.
9143 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9144 EarliestNodeUsed = i;
9145 }
9146
9147 // Find if it is better to use vectors or integers to load and store
9148 // to memory.
9149 EVT JointMemOpVT;
9150 if (UseVectorTy) {
9151 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9152 } else {
9153 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9154 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9155 }
9156
Andrew Trickef9de2a2013-05-25 02:42:55 +00009157 SDLoc LoadDL(LoadNodes[0].MemNode);
9158 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009159
9160 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9161 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9162 FirstLoad->getChain(),
9163 FirstLoad->getBasePtr(),
9164 FirstLoad->getPointerInfo(),
9165 false, false, false,
9166 FirstLoad->getAlignment());
9167
9168 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9169 FirstInChain->getBasePtr(),
9170 FirstInChain->getPointerInfo(), false, false,
9171 FirstInChain->getAlignment());
9172
Nadav Rotemac920662012-10-03 19:30:31 +00009173 // Replace one of the loads with the new load.
9174 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9175 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9176 SDValue(NewLoad.getNode(), 1));
9177
9178 // Remove the rest of the load chains.
9179 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009180 // Replace all chain users of the old load nodes with the chain of the new
9181 // load node.
9182 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009183 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9184 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009185
Nadav Rotemac920662012-10-03 19:30:31 +00009186 // Replace the first store with the new store.
9187 CombineTo(EarliestOp, NewStore);
9188 // Erase all other stores.
9189 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009190 // Remove all Store nodes.
9191 if (StoreNodes[i].MemNode == EarliestOp)
9192 continue;
9193 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9194 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9195 removeFromWorkList(St);
9196 DAG.DeleteNode(St);
9197 }
9198
9199 return true;
9200}
9201
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009202SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009203 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009204 SDValue Chain = ST->getChain();
9205 SDValue Value = ST->getValue();
9206 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009207
Evan Chenga4cf58a2007-05-07 21:27:48 +00009208 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009209 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009210 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009211 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009212 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009213 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009214 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009215 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009216 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009217 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009218 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009219 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009220 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009221 ST->isNonTemporal(), OrigAlign,
9222 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009223 }
Owen Andersona5192842011-04-14 17:30:49 +00009224
Chris Lattner41c80e82011-04-09 02:32:02 +00009225 // Turn 'store undef, Ptr' -> nothing.
9226 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9227 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009228
Nate Begeman8e20c762006-12-11 02:23:46 +00009229 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009230 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009231 // NOTE: If the original store is volatile, this transform must not increase
9232 // the number of stores. For example, on x86-32 an f64 can be stored in one
9233 // processor operation but an i64 (which is not legal) requires two. So the
9234 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009235 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009236 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009237 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009238 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009239 case MVT::f16: // We don't do this for these yet.
9240 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009241 case MVT::f128:
9242 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009243 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009244 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009245 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009246 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009247 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009248 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009249 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009250 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009251 }
9252 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009253 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009254 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009255 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009256 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009257 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009258 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009259 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009260 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009261 }
Owen Andersona5192842011-04-14 17:30:49 +00009262
Chris Lattner41c80e82011-04-09 02:32:02 +00009263 if (!ST->isVolatile() &&
9264 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009265 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009266 // argument passing. Since this is so common, custom legalize the
9267 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009268 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009269 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9270 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009271 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009272
Dan Gohman2af30632007-07-09 22:18:38 +00009273 unsigned Alignment = ST->getAlignment();
9274 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009275 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009276 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009277
Andrew Trickef9de2a2013-05-25 02:42:55 +00009278 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009279 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009280 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009281 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009282 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009283 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009284 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009285 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009286 Ptr, ST->getPointerInfo().getWithOffset(4),
9287 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009288 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009289 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009290 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009291 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009292
Chris Lattnerb7524b62006-12-12 04:16:14 +00009293 break;
Evan Cheng21836982006-12-11 17:25:19 +00009294 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009295 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009296 }
9297
Evan Cheng43cd9e32010-04-01 06:04:33 +00009298 // Try to infer better alignment information than the store already has.
9299 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009300 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9301 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009302 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009303 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009304 ST->isVolatile(), ST->isNonTemporal(), Align,
9305 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009306 }
9307 }
9308
Evan Chengd42641c2011-02-02 01:06:55 +00009309 // Try transforming a pair floating point load / store ops to integer
9310 // load / store ops.
9311 SDValue NewST = TransformFPLoadStorePair(N);
9312 if (NewST.getNode())
9313 return NewST;
9314
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009315 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9316 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkelccc18e12014-01-24 18:25:26 +00009317 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009318 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009319 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009320
Jim Laskey708d0db2006-10-04 16:53:27 +00009321 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009322 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009323 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009324
9325 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009326 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009327 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009328 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009329 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009330 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009331 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009332 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009333
Jim Laskeyd07be232006-09-25 16:29:54 +00009334 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009335 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009336 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009337
Nate Begeman879d8f12009-09-15 00:18:30 +00009338 // Make sure the new and old chains are cleaned up.
9339 AddToWorkList(Token.getNode());
9340
Jim Laskeydcf983c2006-10-13 23:32:28 +00009341 // Don't add users to work list.
9342 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009343 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009344 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009345
Evan Cheng33157702006-11-05 09:31:14 +00009346 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009347 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009348 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009349
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009350 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009351 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009352 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009353 // See if we can simplify the input to this truncstore with knowledge that
9354 // only the low bits are being used. For example:
9355 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009356 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009357 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009358 APInt::getLowBitsSet(
9359 Value.getValueType().getScalarType().getSizeInBits(),
9360 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00009361 AddToWorkList(Value.getNode());
9362 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009363 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009364 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009365
Chris Lattnerf47e3062007-10-13 06:58:48 +00009366 // Otherwise, see if we can simplify the operation with
9367 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009368 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009369 APInt::getLowBitsSet(
9370 Value.getValueType().getScalarType().getSizeInBits(),
9371 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009372 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009373 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009374
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009375 // If this is a load followed by a store to the same location, then the store
9376 // is dead/noop.
9377 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009378 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009379 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009380 // There can't be any side effects between the load and store, such as
9381 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009382 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009383 // The store is dead, remove it.
9384 return Chain;
9385 }
9386 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009387
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009388 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9389 // truncating store. We can do this even if this is already a truncstore.
9390 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009391 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009392 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009393 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009394 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009395 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009396 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009397
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009398 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009399 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009400 if (!LegalTypes) {
9401 bool EverChanged = false;
9402
9403 do {
9404 // There can be multiple store sequences on the same chain.
9405 // Keep trying to merge store sequences until we are unable to do so
9406 // or until we merge the last store on the chain.
9407 bool Changed = MergeConsecutiveStores(ST);
9408 EverChanged |= Changed;
9409 if (!Changed) break;
9410 } while (ST->getOpcode() != ISD::DELETED_NODE);
9411
9412 if (EverChanged)
9413 return SDValue(N, 0);
9414 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009415
Evan Chenga9cda8a2009-05-28 00:35:15 +00009416 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009417}
9418
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009419SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9420 SDValue InVec = N->getOperand(0);
9421 SDValue InVal = N->getOperand(1);
9422 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009423 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009424
Bob Wilson42603952010-05-19 23:42:58 +00009425 // If the inserted element is an UNDEF, just use the input vector.
9426 if (InVal.getOpcode() == ISD::UNDEF)
9427 return InVec;
9428
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009429 EVT VT = InVec.getValueType();
9430
Owen Andersonb2c80da2011-02-25 21:41:48 +00009431 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009432 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9433 return SDValue();
9434
Eli Friedmanb7910b72011-09-09 21:04:06 +00009435 // Check that we know which element is being inserted
9436 if (!isa<ConstantSDNode>(EltNo))
9437 return SDValue();
9438 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009439
Eli Friedmanb7910b72011-09-09 21:04:06 +00009440 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9441 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9442 // vector elements.
9443 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009444 // Do not combine these two vectors if the output vector will not replace
9445 // the input vector.
9446 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009447 Ops.append(InVec.getNode()->op_begin(),
9448 InVec.getNode()->op_end());
9449 } else if (InVec.getOpcode() == ISD::UNDEF) {
9450 unsigned NElts = VT.getVectorNumElements();
9451 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9452 } else {
9453 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009454 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009455
9456 // Insert the element
9457 if (Elt < Ops.size()) {
9458 // All the operands of BUILD_VECTOR must have the same type;
9459 // we enforce that here.
9460 EVT OpVT = Ops[0].getValueType();
9461 if (InVal.getValueType() != OpVT)
9462 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9463 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9464 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9465 Ops[Elt] = InVal;
9466 }
9467
9468 // Return the new vector
9469 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9470 VT, &Ops[0], Ops.size());
Chris Lattner5336a592006-03-19 01:27:56 +00009471}
9472
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009473SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009474 // (vextract (scalar_to_vector val, 0) -> val
9475 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009476 EVT VT = InVec.getValueType();
9477 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009478
Duncan Sands6be291a2011-05-09 08:03:33 +00009479 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9480 // Check if the result type doesn't match the inserted element type. A
9481 // SCALAR_TO_VECTOR may truncate the inserted element and the
9482 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9483 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009484 if (InOp.getValueType() != NVT) {
9485 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009486 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009487 }
9488 return InOp;
9489 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009490
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009491 SDValue EltNo = N->getOperand(1);
9492 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9493
9494 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9495 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009496 // we may introduce new vector instructions which are not backed by TD
9497 // patterns. For example on AVX, extracting elements from a wide vector
9498 // without using extract_subvector.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009499 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9500 && ConstEltNo && !LegalOperations) {
9501 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9502 int NumElem = VT.getVectorNumElements();
9503 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9504 // Find the new index to extract from.
9505 int OrigElt = SVOp->getMaskElt(Elt);
9506
9507 // Extracting an undef index is undef.
9508 if (OrigElt == -1)
9509 return DAG.getUNDEF(NVT);
9510
9511 // Select the right vector half to extract from.
9512 if (OrigElt < NumElem) {
9513 InVec = InVec->getOperand(0);
9514 } else {
9515 InVec = InVec->getOperand(1);
9516 OrigElt -= NumElem;
9517 }
9518
Tom Stellardd42c5942013-08-05 22:22:01 +00009519 EVT IndexTy = TLI.getVectorIdxTy();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009520 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00009521 InVec, DAG.getConstant(OrigElt, IndexTy));
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009522 }
9523
Evan Cheng1120279a2008-05-13 08:35:03 +00009524 // Perform only after legalization to ensure build_vector / vector_shuffle
9525 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009526 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009527
Mon P Wangca6d6de2009-01-17 00:07:25 +00009528 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9529 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9530 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009531
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009532 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009533 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009534 bool NewLoad = false;
Mon P Wangb5eb7202008-12-11 00:26:16 +00009535 bool BCNumEltsChanged = false;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009536 EVT ExtVT = VT.getVectorElementType();
9537 EVT LVT = ExtVT;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009538
Evan Cheng7bf83092012-03-13 22:00:52 +00009539 // If the result of load has to be truncated, then it's not necessarily
9540 // profitable.
Evan Chengd5f8e572012-03-13 22:16:11 +00009541 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
Evan Cheng7bf83092012-03-13 22:00:52 +00009542 return SDValue();
9543
Wesley Peck527da1b2010-11-23 03:31:01 +00009544 if (InVec.getOpcode() == ISD::BITCAST) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009545 // Don't duplicate a load with other uses.
9546 if (!InVec.hasOneUse())
9547 return SDValue();
9548
Owen Anderson53aa7a92009-08-10 22:56:29 +00009549 EVT BCVT = InVec.getOperand(0).getValueType();
9550 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009551 return SDValue();
Mon P Wangb5eb7202008-12-11 00:26:16 +00009552 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9553 BCNumEltsChanged = true;
Evan Cheng1120279a2008-05-13 08:35:03 +00009554 InVec = InVec.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009555 ExtVT = BCVT.getVectorElementType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009556 NewLoad = true;
9557 }
Evan Cheng0de312d2007-10-06 08:19:55 +00009558
Evan Cheng1120279a2008-05-13 08:35:03 +00009559 LoadSDNode *LN0 = NULL;
Nate Begeman5f829d82009-04-29 05:20:52 +00009560 const ShuffleVectorSDNode *SVN = NULL;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009561 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009562 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009563 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009564 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009565 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009566 // Don't duplicate a load with other uses.
9567 if (!InVec.hasOneUse())
9568 return SDValue();
9569
Evan Cheng1120279a2008-05-13 08:35:03 +00009570 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009571 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009572 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9573 // =>
9574 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009575
Eli Friedmane96286c2011-12-26 22:49:32 +00009576 // Don't duplicate a load with other uses.
9577 if (!InVec.hasOneUse())
9578 return SDValue();
9579
Mon P Wangb5eb7202008-12-11 00:26:16 +00009580 // If the bit convert changed the number of elements, it is unsafe
9581 // to examine the mask.
9582 if (BCNumEltsChanged)
9583 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009584
9585 // Select the input vector, guarding against out of range extract vector.
9586 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009587 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009588 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9589
Eli Friedmane96286c2011-12-26 22:49:32 +00009590 if (InVec.getOpcode() == ISD::BITCAST) {
9591 // Don't duplicate a load with other uses.
9592 if (!InVec.hasOneUse())
9593 return SDValue();
9594
Evan Cheng1120279a2008-05-13 08:35:03 +00009595 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +00009596 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00009597 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009598 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +00009599 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng0de312d2007-10-06 08:19:55 +00009600 }
9601 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009602
Eli Friedmane96286c2011-12-26 22:49:32 +00009603 // Make sure we found a non-volatile load and the extractelement is
9604 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +00009605 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009606 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009607
Eric Christopherc6418b12010-11-03 20:44:42 +00009608 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9609 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +00009610 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +00009611
Evan Cheng1120279a2008-05-13 08:35:03 +00009612 unsigned Align = LN0->getAlignment();
9613 if (NewLoad) {
9614 // Check the resultant load doesn't need a higher alignment than the
9615 // original load.
Bill Wendling27d9dd42009-01-30 23:36:47 +00009616 unsigned NewAlign =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009617 TLI.getDataLayout()
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009618 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
Bill Wendling27d9dd42009-01-30 23:36:47 +00009619
Dan Gohman4aa18462009-01-28 17:46:25 +00009620 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009621 return SDValue();
Bill Wendling27d9dd42009-01-30 23:36:47 +00009622
Evan Cheng1120279a2008-05-13 08:35:03 +00009623 Align = NewAlign;
9624 }
9625
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009626 SDValue NewPtr = LN0->getBasePtr();
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009627 unsigned PtrOff = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00009628
Eric Christopherc6418b12010-11-03 20:44:42 +00009629 if (Elt) {
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009630 PtrOff = LVT.getSizeInBits() * Elt / 8;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009631 EVT PtrType = NewPtr.getValueType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009632 if (TLI.isBigEndian())
Duncan Sands13237ac2008-06-06 12:08:01 +00009633 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009634 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
Evan Cheng1120279a2008-05-13 08:35:03 +00009635 DAG.getConstant(PtrOff, PtrType));
9636 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009637
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009638 // The replacement we need to do here is a little tricky: we need to
9639 // replace an extractelement of a load with a load.
9640 // Use ReplaceAllUsesOfValuesWith to do the replacement.
Eli Friedmane96286c2011-12-26 22:49:32 +00009641 // Note that this replacement assumes that the extractvalue is the only
9642 // use of the load; that's okay because we don't want to perform this
9643 // transformation in other cases anyway.
Evan Cheng7bf83092012-03-13 22:00:52 +00009644 SDValue Load;
Evan Chengd5f8e572012-03-13 22:16:11 +00009645 SDValue Chain;
Evan Cheng7bf83092012-03-13 22:00:52 +00009646 if (NVT.bitsGT(LVT)) {
9647 // If the result type of vextract is wider than the load, then issue an
9648 // extending load instead.
9649 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9650 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009651 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
Evan Cheng7bf83092012-03-13 22:00:52 +00009652 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009653 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9654 Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009655 Chain = Load.getValue(1);
9656 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009657 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
Evan Cheng7bf83092012-03-13 22:00:52 +00009658 LN0->getPointerInfo().getWithOffset(PtrOff),
Stephen Lincfe7f352013-07-08 00:37:03 +00009659 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009660 LN0->isInvariant(), Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009661 Chain = Load.getValue(1);
9662 if (NVT.bitsLT(LVT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009663 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009664 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00009665 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009666 }
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009667 WorkListRemover DeadNodes(*this);
9668 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
Evan Chengd5f8e572012-03-13 22:16:11 +00009669 SDValue To[] = { Load, Chain };
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009670 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009671 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9672 // worklist explicitly as well.
9673 AddToWorkList(Load.getNode());
Craig Topperaaeae982012-03-20 05:28:39 +00009674 AddUsersToWorkList(Load.getNode()); // Add users too
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009675 // Make sure to revisit this node to clean it up; it will usually be dead.
9676 AddToWorkList(N);
9677 return SDValue(N, 0);
Evan Cheng0de312d2007-10-06 08:19:55 +00009678 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009679
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009680 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009681}
Evan Cheng0de312d2007-10-06 08:19:55 +00009682
Michael Liao6d106b72012-10-23 23:06:52 +00009683// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9684SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9685 // We perform this optimization post type-legalization because
9686 // the type-legalizer often scalarizes integer-promoted vectors.
9687 // Performing this optimization before may create bit-casts which
9688 // will be type-legalized to complex code sequences.
9689 // We perform this optimization only before the operation legalizer because we
9690 // may introduce illegal operations.
9691 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9692 return SDValue();
9693
Dan Gohmana8665142007-06-25 16:23:39 +00009694 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009695 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009696 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +00009697
Nadav Rotembf6568b2011-10-29 21:23:04 +00009698 // Check to see if this is a BUILD_VECTOR of a bunch of values
9699 // which come from any_extend or zero_extend nodes. If so, we can create
9700 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +00009701 // optimizations. We do not handle sign-extend because we can't fill the sign
9702 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009703 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +00009704 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +00009705
Craig Topper02cb0fb2012-01-17 09:09:48 +00009706 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +00009707 SDValue In = N->getOperand(i);
9708 // Ignore undef inputs.
9709 if (In.getOpcode() == ISD::UNDEF) continue;
9710
9711 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9712 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9713
Nadav Rotemf3103612011-10-31 20:08:25 +00009714 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009715 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +00009716 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009717 break;
9718 }
9719
9720 // The input is a ZeroExt or AnyExt. Check the original type.
9721 EVT InTy = In.getOperand(0).getValueType();
9722
9723 // Check that all of the widened source types are the same.
9724 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +00009725 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009726 SourceType = InTy;
9727 else if (InTy != SourceType) {
9728 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +00009729 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009730 break;
9731 }
9732
9733 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +00009734 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009735 }
9736
Nadav Rotemf3103612011-10-31 20:08:25 +00009737 // In order to have valid types, all of the inputs must be extended from the
9738 // same source type and all of the inputs must be any or zero extend.
9739 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +00009740 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009741 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +00009742 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9743 isPowerOf2_32(SourceType.getSizeInBits());
9744
Nadav Rotem6fd1d322012-03-15 08:49:06 +00009745 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9746 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +00009747 if (!ValidTypes)
9748 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +00009749
Michael Liao6d106b72012-10-23 23:06:52 +00009750 bool isLE = TLI.isLittleEndian();
9751 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9752 assert(ElemRatio > 1 && "Invalid element size ratio");
9753 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9754 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009755
Michael Liao6d106b72012-10-23 23:06:52 +00009756 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9757 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +00009758
Michael Liao6d106b72012-10-23 23:06:52 +00009759 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +00009760 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +00009761 SDValue Cast = N->getOperand(i);
9762 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9763 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9764 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9765 SDValue In;
9766 if (Cast.getOpcode() == ISD::UNDEF)
9767 In = DAG.getUNDEF(SourceType);
9768 else
9769 In = Cast->getOperand(0);
9770 unsigned Index = isLE ? (i * ElemRatio) :
9771 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +00009772
Michael Liao6d106b72012-10-23 23:06:52 +00009773 assert(Index < Ops.size() && "Invalid index");
9774 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009775 }
Chris Lattner5336a592006-03-19 01:27:56 +00009776
Michael Liao6d106b72012-10-23 23:06:52 +00009777 // The type of the new BUILD_VECTOR node.
9778 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9779 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9780 "Invalid vector size");
9781 // Check if the new vector type is legal.
9782 if (!isTypeLegal(VecVT)) return SDValue();
9783
9784 // Make the new BUILD_VECTOR.
9785 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9786
9787 // The new BUILD_VECTOR node has the potential to be further optimized.
9788 AddToWorkList(BV.getNode());
9789 // Bitcast to the desired type.
9790 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9791}
9792
Michael Liao59229792012-10-24 04:14:18 +00009793SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9794 EVT VT = N->getValueType(0);
9795
9796 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009797 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +00009798
9799 EVT SrcVT = MVT::Other;
9800 unsigned Opcode = ISD::DELETED_NODE;
9801 unsigned NumDefs = 0;
9802
9803 for (unsigned i = 0; i != NumInScalars; ++i) {
9804 SDValue In = N->getOperand(i);
9805 unsigned Opc = In.getOpcode();
9806
9807 if (Opc == ISD::UNDEF)
9808 continue;
9809
9810 // If all scalar values are floats and converted from integers.
9811 if (Opcode == ISD::DELETED_NODE &&
9812 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9813 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +00009814 }
Tom Stellard567f8862013-01-02 22:13:01 +00009815
Michael Liao59229792012-10-24 04:14:18 +00009816 if (Opc != Opcode)
9817 return SDValue();
9818
9819 EVT InVT = In.getOperand(0).getValueType();
9820
9821 // If all scalar values are typed differently, bail out. It's chosen to
9822 // simplify BUILD_VECTOR of integer types.
9823 if (SrcVT == MVT::Other)
9824 SrcVT = InVT;
9825 if (SrcVT != InVT)
9826 return SDValue();
9827 NumDefs++;
9828 }
9829
9830 // If the vector has just one element defined, it's not worth to fold it into
9831 // a vectorized one.
9832 if (NumDefs < 2)
9833 return SDValue();
9834
9835 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9836 && "Should only handle conversion from integer to float.");
9837 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9838
9839 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +00009840
9841 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9842 return SDValue();
9843
Michael Liao59229792012-10-24 04:14:18 +00009844 SmallVector<SDValue, 8> Opnds;
9845 for (unsigned i = 0; i != NumInScalars; ++i) {
9846 SDValue In = N->getOperand(i);
9847
9848 if (In.getOpcode() == ISD::UNDEF)
9849 Opnds.push_back(DAG.getUNDEF(SrcVT));
9850 else
9851 Opnds.push_back(In.getOperand(0));
9852 }
9853 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9854 &Opnds[0], Opnds.size());
9855 AddToWorkList(BV.getNode());
9856
9857 return DAG.getNode(Opcode, dl, VT, BV);
9858}
9859
Michael Liao6d106b72012-10-23 23:06:52 +00009860SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9861 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009862 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +00009863 EVT VT = N->getValueType(0);
9864
9865 // A vector built entirely of undefs is undef.
9866 if (ISD::allOperandsUndef(N))
9867 return DAG.getUNDEF(VT);
9868
9869 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9870 if (V.getNode())
9871 return V;
9872
Michael Liao59229792012-10-24 04:14:18 +00009873 V = reduceBuildVecConvertToConvertBuildVec(N);
9874 if (V.getNode())
9875 return V;
9876
Dan Gohmana8665142007-06-25 16:23:39 +00009877 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9878 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9879 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +00009880
9881 // May only combine to shuffle after legalize if shuffle is legal.
9882 if (LegalOperations &&
9883 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9884 return SDValue();
9885
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009886 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +00009887 for (unsigned i = 0; i != NumInScalars; ++i) {
9888 // Ignore undef inputs.
9889 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00009890
Dan Gohmana8665142007-06-25 16:23:39 +00009891 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +00009892 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +00009893 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +00009894 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009895 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +00009896 break;
9897 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009898
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009899 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009900 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +00009901 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9902 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00009903
Gabor Greiff304a7a2008-08-28 21:40:38 +00009904 if (VecIn1.getNode() == 0) {
Chris Lattnerc9992542006-03-28 20:28:38 +00009905 VecIn1 = ExtractedFromVec;
Gabor Greiff304a7a2008-08-28 21:40:38 +00009906 } else if (VecIn2.getNode() == 0) {
Chris Lattnerc9992542006-03-28 20:28:38 +00009907 VecIn2 = ExtractedFromVec;
9908 } else {
9909 // Too many inputs.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009910 VecIn1 = VecIn2 = SDValue(0, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +00009911 break;
9912 }
9913 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009914
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009915 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +00009916 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009917 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +00009918 for (unsigned i = 0; i != NumInScalars; ++i) {
9919 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009920 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +00009921 continue;
9922 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009923
Rafael Espindolab93db662009-04-24 12:40:33 +00009924 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009925 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +00009926 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +00009927 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +00009928 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9929 if (ExtIndex > VT.getVectorNumElements())
9930 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +00009931
Nate Begeman5f829d82009-04-29 05:20:52 +00009932 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +00009933 continue;
9934 }
9935
9936 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +00009937 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009938 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +00009939 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009940
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009941 // We can't generate a shuffle node with mismatched input and output types.
9942 // Attempt to transform a single input vector to the correct type.
9943 if ((VT != VecIn1.getValueType())) {
9944 // We don't support shuffeling between TWO values of different types.
9945 if (VecIn2.getNode() != 0)
9946 return SDValue();
9947
9948 // We only support widening of vectors which are half the size of the
9949 // output registers. For example XMM->YMM widening on X86 with AVX.
9950 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9951 return SDValue();
9952
James Molloy1e5c6112012-09-10 14:01:21 +00009953 // If the input vector type has a different base type to the output
9954 // vector type, bail out.
9955 if (VecIn1.getValueType().getVectorElementType() !=
9956 VT.getVectorElementType())
9957 return SDValue();
9958
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +00009959 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +00009960 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +00009961 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009962 }
9963
9964 // If VecIn2 is unused then change it to undef.
9965 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9966
Nadav Rotem841c9a82012-09-20 08:53:31 +00009967 // Check that we were able to transform all incoming values to the same
9968 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +00009969 if (VecIn2.getValueType() != VecIn1.getValueType() ||
9970 VecIn1.getValueType() != VT)
9971 return SDValue();
9972
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009973 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +00009974 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009975 return SDValue();
9976
Dan Gohmana8665142007-06-25 16:23:39 +00009977 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009978 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +00009979 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009980 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +00009981 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +00009982 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009983
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009984 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +00009985}
9986
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009987SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +00009988 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9989 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
9990 // inputs come from at most two distinct vectors, turn this into a shuffle
9991 // node.
9992
9993 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +00009994 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +00009995 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +00009996
Nadav Rotem01892102012-07-14 21:30:27 +00009997 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +00009998 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +00009999 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010000 return DAG.getUNDEF(VT);
10001
10002 // Optimize concat_vectors where one of the vectors is undef.
10003 if (N->getNumOperands() == 2 &&
10004 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10005 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010006 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010007
10008 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10009 if (In->getOpcode() == ISD::BITCAST &&
10010 !In->getOperand(0)->getValueType(0).isVector()) {
10011 SDValue Scalar = In->getOperand(0);
10012 EVT SclTy = Scalar->getValueType(0);
10013
10014 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10015 return SDValue();
10016
10017 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10018 VT.getSizeInBits() / SclTy.getSizeInBits());
10019 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10020 return SDValue();
10021
10022 SDLoc dl = SDLoc(N);
10023 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10024 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10025 }
10026 }
Nadav Rotem01892102012-07-14 21:30:27 +000010027
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010028 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10029 // nodes often generate nop CONCAT_VECTOR nodes.
10030 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10031 // place the incoming vectors at the exact same location.
10032 SDValue SingleSource = SDValue();
10033 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10034
10035 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10036 SDValue Op = N->getOperand(i);
10037
10038 if (Op.getOpcode() == ISD::UNDEF)
10039 continue;
10040
10041 // Check if this is the identity extract:
10042 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10043 return SDValue();
10044
10045 // Find the single incoming vector for the extract_subvector.
10046 if (SingleSource.getNode()) {
10047 if (Op.getOperand(0) != SingleSource)
10048 return SDValue();
10049 } else {
10050 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010051
10052 // Check the source type is the same as the type of the result.
10053 // If not, this concat may extend the vector, so we can not
10054 // optimize it away.
10055 if (SingleSource.getValueType() != N->getValueType(0))
10056 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010057 }
10058
10059 unsigned IdentityIndex = i * PartNumElem;
10060 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10061 // The extract index must be constant.
10062 if (!CS)
10063 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010064
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010065 // Check that we are reading from the identity index.
10066 if (CS->getZExtValue() != IdentityIndex)
10067 return SDValue();
10068 }
10069
10070 if (SingleSource.getNode())
10071 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010072
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010073 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010074}
10075
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010076SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10077 EVT NVT = N->getValueType(0);
10078 SDValue V = N->getOperand(0);
10079
Michael Liao7a442c802012-10-17 20:48:33 +000010080 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10081 // Combine:
10082 // (extract_subvec (concat V1, V2, ...), i)
10083 // Into:
10084 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010085 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10086 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010087 if (V->getOperand(0).getValueType() != NVT)
10088 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010089 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10090 unsigned NumElems = NVT.getVectorNumElements();
10091 assert((Idx % NumElems) == 0 &&
10092 "IDX in concat is not a multiple of the result vector length.");
10093 return V->getOperand(Idx / NumElems);
10094 }
10095
Michael Liaobb05a1d2013-03-25 23:47:35 +000010096 // Skip bitcasting
10097 if (V->getOpcode() == ISD::BITCAST)
10098 V = V.getOperand(0);
10099
10100 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010101 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010102 // Handle only simple case where vector being inserted and vector
10103 // being extracted are of same type, and are half size of larger vectors.
10104 EVT BigVT = V->getOperand(0).getValueType();
10105 EVT SmallVT = V->getOperand(1).getValueType();
10106 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10107 return SDValue();
10108
10109 // Only handle cases where both indexes are constants with the same type.
10110 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10111 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10112
10113 if (InsIdx && ExtIdx &&
10114 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10115 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10116 // Combine:
10117 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10118 // Into:
10119 // indices are equal or bit offsets are equal => V1
10120 // otherwise => (extract_subvec V1, ExtIdx)
10121 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10122 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10123 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10124 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10125 DAG.getNode(ISD::BITCAST, dl,
10126 N->getOperand(0).getValueType(),
10127 V->getOperand(0)), N->getOperand(1));
10128 }
10129 }
10130
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010131 return SDValue();
10132}
10133
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010134// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10135static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10136 EVT VT = N->getValueType(0);
10137 unsigned NumElts = VT.getVectorNumElements();
10138
10139 SDValue N0 = N->getOperand(0);
10140 SDValue N1 = N->getOperand(1);
10141 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10142
10143 SmallVector<SDValue, 4> Ops;
10144 EVT ConcatVT = N0.getOperand(0).getValueType();
10145 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10146 unsigned NumConcats = NumElts / NumElemsPerConcat;
10147
10148 // Look at every vector that's inserted. We're looking for exact
10149 // subvector-sized copies from a concatenated vector
10150 for (unsigned I = 0; I != NumConcats; ++I) {
10151 // Make sure we're dealing with a copy.
10152 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010153 bool AllUndef = true, NoUndef = true;
10154 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10155 if (SVN->getMaskElt(J) >= 0)
10156 AllUndef = false;
10157 else
10158 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010159 }
10160
Hao Liubc601962013-05-13 02:07:05 +000010161 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010162 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10163 return SDValue();
10164
10165 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10166 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10167 return SDValue();
10168
10169 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10170 if (FirstElt < N0.getNumOperands())
10171 Ops.push_back(N0.getOperand(FirstElt));
10172 else
10173 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10174
10175 } else if (AllUndef) {
10176 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10177 } else { // Mixed with general masks and undefs, can't do optimization.
10178 return SDValue();
10179 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010180 }
10181
Andrew Trickef9de2a2013-05-25 02:42:55 +000010182 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010183 Ops.size());
10184}
10185
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010186SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010187 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010188 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010189
Mon P Wang25f01062008-11-10 04:46:22 +000010190 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010191 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010192
Craig Topper5894fe42012-04-09 05:16:56 +000010193 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010194
Craig Topper279c77b2012-01-04 08:07:43 +000010195 // Canonicalize shuffle undef, undef -> undef
10196 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10197 return DAG.getUNDEF(VT);
10198
10199 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10200
10201 // Canonicalize shuffle v, v -> v, undef
10202 if (N0 == N1) {
10203 SmallVector<int, 8> NewMask;
10204 for (unsigned i = 0; i != NumElts; ++i) {
10205 int Idx = SVN->getMaskElt(i);
10206 if (Idx >= (int)NumElts) Idx -= NumElts;
10207 NewMask.push_back(Idx);
10208 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010209 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010210 &NewMask[0]);
10211 }
10212
10213 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10214 if (N0.getOpcode() == ISD::UNDEF) {
10215 SmallVector<int, 8> NewMask;
10216 for (unsigned i = 0; i != NumElts; ++i) {
10217 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010218 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010219 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010220 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010221 else
10222 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010223 }
10224 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010225 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010226 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010227 &NewMask[0]);
10228 }
10229
10230 // Remove references to rhs if it is undef
10231 if (N1.getOpcode() == ISD::UNDEF) {
10232 bool Changed = false;
10233 SmallVector<int, 8> NewMask;
10234 for (unsigned i = 0; i != NumElts; ++i) {
10235 int Idx = SVN->getMaskElt(i);
10236 if (Idx >= (int)NumElts) {
10237 Idx = -1;
10238 Changed = true;
10239 }
10240 NewMask.push_back(Idx);
10241 }
10242 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010243 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010244 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010245
Bob Wilsonf63da122010-10-28 17:06:14 +000010246 // If it is a splat, check if the argument vector is another splat or a
10247 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010248 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010249 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010250
Dan Gohmana8665142007-06-25 16:23:39 +000010251 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010252 // not the number of vector elements, look through it. Be careful not to
10253 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010254 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010255 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010256 if (ConvInput.getValueType().isVector() &&
10257 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010258 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010259 }
10260
Dan Gohmana8665142007-06-25 16:23:39 +000010261 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010262 assert(V->getNumOperands() == NumElts &&
10263 "BUILD_VECTOR has wrong number of operands");
10264 SDValue Base;
10265 bool AllSame = true;
10266 for (unsigned i = 0; i != NumElts; ++i) {
10267 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10268 Base = V->getOperand(i);
10269 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010270 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010271 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010272 // Splat of <u, u, u, u>, return <u, u, u, u>
10273 if (!Base.getNode())
10274 return N0;
10275 for (unsigned i = 0; i != NumElts; ++i) {
10276 if (V->getOperand(i) != Base) {
10277 AllSame = false;
10278 break;
10279 }
10280 }
10281 // Splat of <x, x, x, x>, return <x, x, x, x>
10282 if (AllSame)
10283 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010284 }
10285 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010286
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010287 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10288 Level < AfterLegalizeVectorOps &&
10289 (N1.getOpcode() == ISD::UNDEF ||
10290 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10291 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10292 SDValue V = partitionShuffleOfConcats(N, DAG);
10293
10294 if (V.getNode())
10295 return V;
10296 }
10297
Nadav Rotemb0783502012-04-01 19:31:22 +000010298 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010299 // and it reverses the swizzle of the previous shuffle then we can
10300 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotemb0783502012-04-01 19:31:22 +000010301 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10302 N1.getOpcode() == ISD::UNDEF) {
10303
Nadav Rotemb0783502012-04-01 19:31:22 +000010304 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10305
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010306 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10307 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10308 return SDValue();
10309
Craig Topper5894fe42012-04-09 05:16:56 +000010310 // The incoming shuffle must be of the same type as the result of the
10311 // current shuffle.
10312 assert(OtherSV->getOperand(0).getValueType() == VT &&
10313 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010314
10315 for (unsigned i = 0; i != NumElts; ++i) {
10316 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010317 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010318 // Next, this index comes from the first value, which is the incoming
10319 // shuffle. Adopt the incoming index.
10320 if (Idx >= 0)
10321 Idx = OtherSV->getMaskElt(Idx);
10322
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010323 // The combined shuffle must map each index to itself.
Craig Topper5894fe42012-04-09 05:16:56 +000010324 if (Idx >= 0 && (unsigned)Idx != i)
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010325 return SDValue();
Nadav Rotemb0783502012-04-01 19:31:22 +000010326 }
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010327
10328 return OtherSV->getOperand(0);
Nadav Rotemb0783502012-04-01 19:31:22 +000010329 }
10330
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010331 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010332}
10333
Evan Chenga320abc2006-04-20 08:56:16 +000010334/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010335/// an AND to a vector_shuffle with the destination vector and a zero vector.
10336/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010337/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010338SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010339 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010340 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010341 SDValue LHS = N->getOperand(0);
10342 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010343 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010344 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010345 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010346 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010347 SmallVector<int, 8> Indices;
10348 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010349 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010350 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010351 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010352 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010353
10354 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010355 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010356 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010357 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010358 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010359 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010360 }
10361
10362 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010363 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010364 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010365 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010366
Dan Gohmana8665142007-06-25 16:23:39 +000010367 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010368 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010369 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010370 DAG.getConstant(0, EltVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010371 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010372 RVT, &ZeroOps[0], ZeroOps.size());
Wesley Peck527da1b2010-11-23 03:31:01 +000010373 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010374 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010375 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010376 }
10377 }
Bill Wendling31b50992009-01-30 23:59:18 +000010378
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010379 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010380}
10381
Dan Gohmana8665142007-06-25 16:23:39 +000010382/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010383SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010384 assert(N->getValueType(0).isVector() &&
10385 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010386
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010387 SDValue LHS = N->getOperand(0);
10388 SDValue RHS = N->getOperand(1);
10389 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010390 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010391
Dan Gohmana8665142007-06-25 16:23:39 +000010392 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010393 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010394 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010395 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010396 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010397 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10398 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010399 return SDValue();
10400
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010401 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010402 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010403 SDValue LHSOp = LHS.getOperand(i);
10404 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010405
Evan Cheng64d28462006-05-31 06:08:35 +000010406 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010407 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10408 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010409 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010410 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010411 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010412 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010413 break;
10414 }
Bill Wendling31b50992009-01-30 23:59:18 +000010415
Bob Wilson54081442010-12-17 23:06:49 +000010416 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010417 EVT RVT = RHSOp.getValueType();
10418 if (RVT != VT) {
10419 // Integer BUILD_VECTOR operands may have types larger than the element
10420 // size (e.g., when the element type is not legal). Prior to type
10421 // legalization, the types may not match between the two BUILD_VECTORS.
10422 // Truncate one of the operands to make them match.
10423 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010424 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010425 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010426 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010427 VT = RVT;
10428 }
10429 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010430 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010431 LHSOp, RHSOp);
10432 if (FoldOp.getOpcode() != ISD::UNDEF &&
10433 FoldOp.getOpcode() != ISD::Constant &&
10434 FoldOp.getOpcode() != ISD::ConstantFP)
10435 break;
10436 Ops.push_back(FoldOp);
10437 AddToWorkList(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010438 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010439
Bob Wilson54081442010-12-17 23:06:49 +000010440 if (Ops.size() == LHS.getNumOperands())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010441 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Bob Wilson54081442010-12-17 23:06:49 +000010442 LHS.getValueType(), &Ops[0], Ops.size());
Chris Lattner0442a182006-04-02 03:25:57 +000010443 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010444
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010445 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000010446}
10447
Craig Topper82384612012-09-11 01:45:21 +000010448/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10449SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000010450 assert(N->getValueType(0).isVector() &&
10451 "SimplifyVUnaryOp only works on vectors!");
10452
10453 SDValue N0 = N->getOperand(0);
10454
10455 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10456 return SDValue();
10457
10458 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10459 SmallVector<SDValue, 8> Ops;
10460 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10461 SDValue Op = N0.getOperand(i);
10462 if (Op.getOpcode() != ISD::UNDEF &&
10463 Op.getOpcode() != ISD::ConstantFP)
10464 break;
10465 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010466 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000010467 if (FoldOp.getOpcode() != ISD::UNDEF &&
10468 FoldOp.getOpcode() != ISD::ConstantFP)
10469 break;
10470 Ops.push_back(FoldOp);
10471 AddToWorkList(FoldOp.getNode());
10472 }
10473
10474 if (Ops.size() != N0.getNumOperands())
10475 return SDValue();
10476
Andrew Trickef9de2a2013-05-25 02:42:55 +000010477 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Craig Topper82384612012-09-11 01:45:21 +000010478 N0.getValueType(), &Ops[0], Ops.size());
10479}
10480
Andrew Trickef9de2a2013-05-25 02:42:55 +000010481SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000010482 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000010483 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000010484
Bill Wendling31b50992009-01-30 23:59:18 +000010485 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000010486 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000010487
Nate Begeman2042aa52005-10-08 00:29:44 +000010488 // If we got a simplified select_cc node back from SimplifySelectCC, then
10489 // break it down into a new SETCC node, and a new SELECT node, and then return
10490 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010491 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010492 // Check to see if we got a select_cc back (to turn into setcc/select).
10493 // Otherwise, just return whatever node we got back, like fabs.
10494 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010495 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010496 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000010497 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000010498 SCC.getOperand(4));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010499 AddToWorkList(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010500 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10501 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000010502 }
Bill Wendling31b50992009-01-30 23:59:18 +000010503
Nate Begeman2042aa52005-10-08 00:29:44 +000010504 return SCC;
10505 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010506 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000010507}
10508
Chris Lattner6c14c352005-10-18 06:04:22 +000010509/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10510/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000010511/// select. Callers of this should assume that TheSelect is deleted if this
10512/// returns true. As such, they should return the appropriate thing (e.g. the
10513/// node) back to the top-level of the DAG combiner loop to avoid it being
10514/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010515bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010516 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010517
Nadav Rotema49a02a2011-02-11 19:57:47 +000010518 // Cannot simplify select with vector condition
10519 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10520
Chris Lattner6c14c352005-10-18 06:04:22 +000010521 // If this is a select from two identical things, try to pull the operation
10522 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000010523 if (LHS.getOpcode() != RHS.getOpcode() ||
10524 !LHS.hasOneUse() || !RHS.hasOneUse())
10525 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010526
Chris Lattner254c4452010-09-21 15:46:59 +000010527 // If this is a load and the token chain is identical, replace the select
10528 // of two loads with a load through a select of the address to load from.
10529 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10530 // constants have been dropped into the constant pool.
10531 if (LHS.getOpcode() == ISD::LOAD) {
10532 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10533 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000010534
Chris Lattner254c4452010-09-21 15:46:59 +000010535 // Token chains must be identical.
10536 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000010537 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000010538 LLD->isVolatile() || RLD->isVolatile() ||
10539 // If this is an EXTLOAD, the VT's must match.
10540 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000010541 // If this is an EXTLOAD, the kind of extension must match.
10542 (LLD->getExtensionType() != RLD->getExtensionType() &&
10543 // The only exception is if one of the extensions is anyext.
10544 LLD->getExtensionType() != ISD::EXTLOAD &&
10545 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000010546 // FIXME: this discards src value information. This is
10547 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000010548 // both potential memory locations. Since we are discarding
10549 // src value info, don't do the transformation if the memory
10550 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000010551 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000010552 RLD->getPointerInfo().getAddrSpace() != 0 ||
10553 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10554 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000010555 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010556
Chris Lattnere3267522010-09-21 15:58:55 +000010557 // Check that the select condition doesn't reach either load. If so,
10558 // folding this will induce a cycle into the DAG. If not, this is safe to
10559 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000010560 SDValue Addr;
10561 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000010562 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10563 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10564 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10565 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000010566 // The loads must not depend on one another.
10567 if (LLD->isPredecessorOf(RLD) ||
10568 RLD->isPredecessorOf(LLD))
10569 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010570 Addr = DAG.getSelect(SDLoc(TheSelect),
10571 LLD->getBasePtr().getValueType(),
10572 TheSelect->getOperand(0), LLD->getBasePtr(),
10573 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000010574 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000010575 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10576 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10577
10578 if ((LLD->hasAnyUseOfValue(1) &&
10579 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000010580 (RLD->hasAnyUseOfValue(1) &&
10581 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000010582 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010583
Andrew Trickef9de2a2013-05-25 02:42:55 +000010584 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000010585 LLD->getBasePtr().getValueType(),
10586 TheSelect->getOperand(0),
10587 TheSelect->getOperand(1),
10588 LLD->getBasePtr(), RLD->getBasePtr(),
10589 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000010590 }
10591
Chris Lattnere3267522010-09-21 15:58:55 +000010592 SDValue Load;
10593 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10594 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010595 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010596 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010597 LLD->getChain(), Addr, MachinePointerInfo(),
10598 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010599 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000010600 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000010601 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10602 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010603 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000010604 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010605 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010606 LLD->getChain(), Addr, MachinePointerInfo(),
10607 LLD->getMemoryVT(), LLD->isVolatile(),
10608 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000010609 }
Chris Lattnere3267522010-09-21 15:58:55 +000010610
10611 // Users of the select now use the result of the load.
10612 CombineTo(TheSelect, Load);
10613
10614 // Users of the old loads now use the new load's chain. We know the
10615 // old-load value is dead now.
10616 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10617 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10618 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000010619 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010620
Chris Lattner6c14c352005-10-18 06:04:22 +000010621 return false;
10622}
10623
Chris Lattner43d63772009-03-11 05:08:08 +000010624/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10625/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010626SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010627 SDValue N2, SDValue N3,
10628 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000010629 // (x ? y : y) -> y.
10630 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000010631
Owen Anderson53aa7a92009-08-10 22:56:29 +000010632 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000010633 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10634 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10635 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010636
10637 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000010638 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000010639 N0, N1, CC, DL, false);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010640 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10641 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010642
10643 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000010644 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010645 return N2;
10646 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000010647 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010648 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010649
Nate Begeman2042aa52005-10-08 00:29:44 +000010650 // Check to see if we can simplify the select into an fabs node
10651 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10652 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000010653 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010654 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10655 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10656 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10657 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000010658 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010659
Nate Begeman2042aa52005-10-08 00:29:44 +000010660 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10661 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10662 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10663 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000010664 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000010665 }
10666 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010667
Chris Lattner43d63772009-03-11 05:08:08 +000010668 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10669 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10670 // in it. This is a win when the constant is not otherwise available because
10671 // it replaces two constant pool loads with one. We only do this if the FP
10672 // type is known to be legal, because if it isn't, then we are before legalize
10673 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000010674 // messing with soft float) and if the ConstantFP is not legal, because if
10675 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000010676 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10677 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10678 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000010679 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10680 TargetLowering::Legal) &&
Chris Lattner43d63772009-03-11 05:08:08 +000010681 // If both constants have multiple uses, then we won't need to do an
10682 // extra load, they are likely around in registers for other users.
10683 (TV->hasOneUse() || FV->hasOneUse())) {
10684 Constant *Elts[] = {
10685 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10686 const_cast<ConstantFP*>(TV->getConstantFPValue())
10687 };
Chris Lattner229907c2011-07-18 04:54:35 +000010688 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010689 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000010690
Chris Lattner43d63772009-03-11 05:08:08 +000010691 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000010692 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000010693 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10694 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000010695 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000010696
10697 // Get the offsets to the 0 and 1 element of the array so that we can
10698 // select between them.
10699 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000010700 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000010701 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000010702
Chris Lattner43d63772009-03-11 05:08:08 +000010703 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000010704 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000010705 N0, N1, CC);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010706 AddToWorkList(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010707 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10708 Cond, One, Zero);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010709 AddToWorkList(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000010710 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000010711 CstOffset);
Dan Gohmane83e1b22011-09-22 23:01:29 +000010712 AddToWorkList(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000010713 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000010714 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000010715 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000010716
10717 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010718 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010719
Nate Begeman2042aa52005-10-08 00:29:44 +000010720 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000010721 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000010722 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000010723 (N1C->isNullValue() || // (a < 0) ? b : 0
10724 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000010725 EVT XType = N0.getValueType();
10726 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000010727 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000010728 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000010729 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000010730 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10731 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000010732 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000010733 SDValue ShCt = DAG.getConstant(ShCtV,
10734 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010735 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010736 XType, N0, ShCt);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010737 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000010738
Duncan Sands11dd4242008-06-08 20:54:56 +000010739 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000010740 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010741 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010742 }
Bill Wendling31b50992009-01-30 23:59:18 +000010743
10744 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000010745 }
Bill Wendling31b50992009-01-30 23:59:18 +000010746
Andrew Trickef9de2a2013-05-25 02:42:55 +000010747 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010748 XType, N0,
10749 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000010750 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010751 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000010752
Duncan Sands11dd4242008-06-08 20:54:56 +000010753 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000010754 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010755 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010756 }
Bill Wendling31b50992009-01-30 23:59:18 +000010757
10758 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000010759 }
10760 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010761
Owen Anderson3231d132010-09-22 22:58:22 +000010762 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10763 // where y is has a single bit set.
10764 // A plaintext description would be, we can turn the SELECT_CC into an AND
10765 // when the condition can be materialized as an all-ones register. Any
10766 // single bit-test can be materialized as an all-ones register with
10767 // shift-left and shift-right-arith.
10768 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10769 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000010770 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000010771 N2C && N2C->isNullValue()) {
10772 SDValue AndLHS = N0->getOperand(0);
10773 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10774 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10775 // Shift the tested bit over the sign bit.
10776 APInt AndMask = ConstAndRHS->getAPIntValue();
10777 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000010778 DAG.getConstant(AndMask.countLeadingZeros(),
10779 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010780 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000010781
Owen Anderson3231d132010-09-22 22:58:22 +000010782 // Now arithmetic right shift it all the way over, so the result is either
10783 // all-ones, or zero.
10784 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000010785 DAG.getConstant(AndMask.getBitWidth()-1,
10786 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010787 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000010788
Owen Anderson3231d132010-09-22 22:58:22 +000010789 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10790 }
10791 }
10792
Nate Begeman6828ed92005-10-10 21:26:48 +000010793 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000010794 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sandsf2641e12011-09-06 19:07:46 +000010795 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10796 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010797
Chris Lattnera083ffc2007-04-11 06:50:51 +000010798 // If the caller doesn't want us to simplify this into a zext of a compare,
10799 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000010800 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010801 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010802
Nate Begeman6828ed92005-10-10 21:26:48 +000010803 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010804 // NOTE: Don't create a SETCC if it's not legal on this target.
10805 if (!LegalOperations ||
10806 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000010807 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010808 SDValue Temp, SCC;
10809 // cast from setcc result type to select result type
10810 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000010811 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010812 N0, N1, CC);
10813 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000010814 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010815 N2.getValueType());
10816 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000010817 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010818 N2.getValueType(), SCC);
10819 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010820 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10821 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000010822 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000010823 }
10824
10825 AddToWorkList(SCC.getNode());
10826 AddToWorkList(Temp.getNode());
10827
10828 if (N2C->getAPIntValue() == 1)
10829 return Temp;
10830
10831 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000010832 return DAG.getNode(
10833 ISD::SHL, DL, N2.getValueType(), Temp,
10834 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10835 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000010836 }
Nate Begeman6828ed92005-10-10 21:26:48 +000010837 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010838
Nate Begeman2042aa52005-10-08 00:29:44 +000010839 // Check to see if this is the equivalent of setcc
10840 // FIXME: Turn all of these into setcc if setcc if setcc is legal
10841 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000010842 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010843 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010844 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000010845 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10846 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000010847 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000010848 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000010849 return Res;
10850 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010851
Bill Wendling31b50992009-01-30 23:59:18 +000010852 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000010853 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010854 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000010855 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010856 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010857 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000010858 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000010859 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000010860 }
Bill Wendling31b50992009-01-30 23:59:18 +000010861 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000010862 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010863 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010864 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010865 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000010866 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000010867 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000010868 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000010869 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000010870 }
Bill Wendling31b50992009-01-30 23:59:18 +000010871 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000010872 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010873 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000010874 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000010875 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000010876 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000010877 }
10878 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010879
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000010880 // Check to see if this is an integer abs.
10881 // select_cc setg[te] X, 0, X, -X ->
10882 // select_cc setgt X, -1, X, -X ->
10883 // select_cc setl[te] X, 0, -X, X ->
10884 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000010885 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000010886 if (N1C) {
10887 ConstantSDNode *SubC = NULL;
10888 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10889 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10890 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10891 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10892 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10893 (N1C->isOne() && CC == ISD::SETLT)) &&
10894 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10895 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10896
Owen Anderson53aa7a92009-08-10 22:56:29 +000010897 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000010898 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010899 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000010900 N0,
10901 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000010902 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010903 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000010904 XType, N0, Shift);
10905 AddToWorkList(Shift.getNode());
10906 AddToWorkList(Add.getNode());
10907 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000010908 }
10909 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010910
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010911 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000010912}
10913
Evan Cheng92658d52007-02-08 22:13:59 +000010914/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010915SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010916 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000010917 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010918 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000010919 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000010920 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000010921}
10922
Nate Begemanc6f067a2005-10-20 02:15:44 +000010923/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10924/// return a DAG expression to select that will generate the same value by
10925/// multiplying by a magic number. See:
10926/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010927SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000010928 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000010929 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000010930
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000010931 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000010932 ii != ee; ++ii)
10933 AddToWorkList(*ii);
10934 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000010935}
10936
10937/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10938/// return a DAG expression to select that will generate the same value by
10939/// multiplying by a magic number. See:
10940/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010941SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000010942 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000010943 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000010944
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000010945 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000010946 ii != ee; ++ii)
10947 AddToWorkList(*ii);
10948 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000010949}
10950
Nate Begeman18150d52009-09-25 06:05:26 +000010951/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000010952// to alias with anything but itself. Provides base object and offset as
10953// results.
Nate Begeman18150d52009-09-25 06:05:26 +000010954static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000010955 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000010956 // Assume it is a primitive operation.
Nate Begeman18150d52009-09-25 06:05:26 +000010957 Base = Ptr; Offset = 0; GV = 0; CV = 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010958
Jim Laskey0463e082006-10-07 23:37:56 +000010959 // If it's an adding a simple constant then integrate the offset.
10960 if (Base.getOpcode() == ISD::ADD) {
10961 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10962 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000010963 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000010964 }
10965 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010966
Nate Begeman18150d52009-09-25 06:05:26 +000010967 // Return the underlying GlobalValue, and update the Offset. Return false
10968 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10969 // by multiple nodes with different offsets.
10970 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10971 GV = G->getGlobal();
10972 Offset += G->getOffset();
10973 return false;
10974 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010975
Nate Begeman18150d52009-09-25 06:05:26 +000010976 // Return the underlying Constant value, and update the Offset. Return false
10977 // for ConstantSDNodes since the same constant pool entry may be represented
10978 // by multiple nodes with different offsets.
10979 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000010980 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10981 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000010982 Offset += C->getOffset();
10983 return false;
10984 }
Jim Laskey0463e082006-10-07 23:37:56 +000010985 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000010986 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000010987}
10988
10989/// isAlias - Return true if there is any possibility that the two addresses
10990/// overlap.
Richard Sandiford981fdeb2013-10-28 12:00:00 +000010991bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskeya15b0eb2006-10-18 12:29:57 +000010992 const Value *SrcValue1, int SrcValueOffset1,
Nate Begeman879d8f12009-09-15 00:18:30 +000010993 unsigned SrcValueAlign1,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000010994 const MDNode *TBAAInfo1,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000010995 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begeman879d8f12009-09-15 00:18:30 +000010996 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000010997 unsigned SrcValueAlign2,
10998 const MDNode *TBAAInfo2) const {
Jim Laskey0463e082006-10-07 23:37:56 +000010999 // If they are the same then they must be aliases.
11000 if (Ptr1 == Ptr2) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011001
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011002 // If they are both volatile then they cannot be reordered.
11003 if (IsVolatile1 && IsVolatile2) return true;
11004
Jim Laskey0463e082006-10-07 23:37:56 +000011005 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011006 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011007 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011008 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011009 const void *CV1, *CV2;
Nate Begeman18150d52009-09-25 06:05:26 +000011010 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11011 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011012
Nate Begeman18150d52009-09-25 06:05:26 +000011013 // If they have a same base address then check to see if they overlap.
11014 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Bill Wendling31b50992009-01-30 23:59:18 +000011015 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011016
Owen Anderson272ff942010-09-20 20:39:59 +000011017 // It is possible for different frame indices to alias each other, mostly
11018 // when tail call optimization reuses return address slots for arguments.
11019 // To catch this case, look up the actual index of frame indices to compute
11020 // the real alias relationship.
11021 if (isFrameIndex1 && isFrameIndex2) {
11022 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11023 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11024 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11025 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11026 }
11027
Wesley Peck527da1b2010-11-23 03:31:01 +000011028 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011029 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011030 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11031 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011032
Nate Begeman879d8f12009-09-15 00:18:30 +000011033 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11034 // compared to the size and offset of the access, we may be able to prove they
11035 // do not alias. This check is conservative for now to catch cases created by
11036 // splitting vector types.
11037 if ((SrcValueAlign1 == SrcValueAlign2) &&
11038 (SrcValueOffset1 != SrcValueOffset2) &&
11039 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11040 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11041 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
Wesley Peck527da1b2010-11-23 03:31:01 +000011042
Nate Begeman879d8f12009-09-15 00:18:30 +000011043 // There is no overlap between these relatively aligned accesses of similar
11044 // size, return no alias.
11045 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11046 return false;
11047 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011048
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011049 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11050 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel31658832013-09-15 02:19:49 +000011051 if (UseAA && SrcValue1 && SrcValue2) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011052 // Use alias analysis information.
Dan Gohman9625d812007-08-27 16:32:11 +000011053 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11054 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11055 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011056 AliasAnalysis::AliasResult AAResult =
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011057 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
11058 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011059 if (AAResult == AliasAnalysis::NoAlias)
11060 return false;
11061 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011062
11063 // Otherwise we have to assume they alias.
11064 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011065}
11066
Nadav Rotem307d7672012-11-29 00:00:08 +000011067bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11068 SDValue Ptr0, Ptr1;
11069 int64_t Size0, Size1;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011070 bool IsVolatile0, IsVolatile1;
Nadav Rotem307d7672012-11-29 00:00:08 +000011071 const Value *SrcValue0, *SrcValue1;
11072 int SrcValueOffset0, SrcValueOffset1;
11073 unsigned SrcValueAlign0, SrcValueAlign1;
11074 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011075 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotem307d7672012-11-29 00:00:08 +000011076 SrcValueAlign0, SrcTBAAInfo0);
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011077 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotem307d7672012-11-29 00:00:08 +000011078 SrcValueAlign1, SrcTBAAInfo1);
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011079 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotemac450eb2012-12-06 17:34:13 +000011080 SrcValueAlign0, SrcTBAAInfo0,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011081 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotemac450eb2012-12-06 17:34:13 +000011082 SrcValueAlign1, SrcTBAAInfo1);
Nadav Rotem307d7672012-11-29 00:00:08 +000011083}
11084
Jim Laskey0463e082006-10-07 23:37:56 +000011085/// FindAliasInfo - Extracts the relevant alias information from the memory
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011086/// node. Returns true if the operand was a nonvolatile load.
Jim Laskey08edf332006-10-11 13:47:09 +000011087bool DAGCombiner::FindAliasInfo(SDNode *N,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011088 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Benjamin Kramer5a377e22012-01-15 11:50:43 +000011089 const Value *&SrcValue,
11090 int &SrcValueOffset,
11091 unsigned &SrcValueAlign,
11092 const MDNode *&TBAAInfo) const {
11093 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11094
11095 Ptr = LS->getBasePtr();
11096 Size = LS->getMemoryVT().getSizeInBits() >> 3;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011097 IsVolatile = LS->isVolatile();
Benjamin Kramer5a377e22012-01-15 11:50:43 +000011098 SrcValue = LS->getSrcValue();
11099 SrcValueOffset = LS->getSrcValueOffset();
11100 SrcValueAlign = LS->getOriginalAlignment();
11101 TBAAInfo = LS->getTBAAInfo();
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011102 return isa<LoadSDNode>(LS) && !IsVolatile;
Jim Laskey0463e082006-10-07 23:37:56 +000011103}
11104
Jim Laskey708d0db2006-10-04 16:53:27 +000011105/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11106/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011107void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011108 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011109 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011110 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011111
Jim Laskeyd07be232006-09-25 16:29:54 +000011112 // Get alias information for node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011113 SDValue Ptr;
Nate Begeman879d8f12009-09-15 00:18:30 +000011114 int64_t Size;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011115 bool IsVolatile;
Nate Begeman879d8f12009-09-15 00:18:30 +000011116 const Value *SrcValue;
11117 int SrcValueOffset;
11118 unsigned SrcValueAlign;
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011119 const MDNode *SrcTBAAInfo;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011120 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11121 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
Jim Laskeyd07be232006-09-25 16:29:54 +000011122
Jim Laskey708d0db2006-10-04 16:53:27 +000011123 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011124 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011125 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011126
Jim Laskey6549d222006-10-05 15:07:25 +000011127 // Look at each chain and determine if it is an alias. If so, add it to the
11128 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011129 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011130 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011131 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011132 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011133
11134 // For TokenFactor nodes, look at each operand and only continue up the
11135 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011136 // find more and revert to original chain since the xform is unlikely to be
11137 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011138 //
11139 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011140 // chain we found before we hit a tokenfactor rather than the original
11141 // chain.
11142 if (Depth > 6 || Aliases.size() == 2) {
11143 Aliases.clear();
11144 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011145 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011146 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011147
Nate Begeman879d8f12009-09-15 00:18:30 +000011148 // Don't bother if we've been before.
11149 if (!Visited.insert(Chain.getNode()))
11150 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011151
Jim Laskey6549d222006-10-05 15:07:25 +000011152 switch (Chain.getOpcode()) {
11153 case ISD::EntryToken:
11154 // Entry token is ideal chain operand, but handled in FindBetterChain.
11155 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011156
Jim Laskey6549d222006-10-05 15:07:25 +000011157 case ISD::LOAD:
11158 case ISD::STORE: {
11159 // Get alias information for Chain.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011160 SDValue OpPtr;
Nate Begeman879d8f12009-09-15 00:18:30 +000011161 int64_t OpSize;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011162 bool OpIsVolatile;
Nate Begeman879d8f12009-09-15 00:18:30 +000011163 const Value *OpSrcValue;
11164 int OpSrcValueOffset;
11165 unsigned OpSrcValueAlign;
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011166 const MDNode *OpSrcTBAAInfo;
Gabor Greiff304a7a2008-08-28 21:40:38 +000011167 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011168 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011169 OpSrcValueAlign,
11170 OpSrcTBAAInfo);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011171
Jim Laskey6549d222006-10-05 15:07:25 +000011172 // If chain is alias then stop here.
11173 if (!(IsLoad && IsOpLoad) &&
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011174 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11175 SrcValueAlign, SrcTBAAInfo,
11176 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011177 OpSrcValueAlign, OpSrcTBAAInfo)) {
Jim Laskey6549d222006-10-05 15:07:25 +000011178 Aliases.push_back(Chain);
11179 } else {
11180 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011181 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011182 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011183 }
Jim Laskey6549d222006-10-05 15:07:25 +000011184 break;
11185 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011186
Jim Laskey6549d222006-10-05 15:07:25 +000011187 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011188 // We have to check each of the operands of the token factor for "small"
11189 // token factors, so we queue them up. Adding the operands to the queue
11190 // (stack) in reverse order maintains the original order and increases the
11191 // likelihood that getNode will find a matching token factor (CSE.)
11192 if (Chain.getNumOperands() > 16) {
11193 Aliases.push_back(Chain);
11194 break;
11195 }
Jim Laskey6549d222006-10-05 15:07:25 +000011196 for (unsigned n = Chain.getNumOperands(); n;)
11197 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011198 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011199 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011200
Jim Laskey6549d222006-10-05 15:07:25 +000011201 default:
11202 // For all other instructions we will just have to take what we can get.
11203 Aliases.push_back(Chain);
11204 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011205 }
11206 }
Hal Finkel51a98382014-01-24 20:12:02 +000011207
11208 // We need to be careful here to also search for aliases through the
11209 // value operand of a store, etc. Consider the following situation:
11210 // Token1 = ...
11211 // L1 = load Token1, %52
11212 // S1 = store Token1, L1, %51
11213 // L2 = load Token1, %52+8
11214 // S2 = store Token1, L2, %51+8
11215 // Token2 = Token(S1, S2)
11216 // L3 = load Token2, %53
11217 // S3 = store Token2, L3, %52
11218 // L4 = load Token2, %53+8
11219 // S4 = store Token2, L4, %52+8
11220 // If we search for aliases of S3 (which loads address %52), and we look
11221 // only through the chain, then we'll miss the trivial dependence on L1
11222 // (which also loads from %52). We then might change all loads and
11223 // stores to use Token1 as their chain operand, which could result in
11224 // copying %53 into %52 before copying %52 into %51 (which should
11225 // happen first).
11226 //
11227 // The problem is, however, that searching for such data dependencies
11228 // can become expensive, and the cost is not directly related to the
11229 // chain depth. Instead, we'll rule out such configurations here by
11230 // insisting that we've visited all chain users (except for users
11231 // of the original chain, which is not necessary). When doing this,
11232 // we need to look through nodes we don't care about (otherwise, things
11233 // like register copies will interfere with trivial cases).
11234
11235 SmallVector<const SDNode *, 16> Worklist;
11236 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11237 IE = Visited.end(); I != IE; ++I)
11238 if (*I != OriginalChain.getNode())
11239 Worklist.push_back(*I);
11240
11241 while (!Worklist.empty()) {
11242 const SDNode *M = Worklist.pop_back_val();
11243
11244 // We have already visited M, and want to make sure we've visited any uses
11245 // of M that we care about. For uses that we've not visisted, and don't
11246 // care about, queue them to the worklist.
11247
11248 for (SDNode::use_iterator UI = M->use_begin(),
11249 UIE = M->use_end(); UI != UIE; ++UI)
11250 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11251 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11252 // We've not visited this use, and we care about it (it could have an
11253 // ordering dependency with the original node).
11254 Aliases.clear();
11255 Aliases.push_back(OriginalChain);
11256 return;
11257 }
11258
11259 // We've not visited this use, but we don't care about it. Mark it as
11260 // visited and enqueue it to the worklist.
11261 Worklist.push_back(*UI);
11262 }
11263 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011264}
11265
11266/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11267/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011268SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11269 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011270
Jim Laskey708d0db2006-10-04 16:53:27 +000011271 // Accumulate all the aliases to this node.
11272 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011273
Dan Gohman4298df62011-05-17 22:20:36 +000011274 // If no operands then chain to entry token.
11275 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011276 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011277
11278 // If a single operand then chain to it. We don't need to revisit it.
11279 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011280 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011281
Jim Laskey708d0db2006-10-04 16:53:27 +000011282 // Construct a custom tailored token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011283 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Nate Begeman879d8f12009-09-15 00:18:30 +000011284 &Aliases[0], Aliases.size());
Jim Laskeyd07be232006-09-25 16:29:54 +000011285}
11286
Nate Begeman21158fc2005-09-01 00:19:25 +000011287// SelectionDAG::Combine - This is the entry point for the file.
11288//
Bill Wendling084669a2009-04-29 00:15:41 +000011289void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011290 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011291 /// run - This is the main entry point to this class.
11292 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011293 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011294}