blob: f346dcfcddd91f9cc53a7040a3abc7dae2c327f5 [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
Nate Begeman21158fc2005-09-01 00:19:25 +000019#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000020#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000029#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000030#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000032#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetLowering.h"
35#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000037#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000038#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000039#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000040using namespace llvm;
41
Chandler Carruth1b9dde02014-04-22 02:02:50 +000042#define DEBUG_TYPE "dagcombine"
43
Chris Lattneraee775a2006-12-19 22:41:21 +000044STATISTIC(NodesCombined , "Number of dag nodes combined");
45STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000047STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000048STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000049STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000050
Nate Begeman21158fc2005-09-01 00:19:25 +000051namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000052 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000053 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000054 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000055
Jim Laskey55e4dca2006-10-18 19:08:31 +000056 static cl::opt<bool>
57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000058 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000059
Hal Finkeldbebb522014-01-25 19:24:54 +000060 static cl::opt<bool>
Hal Finkel3b48d082014-04-12 01:26:00 +000061 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Hal Finkeldbebb522014-01-25 19:24:54 +000062 cl::desc("Enable DAG combiner's use of TBAA"));
63
Hal Finkel9b2617a2014-01-25 17:32:39 +000064#ifndef NDEBUG
65 static cl::opt<std::string>
66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67 cl::desc("Only use DAG-combiner alias analysis in this"
68 " function"));
69#endif
70
Quentin Colombetde0e0622013-10-11 18:29:42 +000071 /// Hidden option to stress test load slicing, i.e., when this option
72 /// is enabled, load slicing bypasses most of its profitability guards.
73 static cl::opt<bool>
74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75 cl::desc("Bypass the profitability model of load "
76 "slicing"),
77 cl::init(false));
78
Jim Laskey6549d222006-10-05 15:07:25 +000079//------------------------------ DAGCombiner ---------------------------------//
80
Nick Lewycky02d5f772009-10-25 06:33:48 +000081 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000082 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000083 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000084 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000085 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000086 bool LegalOperations;
87 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000088 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000089
90 // Worklist of all of the nodes that need to be simplified.
James Molloy67b6b112012-02-16 09:17:04 +000091 //
92 // This has the semantics that when adding to the worklist,
93 // the item added must be next to be processed. It should
94 // also only appear once. The naive approach to this takes
95 // linear time.
96 //
97 // To reduce the insert/remove time to logarithmic, we use
98 // a set and a vector to maintain our worklist.
99 //
100 // The set contains the items on the worklist, but does not
101 // maintain the order they should be visited.
102 //
103 // The vector maintains the order nodes should be visited, but may
104 // contain duplicate or removed nodes. When choosing a node to
105 // visit, we pop off the order stack until we find an item that is
106 // also in the contents set. All operations are O(log N).
107 SmallPtrSet<SDNode*, 64> WorkListContents;
Benjamin Kramere1e549d2012-03-10 00:23:58 +0000108 SmallVector<SDNode*, 64> WorkListOrder;
Nate Begeman21158fc2005-09-01 00:19:25 +0000109
Jim Laskeydcb2b832006-10-16 20:52:31 +0000110 // AA - Used for DAG load/store alias analysis.
111 AliasAnalysis &AA;
112
Nate Begeman21158fc2005-09-01 00:19:25 +0000113 /// AddUsersToWorkList - When an instruction is simplified, add all users of
114 /// the instruction to the work lists because they might get more simplified
115 /// now.
116 ///
117 void AddUsersToWorkList(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000118 for (SDNode *Node : N->uses())
119 AddToWorkList(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000120 }
121
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000122 /// visit - call the node-specific routine that knows how to fold each
123 /// particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000124 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000125
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000126 public:
James Molloy920ae8c2012-02-16 09:48:07 +0000127 /// AddToWorkList - Add to the work list making sure its instance is at the
James Molloy67b6b112012-02-16 09:17:04 +0000128 /// back (next to be processed.)
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000129 void AddToWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000130 WorkListContents.insert(N);
131 WorkListOrder.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000132 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000133
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000134 /// removeFromWorkList - remove all instances of N from the worklist.
135 ///
136 void removeFromWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000137 WorkListContents.erase(N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000138 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000139
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000140 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000141 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000142
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000143 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000144 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000145 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000146
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000147 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000148 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000149 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000150 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000151 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000152
153 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000154
155 private:
156
Chris Lattner375e1a72006-02-17 21:58:01 +0000157 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattner232024e2006-03-01 19:55:35 +0000158 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner375e1a72006-02-17 21:58:01 +0000159 /// propagation. If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000160 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000161 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000163 return SimplifyDemandedBits(Op, Demanded);
164 }
165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000166 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000167
Chris Lattnerffad2162006-11-11 00:39:41 +0000168 bool CombineToPreIndexedLoadStore(SDNode *N);
169 bool CombineToPostIndexedLoadStore(SDNode *N);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000170 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000171
Michael J. Spencerf375d802014-05-29 01:42:45 +0000172 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
173 /// load.
174 ///
175 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
176 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
177 /// \param EltNo index of the vector element to load.
178 /// \param OriginalLoad load that EVE came from to be replaced.
179 /// \returns EVE on success SDValue() on failure.
180 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
181 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000182 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
183 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
184 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
185 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000186 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000187 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000188 SDValue PromoteExtend(SDValue Op);
189 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000190
Craig Toppere0b71182013-07-13 07:43:40 +0000191 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000192 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000193 ISD::NodeType ExtType);
194
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000195 /// combine - call the node-specific routine that knows how to fold each
196 /// particular type of node. If that doesn't do anything, try the
197 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000198 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000199
200 // Visitation implementation - Implement dag node combining for different
201 // node types. The semantics are as follows:
202 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000203 // SDValue.getNode() == 0 - No change was made
204 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
205 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000206 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000207 SDValue visitTokenFactor(SDNode *N);
208 SDValue visitMERGE_VALUES(SDNode *N);
209 SDValue visitADD(SDNode *N);
210 SDValue visitSUB(SDNode *N);
211 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000212 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000213 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000214 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000215 SDValue visitMUL(SDNode *N);
216 SDValue visitSDIV(SDNode *N);
217 SDValue visitUDIV(SDNode *N);
218 SDValue visitSREM(SDNode *N);
219 SDValue visitUREM(SDNode *N);
220 SDValue visitMULHU(SDNode *N);
221 SDValue visitMULHS(SDNode *N);
222 SDValue visitSMUL_LOHI(SDNode *N);
223 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000224 SDValue visitSMULO(SDNode *N);
225 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000226 SDValue visitSDIVREM(SDNode *N);
227 SDValue visitUDIVREM(SDNode *N);
228 SDValue visitAND(SDNode *N);
229 SDValue visitOR(SDNode *N);
230 SDValue visitXOR(SDNode *N);
231 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000232 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000233 SDValue visitSHL(SDNode *N);
234 SDValue visitSRA(SDNode *N);
235 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000236 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000237 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000238 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000239 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000240 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000241 SDValue visitCTPOP(SDNode *N);
242 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000243 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000244 SDValue visitSELECT_CC(SDNode *N);
245 SDValue visitSETCC(SDNode *N);
246 SDValue visitSIGN_EXTEND(SDNode *N);
247 SDValue visitZERO_EXTEND(SDNode *N);
248 SDValue visitANY_EXTEND(SDNode *N);
249 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
250 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000251 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000252 SDValue visitBUILD_PAIR(SDNode *N);
253 SDValue visitFADD(SDNode *N);
254 SDValue visitFSUB(SDNode *N);
255 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000256 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000257 SDValue visitFDIV(SDNode *N);
258 SDValue visitFREM(SDNode *N);
259 SDValue visitFCOPYSIGN(SDNode *N);
260 SDValue visitSINT_TO_FP(SDNode *N);
261 SDValue visitUINT_TO_FP(SDNode *N);
262 SDValue visitFP_TO_SINT(SDNode *N);
263 SDValue visitFP_TO_UINT(SDNode *N);
264 SDValue visitFP_ROUND(SDNode *N);
265 SDValue visitFP_ROUND_INREG(SDNode *N);
266 SDValue visitFP_EXTEND(SDNode *N);
267 SDValue visitFNEG(SDNode *N);
268 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000269 SDValue visitFCEIL(SDNode *N);
270 SDValue visitFTRUNC(SDNode *N);
271 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000272 SDValue visitBRCOND(SDNode *N);
273 SDValue visitBR_CC(SDNode *N);
274 SDValue visitLOAD(SDNode *N);
275 SDValue visitSTORE(SDNode *N);
276 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
277 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
278 SDValue visitBUILD_VECTOR(SDNode *N);
279 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000280 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000281 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000282 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000283
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000284 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000285 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000286
Matt Arsenault985b9de2014-03-17 18:58:01 +0000287 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000288
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000289 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
290 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000291 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
292 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000293 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000294 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000295 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000296 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000297
298 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
299 SDValue &CC) const;
300 bool isOneUseSetCC(SDValue N) const;
301
Scott Michelcf0da6c2009-02-17 22:15:04 +0000302 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000303 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000304 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000305 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000306 SDValue BuildSDIV(SDNode *N);
307 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000308 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
309 bool DemandHighBits = true);
310 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000311 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
312 SDValue InnerPos, SDValue InnerNeg,
313 unsigned PosOpcode, unsigned NegOpcode,
314 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000315 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000316 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000317 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000318 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000319 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000320 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000321
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000322 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000323
Jim Laskey708d0db2006-10-04 16:53:27 +0000324 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
325 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000326 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000327 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000328
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000329 /// isAlias - Return true if there is any possibility that the two addresses
330 /// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000331 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000332
Jim Laskeyd07be232006-09-25 16:29:54 +0000333 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000334 /// looking for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000335 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000336
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000337 /// Merge consecutive store operations into a wide store.
338 /// This optimization uses wide integers or vectors when possible.
339 /// \return True if some memory operations were changed.
340 bool MergeConsecutiveStores(StoreSDNode *N);
341
Adam Nemet67483892014-03-04 23:28:31 +0000342 /// \brief Try to transform a truncation where C is a constant:
343 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
344 ///
345 /// \p N needs to be a truncation and its first operand an AND. Other
346 /// requirements are checked by the function (e.g. that trunc is
347 /// single-use) and if missed an empty SDValue is returned.
348 SDValue distributeTruncateThroughAnd(SDNode *N);
349
Chris Lattner4041ab62010-04-15 04:48:01 +0000350 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000351 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000352 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
353 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
354 AttributeSet FnAttrs =
355 DAG.getMachineFunction().getFunction()->getAttributes();
356 ForCodeSize =
357 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
358 Attribute::OptimizeForSize) ||
359 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
360 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000361
Nate Begeman21158fc2005-09-01 00:19:25 +0000362 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000363 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000364
Chris Lattner4041ab62010-04-15 04:48:01 +0000365 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000366
Chris Lattner4041ab62010-04-15 04:48:01 +0000367 /// getShiftAmountTy - Returns a type large enough to hold any valid
368 /// shift amount - before type legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000369 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000370 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
371 if (LHSTy.isVector())
372 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000373 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
374 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000375 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000376
Chris Lattner4041ab62010-04-15 04:48:01 +0000377 /// isTypeLegal - This method returns true if we are running before type
378 /// legalization or if the specified VT is legal.
379 bool isTypeLegal(const EVT &VT) {
380 if (!LegalTypes) return true;
381 return TLI.isTypeLegal(VT);
382 }
Matt Arsenault758659232013-05-18 00:21:46 +0000383
384 /// getSetCCResultType - Convenience wrapper around
385 /// TargetLowering::getSetCCResultType
386 EVT getSetCCResultType(EVT VT) const {
387 return TLI.getSetCCResultType(*DAG.getContext(), VT);
388 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000389 };
390}
391
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000392
393namespace {
394/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
395/// nodes from the worklist.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000396class WorkListRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000397 DAGCombiner &DC;
398public:
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000399 explicit WorkListRemover(DAGCombiner &dc)
400 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000401
Craig Topper7b883b32014-03-08 06:31:39 +0000402 void NodeDeleted(SDNode *N, SDNode *E) override {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000403 DC.removeFromWorkList(N);
404 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000405};
406}
407
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000408//===----------------------------------------------------------------------===//
409// TargetLowering::DAGCombinerInfo implementation
410//===----------------------------------------------------------------------===//
411
412void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
413 ((DAGCombiner*)DC)->AddToWorkList(N);
414}
415
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000416void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
417 ((DAGCombiner*)DC)->removeFromWorkList(N);
418}
419
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000420SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000421CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
422 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000423}
424
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000425SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000426CombineTo(SDNode *N, SDValue Res, bool AddTo) {
427 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000428}
429
430
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000431SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000432CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
433 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000434}
435
Dan Gohmane58ab792009-01-29 01:59:02 +0000436void TargetLowering::DAGCombinerInfo::
437CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
438 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
439}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000440
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000441//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000442// Helper Functions
443//===----------------------------------------------------------------------===//
444
445/// isNegatibleForFree - Return 1 if we can compute the negated form of the
446/// specified expression for the same cost as the expression itself, or 2 if we
447/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000448static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000449 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000450 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000451 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000452 // fneg is removable even if it has multiple uses.
453 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000454
Chris Lattnere49c9742007-05-14 22:04:50 +0000455 // Don't allow anything with multiple uses.
456 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000457
Chris Lattner46980832007-05-25 02:19:06 +0000458 // Don't recurse exponentially.
459 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000460
Chris Lattnere49c9742007-05-14 22:04:50 +0000461 switch (Op.getOpcode()) {
462 default: return false;
463 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000464 // Don't invert constant FP values after legalize. The negated constant
465 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000466 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000467 case ISD::FADD:
468 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000469 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000470
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000471 // After operation legalization, it might not be legal to create new FSUBs.
472 if (LegalOperations &&
473 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
474 return 0;
475
Craig Topper03f39772012-09-09 22:58:45 +0000476 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000477 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
478 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000479 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000480 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000481 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000482 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000483 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000484 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000485 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000486
Bill Wendling6fbf5492009-01-30 23:10:18 +0000487 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000488 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000489
Chris Lattnere49c9742007-05-14 22:04:50 +0000490 case ISD::FMUL:
491 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000492 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000493
Bill Wendling6fbf5492009-01-30 23:10:18 +0000494 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000495 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
496 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000497 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000498
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000499 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000500 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000501
Chris Lattnere49c9742007-05-14 22:04:50 +0000502 case ISD::FP_EXTEND:
503 case ISD::FP_ROUND:
504 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000505 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000506 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000507 }
508}
509
510/// GetNegatedExpression - If isNegatibleForFree returns true, this function
511/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000512static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000513 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000514 // fneg is removable even if it has multiple uses.
515 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000516
Chris Lattnere49c9742007-05-14 22:04:50 +0000517 // Don't allow anything with multiple uses.
518 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000519
Chris Lattner46980832007-05-25 02:19:06 +0000520 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000521 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000522 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000523 case ISD::ConstantFP: {
524 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
525 V.changeSign();
526 return DAG.getConstantFP(V, Op.getValueType());
527 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000528 case ISD::FADD:
529 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000530 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000531
Bill Wendling6fbf5492009-01-30 23:10:18 +0000532 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000533 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000534 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000535 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000536 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000537 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000538 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000539 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000540 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000541 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000542 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000543 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000544 Op.getOperand(0));
545 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000546 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000547 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000548
Bill Wendling6fbf5492009-01-30 23:10:18 +0000549 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000550 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000551 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000552 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000553
Bill Wendling6fbf5492009-01-30 23:10:18 +0000554 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000555 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000556 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000557
Chris Lattnere49c9742007-05-14 22:04:50 +0000558 case ISD::FMUL:
559 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000560 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000561
Bill Wendling6fbf5492009-01-30 23:10:18 +0000562 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000563 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000564 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000565 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000566 return DAG.getNode(Op.getOpcode(), 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 Lattnere49c9742007-05-14 22:04:50 +0000569 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000570
Bill Wendling6fbf5492009-01-30 23:10:18 +0000571 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000572 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000573 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000574 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000575 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000576
Chris Lattnere49c9742007-05-14 22:04:50 +0000577 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000578 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000579 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000580 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000581 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000582 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000583 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000584 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000585 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000586 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000587 }
588}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000589
Nate Begeman2504fe22005-09-01 23:24:04 +0000590// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000591// that selects between the target values used for true and false, making it
592// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
593// the appropriate nodes based on the type of node we are checking. This
594// simplifies life a bit for the callers.
595bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
596 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000597 if (N.getOpcode() == ISD::SETCC) {
598 LHS = N.getOperand(0);
599 RHS = N.getOperand(1);
600 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000601 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000602 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000603
604 if (N.getOpcode() != ISD::SELECT_CC ||
605 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
606 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
607 return false;
608
609 LHS = N.getOperand(0);
610 RHS = N.getOperand(1);
611 CC = N.getOperand(4);
612 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000613}
614
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000615// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
616// one use. If this is true, it allows the users to invert the operation for
617// free when it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000618bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000619 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000620 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000621 return true;
622 return false;
623}
624
Matt Arsenault985b9de2014-03-17 18:58:01 +0000625/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
626/// elements are all the same constant or undefined.
627static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
628 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
629 if (!C)
630 return false;
631
632 APInt SplatUndef;
633 unsigned SplatBitSize;
634 bool HasAnyUndefs;
635 EVT EltVT = N->getValueType(0).getVectorElementType();
636 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
637 HasAnyUndefs) &&
638 EltVT.getSizeInBits() >= SplatBitSize);
639}
640
641// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000642static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
643 if (isa<ConstantSDNode>(N))
644 return N.getNode();
645 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
646 if(BV && BV->isConstant())
647 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000648 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000649}
650
Matt Arsenault985b9de2014-03-17 18:58:01 +0000651// \brief Returns the SDNode if it is a constant splat BuildVector or constant
652// int.
653static ConstantSDNode *isConstOrConstSplat(SDValue N) {
654 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
655 return CN;
656
Benjamin Kramerda4841b2014-04-26 23:09:49 +0000657 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
658 ConstantSDNode *CN = BV->getConstantSplatValue();
659
660 // BuildVectors can truncate their operands. Ignore that case here.
661 if (CN && CN->getValueType(0) == N.getValueType().getScalarType())
662 return CN;
663 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000664
665 return nullptr;
666}
667
Andrew Trickef9de2a2013-05-25 02:42:55 +0000668SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000669 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000670 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000671 if (N0.getOpcode() == Opc) {
672 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
673 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
674 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
675 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
676 if (!OpNode.getNode())
677 return SDValue();
678 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000679 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000680 if (N0.hasOneUse()) {
681 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
682 // use
683 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
684 if (!OpNode.getNode())
685 return SDValue();
686 AddToWorkList(OpNode.getNode());
687 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000688 }
689 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000690 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000691
Juergen Ributzka68402822014-01-13 21:49:25 +0000692 if (N1.getOpcode() == Opc) {
693 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
694 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
695 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
696 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
697 if (!OpNode.getNode())
698 return SDValue();
699 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
700 }
701 if (N1.hasOneUse()) {
702 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
703 // use
704 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
705 if (!OpNode.getNode())
706 return SDValue();
707 AddToWorkList(OpNode.getNode());
708 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
709 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000710 }
711 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000712
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000713 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000714}
715
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000716SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
717 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000718 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
719 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000720 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000721 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000722 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000723 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000724 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000725 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000726 assert((!To[i].getNode() ||
727 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000728 "Cannot combine value to value of different type!"));
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000729 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000730 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000731 if (AddTo) {
732 // Push the new nodes and any users onto the worklist
733 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000734 if (To[i].getNode()) {
735 AddToWorkList(To[i].getNode());
736 AddUsersToWorkList(To[i].getNode());
737 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000738 }
739 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000740
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000741 // Finally, if the node is now dead, remove it from the graph. The node
742 // may not be dead if the replacement process recursively simplified to
743 // something else needing this node.
744 if (N->use_empty()) {
745 // Nodes can be reintroduced into the worklist. Make sure we do not
746 // process a node that has been replaced.
747 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000748
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000749 // Finally, since the node is now dead, remove it from the graph.
750 DAG.DeleteNode(N);
751 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000752 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000753}
754
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000755void DAGCombiner::
756CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000757 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000758 // are deleted, make sure to remove them from our worklist.
759 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000760 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000761
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000762 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000763 AddToWorkList(TLO.New.getNode());
764 AddUsersToWorkList(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000765
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000766 // Finally, if the node is now dead, remove it from the graph. The node
767 // may not be dead if the replacement process recursively simplified to
768 // something else needing this node.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000769 if (TLO.Old.getNode()->use_empty()) {
770 removeFromWorkList(TLO.Old.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000771
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000772 // If the operands of this node are only used by the node, they will now
773 // be dead. Make sure to visit them first to delete dead nodes early.
Hal Finkel2c77fe52014-05-28 15:33:19 +0000774 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
775 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
776 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
777
Gabor Greiff304a7a2008-08-28 21:40:38 +0000778 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000779 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000780}
781
782/// SimplifyDemandedBits - Check the specified integer node value to see if
783/// it can be simplified or if things it uses can be simplified by bit
784/// propagation. If so, return true.
785bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000786 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000787 APInt KnownZero, KnownOne;
788 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
789 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000790
Dan Gohmane58ab792009-01-29 01:59:02 +0000791 // Revisit the node.
792 AddToWorkList(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000793
Dan Gohmane58ab792009-01-29 01:59:02 +0000794 // Replace the old value with the new one.
795 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000796 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000797 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000798 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000799 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000800 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000801
Dan Gohmane58ab792009-01-29 01:59:02 +0000802 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000803 return true;
804}
805
Evan Cheng0abb54d2010-04-24 04:43:44 +0000806void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000807 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000808 EVT VT = Load->getValueType(0);
809 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000810
Evan Cheng0abb54d2010-04-24 04:43:44 +0000811 DEBUG(dbgs() << "\nReplacing.9 ";
812 Load->dump(&DAG);
813 dbgs() << "\nWith: ";
814 Trunc.getNode()->dump(&DAG);
815 dbgs() << '\n');
816 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000817 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
818 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng0abb54d2010-04-24 04:43:44 +0000819 removeFromWorkList(Load);
820 DAG.DeleteNode(Load);
Evan Chenge8136902010-04-27 19:48:13 +0000821 AddToWorkList(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000822}
823
824SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
825 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000826 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000827 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000828 EVT MemVT = LD->getMemoryVT();
829 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000830 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000831 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000832 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000833 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000834 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000835 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000836 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000837 }
838
Evan Chenge19aa5c2010-04-19 19:29:22 +0000839 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000840 switch (Opc) {
841 default: break;
842 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000843 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000844 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000845 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000846 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000847 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000848 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000849 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000850 case ISD::Constant: {
851 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000852 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000853 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000854 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000855 }
856
857 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000858 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000859 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000860}
861
Evan Cheng0abb54d2010-04-24 04:43:44 +0000862SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000863 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
864 return SDValue();
865 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000866 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000867 bool Replace = false;
868 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000869 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000870 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000871 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000872
873 if (Replace)
874 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
875 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000876 DAG.getValueType(OldVT));
877}
878
Evan Cheng0abb54d2010-04-24 04:43:44 +0000879SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000880 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000881 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000882 bool Replace = false;
883 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000884 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000885 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000886 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000887
888 if (Replace)
889 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
890 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000891}
892
Evan Chengaf56fac2010-04-16 06:14:10 +0000893/// PromoteIntBinOp - Promote the specified integer binary operation if the
894/// target indicates it is beneficial. e.g. On x86, it's usually better to
895/// promote i16 operations to i32 since i16 instructions are longer.
896SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
897 if (!LegalOperations)
898 return SDValue();
899
900 EVT VT = Op.getValueType();
901 if (VT.isVector() || !VT.isInteger())
902 return SDValue();
903
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000904 // If operation type is 'undesirable', e.g. i16 on x86, consider
905 // promoting it.
906 unsigned Opc = Op.getOpcode();
907 if (TLI.isTypeDesirableForOp(Opc, VT))
908 return SDValue();
909
Evan Chengaf56fac2010-04-16 06:14:10 +0000910 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000911 // Consult target whether it is a good idea to promote this operation and
912 // what's the right type to promote it to.
913 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000914 assert(PVT != VT && "Don't know what type to promote to!");
915
Evan Cheng0abb54d2010-04-24 04:43:44 +0000916 bool Replace0 = false;
917 SDValue N0 = Op.getOperand(0);
918 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000919 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000920 return SDValue();
921
Evan Cheng0abb54d2010-04-24 04:43:44 +0000922 bool Replace1 = false;
923 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000924 SDValue NN1;
925 if (N0 == N1)
926 NN1 = NN0;
927 else {
928 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000929 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000930 return SDValue();
931 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000932
Evan Cheng0abb54d2010-04-24 04:43:44 +0000933 AddToWorkList(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000934 if (NN1.getNode())
935 AddToWorkList(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000936
937 if (Replace0)
938 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
939 if (Replace1)
940 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000941
Evan Chenge8136902010-04-27 19:48:13 +0000942 DEBUG(dbgs() << "\nPromoting ";
943 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000944 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000945 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000946 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000947 }
948 return SDValue();
949}
950
951/// PromoteIntShiftOp - Promote the specified integer shift operation if the
952/// target indicates it is beneficial. e.g. On x86, it's usually better to
953/// promote i16 operations to i32 since i16 instructions are longer.
954SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
955 if (!LegalOperations)
956 return SDValue();
957
958 EVT VT = Op.getValueType();
959 if (VT.isVector() || !VT.isInteger())
960 return SDValue();
961
962 // If operation type is 'undesirable', e.g. i16 on x86, consider
963 // promoting it.
964 unsigned Opc = Op.getOpcode();
965 if (TLI.isTypeDesirableForOp(Opc, VT))
966 return SDValue();
967
968 EVT PVT = VT;
969 // Consult target whether it is a good idea to promote this operation and
970 // what's the right type to promote it to.
971 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
972 assert(PVT != VT && "Don't know what type to promote to!");
973
Evan Cheng0abb54d2010-04-24 04:43:44 +0000974 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000975 SDValue N0 = Op.getOperand(0);
976 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000977 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000978 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000979 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000980 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000981 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000982 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000983 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000984
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000985 AddToWorkList(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000986 if (Replace)
987 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000988
Evan Chenge8136902010-04-27 19:48:13 +0000989 DEBUG(dbgs() << "\nPromoting ";
990 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000991 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000992 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +0000993 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +0000994 }
995 return SDValue();
996}
997
Evan Chenge19aa5c2010-04-19 19:29:22 +0000998SDValue DAGCombiner::PromoteExtend(SDValue Op) {
999 if (!LegalOperations)
1000 return SDValue();
1001
1002 EVT VT = Op.getValueType();
1003 if (VT.isVector() || !VT.isInteger())
1004 return SDValue();
1005
1006 // If operation type is 'undesirable', e.g. i16 on x86, consider
1007 // promoting it.
1008 unsigned Opc = Op.getOpcode();
1009 if (TLI.isTypeDesirableForOp(Opc, VT))
1010 return SDValue();
1011
1012 EVT PVT = VT;
1013 // Consult target whether it is a good idea to promote this operation and
1014 // what's the right type to promote it to.
1015 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1016 assert(PVT != VT && "Don't know what type to promote to!");
1017 // fold (aext (aext x)) -> (aext x)
1018 // fold (aext (zext x)) -> (zext x)
1019 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001020 DEBUG(dbgs() << "\nPromoting ";
1021 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001022 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001023 }
1024 return SDValue();
1025}
1026
1027bool DAGCombiner::PromoteLoad(SDValue Op) {
1028 if (!LegalOperations)
1029 return false;
1030
1031 EVT VT = Op.getValueType();
1032 if (VT.isVector() || !VT.isInteger())
1033 return false;
1034
1035 // If operation type is 'undesirable', e.g. i16 on x86, consider
1036 // promoting it.
1037 unsigned Opc = Op.getOpcode();
1038 if (TLI.isTypeDesirableForOp(Opc, VT))
1039 return false;
1040
1041 EVT PVT = VT;
1042 // Consult target whether it is a good idea to promote this operation and
1043 // what's the right type to promote it to.
1044 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1045 assert(PVT != VT && "Don't know what type to promote to!");
1046
Andrew Trickef9de2a2013-05-25 02:42:55 +00001047 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001048 SDNode *N = Op.getNode();
1049 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001050 EVT MemVT = LD->getMemoryVT();
1051 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001052 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001053 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001054 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001055 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001056 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001057 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001058 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1059
Evan Cheng0abb54d2010-04-24 04:43:44 +00001060 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001061 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001062 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001063 Result.getNode()->dump(&DAG);
1064 dbgs() << '\n');
1065 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001066 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1067 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001068 removeFromWorkList(N);
1069 DAG.DeleteNode(N);
Evan Chenge8136902010-04-27 19:48:13 +00001070 AddToWorkList(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001071 return true;
1072 }
1073 return false;
1074}
1075
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001076
Chris Lattnere49c9742007-05-14 22:04:50 +00001077//===----------------------------------------------------------------------===//
1078// Main DAG Combiner implementation
1079//===----------------------------------------------------------------------===//
1080
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001081void DAGCombiner::Run(CombineLevel AtLevel) {
1082 // set the instance variables, so that the various visit routines may use it.
1083 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001084 LegalOperations = Level >= AfterLegalizeVectorOps;
1085 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001086
Evan Cheng5e7658c2008-08-29 22:21:44 +00001087 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001088 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1089 E = DAG.allnodes_end(); I != E; ++I)
James Molloy67b6b112012-02-16 09:17:04 +00001090 AddToWorkList(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001091
Evan Cheng5e7658c2008-08-29 22:21:44 +00001092 // Create a dummy node (which is not added to allnodes), that adds a reference
1093 // to the root node, preventing it from being deleted, and tracking any
1094 // changes of the root.
1095 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001096
Jim Laskeye7d2c242006-10-17 19:33:52 +00001097 // The root of the dag may dangle to deleted nodes until the dag combiner is
1098 // done. Set it to null to avoid confusion.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001099 DAG.setRoot(SDValue());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001100
James Molloy67b6b112012-02-16 09:17:04 +00001101 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001102 // try and combine it.
James Molloy67b6b112012-02-16 09:17:04 +00001103 while (!WorkListContents.empty()) {
1104 SDNode *N;
Jack Carterd4e96152013-10-17 01:34:33 +00001105 // The WorkListOrder holds the SDNodes in order, but it may contain
1106 // duplicates.
James Molloy67b6b112012-02-16 09:17:04 +00001107 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1108 // worklist *should* contain, and check the node we want to visit is should
1109 // actually be visited.
1110 do {
Benjamin Kramere1e549d2012-03-10 00:23:58 +00001111 N = WorkListOrder.pop_back_val();
James Molloy67b6b112012-02-16 09:17:04 +00001112 } while (!WorkListContents.erase(N));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001113
Evan Cheng5e7658c2008-08-29 22:21:44 +00001114 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1115 // N is deleted from the DAG, since they too may now be dead or may have a
1116 // reduced number of uses, allowing other xforms.
1117 if (N->use_empty() && N != &Dummy) {
1118 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1119 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001120
Evan Cheng5e7658c2008-08-29 22:21:44 +00001121 DAG.DeleteNode(N);
1122 continue;
Nate Begeman21158fc2005-09-01 00:19:25 +00001123 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001124
Evan Cheng5e7658c2008-08-29 22:21:44 +00001125 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001126
Craig Topperc0196b12014-04-14 00:51:57 +00001127 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001128 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001129
Evan Cheng5e7658c2008-08-29 22:21:44 +00001130 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001131
Evan Cheng5e7658c2008-08-29 22:21:44 +00001132 // If we get back the same node we passed in, rather than a new node or
1133 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001134 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001135 // mechanics for us, we have no work to do in this case.
1136 if (RV.getNode() == N)
1137 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001138
Evan Cheng5e7658c2008-08-29 22:21:44 +00001139 assert(N->getOpcode() != ISD::DELETED_NODE &&
1140 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1141 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001142
Wesley Peck527da1b2010-11-23 03:31:01 +00001143 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001144 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001145 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001146 RV.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001147 dbgs() << '\n');
Eric Christopherd6300d22011-07-14 01:12:15 +00001148
Devang Patelefec7712011-05-23 22:04:42 +00001149 // Transfer debug value.
1150 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001151 WorkListRemover DeadNodes(*this);
1152 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001153 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001154 else {
1155 assert(N->getValueType(0) == RV.getValueType() &&
1156 N->getNumValues() == 1 && "Type mismatch");
1157 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001158 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001159 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001160
Evan Cheng5e7658c2008-08-29 22:21:44 +00001161 // Push the new node and any users onto the worklist
1162 AddToWorkList(RV.getNode());
1163 AddUsersToWorkList(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001164
Evan Cheng5e7658c2008-08-29 22:21:44 +00001165 // Add any uses of the old node to the worklist in case this node is the
1166 // last one that uses them. They may become dead after this node is
1167 // deleted.
1168 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1169 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001170
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001171 // Finally, if the node is now dead, remove it from the graph. The node
1172 // may not be dead if the replacement process recursively simplified to
1173 // something else needing this node.
1174 if (N->use_empty()) {
1175 // Nodes can be reintroduced into the worklist. Make sure we do not
1176 // process a node that has been replaced.
1177 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001178
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001179 // Finally, since the node is now dead, remove it from the graph.
1180 DAG.DeleteNode(N);
1181 }
Evan Cheng5e7658c2008-08-29 22:21:44 +00001182 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001183
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001184 // If the root changed (e.g. it was a dead load, update the root).
1185 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001186 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001187}
1188
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001189SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001190 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001191 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001192 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001193 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001194 case ISD::ADD: return visitADD(N);
1195 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001196 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001197 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001198 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001199 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001200 case ISD::MUL: return visitMUL(N);
1201 case ISD::SDIV: return visitSDIV(N);
1202 case ISD::UDIV: return visitUDIV(N);
1203 case ISD::SREM: return visitSREM(N);
1204 case ISD::UREM: return visitUREM(N);
1205 case ISD::MULHU: return visitMULHU(N);
1206 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001207 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1208 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001209 case ISD::SMULO: return visitSMULO(N);
1210 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001211 case ISD::SDIVREM: return visitSDIVREM(N);
1212 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001213 case ISD::AND: return visitAND(N);
1214 case ISD::OR: return visitOR(N);
1215 case ISD::XOR: return visitXOR(N);
1216 case ISD::SHL: return visitSHL(N);
1217 case ISD::SRA: return visitSRA(N);
1218 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001219 case ISD::ROTR:
1220 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001221 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001222 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001223 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001224 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001225 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001226 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001227 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001228 case ISD::SELECT_CC: return visitSELECT_CC(N);
1229 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001230 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1231 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001232 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001233 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1234 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001235 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001236 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001237 case ISD::FADD: return visitFADD(N);
1238 case ISD::FSUB: return visitFSUB(N);
1239 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001240 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001241 case ISD::FDIV: return visitFDIV(N);
1242 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001243 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001244 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1245 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1246 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1247 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1248 case ISD::FP_ROUND: return visitFP_ROUND(N);
1249 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1250 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1251 case ISD::FNEG: return visitFNEG(N);
1252 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001253 case ISD::FFLOOR: return visitFFLOOR(N);
1254 case ISD::FCEIL: return visitFCEIL(N);
1255 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001256 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001257 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001258 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001259 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001260 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001261 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001262 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1263 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001264 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001265 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001266 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001267 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001268 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001269}
1270
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001271SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001272 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001273
1274 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001275 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001276 assert(N->getOpcode() != ISD::DELETED_NODE &&
1277 "Node was deleted but visit returned NULL!");
1278
1279 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1280 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1281
1282 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001283 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001284 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001285
1286 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1287 }
1288 }
1289
Evan Chengf1005572010-04-28 07:10:39 +00001290 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001291 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001292 switch (N->getOpcode()) {
1293 default: break;
1294 case ISD::ADD:
1295 case ISD::SUB:
1296 case ISD::MUL:
1297 case ISD::AND:
1298 case ISD::OR:
1299 case ISD::XOR:
1300 RV = PromoteIntBinOp(SDValue(N, 0));
1301 break;
1302 case ISD::SHL:
1303 case ISD::SRA:
1304 case ISD::SRL:
1305 RV = PromoteIntShiftOp(SDValue(N, 0));
1306 break;
1307 case ISD::SIGN_EXTEND:
1308 case ISD::ZERO_EXTEND:
1309 case ISD::ANY_EXTEND:
1310 RV = PromoteExtend(SDValue(N, 0));
1311 break;
1312 case ISD::LOAD:
1313 if (PromoteLoad(SDValue(N, 0)))
1314 RV = SDValue(N, 0);
1315 break;
1316 }
1317 }
1318
Scott Michelcf0da6c2009-02-17 22:15:04 +00001319 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001320 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001321 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001322 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001323 SDValue N0 = N->getOperand(0);
1324 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001325
Evan Cheng31604a62008-03-22 01:55:50 +00001326 // Constant operands are canonicalized to RHS.
1327 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001328 SDValue Ops[] = { N1, N0 };
Evan Cheng31604a62008-03-22 01:55:50 +00001329 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
Craig Topper633d99b2014-04-27 23:22:43 +00001330 Ops);
Evan Chengfe7610f2008-03-24 23:55:16 +00001331 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001332 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001333 }
1334 }
1335
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001336 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001337}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001338
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001339/// getInputChainForNode - Given a node, return its input chain if it has one,
1340/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001341static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001342 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001343 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001344 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001345 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001346 return N->getOperand(NumOps-1);
1347 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001348 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001349 return N->getOperand(i);
1350 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001351 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001352}
1353
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001354SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001355 // If N has two operands, where one has an input chain equal to the other,
1356 // the 'other' chain is redundant.
1357 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001358 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001359 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001360 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001361 return N->getOperand(1);
1362 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001363
Chris Lattner48fb92f2007-05-16 06:37:59 +00001364 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001365 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001366 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001367 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001368
Jim Laskey708d0db2006-10-04 16:53:27 +00001369 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001370 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001371
Jim Laskey0463e082006-10-07 23:37:56 +00001372 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001373 // encountered.
1374 for (unsigned i = 0; i < TFs.size(); ++i) {
1375 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001376
Jim Laskey708d0db2006-10-04 16:53:27 +00001377 // Check each of the operands.
1378 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001379 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001380
Jim Laskey708d0db2006-10-04 16:53:27 +00001381 switch (Op.getOpcode()) {
1382 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001383 // Entry tokens don't need to be added to the list. They are
1384 // rededundant.
1385 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001386 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001387
Jim Laskey708d0db2006-10-04 16:53:27 +00001388 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001389 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001390 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001391 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001392 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001393 // Clean up in case the token factor is removed.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001394 AddToWorkList(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001395 Changed = true;
1396 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001397 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001398 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001399
Jim Laskey708d0db2006-10-04 16:53:27 +00001400 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001401 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001402 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001403 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001404 else
1405 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001406 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001407 }
1408 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001409 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001410
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001411 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001412
1413 // If we've change things around then replace token factor.
1414 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001415 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001416 // The entry token is the only possible outcome.
1417 Result = DAG.getEntryNode();
1418 } else {
1419 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001420 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001421 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001422
Jim Laskeydcf983c2006-10-13 23:32:28 +00001423 // Don't add users to work list.
1424 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001425 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001426
Jim Laskey708d0db2006-10-04 16:53:27 +00001427 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001428}
1429
Chris Lattneree322b42008-02-13 07:25:05 +00001430/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001431SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattneree322b42008-02-13 07:25:05 +00001432 WorkListRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001433 // Replacing results may cause a different MERGE_VALUES to suddenly
1434 // be CSE'd with N, and carry its uses with it. Iterate until no
1435 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001436 // First add the users of this node to the work list so that they
1437 // can be tried again once they have new operands.
1438 AddUsersToWorkList(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001439 do {
1440 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001441 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001442 } while (!N->use_empty());
Chris Lattneree322b42008-02-13 07:25:05 +00001443 removeFromWorkList(N);
1444 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001445 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001446}
1447
Evan Cheng92011002007-01-19 17:51:44 +00001448static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001449SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001450 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001451 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001452 SDValue N00 = N0.getOperand(0);
1453 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001454 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001455
Gabor Greiff304a7a2008-08-28 21:40:38 +00001456 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001457 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001458 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001459 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1460 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001461 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001462 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001463 N00.getOperand(1), N01));
1464 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001465 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001466
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001467 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001468}
1469
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001470SDValue DAGCombiner::visitADD(SDNode *N) {
1471 SDValue N0 = N->getOperand(0);
1472 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001473 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1474 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001475 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001476
1477 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001478 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001479 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001480 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001481
1482 // fold (add x, 0) -> x, vector edition
1483 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1484 return N0;
1485 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1486 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001487 }
Bill Wendling0864a752008-12-10 22:36:00 +00001488
Dan Gohman06563a82007-07-03 14:03:57 +00001489 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001490 if (N0.getOpcode() == ISD::UNDEF)
1491 return N0;
1492 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001493 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001494 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001495 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001496 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001497 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001498 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001499 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001500 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001501 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001502 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001503 // fold (add Sym, c) -> Sym+c
1504 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001505 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001506 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001507 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001508 GA->getOffset() +
1509 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001510 // fold ((c1-A)+c2) -> (c1+c2)-A
1511 if (N1C && N0.getOpcode() == ISD::SUB)
1512 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001513 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001514 DAG.getConstant(N1C->getAPIntValue()+
1515 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001516 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001517 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001518 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001519 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001520 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001521 // fold ((0-A) + B) -> B-A
1522 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1523 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001524 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001525 // fold (A + (0-B)) -> A-B
1526 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1527 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001528 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001529 // fold (A+(B-A)) -> B
1530 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001531 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001532 // fold ((B-A)+A) -> B
1533 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1534 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001535 // fold (A+(B-(A+C))) to (B-C)
1536 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001537 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001538 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001539 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001540 // fold (A+(B-(C+A))) to (B-C)
1541 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001542 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001543 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001544 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001545 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001546 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1547 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001548 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001549 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001550 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001551
Dale Johannesen8c766702008-12-02 01:30:54 +00001552 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1553 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1554 SDValue N00 = N0.getOperand(0);
1555 SDValue N01 = N0.getOperand(1);
1556 SDValue N10 = N1.getOperand(0);
1557 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001558
1559 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001560 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1561 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1562 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001563 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001564
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001565 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1566 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001567
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001568 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001569 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001570 APInt LHSZero, LHSOne;
1571 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001572 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001573
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001574 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001575 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001576
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001577 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1578 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001579 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1580 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1581 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1582 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001583 }
1584 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001585
Evan Cheng92011002007-01-19 17:51:44 +00001586 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001587 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001588 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001589 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001590 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001591 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001592 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001593 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001594 }
1595
Dan Gohman954f4902010-01-19 23:30:49 +00001596 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1597 if (N1.getOpcode() == ISD::SHL &&
1598 N1.getOperand(0).getOpcode() == ISD::SUB)
1599 if (ConstantSDNode *C =
1600 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1601 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001602 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1603 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001604 N1.getOperand(0).getOperand(1),
1605 N1.getOperand(1)));
1606 if (N0.getOpcode() == ISD::SHL &&
1607 N0.getOperand(0).getOpcode() == ISD::SUB)
1608 if (ConstantSDNode *C =
1609 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1610 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001611 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1612 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001613 N0.getOperand(0).getOperand(1),
1614 N0.getOperand(1)));
1615
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001616 if (N1.getOpcode() == ISD::AND) {
1617 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001618 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001619 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1620 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001621
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001622 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1623 // and similar xforms where the inner op is either ~0 or 0.
1624 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001625 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001626 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1627 }
1628 }
1629
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001630 // add (sext i1), X -> sub X, (zext i1)
1631 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1632 N0.getOperand(0).getValueType() == MVT::i1 &&
1633 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001634 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001635 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1636 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1637 }
1638
Evan Chengf1005572010-04-28 07:10:39 +00001639 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001640}
1641
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001642SDValue DAGCombiner::visitADDC(SDNode *N) {
1643 SDValue N0 = N->getOperand(0);
1644 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001645 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1646 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001647 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001648
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001649 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001650 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001651 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001652 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001653 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001654
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001655 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001656 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001657 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001658
Chris Lattner47206662007-03-04 20:40:38 +00001659 // fold (addc x, 0) -> x + no carry out
1660 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001661 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001662 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001663
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001664 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001665 APInt LHSZero, LHSOne;
1666 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001667 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001668
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001669 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001670 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001671
Chris Lattner47206662007-03-04 20:40:38 +00001672 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1673 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001674 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001675 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001676 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001677 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001678 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001679
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001680 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001681}
1682
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001683SDValue DAGCombiner::visitADDE(SDNode *N) {
1684 SDValue N0 = N->getOperand(0);
1685 SDValue N1 = N->getOperand(1);
1686 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001687 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1688 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001689
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001690 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001691 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001692 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001693 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001694
Chris Lattner47206662007-03-04 20:40:38 +00001695 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001696 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001697 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001698
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001699 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001700}
1701
Eric Christophere5ca1e02011-02-16 04:50:12 +00001702// Since it may not be valid to emit a fold to zero for vector initializers
1703// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001704static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001705 SelectionDAG &DAG,
1706 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001707 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001708 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001709 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1710 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001711 return SDValue();
1712}
1713
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001714SDValue DAGCombiner::visitSUB(SDNode *N) {
1715 SDValue N0 = N->getOperand(0);
1716 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001717 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1718 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001719 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001720 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001721 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001722
Dan Gohmana8665142007-06-25 16:23:39 +00001723 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001724 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001725 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001726 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001727
1728 // fold (sub x, 0) -> x, vector edition
1729 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1730 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001731 }
Bill Wendling0864a752008-12-10 22:36:00 +00001732
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001733 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001734 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001735 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001736 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001737 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001738 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001739 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001740 // fold (sub x, c) -> (add x, -c)
1741 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001742 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001743 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001744 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1745 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001746 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001747 // fold A-(A-B) -> B
1748 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1749 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001750 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001751 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001752 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001753 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001754 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001755 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001756 // fold C2-(A+C1) -> (C2-C1)-A
1757 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001758 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1759 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001760 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001761 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001762 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001763 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001764 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001765 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1766 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001767 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001768 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001769 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001770 // fold ((A+(C+B))-B) -> A+C
1771 if (N0.getOpcode() == ISD::ADD &&
1772 N0.getOperand(1).getOpcode() == ISD::ADD &&
1773 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001774 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001775 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001776 // fold ((A-(B-C))-C) -> A-B
1777 if (N0.getOpcode() == ISD::SUB &&
1778 N0.getOperand(1).getOpcode() == ISD::SUB &&
1779 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001780 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001781 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001782
Dan Gohman06563a82007-07-03 14:03:57 +00001783 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001784 if (N0.getOpcode() == ISD::UNDEF)
1785 return N0;
1786 if (N1.getOpcode() == ISD::UNDEF)
1787 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001788
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001789 // If the relocation model supports it, consider symbol offsets.
1790 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001791 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001792 // fold (sub Sym, c) -> Sym-c
1793 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001794 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001795 GA->getOffset() -
1796 (uint64_t)N1C->getSExtValue());
1797 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1798 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1799 if (GA->getGlobal() == GB->getGlobal())
1800 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1801 VT);
1802 }
1803
Evan Chengf1005572010-04-28 07:10:39 +00001804 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001805}
1806
Craig Topper43a1bd62012-01-07 09:06:39 +00001807SDValue DAGCombiner::visitSUBC(SDNode *N) {
1808 SDValue N0 = N->getOperand(0);
1809 SDValue N1 = N->getOperand(1);
1810 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1811 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1812 EVT VT = N0.getValueType();
1813
1814 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001815 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001816 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1817 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001818 MVT::Glue));
1819
1820 // fold (subc x, x) -> 0 + no borrow
1821 if (N0 == N1)
1822 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001823 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001824 MVT::Glue));
1825
1826 // fold (subc x, 0) -> x + no borrow
1827 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001828 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001829 MVT::Glue));
1830
1831 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1832 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001833 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1834 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001835 MVT::Glue));
1836
1837 return SDValue();
1838}
1839
1840SDValue DAGCombiner::visitSUBE(SDNode *N) {
1841 SDValue N0 = N->getOperand(0);
1842 SDValue N1 = N->getOperand(1);
1843 SDValue CarryIn = N->getOperand(2);
1844
1845 // fold (sube x, y, false) -> (subc x, y)
1846 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001847 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001848
1849 return SDValue();
1850}
1851
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001852SDValue DAGCombiner::visitMUL(SDNode *N) {
1853 SDValue N0 = N->getOperand(0);
1854 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001855 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001856
Dan Gohman06563a82007-07-03 14:03:57 +00001857 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001858 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001859 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001860
1861 bool N0IsConst = false;
1862 bool N1IsConst = false;
1863 APInt ConstValue0, ConstValue1;
1864 // fold vector ops
1865 if (VT.isVector()) {
1866 SDValue FoldedVOp = SimplifyVBinOp(N);
1867 if (FoldedVOp.getNode()) return FoldedVOp;
1868
1869 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1870 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1871 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001872 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001873 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1874 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001875 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001876 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1877 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001878 }
1879
Nate Begeman21158fc2005-09-01 00:19:25 +00001880 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001881 if (N0IsConst && N1IsConst)
1882 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1883
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001884 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001885 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001886 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001887 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001888 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001889 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001890 // We require a splat of the entire scalar bit width for non-contiguous
1891 // bit patterns.
1892 bool IsFullSplat =
1893 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001894 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001895 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001896 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001897 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001898 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001899 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001900 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001901 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001902 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001903 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001904 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001905 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001906 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001907 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001908 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001909 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001910 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001911 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001912 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001913 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001914 DAG.getConstant(Log2Val,
1915 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001916 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001917
1918 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001919 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001920 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001921 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1922 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001923 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001924 N1, N0.getOperand(1));
Gabor Greiff304a7a2008-08-28 21:40:38 +00001925 AddToWorkList(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001926 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001927 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001928 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001929
Chris Lattner324871e2006-03-01 03:44:24 +00001930 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1931 // use.
1932 {
Craig Topperc0196b12014-04-14 00:51:57 +00001933 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001934 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001935 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001936 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1937 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001938 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001939 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001940 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001941 isa<ConstantSDNode>(N1.getOperand(1)) &&
1942 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001943 Sh = N1; Y = N0;
1944 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001945
Gabor Greiff304a7a2008-08-28 21:40:38 +00001946 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001947 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001948 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001949 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001950 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001951 }
1952 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001953
Chris Lattnerf29f5202006-03-04 23:33:26 +00001954 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001955 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1956 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1957 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001958 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1959 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001960 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001961 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001962 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001963
Nate Begeman22e251a2006-02-03 06:46:56 +00001964 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001965 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001966 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001967 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001968
Evan Chengf1005572010-04-28 07:10:39 +00001969 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001970}
1971
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001972SDValue DAGCombiner::visitSDIV(SDNode *N) {
1973 SDValue N0 = N->getOperand(0);
1974 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00001975 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1976 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001977 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001978
Dan Gohmana8665142007-06-25 16:23:39 +00001979 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001980 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001981 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001982 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00001983 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001984
Nate Begeman21158fc2005-09-01 00:19:25 +00001985 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001986 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00001987 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00001988 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00001989 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00001990 return N0;
1991 // fold (sdiv X, -1) -> 0-X
1992 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001993 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00001994 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00001995 // If we know the sign bits of both operands are zero, strength reduce to a
1996 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00001997 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00001998 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001999 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002000 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002001 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002002
Nate Begeman57b35672006-02-17 07:26:20 +00002003 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002004 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2005 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002006 // If dividing by powers of two is cheap, then don't perform the following
2007 // fold.
2008 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002009 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002010
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002011 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002012
Chris Lattner471627c2006-02-16 08:02:36 +00002013 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002014 SDValue SGN =
2015 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2016 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2017 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002018 AddToWorkList(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002019
Chris Lattner471627c2006-02-16 08:02:36 +00002020 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002021 SDValue SRL =
2022 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2023 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2024 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002025 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002026 AddToWorkList(SRL.getNode());
2027 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002028 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002029 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002030
Nate Begeman4dd38312005-10-21 00:02:42 +00002031 // If we're dividing by a positive value, we're done. Otherwise, we must
2032 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002033 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002034 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002035
Gabor Greiff304a7a2008-08-28 21:40:38 +00002036 AddToWorkList(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002037 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002038 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002039
Nate Begemanc6f067a2005-10-20 02:15:44 +00002040 // if integer divide is expensive and we satisfy the requirements, emit an
2041 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002042 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002043 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002044 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002045 }
Dan Gohmana8665142007-06-25 16:23:39 +00002046
Dan Gohman06563a82007-07-03 14:03:57 +00002047 // undef / X -> 0
2048 if (N0.getOpcode() == ISD::UNDEF)
2049 return DAG.getConstant(0, VT);
2050 // X / undef -> undef
2051 if (N1.getOpcode() == ISD::UNDEF)
2052 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002053
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002054 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002055}
2056
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002057SDValue DAGCombiner::visitUDIV(SDNode *N) {
2058 SDValue N0 = N->getOperand(0);
2059 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002060 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2061 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002062 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002063
Dan Gohmana8665142007-06-25 16:23:39 +00002064 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002065 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002066 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002067 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002068 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002069
Nate Begeman21158fc2005-09-01 00:19:25 +00002070 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002071 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002072 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002073 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002074 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002075 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002076 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002077 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002078 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002079 if (N1.getOpcode() == ISD::SHL) {
2080 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002081 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002082 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002083 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002084 N1.getOperand(1),
2085 DAG.getConstant(SHC->getAPIntValue()
2086 .logBase2(),
2087 ADDVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002088 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002089 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002090 }
2091 }
2092 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002093 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002094 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002095 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002096 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002097 }
Dan Gohmana8665142007-06-25 16:23:39 +00002098
Dan Gohman06563a82007-07-03 14:03:57 +00002099 // undef / X -> 0
2100 if (N0.getOpcode() == ISD::UNDEF)
2101 return DAG.getConstant(0, VT);
2102 // X / undef -> undef
2103 if (N1.getOpcode() == ISD::UNDEF)
2104 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002105
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002106 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002107}
2108
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002109SDValue DAGCombiner::visitSREM(SDNode *N) {
2110 SDValue N0 = N->getOperand(0);
2111 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002112 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2113 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002114 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002115
Nate Begeman21158fc2005-09-01 00:19:25 +00002116 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002117 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002118 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002119 // If we know the sign bits of both operands are zero, strength reduce to a
2120 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002121 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002122 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002123 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002124 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002125
Dan Gohman9a693412007-11-26 23:46:11 +00002126 // If X/C can be simplified by the division-by-constant logic, lower
2127 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002128 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002129 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002130 AddToWorkList(Div.getNode());
2131 SDValue OptimizedDiv = combine(Div.getNode());
2132 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002133 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002134 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002135 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002136 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002137 return Sub;
2138 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002139 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002140
Dan Gohman06563a82007-07-03 14:03:57 +00002141 // undef % X -> 0
2142 if (N0.getOpcode() == ISD::UNDEF)
2143 return DAG.getConstant(0, VT);
2144 // X % undef -> undef
2145 if (N1.getOpcode() == ISD::UNDEF)
2146 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002147
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002148 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002149}
2150
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002151SDValue DAGCombiner::visitUREM(SDNode *N) {
2152 SDValue N0 = N->getOperand(0);
2153 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002154 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2155 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002156 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002157
Nate Begeman21158fc2005-09-01 00:19:25 +00002158 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002159 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002160 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002161 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002162 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002163 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002164 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002165 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2166 if (N1.getOpcode() == ISD::SHL) {
2167 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002168 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002169 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002170 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002171 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002172 VT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002173 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002174 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002175 }
2176 }
2177 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002178
Dan Gohman9a693412007-11-26 23:46:11 +00002179 // If X/C can be simplified by the division-by-constant logic, lower
2180 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002181 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002182 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman1df80f62008-09-08 16:59:01 +00002183 AddToWorkList(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002184 SDValue OptimizedDiv = combine(Div.getNode());
2185 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002186 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002187 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002188 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002189 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002190 return Sub;
2191 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002192 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002193
Dan Gohman06563a82007-07-03 14:03:57 +00002194 // undef % X -> 0
2195 if (N0.getOpcode() == ISD::UNDEF)
2196 return DAG.getConstant(0, VT);
2197 // X % undef -> undef
2198 if (N1.getOpcode() == ISD::UNDEF)
2199 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002200
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002201 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002202}
2203
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002204SDValue DAGCombiner::visitMULHS(SDNode *N) {
2205 SDValue N0 = N->getOperand(0);
2206 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002207 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002208 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002209 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002210
Nate Begeman21158fc2005-09-01 00:19:25 +00002211 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002212 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002213 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002214 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002215 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002216 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002217 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002218 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002219 // fold (mulhs 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 mulhs 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::SIGN_EXTEND, DL, NewVT, N0);
2231 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2232 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002233 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 Gohman2ce6f2a2008-07-27 21:46:04 +00002242SDValue DAGCombiner::visitMULHU(SDNode *N) {
2243 SDValue N0 = N->getOperand(0);
2244 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002245 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002246 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002247 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002248
Nate Begeman21158fc2005-09-01 00:19:25 +00002249 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002250 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002251 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002252 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002253 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002254 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002255 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002256 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002257 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002258
Chris Lattner10bd29f2010-12-13 08:39:01 +00002259 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2260 // plus a shift.
2261 if (VT.isSimple() && !VT.isVector()) {
2262 MVT Simple = VT.getSimpleVT();
2263 unsigned SimpleSize = Simple.getSizeInBits();
2264 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2265 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2266 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2267 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2268 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2269 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002270 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002271 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2272 }
2273 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002274
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002275 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002276}
2277
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002278/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2279/// compute two values. LoOp and HiOp give the opcodes for the two computations
2280/// that are being performed. Return true if a simplification was made.
2281///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002282SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002283 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002284 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002285 bool HiExists = N->hasAnyUseOfValue(1);
2286 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002287 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002288 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002289 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002290 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002291 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002292 }
2293
2294 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002295 bool LoExists = N->hasAnyUseOfValue(0);
2296 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002297 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002298 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002299 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002300 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002301 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002302 }
2303
Evan Chengece4c682007-11-08 09:25:29 +00002304 // If both halves are used, return as it is.
2305 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002306 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002307
2308 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002309 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002310 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002311 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002312 AddToWorkList(Lo.getNode());
2313 SDValue LoOpt = combine(Lo.getNode());
2314 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002315 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002316 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002317 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002318 }
2319
Evan Chengece4c682007-11-08 09:25:29 +00002320 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002321 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002322 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002323 AddToWorkList(Hi.getNode());
2324 SDValue HiOpt = combine(Hi.getNode());
2325 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002326 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002327 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002328 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002329 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002330
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002331 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002332}
2333
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002334SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2335 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002336 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002337
Chris Lattner15090e12010-12-15 06:04:19 +00002338 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002339 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002340
2341 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2342 // plus a shift.
2343 if (VT.isSimple() && !VT.isVector()) {
2344 MVT Simple = VT.getSimpleVT();
2345 unsigned SimpleSize = Simple.getSizeInBits();
2346 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2347 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2348 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2349 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2350 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2351 // Compute the high part as N1.
2352 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002353 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002354 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2355 // Compute the low part as N0.
2356 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2357 return CombineTo(N, Lo, Hi);
2358 }
2359 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002360
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002361 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002362}
2363
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002364SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2365 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002366 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002367
Chris Lattner15090e12010-12-15 06:04:19 +00002368 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002369 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002370
Chris Lattner15090e12010-12-15 06:04:19 +00002371 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2372 // plus a shift.
2373 if (VT.isSimple() && !VT.isVector()) {
2374 MVT Simple = VT.getSimpleVT();
2375 unsigned SimpleSize = Simple.getSizeInBits();
2376 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2377 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2378 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2379 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2380 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2381 // Compute the high part as N1.
2382 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002383 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002384 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2385 // Compute the low part as N0.
2386 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2387 return CombineTo(N, Lo, Hi);
2388 }
2389 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002390
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002391 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002392}
2393
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002394SDValue DAGCombiner::visitSMULO(SDNode *N) {
2395 // (smulo x, 2) -> (saddo x, x)
2396 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2397 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002398 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002399 N->getOperand(0), N->getOperand(0));
2400
2401 return SDValue();
2402}
2403
2404SDValue DAGCombiner::visitUMULO(SDNode *N) {
2405 // (umulo x, 2) -> (uaddo x, x)
2406 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2407 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002408 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002409 N->getOperand(0), N->getOperand(0));
2410
2411 return SDValue();
2412}
2413
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002414SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2415 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002416 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002417
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002418 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002419}
2420
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002421SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2422 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002423 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002424
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002425 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002426}
2427
Chris Lattner8d6fc202006-05-05 05:51:50 +00002428/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2429/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002430SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2431 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002432 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002433 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002434
Dan Gohmandd5286d2010-01-14 03:08:49 +00002435 // Bail early if none of these transforms apply.
2436 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2437
Chris Lattner002ee912006-05-05 06:31:05 +00002438 // For each of OP in AND/OR/XOR:
2439 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2440 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2441 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002442 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002443 //
2444 // do not sink logical op inside of a vector extend, since it may combine
2445 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002446 EVT Op0VT = N0.getOperand(0).getValueType();
2447 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002448 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002449 // Avoid infinite looping with PromoteIntBinOp.
2450 (N0.getOpcode() == ISD::ANY_EXTEND &&
2451 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002452 (N0.getOpcode() == ISD::TRUNCATE &&
2453 (!TLI.isZExtFree(VT, Op0VT) ||
2454 !TLI.isTruncateFree(Op0VT, VT)) &&
2455 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002456 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002457 Op0VT == N1.getOperand(0).getValueType() &&
2458 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002459 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002460 N0.getOperand(0).getValueType(),
2461 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002462 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002463 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002464 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002465
Chris Lattner5ac42932006-05-05 06:10:43 +00002466 // For each of OP in SHL/SRL/SRA/AND...
2467 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2468 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2469 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002470 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002471 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002472 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002473 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002474 N0.getOperand(0).getValueType(),
2475 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002476 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002477 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002478 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002479 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002480
Nadav Rotemb0783502012-04-01 19:31:22 +00002481 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2482 // Only perform this optimization after type legalization and before
2483 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2484 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2485 // we don't want to undo this promotion.
2486 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2487 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002488 if ((N0.getOpcode() == ISD::BITCAST ||
2489 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2490 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002491 SDValue In0 = N0.getOperand(0);
2492 SDValue In1 = N1.getOperand(0);
2493 EVT In0Ty = In0.getValueType();
2494 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002495 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002496 // If both incoming values are integers, and the original types are the
2497 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002498 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002499 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2500 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotemb0783502012-04-01 19:31:22 +00002501 AddToWorkList(Op.getNode());
2502 return BC;
2503 }
2504 }
2505
2506 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2507 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2508 // If both shuffles use the same mask, and both shuffle within a single
2509 // vector, then it is worthwhile to move the swizzle after the operation.
2510 // The type-legalizer generates this pattern when loading illegal
2511 // vector types from memory. In many cases this allows additional shuffle
2512 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002513 // There are other cases where moving the shuffle after the xor/and/or
2514 // is profitable even if shuffles don't perform a swizzle.
2515 // If both shuffles use the same mask, and both shuffles have the same first
2516 // or second operand, then it might still be profitable to move the shuffle
2517 // after the xor/and/or operation.
2518 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002519 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2520 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002521
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002522 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002523 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002524
Nadav Rotemb0783502012-04-01 19:31:22 +00002525 // Check that both shuffles use the same mask. The masks are known to be of
2526 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002527 // Check also that shuffles have only one use to avoid introducing extra
2528 // instructions.
2529 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2530 SVN0->getMask().equals(SVN1->getMask())) {
2531 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002532
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002533 // Don't try to fold this node if it requires introducing a
2534 // build vector of all zeros that might be illegal at this stage.
2535 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2536 if (!LegalTypes)
2537 ShOp = DAG.getConstant(0, VT);
2538 else
2539 ShOp = SDValue();
2540 }
2541
2542 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2543 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2544 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2545 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2546 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2547 N0->getOperand(0), N1->getOperand(0));
2548 AddToWorkList(NewNode.getNode());
2549 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2550 &SVN0->getMask()[0]);
2551 }
2552
2553 // Don't try to fold this node if it requires introducing a
2554 // build vector of all zeros that might be illegal at this stage.
2555 ShOp = N0->getOperand(0);
2556 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2557 if (!LegalTypes)
2558 ShOp = DAG.getConstant(0, VT);
2559 else
2560 ShOp = SDValue();
2561 }
2562
2563 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2564 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2565 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2566 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2567 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2568 N0->getOperand(1), N1->getOperand(1));
2569 AddToWorkList(NewNode.getNode());
2570 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2571 &SVN0->getMask()[0]);
2572 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002573 }
2574 }
Craig Topper9c3da312012-04-09 07:19:09 +00002575
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002576 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002577}
2578
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002579SDValue DAGCombiner::visitAND(SDNode *N) {
2580 SDValue N0 = N->getOperand(0);
2581 SDValue N1 = N->getOperand(1);
2582 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002583 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2584 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002585 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002586 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002587
Dan Gohmana8665142007-06-25 16:23:39 +00002588 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002589 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002590 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002591 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002592
2593 // fold (and x, 0) -> 0, vector edition
2594 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2595 return N0;
2596 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2597 return N1;
2598
2599 // fold (and x, -1) -> x, vector edition
2600 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2601 return N1;
2602 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2603 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002604 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002605
Dan Gohman06563a82007-07-03 14:03:57 +00002606 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002607 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002608 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002609 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002610 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002611 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002612 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002613 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002614 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002615 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002616 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002617 return N0;
2618 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002619 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002620 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002621 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002622 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002623 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002624 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002625 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002626 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002627 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002628 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002629 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002630 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002631 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2632 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002633 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002634 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002635 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002636 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002637 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002638 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002639
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002640 // Replace uses of the AND with uses of the Zero extend node.
2641 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002642
Chris Lattner49beaf42006-02-02 07:17:31 +00002643 // We actually want to replace all uses of the any_extend with the
2644 // zero_extend, to avoid duplicating things. This will later cause this
2645 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002646 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002647 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002648 }
2649 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002650 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002651 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2652 // already be zero by virtue of the width of the base type of the load.
2653 //
2654 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2655 // more cases.
2656 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2657 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2658 N0.getOpcode() == ISD::LOAD) {
2659 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2660 N0 : N0.getOperand(0) );
2661
2662 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2663 // This can be a pure constant or a vector splat, in which case we treat the
2664 // vector as a scalar and use the splat value.
2665 APInt Constant = APInt::getNullValue(1);
2666 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2667 Constant = C->getAPIntValue();
2668 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2669 APInt SplatValue, SplatUndef;
2670 unsigned SplatBitSize;
2671 bool HasAnyUndefs;
2672 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2673 SplatBitSize, HasAnyUndefs);
2674 if (IsSplat) {
2675 // Undef bits can contribute to a possible optimisation if set, so
2676 // set them.
2677 SplatValue |= SplatUndef;
2678
2679 // The splat value may be something like "0x00FFFFFF", which means 0 for
2680 // the first vector value and FF for the rest, repeating. We need a mask
2681 // that will apply equally to all members of the vector, so AND all the
2682 // lanes of the constant together.
2683 EVT VT = Vector->getValueType(0);
2684 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002685
2686 // If the splat value has been compressed to a bitlength lower
2687 // than the size of the vector lane, we need to re-expand it to
2688 // the lane size.
2689 if (BitWidth > SplatBitSize)
2690 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2691 SplatBitSize < BitWidth;
2692 SplatBitSize = SplatBitSize * 2)
2693 SplatValue |= SplatValue.shl(SplatBitSize);
2694
James Molloy862fe492012-02-20 12:02:38 +00002695 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002696 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002697 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2698 }
2699 }
2700
2701 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2702 // actually legal and isn't going to get expanded, else this is a false
2703 // optimisation.
2704 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2705 Load->getMemoryVT());
2706
2707 // Resize the constant to the same size as the original memory access before
2708 // extension. If it is still the AllOnesValue then this AND is completely
2709 // unneeded.
2710 Constant =
2711 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2712
2713 bool B;
2714 switch (Load->getExtensionType()) {
2715 default: B = false; break;
2716 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2717 case ISD::ZEXTLOAD:
2718 case ISD::NON_EXTLOAD: B = true; break;
2719 }
2720
2721 if (B && Constant.isAllOnesValue()) {
2722 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2723 // preserve semantics once we get rid of the AND.
2724 SDValue NewLoad(Load, 0);
2725 if (Load->getExtensionType() == ISD::EXTLOAD) {
2726 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002727 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002728 Load->getChain(), Load->getBasePtr(),
2729 Load->getOffset(), Load->getMemoryVT(),
2730 Load->getMemOperand());
2731 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002732 if (Load->getNumValues() == 3) {
2733 // PRE/POST_INC loads have 3 values.
2734 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2735 NewLoad.getValue(2) };
2736 CombineTo(Load, To, 3, true);
2737 } else {
2738 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2739 }
James Molloy862fe492012-02-20 12:02:38 +00002740 }
2741
2742 // Fold the AND away, taking care not to fold to the old load node if we
2743 // replaced it.
2744 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2745
2746 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2747 }
2748 }
Nate Begeman049b7482005-09-09 19:49:52 +00002749 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2750 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2751 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2752 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002753
Nate Begeman049b7482005-09-09 19:49:52 +00002754 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002755 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002756 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002757 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002758 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002759 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002760 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002761 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002762 }
Bill Wendling86171912009-01-30 20:43:18 +00002763 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002764 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002765 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002766 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002767 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002768 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002769 }
Bill Wendling86171912009-01-30 20:43:18 +00002770 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002771 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002772 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002773 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002774 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002775 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002776 }
2777 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002778 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2779 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2780 Op0 == Op1 && LL.getValueType().isInteger() &&
2781 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2782 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2783 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2784 cast<ConstantSDNode>(RR)->isNullValue()))) {
2785 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2786 LL, DAG.getConstant(1, LL.getValueType()));
2787 AddToWorkList(ADDNode.getNode());
2788 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2789 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2790 }
Nate Begeman049b7482005-09-09 19:49:52 +00002791 // canonicalize equivalent to ll == rl
2792 if (LL == RR && LR == RL) {
2793 Op1 = ISD::getSetCCSwappedOperands(Op1);
2794 std::swap(RL, RR);
2795 }
2796 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002797 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002798 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002799 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002800 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002801 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2802 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002803 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002804 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002805 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002806 }
2807 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002808
Bill Wendling86171912009-01-30 20:43:18 +00002809 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002810 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002811 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002812 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002813 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002814
Nate Begemandc7bba92006-02-03 22:24:05 +00002815 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2816 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002817 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002818 SimplifyDemandedBits(SDValue(N, 0)))
2819 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002820
Nate Begeman02b23c62005-10-13 03:11:28 +00002821 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002822 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002823 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002824 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002825 // If we zero all the possible extended bits, then we can turn this into
2826 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002827 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002828 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002829 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002830 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002831 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002832 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002833 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002834 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002835 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002836 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002837 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002838 }
2839 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002840 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002841 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002842 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002843 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002844 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002845 // If we zero all the possible extended bits, then we can turn this into
2846 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002847 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002848 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002849 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002850 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002851 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002852 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002853 LN0->getChain(), LN0->getBasePtr(),
2854 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002855 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002856 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002857 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002858 }
2859 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002860
Chris Lattnerf0032b32006-02-28 06:49:37 +00002861 // fold (and (load x), 255) -> (zextload x, i8)
2862 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002863 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2864 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2865 (N0.getOpcode() == ISD::ANY_EXTEND &&
2866 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2867 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2868 LoadSDNode *LN0 = HasAnyExt
2869 ? cast<LoadSDNode>(N0.getOperand(0))
2870 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002871 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002872 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002873 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002874 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2875 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2876 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002877
Evan Cheng166a4e62010-01-06 19:38:29 +00002878 if (ExtVT == LoadedVT &&
2879 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002880 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002881
2882 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002883 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002884 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2885 LN0->getMemOperand());
Chris Lattner88de3842010-01-07 21:53:27 +00002886 AddToWorkList(N);
2887 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2888 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2889 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002890
Chris Lattner88de3842010-01-07 21:53:27 +00002891 // Do not change the width of a volatile load.
2892 // Do not generate loads of non-round integer types since these can
2893 // be expensive (and would be wrong if the type is not byte sized).
2894 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2895 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2896 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002897
Chris Lattner88de3842010-01-07 21:53:27 +00002898 unsigned Alignment = LN0->getAlignment();
2899 SDValue NewPtr = LN0->getBasePtr();
2900
2901 // For big endian targets, we need to add an offset to the pointer
2902 // to load the correct bytes. For little endian systems, we merely
2903 // need to read fewer bytes from the same pointer.
2904 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002905 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2906 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2907 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002908 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002909 NewPtr, DAG.getConstant(PtrOff, PtrType));
2910 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002911 }
Chris Lattner88de3842010-01-07 21:53:27 +00002912
2913 AddToWorkList(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002914
Chris Lattner88de3842010-01-07 21:53:27 +00002915 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2916 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002917 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002918 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002919 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002920 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002921 Alignment, LN0->getTBAAInfo());
Chris Lattner88de3842010-01-07 21:53:27 +00002922 AddToWorkList(N);
2923 CombineTo(LN0, Load, Load.getValue(1));
2924 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002925 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002926 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002927 }
2928 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002929
Evan Chenge6a3b032012-07-17 18:54:11 +00002930 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2931 VT.getSizeInBits() <= 64) {
2932 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2933 APInt ADDC = ADDI->getAPIntValue();
2934 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2935 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2936 // immediate for an add, but it is legal if its top c2 bits are set,
2937 // transform the ADD so the immediate doesn't need to be materialized
2938 // in a register.
2939 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2940 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2941 SRLI->getZExtValue());
2942 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2943 ADDC |= Mask;
2944 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2945 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002946 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002947 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2948 CombineTo(N0.getNode(), NewAdd);
2949 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2950 }
2951 }
2952 }
2953 }
2954 }
2955 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002956
Tim Northover819bfb52013-08-27 13:46:45 +00002957 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2958 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2959 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2960 N0.getOperand(1), false);
2961 if (BSwap.getNode())
2962 return BSwap;
2963 }
2964
Evan Chengf1005572010-04-28 07:10:39 +00002965 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002966}
2967
Evan Cheng4c0bd962011-06-21 06:01:08 +00002968/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2969///
2970SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2971 bool DemandHighBits) {
2972 if (!LegalOperations)
2973 return SDValue();
2974
2975 EVT VT = N->getValueType(0);
2976 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2977 return SDValue();
2978 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2979 return SDValue();
2980
2981 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2982 bool LookPassAnd0 = false;
2983 bool LookPassAnd1 = false;
2984 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2985 std::swap(N0, N1);
2986 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2987 std::swap(N0, N1);
2988 if (N0.getOpcode() == ISD::AND) {
2989 if (!N0.getNode()->hasOneUse())
2990 return SDValue();
2991 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2992 if (!N01C || N01C->getZExtValue() != 0xFF00)
2993 return SDValue();
2994 N0 = N0.getOperand(0);
2995 LookPassAnd0 = true;
2996 }
2997
2998 if (N1.getOpcode() == ISD::AND) {
2999 if (!N1.getNode()->hasOneUse())
3000 return SDValue();
3001 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3002 if (!N11C || N11C->getZExtValue() != 0xFF)
3003 return SDValue();
3004 N1 = N1.getOperand(0);
3005 LookPassAnd1 = true;
3006 }
3007
3008 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3009 std::swap(N0, N1);
3010 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3011 return SDValue();
3012 if (!N0.getNode()->hasOneUse() ||
3013 !N1.getNode()->hasOneUse())
3014 return SDValue();
3015
3016 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3017 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3018 if (!N01C || !N11C)
3019 return SDValue();
3020 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3021 return SDValue();
3022
3023 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3024 SDValue N00 = N0->getOperand(0);
3025 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3026 if (!N00.getNode()->hasOneUse())
3027 return SDValue();
3028 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3029 if (!N001C || N001C->getZExtValue() != 0xFF)
3030 return SDValue();
3031 N00 = N00.getOperand(0);
3032 LookPassAnd0 = true;
3033 }
3034
3035 SDValue N10 = N1->getOperand(0);
3036 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3037 if (!N10.getNode()->hasOneUse())
3038 return SDValue();
3039 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3040 if (!N101C || N101C->getZExtValue() != 0xFF00)
3041 return SDValue();
3042 N10 = N10.getOperand(0);
3043 LookPassAnd1 = true;
3044 }
3045
3046 if (N00 != N10)
3047 return SDValue();
3048
Tim Northover819bfb52013-08-27 13:46:45 +00003049 // Make sure everything beyond the low halfword gets set to zero since the SRL
3050 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003051 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003052 if (DemandHighBits && OpSizeInBits > 16) {
3053 // If the left-shift isn't masked out then the only way this is a bswap is
3054 // if all bits beyond the low 8 are 0. In that case the entire pattern
3055 // reduces to a left shift anyway: leave it for other parts of the combiner.
3056 if (!LookPassAnd0)
3057 return SDValue();
3058
3059 // However, if the right shift isn't masked out then it might be because
3060 // it's not needed. See if we can spot that too.
3061 if (!LookPassAnd1 &&
3062 !DAG.MaskedValueIsZero(
3063 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3064 return SDValue();
3065 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003066
Andrew Trickef9de2a2013-05-25 02:42:55 +00003067 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003068 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003069 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003070 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3071 return Res;
3072}
3073
3074/// isBSwapHWordElement - Return true if the specified node is an element
3075/// that makes up a 32-bit packed halfword byteswap. i.e.
3076/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003077static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003078 if (!N.getNode()->hasOneUse())
3079 return false;
3080
3081 unsigned Opc = N.getOpcode();
3082 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3083 return false;
3084
3085 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3086 if (!N1C)
3087 return false;
3088
3089 unsigned Num;
3090 switch (N1C->getZExtValue()) {
3091 default:
3092 return false;
3093 case 0xFF: Num = 0; break;
3094 case 0xFF00: Num = 1; break;
3095 case 0xFF0000: Num = 2; break;
3096 case 0xFF000000: Num = 3; break;
3097 }
3098
3099 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3100 SDValue N0 = N.getOperand(0);
3101 if (Opc == ISD::AND) {
3102 if (Num == 0 || Num == 2) {
3103 // (x >> 8) & 0xff
3104 // (x >> 8) & 0xff0000
3105 if (N0.getOpcode() != ISD::SRL)
3106 return false;
3107 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3108 if (!C || C->getZExtValue() != 8)
3109 return false;
3110 } else {
3111 // (x << 8) & 0xff00
3112 // (x << 8) & 0xff000000
3113 if (N0.getOpcode() != ISD::SHL)
3114 return false;
3115 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3116 if (!C || C->getZExtValue() != 8)
3117 return false;
3118 }
3119 } else if (Opc == ISD::SHL) {
3120 // (x & 0xff) << 8
3121 // (x & 0xff0000) << 8
3122 if (Num != 0 && Num != 2)
3123 return false;
3124 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3125 if (!C || C->getZExtValue() != 8)
3126 return false;
3127 } else { // Opc == ISD::SRL
3128 // (x & 0xff00) >> 8
3129 // (x & 0xff000000) >> 8
3130 if (Num != 1 && Num != 3)
3131 return false;
3132 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3133 if (!C || C->getZExtValue() != 8)
3134 return false;
3135 }
3136
3137 if (Parts[Num])
3138 return false;
3139
3140 Parts[Num] = N0.getOperand(0).getNode();
3141 return true;
3142}
3143
3144/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3145/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3146/// => (rotl (bswap x), 16)
3147SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3148 if (!LegalOperations)
3149 return SDValue();
3150
3151 EVT VT = N->getValueType(0);
3152 if (VT != MVT::i32)
3153 return SDValue();
3154 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3155 return SDValue();
3156
Craig Topperc0196b12014-04-14 00:51:57 +00003157 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003158 // Look for either
3159 // (or (or (and), (and)), (or (and), (and)))
3160 // (or (or (or (and), (and)), (and)), (and))
3161 if (N0.getOpcode() != ISD::OR)
3162 return SDValue();
3163 SDValue N00 = N0.getOperand(0);
3164 SDValue N01 = N0.getOperand(1);
3165
Evan Chengbf0baa92012-12-13 01:34:32 +00003166 if (N1.getOpcode() == ISD::OR &&
3167 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003168 // (or (or (and), (and)), (or (and), (and)))
3169 SDValue N000 = N00.getOperand(0);
3170 if (!isBSwapHWordElement(N000, Parts))
3171 return SDValue();
3172
3173 SDValue N001 = N00.getOperand(1);
3174 if (!isBSwapHWordElement(N001, Parts))
3175 return SDValue();
3176 SDValue N010 = N01.getOperand(0);
3177 if (!isBSwapHWordElement(N010, Parts))
3178 return SDValue();
3179 SDValue N011 = N01.getOperand(1);
3180 if (!isBSwapHWordElement(N011, Parts))
3181 return SDValue();
3182 } else {
3183 // (or (or (or (and), (and)), (and)), (and))
3184 if (!isBSwapHWordElement(N1, Parts))
3185 return SDValue();
3186 if (!isBSwapHWordElement(N01, Parts))
3187 return SDValue();
3188 if (N00.getOpcode() != ISD::OR)
3189 return SDValue();
3190 SDValue N000 = N00.getOperand(0);
3191 if (!isBSwapHWordElement(N000, Parts))
3192 return SDValue();
3193 SDValue N001 = N00.getOperand(1);
3194 if (!isBSwapHWordElement(N001, Parts))
3195 return SDValue();
3196 }
3197
3198 // Make sure the parts are all coming from the same node.
3199 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3200 return SDValue();
3201
Andrew Trickef9de2a2013-05-25 02:42:55 +00003202 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003203 SDValue(Parts[0],0));
3204
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003205 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003206 // do (x << 16) | (x >> 16).
3207 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3208 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003209 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003210 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003211 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3212 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3213 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3214 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003215}
3216
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003217SDValue DAGCombiner::visitOR(SDNode *N) {
3218 SDValue N0 = N->getOperand(0);
3219 SDValue N1 = N->getOperand(1);
3220 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003221 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3222 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003223 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003224
Dan Gohmana8665142007-06-25 16:23:39 +00003225 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003226 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003227 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003228 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003229
3230 // fold (or x, 0) -> x, vector edition
3231 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3232 return N1;
3233 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3234 return N0;
3235
3236 // fold (or x, -1) -> -1, vector edition
3237 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3238 return N0;
3239 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3240 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003241
3242 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3243 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3244 // Do this only if the resulting shuffle is legal.
3245 if (isa<ShuffleVectorSDNode>(N0) &&
3246 isa<ShuffleVectorSDNode>(N1) &&
3247 N0->getOperand(1) == N1->getOperand(1) &&
3248 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3249 bool CanFold = true;
3250 unsigned NumElts = VT.getVectorNumElements();
3251 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3252 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3253 // We construct two shuffle masks:
3254 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3255 // and N1 as the second operand.
3256 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3257 // and N0 as the second operand.
3258 // We do this because OR is commutable and therefore there might be
3259 // two ways to fold this node into a shuffle.
3260 SmallVector<int,4> Mask1;
3261 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003262
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003263 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3264 int M0 = SV0->getMaskElt(i);
3265 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003266
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003267 // Both shuffle indexes are undef. Propagate Undef.
3268 if (M0 < 0 && M1 < 0) {
3269 Mask1.push_back(M0);
3270 Mask2.push_back(M0);
3271 continue;
3272 }
3273
3274 if (M0 < 0 || M1 < 0 ||
3275 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3276 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3277 CanFold = false;
3278 break;
3279 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003280
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003281 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3282 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3283 }
3284
3285 if (CanFold) {
3286 // Fold this sequence only if the resulting shuffle is 'legal'.
3287 if (TLI.isShuffleMaskLegal(Mask1, VT))
3288 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3289 N1->getOperand(0), &Mask1[0]);
3290 if (TLI.isShuffleMaskLegal(Mask2, VT))
3291 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3292 N0->getOperand(0), &Mask2[0]);
3293 }
3294 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003295 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003296
Dan Gohman06563a82007-07-03 14:03:57 +00003297 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003298 if (!LegalOperations &&
3299 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003300 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3301 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3302 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003303 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003304 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003305 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003306 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003307 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003308 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003309 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003310 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003311 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003312 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003313 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003314 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003315 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003316 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003317 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003318
3319 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3320 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003321 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003322 return BSwap;
3323 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003324 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003325 return BSwap;
3326
Nate Begeman22e251a2006-02-03 06:46:56 +00003327 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003328 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003329 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003330 return ROR;
3331 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003332 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003333 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003334 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003335 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003336 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3337 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3338 if (!COR.getNode())
3339 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003340 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3341 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003342 N0.getOperand(0), N1), COR);
3343 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003344 }
Nate Begeman049b7482005-09-09 19:49:52 +00003345 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3346 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3347 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3348 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003349
Nate Begeman049b7482005-09-09 19:49:52 +00003350 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003351 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003352 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3353 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003354 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003355 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003356 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003357 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003358 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003359 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003360 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003361 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3362 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003363 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003364 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003365 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003366 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003367 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003368 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003369 }
3370 }
3371 // canonicalize equivalent to ll == rl
3372 if (LL == RR && LR == RL) {
3373 Op1 = ISD::getSetCCSwappedOperands(Op1);
3374 std::swap(RL, RR);
3375 }
3376 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003377 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003378 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003379 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003380 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003381 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3382 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003383 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003384 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003385 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003386 }
3387 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003388
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003389 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003390 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003391 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003392 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003393 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003394
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003395 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003396 if (N0.getOpcode() == ISD::AND &&
3397 N1.getOpcode() == ISD::AND &&
3398 N0.getOperand(1).getOpcode() == ISD::Constant &&
3399 N1.getOperand(1).getOpcode() == ISD::Constant &&
3400 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003401 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003402 // We can only do this xform if we know that bits from X that are set in C2
3403 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003404 const APInt &LHSMask =
3405 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3406 const APInt &RHSMask =
3407 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003408
Dan Gohman309d3d52007-06-22 14:59:07 +00003409 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3410 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003411 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003412 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003413 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003414 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003415 }
3416 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003417
Chris Lattner97614c82006-09-14 20:50:57 +00003418 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003419 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003420 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003421
Dan Gohman600f62b2010-06-24 14:30:44 +00003422 // Simplify the operands using demanded-bits information.
3423 if (!VT.isVector() &&
3424 SimplifyDemandedBits(SDValue(N, 0)))
3425 return SDValue(N, 0);
3426
Evan Chengf1005572010-04-28 07:10:39 +00003427 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003428}
3429
Chris Lattner97614c82006-09-14 20:50:57 +00003430/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003431static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003432 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003433 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003434 Mask = Op.getOperand(1);
3435 Op = Op.getOperand(0);
3436 } else {
3437 return false;
3438 }
3439 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003440
Chris Lattner97614c82006-09-14 20:50:57 +00003441 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3442 Shift = Op;
3443 return true;
3444 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003445
Scott Michelcf0da6c2009-02-17 22:15:04 +00003446 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003447}
3448
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003449// Return true if we can prove that, whenever Neg and Pos are both in the
3450// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003451// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3452//
3453// (or (shift1 X, Neg), (shift2 X, Pos))
3454//
Adam Nemetc6553a82014-03-07 23:56:24 +00003455// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3456// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3457// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003458static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003459 // If OpSize is a power of 2 then:
3460 //
3461 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3462 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3463 //
3464 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3465 // for the stronger condition:
3466 //
3467 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3468 //
3469 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3470 // we can just replace Neg with Neg' for the rest of the function.
3471 //
3472 // In other cases we check for the even stronger condition:
3473 //
3474 // Neg == OpSize - Pos [B]
3475 //
3476 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3477 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003478 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003479 // We could actually use [A] whenever OpSize is a power of 2, but the
3480 // only extra cases that it would match are those uninteresting ones
3481 // where Neg and Pos are never in range at the same time. E.g. for
3482 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3483 // as well as (sub 32, Pos), but:
3484 //
3485 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3486 //
3487 // always invokes undefined behavior for 32-bit X.
3488 //
3489 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003490 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003491 if (Neg.getOpcode() == ISD::AND &&
3492 isPowerOf2_64(OpSize) &&
3493 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3494 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3495 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003496 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003497 }
3498
Richard Sandiford0f264db2014-01-09 10:49:40 +00003499 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3500 if (Neg.getOpcode() != ISD::SUB)
3501 return 0;
3502 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3503 if (!NegC)
3504 return 0;
3505 SDValue NegOp1 = Neg.getOperand(1);
3506
Adam Nemet5117f5d2014-03-07 23:56:28 +00003507 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3508 // Pos'. The truncation is redundant for the purpose of the equality.
3509 if (MaskLoBits &&
3510 Pos.getOpcode() == ISD::AND &&
3511 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3512 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3513 Pos = Pos.getOperand(0);
3514
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003515 // The condition we need is now:
3516 //
3517 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3518 //
3519 // If NegOp1 == Pos then we need:
3520 //
3521 // OpSize & Mask == NegC & Mask
3522 //
3523 // (because "x & Mask" is a truncation and distributes through subtraction).
3524 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003525 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003526 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003527 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3528 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003529 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003530 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3531 //
3532 // which, again because "x & Mask" is a truncation, becomes:
3533 //
3534 // NegC & Mask == (OpSize - PosC) & Mask
3535 // OpSize & Mask == (NegC + PosC) & Mask
3536 else if (Pos.getOpcode() == ISD::ADD &&
3537 Pos.getOperand(0) == NegOp1 &&
3538 Pos.getOperand(1).getOpcode() == ISD::Constant)
3539 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3540 NegC->getAPIntValue());
3541 else
3542 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003543
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003544 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003545 if (MaskLoBits)
3546 // Opsize & Mask is 0 since Mask is Opsize - 1.
3547 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003548 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003549}
3550
Richard Sandiford95c864d2014-01-08 15:40:47 +00003551// A subroutine of MatchRotate used once we have found an OR of two opposite
3552// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3553// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3554// former being preferred if supported. InnerPos and InnerNeg are Pos and
3555// Neg with outer conversions stripped away.
3556SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3557 SDValue Neg, SDValue InnerPos,
3558 SDValue InnerNeg, unsigned PosOpcode,
3559 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003560 // fold (or (shl x, (*ext y)),
3561 // (srl x, (*ext (sub 32, y)))) ->
3562 // (rotl x, y) or (rotr x, (sub 32, y))
3563 //
3564 // fold (or (shl x, (*ext (sub 32, y))),
3565 // (srl x, (*ext y))) ->
3566 // (rotr x, y) or (rotl x, (sub 32, y))
3567 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003568 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003569 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3570 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3571 HasPos ? Pos : Neg).getNode();
3572 }
3573
Craig Topperc0196b12014-04-14 00:51:57 +00003574 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003575}
3576
Chris Lattner97614c82006-09-14 20:50:57 +00003577// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3578// idioms for rotate, and if the target supports rotation instructions, generate
3579// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003580SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003581 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003582 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003583 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003584
3585 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003586 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3587 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003588 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003589
Chris Lattner97614c82006-09-14 20:50:57 +00003590 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003591 SDValue LHSShift; // The shift.
3592 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003593 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003594 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003595
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003596 SDValue RHSShift; // The shift.
3597 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003598 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003599 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003600
Chris Lattner97614c82006-09-14 20:50:57 +00003601 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003602 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003603
3604 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003605 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003606
Chris Lattner97614c82006-09-14 20:50:57 +00003607 // Canonicalize shl to left side in a shl/srl pair.
3608 if (RHSShift.getOpcode() == ISD::SHL) {
3609 std::swap(LHS, RHS);
3610 std::swap(LHSShift, RHSShift);
3611 std::swap(LHSMask , RHSMask );
3612 }
3613
Duncan Sands13237ac2008-06-06 12:08:01 +00003614 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003615 SDValue LHSShiftArg = LHSShift.getOperand(0);
3616 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003617 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003618 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003619
3620 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3621 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003622 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3623 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003624 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3625 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003626 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003627 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003628
Craig Topper65161fa2012-09-29 06:54:22 +00003629 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3630 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003631
Chris Lattner97614c82006-09-14 20:50:57 +00003632 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003633 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003634 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003635
Gabor Greiff304a7a2008-08-28 21:40:38 +00003636 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003637 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3638 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003639 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003640 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003641 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3642 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003643 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003644
Bill Wendling35972a92009-01-30 21:14:50 +00003645 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003646 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003647
Gabor Greiff304a7a2008-08-28 21:40:38 +00003648 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003649 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003650
Chris Lattner97614c82006-09-14 20:50:57 +00003651 // If there is a mask here, and we have a variable shift, we can't be sure
3652 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003653 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003654 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003655
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003656 // If the shift amount is sign/zext/any-extended just peel it off.
3657 SDValue LExtOp0 = LHSShiftAmt;
3658 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003659 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3660 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3661 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3662 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3663 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3664 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3665 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3666 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003667 LExtOp0 = LHSShiftAmt.getOperand(0);
3668 RExtOp0 = RHSShiftAmt.getOperand(0);
3669 }
3670
Richard Sandiford95c864d2014-01-08 15:40:47 +00003671 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3672 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3673 if (TryL)
3674 return TryL;
3675
3676 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3677 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3678 if (TryR)
3679 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003680
Craig Topperc0196b12014-04-14 00:51:57 +00003681 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003682}
3683
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003684SDValue DAGCombiner::visitXOR(SDNode *N) {
3685 SDValue N0 = N->getOperand(0);
3686 SDValue N1 = N->getOperand(1);
3687 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003688 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3689 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003690 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003691
Dan Gohmana8665142007-06-25 16:23:39 +00003692 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003693 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003694 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003695 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003696
3697 // fold (xor x, 0) -> x, vector edition
3698 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3699 return N1;
3700 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3701 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003702 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003703
Evan Chengdf1690d2008-03-25 20:08:07 +00003704 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3705 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3706 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003707 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003708 if (N0.getOpcode() == ISD::UNDEF)
3709 return N0;
3710 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003711 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003712 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003713 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003714 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003715 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003716 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003717 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003718 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003719 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003720 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003721 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003722 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003723 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003724 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003725
Nate Begeman21158fc2005-09-01 00:19:25 +00003726 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003727 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003728 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003729 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3730 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003731
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003732 if (!LegalOperations ||
3733 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003734 switch (N0.getOpcode()) {
3735 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003736 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003737 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003738 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003739 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003740 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003741 N0.getOperand(3), NotCC);
3742 }
3743 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003744 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003745
Chris Lattner58c227b2007-09-10 21:39:07 +00003746 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003747 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003748 N0.getNode()->hasOneUse() &&
3749 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003750 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003751 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003752 DAG.getConstant(1, V.getValueType()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00003753 AddToWorkList(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003754 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003755 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003756
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003757 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003758 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003759 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003760 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003761 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3762 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003763 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3764 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003765 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003766 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003767 }
3768 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003769 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003770 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003771 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003772 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003773 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3774 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003775 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3776 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003777 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003778 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003779 }
3780 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003781 // fold (xor (and x, y), y) -> (and (not x), y)
3782 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003783 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003784 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003785 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer386ab7f2013-05-08 06:44:42 +00003786 AddToWorkList(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003787 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003788 }
Bill Wendling35972a92009-01-30 21:14:50 +00003789 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003790 if (N1C && N0.getOpcode() == ISD::XOR) {
3791 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3792 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3793 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003794 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003795 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003796 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003797 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003798 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003799 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003800 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003801 }
3802 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003803 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003804 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003805
Chris Lattner8d6fc202006-05-05 05:51:50 +00003806 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3807 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003808 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003809 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003810 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003811
Chris Lattner098c01e2006-04-08 04:15:24 +00003812 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003813 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003814 SimplifyDemandedBits(SDValue(N, 0)))
3815 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003816
Evan Chengf1005572010-04-28 07:10:39 +00003817 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003818}
3819
Chris Lattner7c709a52007-12-06 07:33:36 +00003820/// visitShiftByConstant - Handle transforms common to the three shifts, when
3821/// the shift amount is a constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003822SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003823 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003824 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003825 return SDValue();
3826
Gabor Greiff304a7a2008-08-28 21:40:38 +00003827 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003828 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003829
Chris Lattner7c709a52007-12-06 07:33:36 +00003830 // We want to pull some binops through shifts, so that we have (and (shift))
3831 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3832 // thing happens with address calculations, so it's important to canonicalize
3833 // it.
3834 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003835
Chris Lattner7c709a52007-12-06 07:33:36 +00003836 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003837 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003838 case ISD::OR:
3839 case ISD::XOR:
3840 HighBitSet = false; // We can only transform sra if the high bit is clear.
3841 break;
3842 case ISD::AND:
3843 HighBitSet = true; // We can only transform sra if the high bit is set.
3844 break;
3845 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003846 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003847 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003848 HighBitSet = false; // We can only transform sra if the high bit is clear.
3849 break;
3850 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003851
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003852 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003853 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003854 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003855
3856 // FIXME: disable this unless the input to the binop is a shift by a constant.
3857 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003858 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003859 // void foo(int *X, int i) { X[i & 1235] = 1; }
3860 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003861 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003862 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003863 BinOpLHSVal->getOpcode() != ISD::SRA &&
3864 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3865 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003866 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003867
Owen Anderson53aa7a92009-08-10 22:56:29 +00003868 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003869
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003870 // If this is a signed shift right, and the high bit is modified by the
3871 // logical operation, do not perform the transformation. The highBitSet
3872 // boolean indicates the value of the high bit of the constant which would
3873 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003874 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003875 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3876 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003877 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003878 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003879
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003880 if (!TLI.isDesirableToCommuteWithShift(LHS))
3881 return SDValue();
3882
Chris Lattner7c709a52007-12-06 07:33:36 +00003883 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003884 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003885 N->getValueType(0),
3886 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003887 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003888
3889 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003890 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003891 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003892 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003893
3894 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003895 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003896}
3897
Adam Nemet67483892014-03-04 23:28:31 +00003898SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3899 assert(N->getOpcode() == ISD::TRUNCATE);
3900 assert(N->getOperand(0).getOpcode() == ISD::AND);
3901
3902 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3903 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3904 SDValue N01 = N->getOperand(0).getOperand(1);
3905
Matt Arsenault985b9de2014-03-17 18:58:01 +00003906 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003907 EVT TruncVT = N->getValueType(0);
3908 SDValue N00 = N->getOperand(0).getOperand(0);
3909 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003910 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003911
3912 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3913 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3914 DAG.getConstant(TruncC, TruncVT));
3915 }
3916 }
3917
3918 return SDValue();
3919}
Adam Nemet7f928f12014-03-07 23:56:30 +00003920
3921SDValue DAGCombiner::visitRotate(SDNode *N) {
3922 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3923 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3924 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3925 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3926 if (NewOp1.getNode())
3927 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3928 N->getOperand(0), NewOp1);
3929 }
3930 return SDValue();
3931}
3932
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003933SDValue DAGCombiner::visitSHL(SDNode *N) {
3934 SDValue N0 = N->getOperand(0);
3935 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003936 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3937 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003938 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003939 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003940
Daniel Sandersa1840d22013-11-11 17:23:41 +00003941 // fold vector ops
3942 if (VT.isVector()) {
3943 SDValue FoldedVOp = SimplifyVBinOp(N);
3944 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003945
3946 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3947 // If setcc produces all-one true value then:
3948 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00003949 if (N1CV && N1CV->isConstant()) {
3950 if (N0.getOpcode() == ISD::AND &&
3951 TLI.getBooleanContents(true) ==
3952 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3953 SDValue N00 = N0->getOperand(0);
3954 SDValue N01 = N0->getOperand(1);
3955 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003956
Matt Arsenault985b9de2014-03-17 18:58:01 +00003957 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3958 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3959 if (C.getNode())
3960 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3961 }
3962 } else {
3963 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003964 }
3965 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00003966 }
3967
Nate Begeman21158fc2005-09-01 00:19:25 +00003968 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003969 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003970 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003971 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003972 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003973 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003974 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00003975 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003976 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003977 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003978 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003979 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00003980 // fold (shl undef, x) -> 0
3981 if (N0.getOpcode() == ISD::UNDEF)
3982 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003983 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003984 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00003985 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00003986 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00003987 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003988 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00003989 N1.getOperand(0).getOpcode() == ISD::AND) {
3990 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3991 if (NewOp1.getNode())
3992 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003993 }
3994
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003995 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3996 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003997
3998 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00003999 if (N1C && N0.getOpcode() == ISD::SHL) {
4000 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4001 uint64_t c1 = N0C1->getZExtValue();
4002 uint64_t c2 = N1C->getZExtValue();
4003 if (c1 + c2 >= OpSizeInBits)
4004 return DAG.getConstant(0, VT);
4005 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4006 DAG.getConstant(c1 + c2, N1.getValueType()));
4007 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004008 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004009
4010 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4011 // For this to be valid, the second form must not preserve any of the bits
4012 // that are shifted out by the inner shift in the first form. This means
4013 // the outer shift size must be >= the number of bits added by the ext.
4014 // As a corollary, we don't care what kind of ext it is.
4015 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4016 N0.getOpcode() == ISD::ANY_EXTEND ||
4017 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004018 N0.getOperand(0).getOpcode() == ISD::SHL) {
4019 SDValue N0Op0 = N0.getOperand(0);
4020 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4021 uint64_t c1 = N0Op0C1->getZExtValue();
4022 uint64_t c2 = N1C->getZExtValue();
4023 EVT InnerShiftVT = N0Op0.getValueType();
4024 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4025 if (c2 >= OpSizeInBits - InnerShiftSize) {
4026 if (c1 + c2 >= OpSizeInBits)
4027 return DAG.getConstant(0, VT);
4028 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4029 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4030 N0Op0->getOperand(0)),
4031 DAG.getConstant(c1 + c2, N1.getValueType()));
4032 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004033 }
4034 }
4035
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004036 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4037 // Only fold this if the inner zext has no other uses to avoid increasing
4038 // the total number of instructions.
4039 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004040 N0.getOperand(0).getOpcode() == ISD::SRL) {
4041 SDValue N0Op0 = N0.getOperand(0);
4042 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4043 uint64_t c1 = N0Op0C1->getZExtValue();
4044 if (c1 < VT.getScalarSizeInBits()) {
4045 uint64_t c2 = N1C->getZExtValue();
4046 if (c1 == c2) {
4047 SDValue NewOp0 = N0.getOperand(0);
4048 EVT CountVT = NewOp0.getOperand(1).getValueType();
4049 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4050 NewOp0, DAG.getConstant(c2, CountVT));
4051 AddToWorkList(NewSHL.getNode());
4052 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4053 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004054 }
4055 }
4056 }
4057
Eli Friedman1877ac92011-06-09 22:14:44 +00004058 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4059 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004060 // Only fold this if the inner shift has no other uses -- if it does, folding
4061 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004062 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4063 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4064 uint64_t c1 = N0C1->getZExtValue();
4065 if (c1 < OpSizeInBits) {
4066 uint64_t c2 = N1C->getZExtValue();
4067 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4068 SDValue Shift;
4069 if (c2 > c1) {
4070 Mask = Mask.shl(c2 - c1);
4071 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4072 DAG.getConstant(c2 - c1, N1.getValueType()));
4073 } else {
4074 Mask = Mask.lshr(c1 - c2);
4075 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4076 DAG.getConstant(c1 - c2, N1.getValueType()));
4077 }
4078 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4079 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004080 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004081 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004082 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004083 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004084 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004085 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004086 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004087 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4088 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004089 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004090 HiBitsMask);
4091 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004092
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004093 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004094 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004095 if (NewSHL.getNode())
4096 return NewSHL;
4097 }
4098
Evan Chengf1005572010-04-28 07:10:39 +00004099 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004100}
4101
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004102SDValue DAGCombiner::visitSRA(SDNode *N) {
4103 SDValue N0 = N->getOperand(0);
4104 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004105 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4106 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004107 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004108 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004109
Daniel Sandersa1840d22013-11-11 17:23:41 +00004110 // fold vector ops
4111 if (VT.isVector()) {
4112 SDValue FoldedVOp = SimplifyVBinOp(N);
4113 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004114
4115 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004116 }
4117
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004118 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004119 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004120 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004121 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004122 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004123 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004124 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004125 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004126 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004127 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004128 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004129 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004130 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004131 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004132 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004133 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4134 // sext_inreg.
4135 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004136 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004137 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4138 if (VT.isVector())
4139 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4140 ExtVT, VT.getVectorNumElements());
4141 if ((!LegalOperations ||
4142 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004143 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004144 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004145 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004146
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004147 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004148 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004149 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004150 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004151 if (Sum >= OpSizeInBits)
4152 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004153 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004154 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004155 }
4156 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004157
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004158 // fold (sra (shl X, m), (sub result_size, n))
4159 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004160 // result_size - n != m.
4161 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004162 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004163 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004164 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004165 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4166 if (N01C) {
4167 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004168 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004169 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4170
4171 if (VT.isVector())
4172 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4173
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004174 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004175 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004176
Scott Michelcf0da6c2009-02-17 22:15:04 +00004177 // If the shift is not a no-op (in which case this should be just a sign
4178 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004179 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004180 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004181 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004182 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4183 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004184 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004185
Owen Andersonb2c80da2011-02-25 21:41:48 +00004186 SDValue Amt = DAG.getConstant(ShiftAmt,
4187 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004188 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004189 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004190 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004191 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004192 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004193 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004194 }
4195 }
4196 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004197
Duncan Sands3ed76882009-02-01 18:06:53 +00004198 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004199 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004200 N1.getOperand(0).getOpcode() == ISD::AND) {
4201 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4202 if (NewOp1.getNode())
4203 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004204 }
4205
Matt Arsenault985b9de2014-03-17 18:58:01 +00004206 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004207 // if c1 is equal to the number of bits the trunc removes
4208 if (N0.getOpcode() == ISD::TRUNCATE &&
4209 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4210 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4211 N0.getOperand(0).hasOneUse() &&
4212 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004213 N1C) {
4214 SDValue N0Op0 = N0.getOperand(0);
4215 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4216 unsigned LargeShiftVal = LargeShift->getZExtValue();
4217 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004218
Matt Arsenault985b9de2014-03-17 18:58:01 +00004219 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4220 SDValue Amt =
4221 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4222 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4223 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4224 N0Op0.getOperand(0), Amt);
4225 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4226 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004227 }
4228 }
4229
Scott Michelcf0da6c2009-02-17 22:15:04 +00004230 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004231 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4232 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004233
4234
Nate Begeman21158fc2005-09-01 00:19:25 +00004235 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004236 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004237 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004238
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004239 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004240 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004241 if (NewSRA.getNode())
4242 return NewSRA;
4243 }
4244
Evan Chengf1005572010-04-28 07:10:39 +00004245 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004246}
4247
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004248SDValue DAGCombiner::visitSRL(SDNode *N) {
4249 SDValue N0 = N->getOperand(0);
4250 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004251 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4252 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004253 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004254 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004255
Daniel Sandersa1840d22013-11-11 17:23:41 +00004256 // fold vector ops
4257 if (VT.isVector()) {
4258 SDValue FoldedVOp = SimplifyVBinOp(N);
4259 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004260
4261 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004262 }
4263
Nate Begeman21158fc2005-09-01 00:19:25 +00004264 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004265 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004266 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004267 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004268 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004269 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004270 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004271 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004272 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004273 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004274 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004275 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004276 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004277 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004278 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004279 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004280
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004281 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004282 if (N1C && N0.getOpcode() == ISD::SRL) {
4283 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4284 uint64_t c1 = N01C->getZExtValue();
4285 uint64_t c2 = N1C->getZExtValue();
4286 if (c1 + c2 >= OpSizeInBits)
4287 return DAG.getConstant(0, VT);
4288 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4289 DAG.getConstant(c1 + c2, N1.getValueType()));
4290 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004291 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004292
Dale Johannesencd538af2010-12-17 21:45:49 +00004293 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004294 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4295 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004296 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004297 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004298 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4299 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004300 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4301 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004302 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004303 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004304 if (c1 + OpSizeInBits == InnerShiftSize) {
4305 if (c1 + c2 >= InnerShiftSize)
4306 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004307 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4308 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004309 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004310 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004311 }
4312 }
4313
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004314 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004315 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4316 unsigned BitSize = N0.getScalarValueSizeInBits();
4317 if (BitSize <= 64) {
4318 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4319 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4320 DAG.getConstant(~0ULL >> ShAmt, VT));
4321 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004322 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004323
Michael Liao62ebfd82013-06-21 18:45:27 +00004324 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004325 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4326 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004327 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004328 unsigned BitSize = SmallVT.getScalarSizeInBits();
4329 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004330 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004331
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004332 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004333 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004334 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004335 N0.getOperand(0),
4336 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004337 AddToWorkList(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004338 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004339 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4340 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4341 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004342 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004343 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004344
Chris Lattner2e33fb42006-10-12 20:23:19 +00004345 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4346 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004347 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004348 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004349 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004350 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004351
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004352 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004353 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004354 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004355 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004356 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004357
Chris Lattner49932492006-04-02 06:11:11 +00004358 // If any of the input bits are KnownOne, then the input couldn't be all
4359 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004360 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004361
Chris Lattner49932492006-04-02 06:11:11 +00004362 // If all of the bits input the to ctlz node are known to be zero, then
4363 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004364 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004365 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004366
Chris Lattner49932492006-04-02 06:11:11 +00004367 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004368 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004369 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004370 // could be set on input to the CTLZ node. If this bit is set, the SRL
4371 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4372 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004373 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004374 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004375
Chris Lattner49932492006-04-02 06:11:11 +00004376 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004377 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004378 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004379 AddToWorkList(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004380 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004381
Andrew Trickef9de2a2013-05-25 02:42:55 +00004382 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004383 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004384 }
4385 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004386
Duncan Sands3ed76882009-02-01 18:06:53 +00004387 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004388 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004389 N1.getOperand(0).getOpcode() == ISD::AND) {
4390 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4391 if (NewOp1.getNode())
4392 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004393 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004394
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004395 // fold operands of srl based on knowledge that the low bits are not
4396 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004397 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4398 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004399
Evan Chengb175de62009-12-18 21:31:31 +00004400 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004401 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004402 if (NewSRL.getNode())
4403 return NewSRL;
4404 }
4405
Dan Gohman600f62b2010-06-24 14:30:44 +00004406 // Attempt to convert a srl of a load into a narrower zero-extending load.
4407 SDValue NarrowLoad = ReduceLoadWidth(N);
4408 if (NarrowLoad.getNode())
4409 return NarrowLoad;
4410
Evan Chengb175de62009-12-18 21:31:31 +00004411 // Here is a common situation. We want to optimize:
4412 //
4413 // %a = ...
4414 // %b = and i32 %a, 2
4415 // %c = srl i32 %b, 1
4416 // brcond i32 %c ...
4417 //
4418 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004419 //
Evan Chengb175de62009-12-18 21:31:31 +00004420 // %a = ...
4421 // %b = and %a, 2
4422 // %c = setcc eq %b, 0
4423 // brcond %c ...
4424 //
4425 // However when after the source operand of SRL is optimized into AND, the SRL
4426 // itself may not be optimized further. Look for it and add the BRCOND into
4427 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004428 if (N->hasOneUse()) {
4429 SDNode *Use = *N->use_begin();
4430 if (Use->getOpcode() == ISD::BRCOND)
4431 AddToWorkList(Use);
4432 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4433 // Also look pass the truncate.
4434 Use = *Use->use_begin();
4435 if (Use->getOpcode() == ISD::BRCOND)
4436 AddToWorkList(Use);
4437 }
4438 }
Evan Chengb175de62009-12-18 21:31:31 +00004439
Evan Chengf1005572010-04-28 07:10:39 +00004440 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004441}
4442
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004443SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4444 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004445 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004446
4447 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004448 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004449 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004450 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004451}
4452
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004453SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4454 SDValue N0 = N->getOperand(0);
4455 EVT VT = N->getValueType(0);
4456
4457 // fold (ctlz_zero_undef c1) -> c2
4458 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004459 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004460 return SDValue();
4461}
4462
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004463SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4464 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004465 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004466
Nate Begeman21158fc2005-09-01 00:19:25 +00004467 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004468 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004469 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004470 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004471}
4472
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004473SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4474 SDValue N0 = N->getOperand(0);
4475 EVT VT = N->getValueType(0);
4476
4477 // fold (cttz_zero_undef c1) -> c2
4478 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004479 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004480 return SDValue();
4481}
4482
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004483SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4484 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004485 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004486
Nate Begeman21158fc2005-09-01 00:19:25 +00004487 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004488 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004489 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004490 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004491}
4492
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004493SDValue DAGCombiner::visitSELECT(SDNode *N) {
4494 SDValue N0 = N->getOperand(0);
4495 SDValue N1 = N->getOperand(1);
4496 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004497 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4498 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4499 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004500 EVT VT = N->getValueType(0);
4501 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004502
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004503 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004504 if (N1 == N2)
4505 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004506 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004507 if (N0C && !N0C->isNullValue())
4508 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004509 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004510 if (N0C && N0C->isNullValue())
4511 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004512 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004513 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004514 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004515 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004516 if (VT.isInteger() &&
Owen Anderson9f944592009-08-11 20:47:22 +00004517 (VT0 == MVT::i1 ||
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004518 (VT0.isInteger() &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00004519 TLI.getBooleanContents(false) ==
4520 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004521 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004522 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004523 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004524 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004525 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004526 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004527 N0, DAG.getConstant(1, VT0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004528 AddToWorkList(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004529 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004530 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4531 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004532 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004533 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004534 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004535 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004536 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004537 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004538 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004539 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004540 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004541 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004542 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004543 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004544 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004545 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004546 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004547 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004548 // fold (select X, X, Y) -> (or X, Y)
4549 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004550 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004551 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004552 // fold (select X, Y, X) -> (and X, Y)
4553 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004554 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004555 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004556
Chris Lattner6c14c352005-10-18 06:04:22 +00004557 // If we can fold this based on the true/false value, do so.
4558 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004559 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004560
Nate Begemanc760f802005-09-19 22:34:01 +00004561 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004562 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman7e7f4392006-02-01 07:19:44 +00004563 // FIXME:
Owen Anderson9f944592009-08-11 20:47:22 +00004564 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman7e7f4392006-02-01 07:19:44 +00004565 // having to say they don't support SELECT_CC on every type the DAG knows
4566 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson9f944592009-08-11 20:47:22 +00004567 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman3f323842009-08-02 16:19:38 +00004568 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004569 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004570 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004571 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004572 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004573 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004574
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004575 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004576}
4577
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004578static
4579std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4580 SDLoc DL(N);
4581 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004582 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004583
4584 // Split the inputs.
4585 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004586 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4587 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004588
4589 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4590 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4591
4592 return std::make_pair(Lo, Hi);
4593}
4594
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004595SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4596 SDValue N0 = N->getOperand(0);
4597 SDValue N1 = N->getOperand(1);
4598 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004599 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004600
4601 // Canonicalize integer abs.
4602 // vselect (setg[te] X, 0), X, -X ->
4603 // vselect (setgt X, -1), X, -X ->
4604 // vselect (setl[te] X, 0), -X, X ->
4605 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4606 if (N0.getOpcode() == ISD::SETCC) {
4607 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4608 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4609 bool isAbs = false;
4610 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4611
4612 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4613 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4614 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4615 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4616 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4617 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4618 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4619
4620 if (isAbs) {
4621 EVT VT = LHS.getValueType();
4622 SDValue Shift = DAG.getNode(
4623 ISD::SRA, DL, VT, LHS,
4624 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4625 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4626 AddToWorkList(Shift.getNode());
4627 AddToWorkList(Add.getNode());
4628 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4629 }
4630 }
4631
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004632 // If the VSELECT result requires splitting and the mask is provided by a
4633 // SETCC, then split both nodes and its operands before legalization. This
4634 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4635 // and enables future optimizations (e.g. min/max pattern matching on X86).
4636 if (N0.getOpcode() == ISD::SETCC) {
4637 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004638
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004639 // Check if any splitting is required.
4640 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4641 TargetLowering::TypeSplitVector)
4642 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004643
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004644 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004645 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4646 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4647 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004648
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004649 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4650 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004651
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004652 // Add the new VSELECT nodes to the work list in case they need to be split
4653 // again.
4654 AddToWorkList(Lo.getNode());
4655 AddToWorkList(Hi.getNode());
4656
4657 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004658 }
4659
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004660 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4661 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4662 return N1;
4663 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4664 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4665 return N2;
4666
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004667 return SDValue();
4668}
4669
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004670SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4671 SDValue N0 = N->getOperand(0);
4672 SDValue N1 = N->getOperand(1);
4673 SDValue N2 = N->getOperand(2);
4674 SDValue N3 = N->getOperand(3);
4675 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004676 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004677
Nate Begemanc760f802005-09-19 22:34:01 +00004678 // fold select_cc lhs, rhs, x, x, cc -> x
4679 if (N2 == N3)
4680 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004681
Chris Lattner8b68dec2006-09-20 06:19:26 +00004682 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004683 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004684 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004685 if (SCC.getNode()) {
4686 AddToWorkList(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004687
Stephen Lin605207f2013-06-15 04:03:33 +00004688 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4689 if (!SCCC->isNullValue())
4690 return N2; // cond always true -> true val
4691 else
4692 return N3; // cond always false -> false val
4693 }
4694
4695 // Fold to a simpler select_cc
4696 if (SCC.getOpcode() == ISD::SETCC)
4697 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4698 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4699 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004700 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004701
Chris Lattner6c14c352005-10-18 06:04:22 +00004702 // If we can fold this based on the true/false value, do so.
4703 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004704 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004705
Nate Begemanc760f802005-09-19 22:34:01 +00004706 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004707 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004708}
4709
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004710SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004711 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004712 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004713 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004714}
4715
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004716// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4717// dag node into a ConstantSDNode or a build_vector of constants.
4718// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004719// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004720// Vector extends are not folded if operations are legal; this is to
4721// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004722static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4723 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004724 bool LegalOperations) {
4725 unsigned Opcode = N->getOpcode();
4726 SDValue N0 = N->getOperand(0);
4727 EVT VT = N->getValueType(0);
4728
4729 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4730 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4731
4732 // fold (sext c1) -> c1
4733 // fold (zext c1) -> c1
4734 // fold (aext c1) -> c1
4735 if (isa<ConstantSDNode>(N0))
4736 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4737
4738 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4739 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4740 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004741 EVT SVT = VT.getScalarType();
4742 if (!(VT.isVector() &&
4743 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004744 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004745 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004746
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004747 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004748 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004749 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4750 unsigned ShAmt = VTBits - EVTBits;
4751 SmallVector<SDValue, 8> Elts;
4752 unsigned NumElts = N0->getNumOperands();
4753 SDLoc DL(N);
4754
4755 for (unsigned i=0; i != NumElts; ++i) {
4756 SDValue Op = N0->getOperand(i);
4757 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004758 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004759 continue;
4760 }
4761
4762 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4763 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4764 if (Opcode == ISD::SIGN_EXTEND)
4765 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004766 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004767 else
4768 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004769 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004770 }
4771
Craig Topper48d114b2014-04-26 18:35:24 +00004772 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004773}
4774
Evan Chenge106e2f2007-10-29 19:58:20 +00004775// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004776// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004777// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004778// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004779static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004780 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004781 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004782 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004783 bool HasCopyToRegUses = false;
4784 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004785 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4786 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004787 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004788 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004789 if (User == N)
4790 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004791 if (UI.getUse().getResNo() != N0.getResNo())
4792 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004793 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004794 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004795 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4796 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4797 // Sign bits will be lost after a zext.
4798 return false;
4799 bool Add = false;
4800 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004801 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004802 if (UseOp == N0)
4803 continue;
4804 if (!isa<ConstantSDNode>(UseOp))
4805 return false;
4806 Add = true;
4807 }
4808 if (Add)
4809 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004810 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004811 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004812 // If truncates aren't free and there are users we can't
4813 // extend, it isn't worthwhile.
4814 if (!isTruncFree)
4815 return false;
4816 // Remember if this value is live-out.
4817 if (User->getOpcode() == ISD::CopyToReg)
4818 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004819 }
4820
4821 if (HasCopyToRegUses) {
4822 bool BothLiveOut = false;
4823 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4824 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004825 SDUse &Use = UI.getUse();
4826 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4827 BothLiveOut = true;
4828 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004829 }
4830 }
4831 if (BothLiveOut)
4832 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004833 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004834 return ExtendNodes.size();
4835 }
4836 return true;
4837}
4838
Craig Toppere0b71182013-07-13 07:43:40 +00004839void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004840 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004841 ISD::NodeType ExtType) {
4842 // Extend SetCC uses if necessary.
4843 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4844 SDNode *SetCC = SetCCs[i];
4845 SmallVector<SDValue, 4> Ops;
4846
4847 for (unsigned j = 0; j != 2; ++j) {
4848 SDValue SOp = SetCC->getOperand(j);
4849 if (SOp == Trunc)
4850 Ops.push_back(ExtLoad);
4851 else
4852 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4853 }
4854
4855 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00004856 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004857 }
4858}
4859
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004860SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4861 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004862 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004863
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004864 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4865 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004866 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004867
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004868 // fold (sext (sext x)) -> (sext x)
4869 // fold (sext (aext x)) -> (sext x)
4870 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004871 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004872 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004873
Chris Lattnerfce448f2007-02-26 03:13:59 +00004874 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004875 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4876 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004877 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4878 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004879 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4880 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004881 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004882 // CombineTo deleted the truncate, if needed, but not what's under it.
4883 AddToWorkList(oye);
4884 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004885 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004886 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004887
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004888 // See if the value being truncated is already sign extended. If so, just
4889 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004890 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004891 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4892 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4893 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004894 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004895
Chris Lattnerfce448f2007-02-26 03:13:59 +00004896 if (OpBits == DestBits) {
4897 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4898 // bits, it is already ready.
4899 if (NumSignBits > DestBits-MidBits)
4900 return Op;
4901 } else if (OpBits < DestBits) {
4902 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4903 // bits, just sext from i32.
4904 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004905 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00004906 } else {
4907 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4908 // bits, just truncate to i32.
4909 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004910 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00004911 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004912
Chris Lattnerfce448f2007-02-26 03:13:59 +00004913 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004914 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4915 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004916 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004917 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004918 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004919 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4920 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004921 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00004922 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00004923 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004924
Evan Chengbce7c472005-12-14 02:19:23 +00004925 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00004926 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00004927 // on vectors in one instruction. We only perform this transformation on
4928 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00004929 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00004930 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004931 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00004932 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004933 bool DoXform = true;
4934 SmallVector<SDNode*, 4> SetCCs;
4935 if (!N0.hasOneUse())
4936 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4937 if (DoXform) {
4938 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004939 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00004940 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004941 LN0->getBasePtr(), N0.getValueType(),
4942 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00004943 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004944 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004945 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004946 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004947 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004948 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004949 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00004950 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00004951 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004952
4953 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4954 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004955 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4956 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00004957 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00004958 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004959 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00004960 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004961 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00004962 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004963 LN0->getBasePtr(), MemVT,
4964 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00004965 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00004966 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004967 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004968 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00004969 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004970 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00004971 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004972 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004973
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004974 // fold (sext (and/or/xor (load x), cst)) ->
4975 // (and/or/xor (sextload x), (sext cst))
4976 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4977 N0.getOpcode() == ISD::XOR) &&
4978 isa<LoadSDNode>(N0.getOperand(0)) &&
4979 N0.getOperand(1).getOpcode() == ISD::Constant &&
4980 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4981 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4982 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00004983 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004984 bool DoXform = true;
4985 SmallVector<SDNode*, 4> SetCCs;
4986 if (!N0.hasOneUse())
4987 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4988 SetCCs, TLI);
4989 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004990 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004991 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004992 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004993 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004994 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4995 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004996 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004997 ExtLoad, DAG.getConstant(Mask, VT));
4998 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004999 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005000 N0.getOperand(0).getValueType(), ExtLoad);
5001 CombineTo(N, And);
5002 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005003 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005004 ISD::SIGN_EXTEND);
5005 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5006 }
5007 }
5008 }
5009
Chris Lattner65786b02007-04-11 05:32:27 +00005010 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner4ac60732009-07-08 00:31:33 +00005011 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005012 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005013 if (VT.isVector() && !LegalOperations &&
Stephen Lincfe7f352013-07-08 00:37:03 +00005014 TLI.getBooleanContents(true) ==
Owen Anderson2d4cca32013-04-23 18:09:28 +00005015 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohmane82c25e2010-04-30 17:19:19 +00005016 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem9d376b62012-04-11 08:26:11 +00005017 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5018 // of the same size as the compared operands. Only optimize sext(setcc())
5019 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005020 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005021
5022 // We know that the # elements of the results is the same as the
5023 // # elements of the compare (and the # elements of the compare result
5024 // for that matter). Check to see that they are the same size. If so,
5025 // we know that the element size of the sext'd result matches the
5026 // element size of the compare operands.
5027 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005028 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005029 N0.getOperand(1),
5030 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005031
Dan Gohmane82c25e2010-04-30 17:19:19 +00005032 // If the desired elements are smaller or larger than the source
5033 // elements we can use a matching integer vector type and then
5034 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005035 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005036 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005037 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005038 N0.getOperand(0), N0.getOperand(1),
5039 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005040 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005041 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005042 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005043
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005044 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005045 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005046 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005047 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005048 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005049 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005050 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005051 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005052 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005053
5054 if (!VT.isVector()) {
5055 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5056 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5057 SDLoc DL(N);
5058 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5059 SDValue SetCC = DAG.getSetCC(DL,
5060 SetCCVT,
5061 N0.getOperand(0), N0.getOperand(1), CC);
5062 EVT SelectVT = getSetCCResultType(VT);
5063 return DAG.getSelect(DL, VT,
5064 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5065 NegOne, DAG.getConstant(0, VT));
5066
5067 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005068 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005069 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005070
Dan Gohman3eb10f72008-04-28 16:58:24 +00005071 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005072 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005073 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005074 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005075
Evan Chengf1005572010-04-28 07:10:39 +00005076 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005077}
5078
Rafael Espindola8f62b322012-04-09 16:06:03 +00005079// isTruncateOf - If N is a truncate of some other value, return true, record
5080// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5081// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005082// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005083static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5084 APInt &KnownZero) {
5085 APInt KnownOne;
5086 if (N->getOpcode() == ISD::TRUNCATE) {
5087 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005088 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005089 return true;
5090 }
5091
5092 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5093 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5094 return false;
5095
5096 SDValue Op0 = N->getOperand(0);
5097 SDValue Op1 = N->getOperand(1);
5098 assert(Op0.getValueType() == Op1.getValueType());
5099
5100 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5101 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005102 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005103 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005104 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005105 Op = Op0;
5106 else
5107 return false;
5108
Jay Foada0653a32014-05-14 21:14:37 +00005109 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005110
5111 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5112 return false;
5113
5114 return true;
5115}
5116
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005117SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5118 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005119 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005120
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005121 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5122 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005123 return SDValue(Res, 0);
5124
Nate Begeman21158fc2005-09-01 00:19:25 +00005125 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005126 // fold (zext (aext x)) -> (zext x)
5127 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005128 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005129 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005130
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005131 // fold (zext (truncate x)) -> (zext x) or
5132 // (zext (truncate x)) -> (truncate x)
5133 // This is valid when the truncated bits of x are already zero.
5134 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005135 SDValue Op;
5136 APInt KnownZero;
5137 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5138 APInt TruncatedBits =
5139 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5140 APInt(Op.getValueSizeInBits(), 0) :
5141 APInt::getBitsSet(Op.getValueSizeInBits(),
5142 N0.getValueSizeInBits(),
5143 std::min(Op.getValueSizeInBits(),
5144 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005145 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005146 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005147 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005148 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005149 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005150
5151 return Op;
5152 }
5153 }
5154
Evan Cheng464dc9b2007-03-22 01:54:19 +00005155 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5156 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005157 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005158 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5159 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005160 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5161 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005162 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005163 // CombineTo deleted the truncate, if needed, but not what's under it.
5164 AddToWorkList(oye);
5165 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005166 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005167 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005168 }
5169
Chris Lattnera31f0a62006-09-21 06:00:20 +00005170 // fold (zext (truncate x)) -> (and x, mask)
5171 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005172 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005173
5174 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5175 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5176 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5177 if (NarrowLoad.getNode()) {
5178 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5179 if (NarrowLoad.getNode() != N0.getNode()) {
5180 CombineTo(N0.getNode(), NarrowLoad);
5181 // CombineTo deleted the truncate, if needed, but not what's under it.
5182 AddToWorkList(oye);
5183 }
5184 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5185 }
5186
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005187 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005188 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005189 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005190 AddToWorkList(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005191 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005192 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005193 AddToWorkList(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005194 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005195 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005196 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005197 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005198
Dan Gohmanad3e5492009-04-08 00:15:30 +00005199 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5200 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005201 if (N0.getOpcode() == ISD::AND &&
5202 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005203 N0.getOperand(1).getOpcode() == ISD::Constant &&
5204 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5205 N0.getValueType()) ||
5206 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005207 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005208 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005209 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005210 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005211 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005212 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005213 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005214 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005215 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005216 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005217 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005218
Evan Chengbce7c472005-12-14 02:19:23 +00005219 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005220 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005221 // on vectors in one instruction. We only perform this transformation on
5222 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005223 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005224 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005225 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005226 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005227 bool DoXform = true;
5228 SmallVector<SDNode*, 4> SetCCs;
5229 if (!N0.hasOneUse())
5230 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5231 if (DoXform) {
5232 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005233 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005234 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005235 LN0->getBasePtr(), N0.getValueType(),
5236 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005237 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005238 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005239 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005240 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005241
Andrew Trickef9de2a2013-05-25 02:42:55 +00005242 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005243 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005244 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005245 }
Evan Chengbce7c472005-12-14 02:19:23 +00005246 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005247
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005248 // fold (zext (and/or/xor (load x), cst)) ->
5249 // (and/or/xor (zextload x), (zext cst))
5250 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5251 N0.getOpcode() == ISD::XOR) &&
5252 isa<LoadSDNode>(N0.getOperand(0)) &&
5253 N0.getOperand(1).getOpcode() == ISD::Constant &&
5254 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5255 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5256 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005257 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005258 bool DoXform = true;
5259 SmallVector<SDNode*, 4> SetCCs;
5260 if (!N0.hasOneUse())
5261 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5262 SetCCs, TLI);
5263 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005264 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005265 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005266 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005267 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005268 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5269 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005270 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005271 ExtLoad, DAG.getConstant(Mask, VT));
5272 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005273 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005274 N0.getOperand(0).getValueType(), ExtLoad);
5275 CombineTo(N, And);
5276 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005277 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005278 ISD::ZERO_EXTEND);
5279 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5280 }
5281 }
5282 }
5283
Chris Lattner7dac1082005-12-14 19:05:06 +00005284 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5285 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005286 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5287 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005288 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005289 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005290 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005291 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005292 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005293 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005294 LN0->getBasePtr(), MemVT,
5295 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005296 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005297 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005298 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005299 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005300 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005301 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005302 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005303 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005304
Chris Lattner65786b02007-04-11 05:32:27 +00005305 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005306 if (!LegalOperations && VT.isVector() &&
5307 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005308 EVT N0VT = N0.getOperand(0).getValueType();
5309 if (getSetCCResultType(N0VT) == N0.getValueType())
5310 return SDValue();
5311
Evan Chengabd0ad52010-05-19 01:08:17 +00005312 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5313 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005314 EVT EltVT = VT.getVectorElementType();
5315 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5316 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005317 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005318 // We know that the # elements of the results is the same as the
5319 // # elements of the compare (and the # elements of the compare result
5320 // for that matter). Check to see that they are the same size. If so,
5321 // we know that the element size of the sext'd result matches the
5322 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005323 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5324 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005325 N0.getOperand(1),
5326 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005327 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005328 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005329
5330 // If the desired elements are smaller or larger than the source
5331 // elements we can use a matching integer vector type and then
5332 // truncate/sign extend
5333 EVT MatchingElementType =
5334 EVT::getIntegerVT(*DAG.getContext(),
5335 N0VT.getScalarType().getSizeInBits());
5336 EVT MatchingVectorType =
5337 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5338 N0VT.getVectorNumElements());
5339 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005340 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005341 N0.getOperand(1),
5342 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005343 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5344 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005345 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005346 }
5347
5348 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005349 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005350 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005351 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005352 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005353 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005354 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005355
Evan Cheng852c4862009-12-15 03:00:32 +00005356 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005357 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005358 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005359 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5360 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005361 SDValue ShAmt = N0.getOperand(1);
5362 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005363 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005364 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005365 // If the original shl may be shifting out bits, do not perform this
5366 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005367 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5368 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5369 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005370 return SDValue();
5371 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005372
Andrew Trickef9de2a2013-05-25 02:42:55 +00005373 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005374
5375 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005376 if (VT.getSizeInBits() >= 256)
5377 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005378
Chris Lattnere95d1952011-02-13 19:09:16 +00005379 return DAG.getNode(N0.getOpcode(), DL, VT,
5380 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5381 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005382 }
5383
Evan Chengf1005572010-04-28 07:10:39 +00005384 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005385}
5386
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005387SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5388 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005389 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005390
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005391 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5392 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005393 return SDValue(Res, 0);
5394
Chris Lattner812646a2006-05-05 05:58:59 +00005395 // fold (aext (aext x)) -> (aext x)
5396 // fold (aext (zext x)) -> (zext x)
5397 // fold (aext (sext x)) -> (sext x)
5398 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5399 N0.getOpcode() == ISD::ZERO_EXTEND ||
5400 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005401 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005402
Evan Cheng464dc9b2007-03-22 01:54:19 +00005403 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5404 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5405 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005406 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5407 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005408 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5409 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005410 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005411 // CombineTo deleted the truncate, if needed, but not what's under it.
5412 AddToWorkList(oye);
5413 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005414 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005415 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005416 }
5417
Chris Lattner8746e2c2006-09-20 06:29:17 +00005418 // fold (aext (truncate x))
5419 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005420 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005421 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005422 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005423 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005424 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5425 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005426 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005427
Dan Gohmanad3e5492009-04-08 00:15:30 +00005428 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5429 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005430 if (N0.getOpcode() == ISD::AND &&
5431 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005432 N0.getOperand(1).getOpcode() == ISD::Constant &&
5433 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5434 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005435 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005436 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005437 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005438 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005439 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005440 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005441 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005442 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005443 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005444 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005445 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005446
Chris Lattner812646a2006-05-05 05:58:59 +00005447 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005448 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005449 // on vectors in one instruction. We only perform this transformation on
5450 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005451 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005452 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005453 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005454 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005455 bool DoXform = true;
5456 SmallVector<SDNode*, 4> SetCCs;
5457 if (!N0.hasOneUse())
5458 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5459 if (DoXform) {
5460 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005461 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005462 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005463 LN0->getBasePtr(), N0.getValueType(),
5464 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005465 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005466 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005467 N0.getValueType(), ExtLoad);
5468 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005469 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005470 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005471 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5472 }
Chris Lattner812646a2006-05-05 05:58:59 +00005473 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005474
Chris Lattner812646a2006-05-05 05:58:59 +00005475 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5476 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5477 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005478 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005479 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005480 N0.hasOneUse()) {
5481 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005482 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005483 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005484 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5485 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5486 VT, LN0->getChain(), LN0->getBasePtr(),
5487 MemVT, LN0->getMemOperand());
5488 CombineTo(N, ExtLoad);
5489 CombineTo(N0.getNode(),
5490 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5491 N0.getValueType(), ExtLoad),
5492 ExtLoad.getValue(1));
5493 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5494 }
Chris Lattner812646a2006-05-05 05:58:59 +00005495 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005496
Chris Lattner65786b02007-04-11 05:32:27 +00005497 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005498 // For vectors:
5499 // aext(setcc) -> vsetcc
5500 // aext(setcc) -> truncate(vsetcc)
5501 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005502 // Only do this before legalize for now.
5503 if (VT.isVector() && !LegalOperations) {
5504 EVT N0VT = N0.getOperand(0).getValueType();
5505 // We know that the # elements of the results is the same as the
5506 // # elements of the compare (and the # elements of the compare result
5507 // for that matter). Check to see that they are the same size. If so,
5508 // we know that the element size of the sext'd result matches the
5509 // element size of the compare operands.
5510 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005511 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005512 N0.getOperand(1),
5513 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005514 // If the desired elements are smaller or larger than the source
5515 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005516 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005517 else {
Hao Liuc636d152014-04-22 09:57:06 +00005518 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005519 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005520 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005521 N0.getOperand(1),
5522 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005523 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005524 }
5525 }
5526
5527 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005528 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005529 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005530 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005531 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005532 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005533 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005534 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005535
Evan Chengf1005572010-04-28 07:10:39 +00005536 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005537}
5538
Chris Lattner5e6fe052007-10-13 06:35:54 +00005539/// GetDemandedBits - See if the specified operand can be simplified with the
5540/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005541/// simpler operand, otherwise return a null SDValue.
5542SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005543 switch (V.getOpcode()) {
5544 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005545 case ISD::Constant: {
5546 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005547 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005548 const APInt &CVal = CV->getAPIntValue();
5549 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005550 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005551 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005552 break;
5553 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005554 case ISD::OR:
5555 case ISD::XOR:
5556 // If the LHS or RHS don't contribute bits to the or, drop them.
5557 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5558 return V.getOperand(1);
5559 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5560 return V.getOperand(0);
5561 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005562 case ISD::SRL:
5563 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005564 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005565 break;
5566 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5567 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005568 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005569
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005570 // Watch out for shift count overflow though.
5571 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005572 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005573 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005574 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005575 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005576 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005577 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005578 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005579 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005580}
5581
Evan Cheng464dc9b2007-03-22 01:54:19 +00005582/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5583/// bits and then truncated to a narrower type and where N is a multiple
5584/// of number of bits of the narrower type, transform it to a narrower load
5585/// from address + N / num of bits of new type. If the result is to be
5586/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005587SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005588 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005589
Evan Cheng464dc9b2007-03-22 01:54:19 +00005590 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005591 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005592 EVT VT = N->getValueType(0);
5593 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005594
Dan Gohman550c9af2008-08-14 20:04:46 +00005595 // This transformation isn't valid for vector loads.
5596 if (VT.isVector())
5597 return SDValue();
5598
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005599 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005600 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005601 if (Opc == ISD::SIGN_EXTEND_INREG) {
5602 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005603 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005604 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005605 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005606 ExtType = ISD::ZEXTLOAD;
5607 N0 = SDValue(N, 0);
5608 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5609 if (!N01) return SDValue();
5610 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5611 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005612 }
Richard Osborne272e0842011-01-31 17:41:44 +00005613 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5614 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005615
Owen Anderson53aa7a92009-08-10 22:56:29 +00005616 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005617
Chris Lattner9a499e92010-12-22 08:01:44 +00005618 // Do not generate loads of non-round integer types since these can
5619 // be expensive (and would be wrong if the type is not byte sized).
5620 if (!ExtVT.isRound())
5621 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005622
Evan Cheng464dc9b2007-03-22 01:54:19 +00005623 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005624 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005625 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005626 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005627 // Is the shift amount a multiple of size of VT?
5628 if ((ShAmt & (EVTBits-1)) == 0) {
5629 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005630 // Is the load width a multiple of size of VT?
5631 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005632 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005633 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005634
Chris Lattnercafc1e62010-12-22 08:02:57 +00005635 // At this point, we must have a load or else we can't do the transform.
5636 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005637
Chandler Carruthb27041c2012-12-11 00:36:57 +00005638 // Because a SRL must be assumed to *need* to zero-extend the high bits
5639 // (as opposed to anyext the high bits), we can't combine the zextload
5640 // lowering of SRL and an sextload.
5641 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5642 return SDValue();
5643
Chris Lattnera2050552010-10-01 05:36:09 +00005644 // If the shift amount is larger than the input type then we're not
5645 // accessing any of the loaded bytes. If the load was a zextload/extload
5646 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005647 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005648 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005649 }
5650 }
5651
Dan Gohman68fb0042010-11-03 01:47:46 +00005652 // If the load is shifted left (and the result isn't shifted back right),
5653 // we can fold the truncate through the shift.
5654 unsigned ShLeftAmt = 0;
5655 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005656 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005657 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5658 ShLeftAmt = N01->getZExtValue();
5659 N0 = N0.getOperand(0);
5660 }
5661 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005662
Chris Lattner222374d2010-12-22 07:36:50 +00005663 // If we haven't found a load, we can't narrow it. Don't transform one with
5664 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005665 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5666 return SDValue();
5667
5668 // Don't change the width of a volatile load.
5669 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5670 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005671 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005672
Chris Lattner9a499e92010-12-22 08:01:44 +00005673 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005674 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005675 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005676
Bill Schmidtd006c692013-01-14 22:04:38 +00005677 // For the transform to be legal, the load must produce only two values
5678 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005679 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005680 // transformation is not equivalent, and the downstream logic to replace
5681 // uses gets things wrong.
5682 if (LN0->getNumValues() > 2)
5683 return SDValue();
5684
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005685 // If the load that we're shrinking is an extload and we're not just
5686 // discarding the extension we can't simply shrink the load. Bail.
5687 // TODO: It would be possible to merge the extensions in some cases.
5688 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5689 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5690 return SDValue();
5691
Chris Lattner222374d2010-12-22 07:36:50 +00005692 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005693
Evan Cheng4c6f9172012-06-26 01:19:33 +00005694 if (PtrType == MVT::Untyped || PtrType.isExtended())
5695 // It's not possible to generate a constant of extended or untyped type.
5696 return SDValue();
5697
Chris Lattner222374d2010-12-22 07:36:50 +00005698 // For big endian targets, we need to adjust the offset to the pointer to
5699 // load the correct bytes.
5700 if (TLI.isBigEndian()) {
5701 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5702 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5703 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005704 }
5705
Chris Lattner222374d2010-12-22 07:36:50 +00005706 uint64_t PtrOff = ShAmt / 8;
5707 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005708 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005709 PtrType, LN0->getBasePtr(),
5710 DAG.getConstant(PtrOff, PtrType));
5711 AddToWorkList(NewPtr.getNode());
5712
Chris Lattner9a499e92010-12-22 08:01:44 +00005713 SDValue Load;
5714 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005715 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005716 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005717 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005718 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005719 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005720 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005721 LN0->getPointerInfo().getWithOffset(PtrOff),
5722 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005723 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005724
5725 // Replace the old load's chain with the new load's chain.
5726 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005727 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005728
5729 // Shift the result left, if we've swallowed a left shift.
5730 SDValue Result = Load;
5731 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005732 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005733 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5734 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005735 // If the shift amount is as large as the result size (but, presumably,
5736 // no larger than the source) then the useful bits of the result are
5737 // zero; we can't simply return the shortened shift, because the result
5738 // of that operation is undefined.
5739 if (ShLeftAmt >= VT.getSizeInBits())
5740 Result = DAG.getConstant(0, VT);
5741 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005742 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005743 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005744 }
5745
5746 // Return the new loaded value.
5747 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005748}
5749
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005750SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5751 SDValue N0 = N->getOperand(0);
5752 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005753 EVT VT = N->getValueType(0);
5754 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005755 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005756 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005757
Nate Begeman21158fc2005-09-01 00:19:25 +00005758 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005759 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005760 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005761
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005762 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005763 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005764 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005765
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005766 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5767 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005768 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005769 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005770 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005771
Dan Gohman345d63c2008-07-31 00:50:31 +00005772 // fold (sext_in_reg (sext x)) -> (sext x)
5773 // fold (sext_in_reg (aext x)) -> (sext x)
5774 // if x is small enough.
5775 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5776 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005777 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5778 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005779 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005780 }
5781
Chris Lattner9ad59152007-04-17 19:03:21 +00005782 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005783 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005784 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005785
Chris Lattner9ad59152007-04-17 19:03:21 +00005786 // fold operands of sext_in_reg based on knowledge that the top bits are not
5787 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005788 if (SimplifyDemandedBits(SDValue(N, 0)))
5789 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005790
Evan Cheng464dc9b2007-03-22 01:54:19 +00005791 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5792 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005793 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005794 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005795 return NarrowLoad;
5796
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005797 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005798 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005799 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5800 if (N0.getOpcode() == ISD::SRL) {
5801 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005802 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005803 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005804 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005805 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005806 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005807 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005808 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005809 }
5810 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005811
Nate Begeman02b23c62005-10-13 03:11:28 +00005812 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005813 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005814 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005815 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005816 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005817 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005818 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005819 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005820 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005821 LN0->getBasePtr(), EVT,
5822 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005823 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005824 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky14a4af02012-12-19 07:50:20 +00005825 AddToWorkList(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005826 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005827 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005828 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005829 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005830 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005831 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005832 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005833 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005834 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005835 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005836 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005837 LN0->getBasePtr(), EVT,
5838 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005839 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005840 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005841 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005842 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005843
5844 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5845 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5846 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5847 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005848 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005849 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005850 BSwap, N1);
5851 }
5852
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005853 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5854 // into a build_vector.
5855 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5856 SmallVector<SDValue, 8> Elts;
5857 unsigned NumElts = N0->getNumOperands();
5858 unsigned ShAmt = VTBits - EVTBits;
5859
5860 for (unsigned i = 0; i != NumElts; ++i) {
5861 SDValue Op = N0->getOperand(i);
5862 if (Op->getOpcode() == ISD::UNDEF) {
5863 Elts.push_back(Op);
5864 continue;
5865 }
5866
5867 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005868 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5869 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005870 Op.getValueType()));
5871 }
5872
Craig Topper48d114b2014-04-26 18:35:24 +00005873 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005874 }
5875
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005876 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005877}
5878
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005879SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5880 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005881 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005882 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005883
5884 // noop truncate
5885 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005886 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005887 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005888 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005889 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005890 // fold (truncate (truncate x)) -> (truncate x)
5891 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005892 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005893 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005894 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5895 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005896 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005897 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005898 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005899 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005900 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005901 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005902 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00005903 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005904 // if the source and dest are the same type, we can drop both the extend
5905 // and the truncate.
5906 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005907 }
Evan Chengd63baea2007-03-21 20:14:05 +00005908
Nadav Rotem4f4546b2012-02-05 11:39:23 +00005909 // Fold extract-and-trunc into a narrow extract. For example:
5910 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5911 // i32 y = TRUNCATE(i64 x)
5912 // -- becomes --
5913 // v16i8 b = BITCAST (v2i64 val)
5914 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5915 //
5916 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005917 // creates this pattern) and before operation legalization after which
5918 // we need to be more careful about the vector instructions that we generate.
5919 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00005920 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005921
5922 EVT VecTy = N0.getOperand(0).getValueType();
5923 EVT ExTy = N0.getValueType();
5924 EVT TrTy = N->getValueType(0);
5925
5926 unsigned NumElem = VecTy.getVectorNumElements();
5927 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5928
5929 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5930 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5931
5932 SDValue EltNo = N0->getOperand(1);
5933 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5934 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00005935 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005936 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5937
Andrew Trickef9de2a2013-05-25 02:42:55 +00005938 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005939 NVT, N0.getOperand(0));
5940
5941 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005942 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00005943 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005944 }
5945 }
5946
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005947 // Fold a series of buildvector, bitcast, and truncate if possible.
5948 // For example fold
5949 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5950 // (2xi32 (buildvector x, y)).
5951 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5952 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5953 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5954 N0.getOperand(0).hasOneUse()) {
5955
5956 SDValue BuildVect = N0.getOperand(0);
5957 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5958 EVT TruncVecEltTy = VT.getVectorElementType();
5959
5960 // Check that the element types match.
5961 if (BuildVectEltTy == TruncVecEltTy) {
5962 // Now we only need to compute the offset of the truncated elements.
5963 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5964 unsigned TruncVecNumElts = VT.getVectorNumElements();
5965 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5966
5967 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5968 "Invalid number of elements");
5969
5970 SmallVector<SDValue, 8> Opnds;
5971 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5972 Opnds.push_back(BuildVect.getOperand(i));
5973
Craig Topper48d114b2014-04-26 18:35:24 +00005974 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005975 }
5976 }
5977
Chris Lattner5e6fe052007-10-13 06:35:54 +00005978 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00005979 // only the low bits are being used.
5980 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00005981 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00005982 // may have different active low bits.
5983 if (!VT.isVector()) {
5984 SDValue Shorter =
5985 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5986 VT.getSizeInBits()));
5987 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005988 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00005989 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005990 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00005991 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00005992 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5993 SDValue Reduced = ReduceLoadWidth(N);
5994 if (Reduced.getNode())
5995 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00005996 // Handle the case where the load remains an extending load even
5997 // after truncation.
5998 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5999 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6000 if (!LN0->isVolatile() &&
6001 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6002 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6003 VT, LN0->getChain(), LN0->getBasePtr(),
6004 LN0->getMemoryVT(),
6005 LN0->getMemOperand());
6006 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6007 return NewLoad;
6008 }
6009 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006010 }
Michael Liao3ac82012012-10-17 23:45:54 +00006011 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6012 // where ... are all 'undef'.
6013 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6014 SmallVector<EVT, 8> VTs;
6015 SDValue V;
6016 unsigned Idx = 0;
6017 unsigned NumDefs = 0;
6018
6019 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6020 SDValue X = N0.getOperand(i);
6021 if (X.getOpcode() != ISD::UNDEF) {
6022 V = X;
6023 Idx = i;
6024 NumDefs++;
6025 }
6026 // Stop if more than one members are non-undef.
6027 if (NumDefs > 1)
6028 break;
6029 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6030 VT.getVectorElementType(),
6031 X.getValueType().getVectorNumElements()));
6032 }
6033
6034 if (NumDefs == 0)
6035 return DAG.getUNDEF(VT);
6036
6037 if (NumDefs == 1) {
6038 assert(V.getNode() && "The single defined operand is empty!");
6039 SmallVector<SDValue, 8> Opnds;
6040 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6041 if (i != Idx) {
6042 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6043 continue;
6044 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006045 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao3ac82012012-10-17 23:45:54 +00006046 AddToWorkList(NV.getNode());
6047 Opnds.push_back(NV);
6048 }
Craig Topper48d114b2014-04-26 18:35:24 +00006049 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006050 }
6051 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006052
6053 // Simplify the operands using demanded-bits information.
6054 if (!VT.isVector() &&
6055 SimplifyDemandedBits(SDValue(N, 0)))
6056 return SDValue(N, 0);
6057
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006058 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006059}
6060
Evan Chengb980f6f2008-05-12 23:04:07 +00006061static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006062 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006063 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006064 return Elt.getNode();
6065 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006066}
6067
6068/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006069/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006070SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006071 assert(N->getOpcode() == ISD::BUILD_PAIR);
6072
Nate Begeman624690c2009-06-05 21:37:30 +00006073 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6074 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006075 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006076 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006077 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006078 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006079
Evan Chengb980f6f2008-05-12 23:04:07 +00006080 if (ISD::isNON_EXTLoad(LD2) &&
6081 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006082 // If both are volatile this would reduce the number of volatile loads.
6083 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006084 !LD1->isVolatile() &&
6085 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006086 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006087 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006088 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006089 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006090
Duncan Sands8651e9c2008-06-13 19:07:40 +00006091 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006092 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006093 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006094 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006095 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006096 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006097
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006098 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006099}
6100
Wesley Peck527da1b2010-11-23 03:31:01 +00006101SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006102 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006103 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006104
Dan Gohmana8665142007-06-25 16:23:39 +00006105 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6106 // Only do this before legalize, since afterward the target may be depending
6107 // on the bitconvert.
6108 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006109 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006110 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006111 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006112 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006113
Owen Anderson53aa7a92009-08-10 22:56:29 +00006114 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006115 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006116 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006117 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006118 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006119 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006120
Dan Gohman921ddd62008-09-05 01:58:21 +00006121 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006122 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006123 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006124 if (Res.getNode() != N) {
6125 if (!LegalOperations ||
6126 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6127 return Res;
6128
6129 // Folding it resulted in an illegal node, and it's too late to
6130 // do that. Clean up the old node and forego the transformation.
6131 // Ideally this won't happen very often, because instcombine
6132 // and the earlier dagcombine runs (where illegal nodes are
6133 // permitted) should have folded most of them already.
6134 DAG.DeleteNode(Res.getNode());
6135 }
Chris Lattnera1874602005-12-23 05:30:37 +00006136 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006137
Bill Wendling4e0a6152009-01-30 22:44:24 +00006138 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006139 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006140 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006141 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006142
Chris Lattner54560f62005-12-23 05:44:41 +00006143 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006144 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006145 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006146 // Do not change the width of a volatile load.
6147 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006148 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6149 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006150 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006151 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006152 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006153 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006154
Evan Chenga4cf58a2007-05-07 21:27:48 +00006155 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006156 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006157 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006158 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006159 LN0->isInvariant(), OrigAlign,
6160 LN0->getTBAAInfo());
Evan Chenga4cf58a2007-05-07 21:27:48 +00006161 AddToWorkList(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006162 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006163 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006164 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006165 Load.getValue(1));
6166 return Load;
6167 }
Chris Lattner54560f62005-12-23 05:44:41 +00006168 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006169
Bill Wendling4e0a6152009-01-30 22:44:24 +00006170 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6171 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006172 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006173 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6174 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006175 N0.getNode()->hasOneUse() && VT.isInteger() &&
6176 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006177 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006178 N0.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006179 AddToWorkList(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006180
Duncan Sands13237ac2008-06-06 12:08:01 +00006181 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006182 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006183 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006184 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006185 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006186 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006187 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006188 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006189
Bill Wendling4e0a6152009-01-30 22:44:24 +00006190 // fold (bitconvert (fcopysign cst, x)) ->
6191 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6192 // Note that we don't handle (copysign x, cst) because this can always be
6193 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006194 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006195 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006196 VT.isInteger() && !VT.isVector()) {
6197 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006198 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006199 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006200 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006201 IntXVT, N0.getOperand(1));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006202 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006203
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006204 // If X has a different width than the result/lhs, sext it or truncate it.
6205 unsigned VTWidth = VT.getSizeInBits();
6206 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006207 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006208 AddToWorkList(X.getNode());
6209 } else if (OrigXWidth > VTWidth) {
6210 // To get the sign bit in the right place, we have to shift it right
6211 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006212 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006213 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006214 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6215 AddToWorkList(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006216 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006217 AddToWorkList(X.getNode());
6218 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006219
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006220 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006221 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006222 X, DAG.getConstant(SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006223 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006224
Andrew Trickef9de2a2013-05-25 02:42:55 +00006225 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006226 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006227 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006228 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006229 AddToWorkList(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006230
Andrew Trickef9de2a2013-05-25 02:42:55 +00006231 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006232 }
Chris Lattner888560d2008-01-27 17:42:27 +00006233 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006234
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006235 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006236 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006237 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6238 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006239 return CombineLD;
6240 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006241
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006242 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006243}
6244
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006245SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006246 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006247 return CombineConsecutiveLoads(N, VT);
6248}
6249
Wesley Peck527da1b2010-11-23 03:31:01 +00006250/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006251/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006252/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006253SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006254ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006255 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006256
Chris Lattnere4e64b62006-04-02 02:53:43 +00006257 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006258 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006259
Duncan Sands13237ac2008-06-06 12:08:01 +00006260 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6261 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006262
Chris Lattnere4e64b62006-04-02 02:53:43 +00006263 // If this is a conversion of N elements of one type to N elements of another
6264 // type, convert each element. This handles FP<->INT cases.
6265 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006266 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6267 BV->getValueType(0).getVectorNumElements());
6268
6269 // Due to the FP element handling below calling this routine recursively,
6270 // we can end up with a scalar-to-vector node here.
6271 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006272 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6273 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006274 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006275
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006276 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006277 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006278 SDValue Op = BV->getOperand(i);
6279 // If the vector element type is not legal, the BUILD_VECTOR operands
6280 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006281 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006282 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6283 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006284 DstEltVT, Op));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006285 AddToWorkList(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006286 }
Craig Topper48d114b2014-04-26 18:35:24 +00006287 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006288 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006289
Chris Lattnere4e64b62006-04-02 02:53:43 +00006290 // Otherwise, we're growing or shrinking the elements. To avoid having to
6291 // handle annoying details of growing/shrinking FP values, we convert them to
6292 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006293 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006294 // Convert the input float vector to a int vector where the elements are the
6295 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006296 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006297 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006298 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006299 SrcEltVT = IntVT;
6300 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006301
Chris Lattnere4e64b62006-04-02 02:53:43 +00006302 // Now we know the input is an integer vector. If the output is a FP type,
6303 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006304 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006305 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006306 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006307 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006308
Chris Lattnere4e64b62006-04-02 02:53:43 +00006309 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006310 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006311 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006312
Chris Lattnere4e64b62006-04-02 02:53:43 +00006313 // Okay, we know the src/dst types are both integers of differing types.
6314 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006315 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006316 if (SrcBitSize < DstBitSize) {
6317 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006318
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006319 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006320 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006321 i += NumInputsPerOutput) {
6322 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006323 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006324 bool EltIsUndef = true;
6325 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6326 // Shift the previously computed bits over.
6327 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006328 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006329 if (Op.getOpcode() == ISD::UNDEF) continue;
6330 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006331
Jay Foad583abbc2010-12-07 08:25:19 +00006332 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006333 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006334 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006335
Chris Lattnere4e64b62006-04-02 02:53:43 +00006336 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006337 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006338 else
6339 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6340 }
6341
Owen Anderson117c9e82009-08-12 00:36:31 +00006342 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006343 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006344 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006345
Chris Lattnere4e64b62006-04-02 02:53:43 +00006346 // Finally, this must be the case where we are shrinking elements: each input
6347 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006348 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006349 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006350 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6351 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006352 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006353
Dan Gohmana8665142007-06-25 16:23:39 +00006354 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006355 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6356 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006357 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006358 continue;
6359 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006360
Jay Foad583abbc2010-12-07 08:25:19 +00006361 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6362 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006363
Chris Lattnere4e64b62006-04-02 02:53:43 +00006364 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006365 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006366 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006367 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006368 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006369 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006370 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006371 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006372 }
6373
6374 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006375 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006376 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6377 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006378
Craig Topper48d114b2014-04-26 18:35:24 +00006379 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006380}
6381
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006382SDValue DAGCombiner::visitFADD(SDNode *N) {
6383 SDValue N0 = N->getOperand(0);
6384 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006385 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6386 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006387 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006388
Dan Gohmana8665142007-06-25 16:23:39 +00006389 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006390 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006391 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006392 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006393 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006394
Lang Hamesa33db652012-06-14 20:37:15 +00006395 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006396 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006397 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006398 // canonicalize constant to RHS
6399 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006400 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006401 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006402 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6403 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006404 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006405 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006406 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006407 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006408 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006409 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006410 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006411 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006412 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006413 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006414 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006415
Chris Lattner0199fd62007-01-08 23:04:05 +00006416 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006417 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6418 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6419 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006420 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6421 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006422 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006423
Shuxin Yang93b1f122013-03-25 22:52:29 +00006424 // No FP constant should be created after legalization as Instruction
6425 // Selection pass has hard time in dealing with FP constant.
6426 //
6427 // We don't need test this condition for transformation like following, as
6428 // the DAG being transformed implies it is legal to take FP constant as
6429 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006430 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006431 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006432 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006433 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6434
Owen Andersonb351c8d2012-11-01 02:00:53 +00006435 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006436 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006437 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006438 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006439
6440 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006441 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006442 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006443 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006444
Owen Andersoncc61f872012-08-30 23:35:16 +00006445 // In unsafe math mode, we can fold chains of FADD's of the same value
6446 // into multiplications. This transform is not safe in general because
6447 // we are reducing the number of rounding steps.
6448 if (DAG.getTarget().Options.UnsafeFPMath &&
6449 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6450 !N0CFP && !N1CFP) {
6451 if (N0.getOpcode() == ISD::FMUL) {
6452 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6453 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6454
Stephen Line31f2d22013-06-14 18:17:35 +00006455 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006456 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006457 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006458 SDValue(CFP00, 0),
6459 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006460 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006461 N1, NewCFP);
6462 }
6463
Stephen Line31f2d22013-06-14 18:17:35 +00006464 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006465 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006466 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006467 SDValue(CFP01, 0),
6468 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006469 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006470 N1, NewCFP);
6471 }
6472
Stephen Line31f2d22013-06-14 18:17:35 +00006473 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006474 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6475 N1.getOperand(0) == N1.getOperand(1) &&
6476 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006477 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006478 SDValue(CFP00, 0),
6479 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006480 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006481 N0.getOperand(1), NewCFP);
6482 }
6483
Stephen Line31f2d22013-06-14 18:17:35 +00006484 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006485 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6486 N1.getOperand(0) == N1.getOperand(1) &&
6487 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006488 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006489 SDValue(CFP01, 0),
6490 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006491 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006492 N0.getOperand(0), NewCFP);
6493 }
6494 }
6495
6496 if (N1.getOpcode() == ISD::FMUL) {
6497 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6498 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6499
Stephen Line31f2d22013-06-14 18:17:35 +00006500 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006501 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006502 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006503 SDValue(CFP10, 0),
6504 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006505 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006506 N0, NewCFP);
6507 }
6508
Stephen Line31f2d22013-06-14 18:17:35 +00006509 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006510 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006511 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006512 SDValue(CFP11, 0),
6513 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006514 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006515 N0, NewCFP);
6516 }
6517
Owen Andersoncc61f872012-08-30 23:35:16 +00006518
Stephen Line31f2d22013-06-14 18:17:35 +00006519 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6520 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6521 N0.getOperand(0) == N0.getOperand(1) &&
6522 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006523 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006524 SDValue(CFP10, 0),
6525 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006526 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006527 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006528 }
6529
Stephen Line31f2d22013-06-14 18:17:35 +00006530 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6531 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6532 N0.getOperand(0) == N0.getOperand(1) &&
6533 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006534 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006535 SDValue(CFP11, 0),
6536 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006537 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006538 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006539 }
6540 }
6541
Shuxin Yang93b1f122013-03-25 22:52:29 +00006542 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006543 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006544 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006545 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006546 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006547 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006548 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006549 }
6550
Shuxin Yang93b1f122013-03-25 22:52:29 +00006551 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006552 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006553 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006554 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006555 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006556 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006557 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006558 }
6559
Stephen Lin4e69d012013-06-14 21:33:58 +00006560 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006561 if (AllowNewFpConst &&
6562 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006563 N0.getOperand(0) == N0.getOperand(1) &&
6564 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006565 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006566 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006567 N0.getOperand(0),
6568 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006569 }
6570
Lang Hames39fb1d02012-06-19 22:51:23 +00006571 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006572 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006573 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006574 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6575 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006576
6577 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006578 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006579 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006580 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006581
Michael Liaoec3850122012-09-01 04:09:16 +00006582 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006583 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006584 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006585 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006586 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006587 }
6588
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006589 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006590}
6591
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006592SDValue DAGCombiner::visitFSUB(SDNode *N) {
6593 SDValue N0 = N->getOperand(0);
6594 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006595 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6596 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006597 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006598 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006599
Dan Gohmana8665142007-06-25 16:23:39 +00006600 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006601 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006602 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006603 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006604 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006605
Nate Begeman418c6e42005-10-18 00:28:13 +00006606 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006607 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006608 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006609 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006610 if (DAG.getTarget().Options.UnsafeFPMath &&
6611 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006612 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006613 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006614 if (DAG.getTarget().Options.UnsafeFPMath &&
6615 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006616 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006617 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006618 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006619 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006620 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006621 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006622 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006623 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006624 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006625
Bill Wendlingdf170db2012-03-15 05:12:00 +00006626 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006627 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006628 // (fsub x, (fadd x, y)) -> (fneg y) &
6629 // (fsub x, (fadd y, x)) -> (fneg y)
6630 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006631 if (N0 == N1)
6632 return DAG.getConstantFP(0.0f, VT);
6633
Bill Wendlingdf170db2012-03-15 05:12:00 +00006634 if (N1.getOpcode() == ISD::FADD) {
6635 SDValue N10 = N1->getOperand(0);
6636 SDValue N11 = N1->getOperand(1);
6637
6638 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6639 &DAG.getTarget().Options))
6640 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006641
Stephen Lin8e8424e2013-07-09 00:44:49 +00006642 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6643 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006644 return GetNegatedExpression(N10, DAG, LegalOperations);
6645 }
6646 }
6647
Lang Hames39fb1d02012-06-19 22:51:23 +00006648 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006649 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006650 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006651 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6652 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006653
6654 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006655 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006656 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006657 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006658 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006659
6660 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6661 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006662 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006663 return DAG.getNode(ISD::FMA, dl, VT,
6664 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006665 N1.getOperand(0)),
6666 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006667
Stephen Lin8e8424e2013-07-09 00:44:49 +00006668 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006669 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006670 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6671 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6672 SDValue N00 = N0.getOperand(0).getOperand(0);
6673 SDValue N01 = N0.getOperand(0).getOperand(1);
6674 return DAG.getNode(ISD::FMA, dl, VT,
6675 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6676 DAG.getNode(ISD::FNEG, dl, VT, N1));
6677 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006678 }
6679
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006680 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006681}
6682
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006683SDValue DAGCombiner::visitFMUL(SDNode *N) {
6684 SDValue N0 = N->getOperand(0);
6685 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006686 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6687 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006688 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006689 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006690
Dan Gohmana8665142007-06-25 16:23:39 +00006691 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006692 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006693 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006694 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006695 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006696
Nate Begemanec48a1b2005-10-17 20:40:11 +00006697 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006698 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006699 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006700 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006701 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006702 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006703 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006704 if (DAG.getTarget().Options.UnsafeFPMath &&
6705 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006706 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006707 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006708 if (DAG.getTarget().Options.UnsafeFPMath &&
6709 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006710 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006711 // fold (fmul A, 1.0) -> A
6712 if (N1CFP && N1CFP->isExactlyValue(1.0))
6713 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006714 // fold (fmul X, 2.0) -> (fadd X, X)
6715 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006716 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006717 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006718 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006719 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006720 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006721
Bill Wendling3dc5d242009-01-30 22:57:07 +00006722 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006723 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006724 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006725 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006726 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006727 // Both can be negated for free, check to see if at least one is cheaper
6728 // negated.
6729 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006730 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006731 GetNegatedExpression(N0, DAG, LegalOperations),
6732 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006733 }
6734 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006735
Chris Lattner0199fd62007-01-08 23:04:05 +00006736 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006737 if (DAG.getTarget().Options.UnsafeFPMath &&
6738 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006739 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006740 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6741 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006742 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006743
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006744 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006745}
6746
Owen Anderson41b06652012-05-02 22:17:40 +00006747SDValue DAGCombiner::visitFMA(SDNode *N) {
6748 SDValue N0 = N->getOperand(0);
6749 SDValue N1 = N->getOperand(1);
6750 SDValue N2 = N->getOperand(2);
6751 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6752 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6753 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006754 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006755
Owen Andersonb351c8d2012-11-01 02:00:53 +00006756 if (DAG.getTarget().Options.UnsafeFPMath) {
6757 if (N0CFP && N0CFP->isZero())
6758 return N2;
6759 if (N1CFP && N1CFP->isZero())
6760 return N2;
6761 }
Owen Anderson41b06652012-05-02 22:17:40 +00006762 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006763 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006764 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006765 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006766
Owen Andersonc7aaf522012-05-30 18:50:39 +00006767 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006768 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006769 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006770
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006771 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6772 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6773 N2.getOpcode() == ISD::FMUL &&
6774 N0 == N2.getOperand(0) &&
6775 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6776 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6777 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6778 }
6779
6780
6781 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6782 if (DAG.getTarget().Options.UnsafeFPMath &&
6783 N0.getOpcode() == ISD::FMUL && N1CFP &&
6784 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6785 return DAG.getNode(ISD::FMA, dl, VT,
6786 N0.getOperand(0),
6787 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6788 N2);
6789 }
6790
6791 // (fma x, 1, y) -> (fadd x, y)
6792 // (fma x, -1, y) -> (fadd (fneg x), y)
6793 if (N1CFP) {
6794 if (N1CFP->isExactlyValue(1.0))
6795 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6796
6797 if (N1CFP->isExactlyValue(-1.0) &&
6798 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6799 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6800 AddToWorkList(RHSNeg.getNode());
6801 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6802 }
6803 }
6804
6805 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006806 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6807 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006808 DAG.getNode(ISD::FADD, dl, VT,
6809 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006810
6811 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6812 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006813 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6814 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006815 DAG.getNode(ISD::FADD, dl, VT,
6816 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006817
6818
Owen Anderson41b06652012-05-02 22:17:40 +00006819 return SDValue();
6820}
6821
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006822SDValue DAGCombiner::visitFDIV(SDNode *N) {
6823 SDValue N0 = N->getOperand(0);
6824 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006825 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6826 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006827 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006828 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006829
Dan Gohmana8665142007-06-25 16:23:39 +00006830 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006831 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006832 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006833 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006834 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006835
Nate Begeman569c4392006-01-18 22:35:16 +00006836 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006837 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006838 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006839
Duncan Sands2f1dc382012-04-08 18:08:12 +00006840 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006841 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006842 // Compute the reciprocal 1.0 / c2.
6843 APFloat N1APF = N1CFP->getValueAPF();
6844 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6845 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006846 // Only do the transform if the reciprocal is a legal fp immediate that
6847 // isn't too nasty (eg NaN, denormal, ...).
6848 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006849 (!LegalOperations ||
6850 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6851 // backend)... we should handle this gracefully after Legalize.
6852 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6853 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6854 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006855 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006856 DAG.getConstantFP(Recip, VT));
6857 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006858
Bill Wendling3dc5d242009-01-30 22:57:07 +00006859 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006860 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006861 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006862 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006863 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006864 // Both can be negated for free, check to see if at least one is cheaper
6865 // negated.
6866 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006867 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006868 GetNegatedExpression(N0, DAG, LegalOperations),
6869 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006870 }
6871 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006872
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006873 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006874}
6875
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006876SDValue DAGCombiner::visitFREM(SDNode *N) {
6877 SDValue N0 = N->getOperand(0);
6878 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006879 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6880 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006881 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006882
Nate Begeman569c4392006-01-18 22:35:16 +00006883 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006884 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006885 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00006886
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006887 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006888}
6889
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006890SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6891 SDValue N0 = N->getOperand(0);
6892 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006893 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6894 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006895 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00006896
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006897 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00006898 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006899
Chris Lattner3bc40502006-03-05 05:30:57 +00006900 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00006901 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006902 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6903 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00006904 if (!V.isNegative()) {
6905 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006906 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006907 } else {
6908 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006909 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6910 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00006911 }
Chris Lattner3bc40502006-03-05 05:30:57 +00006912 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006913
Chris Lattner3bc40502006-03-05 05:30:57 +00006914 // copysign(fabs(x), y) -> copysign(x, y)
6915 // copysign(fneg(x), y) -> copysign(x, y)
6916 // copysign(copysign(x,z), y) -> copysign(x, y)
6917 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6918 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006919 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006920 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006921
6922 // copysign(x, abs(y)) -> abs(x)
6923 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006924 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006925
Chris Lattner3bc40502006-03-05 05:30:57 +00006926 // copysign(x, copysign(y,z)) -> copysign(x, z)
6927 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006928 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006929 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006930
Chris Lattner3bc40502006-03-05 05:30:57 +00006931 // copysign(x, fp_extend(y)) -> copysign(x, y)
6932 // copysign(x, fp_round(y)) -> copysign(x, y)
6933 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006934 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006935 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006936
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006937 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00006938}
6939
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006940SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6941 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006942 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006943 EVT VT = N->getValueType(0);
6944 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006945
Nate Begeman21158fc2005-09-01 00:19:25 +00006946 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006947 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006948 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006949 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006950 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006951 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006952
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006953 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6954 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006955 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6956 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006957 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006958 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006959 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006960 }
Bill Wendling0bd29742009-01-30 23:15:49 +00006961
Alp Tokercb402912014-01-24 17:20:08 +00006962 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006963 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6964 // having to say they don't support SELECT_CC on every type the DAG knows
6965 // about, since there is no way to mark an opcode illegal at all value types
6966 // (See also visitSELECT)
6967 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6968 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6969 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6970 !VT.isVector() &&
6971 (!LegalOperations ||
6972 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6973 SDValue Ops[] =
6974 { N0.getOperand(0), N0.getOperand(1),
6975 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6976 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00006977 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00006978 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006979
Nadav Rotem90560762012-07-23 07:59:50 +00006980 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6981 // (select_cc x, y, 1.0, 0.0,, cc)
6982 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6983 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6984 (!LegalOperations ||
6985 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6986 SDValue Ops[] =
6987 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6988 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6989 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00006990 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00006991 }
Owen Andersond4b841f2012-07-09 20:31:12 +00006992 }
6993
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006994 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006995}
6996
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006997SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6998 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006999 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007000 EVT VT = N->getValueType(0);
7001 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007002
Nate Begeman21158fc2005-09-01 00:19:25 +00007003 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007004 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007005 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007006 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007007 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007008 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007009
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007010 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7011 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007012 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7013 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007014 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007015 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007016 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007017 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007018
Alp Tokercb402912014-01-24 17:20:08 +00007019 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00007020 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7021 // having to say they don't support SELECT_CC on every type the DAG knows
7022 // about, since there is no way to mark an opcode illegal at all value types
7023 // (See also visitSELECT)
7024 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7025 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007026
Nadav Rotem90560762012-07-23 07:59:50 +00007027 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7028 (!LegalOperations ||
7029 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7030 SDValue Ops[] =
7031 { N0.getOperand(0), N0.getOperand(1),
7032 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7033 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007034 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007035 }
7036 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007037
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007038 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007039}
7040
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007041SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7042 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007043 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007044 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007045
Nate Begeman21158fc2005-09-01 00:19:25 +00007046 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007047 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007048 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007049
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007050 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007051}
7052
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007053SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7054 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007055 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007056 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007057
Nate Begeman21158fc2005-09-01 00:19:25 +00007058 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007059 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007060 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007061
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007062 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007063}
7064
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007065SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7066 SDValue N0 = N->getOperand(0);
7067 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007068 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007069 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007070
Nate Begeman21158fc2005-09-01 00:19:25 +00007071 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007072 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007073 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007074
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007075 // fold (fp_round (fp_extend x)) -> x
7076 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7077 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007078
Chris Lattner0feb1b02008-01-24 06:45:35 +00007079 // fold (fp_round (fp_round x)) -> (fp_round x)
7080 if (N0.getOpcode() == ISD::FP_ROUND) {
7081 // This is a value preserving truncation if both round's are.
7082 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007083 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007084 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007085 DAG.getIntPtrConstant(IsTrunc));
7086 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007087
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007088 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007089 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007090 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007091 N0.getOperand(0), N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007092 AddToWorkList(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007093 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007094 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007095 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007096
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007097 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007098}
7099
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007100SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7101 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007102 EVT VT = N->getValueType(0);
7103 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007104 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007105
Nate Begeman21158fc2005-09-01 00:19:25 +00007106 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007107 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007108 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007109 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007110 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007111
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007112 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007113}
7114
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007115SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7116 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007117 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007118 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007119
Chris Lattner5919b482007-12-29 06:55:23 +00007120 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007121 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007122 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007123 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007124
Nate Begeman21158fc2005-09-01 00:19:25 +00007125 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007126 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007127 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007128
7129 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7130 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007131 if (N0.getOpcode() == ISD::FP_ROUND
7132 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007133 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007134 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007135 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007136 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007137 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007138 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007139 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007140
Chris Lattner72733e52008-01-17 07:00:52 +00007141 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007142 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007143 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00007144 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007145 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007146 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007147 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007148 LN0->getBasePtr(), N0.getValueType(),
7149 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007150 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007151 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007152 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007153 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007154 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007155 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007156 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007157
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007158 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007159}
7160
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007161SDValue DAGCombiner::visitFNEG(SDNode *N) {
7162 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007163 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007164
Craig Topper82384612012-09-11 01:45:21 +00007165 if (VT.isVector()) {
7166 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7167 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007168 }
7169
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007170 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7171 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007172 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007173
Chris Lattner888560d2008-01-27 17:42:27 +00007174 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7175 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007176 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007177 !VT.isVector() &&
7178 N0.getNode()->hasOneUse() &&
7179 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007180 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007181 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007182 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007183 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007184 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007185 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007186 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007187 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007188 }
7189 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007190
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007191 // (fneg (fmul c, x)) -> (fmul -c, x)
7192 if (N0.getOpcode() == ISD::FMUL) {
7193 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007194 if (CFP1) {
7195 APFloat CVal = CFP1->getValueAPF();
7196 CVal.changeSign();
7197 if (Level >= AfterLegalizeDAG &&
7198 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7199 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7200 return DAG.getNode(
7201 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7202 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7203 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007204 }
7205
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007206 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007207}
7208
Owen Andersona40319b2012-08-13 23:32:49 +00007209SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7210 SDValue N0 = N->getOperand(0);
7211 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7212 EVT VT = N->getValueType(0);
7213
7214 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007215 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007216 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007217
7218 return SDValue();
7219}
7220
7221SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7222 SDValue N0 = N->getOperand(0);
7223 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7224 EVT VT = N->getValueType(0);
7225
7226 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007227 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007228 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007229
7230 return SDValue();
7231}
7232
7233SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7234 SDValue N0 = N->getOperand(0);
7235 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7236 EVT VT = N->getValueType(0);
7237
7238 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007239 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007240 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007241
7242 return SDValue();
7243}
7244
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007245SDValue DAGCombiner::visitFABS(SDNode *N) {
7246 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007247 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007248 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007249
Craig Topper82384612012-09-11 01:45:21 +00007250 if (VT.isVector()) {
7251 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7252 if (FoldedVOp.getNode()) return FoldedVOp;
7253 }
7254
Nate Begeman21158fc2005-09-01 00:19:25 +00007255 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007256 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007257 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007258 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007259 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007260 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007261 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007262 // fold (fabs (fcopysign x, y)) -> (fabs x)
7263 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007264 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007265
Chris Lattner888560d2008-01-27 17:42:27 +00007266 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7267 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007268 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007269 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007270 N0.getOperand(0).getValueType().isInteger() &&
7271 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007272 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007273 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007274 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007275 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007276 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007277 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007278 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007279 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007280 }
7281 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007282
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007283 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007284}
7285
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007286SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7287 SDValue Chain = N->getOperand(0);
7288 SDValue N1 = N->getOperand(1);
7289 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007290
Dan Gohman82e80012009-11-17 00:47:23 +00007291 // If N is a constant we could fold this into a fallthrough or unconditional
7292 // branch. However that doesn't happen very often in normal code, because
7293 // Instcombine/SimplifyCFG should have handled the available opportunities.
7294 // If we did this folding here, it would be necessary to update the
7295 // MachineBasicBlock CFG, which is awkward.
7296
Nate Begeman7e7f4392006-02-01 07:19:44 +00007297 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7298 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007299 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007300 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7301 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007302 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007303 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007304 N1.getOperand(0), N1.getOperand(1), N2);
7305 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007306
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007307 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7308 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7309 (N1.getOperand(0).hasOneUse() &&
7310 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007311 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007312 if (N1.getOpcode() == ISD::TRUNCATE) {
7313 // Look pass the truncate.
7314 Trunc = N1.getNode();
7315 N1 = N1.getOperand(0);
7316 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007317
Bill Wendlingaa28be62009-03-26 06:14:09 +00007318 // Match this pattern so that we can generate simpler code:
7319 //
7320 // %a = ...
7321 // %b = and i32 %a, 2
7322 // %c = srl i32 %b, 1
7323 // brcond i32 %c ...
7324 //
7325 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007326 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007327 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007328 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007329 // %c = setcc eq %b, 0
7330 // brcond %c ...
7331 //
7332 // This applies only when the AND constant value has one bit set and the
7333 // SRL constant is equal to the log2 of the AND constant. The back-end is
7334 // smart enough to convert the result into a TEST/JMP sequence.
7335 SDValue Op0 = N1.getOperand(0);
7336 SDValue Op1 = N1.getOperand(1);
7337
7338 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007339 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007340 SDValue AndOp1 = Op0.getOperand(1);
7341
7342 if (AndOp1.getOpcode() == ISD::Constant) {
7343 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7344
7345 if (AndConst.isPowerOf2() &&
7346 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7347 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007348 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007349 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007350 Op0, DAG.getConstant(0, Op0.getValueType()),
7351 ISD::SETNE);
7352
Andrew Trickef9de2a2013-05-25 02:42:55 +00007353 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007354 MVT::Other, Chain, SetCC, N2);
7355 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7356 // will convert it back to (X & C1) >> C2.
7357 CombineTo(N, NewBRCond, false);
7358 // Truncate is dead.
7359 if (Trunc) {
7360 removeFromWorkList(Trunc);
7361 DAG.DeleteNode(Trunc);
7362 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007363 // Replace the uses of SRL with SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00007364 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007365 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007366 removeFromWorkList(N1.getNode());
7367 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007368 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007369 }
7370 }
7371 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007372
7373 if (Trunc)
7374 // Restore N1 if the above transformation doesn't match.
7375 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007376 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007377
Evan Cheng228c31f2010-02-27 07:36:59 +00007378 // Transform br(xor(x, y)) -> br(x != y)
7379 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7380 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7381 SDNode *TheXor = N1.getNode();
7382 SDValue Op0 = TheXor->getOperand(0);
7383 SDValue Op1 = TheXor->getOperand(1);
7384 if (Op0.getOpcode() == Op1.getOpcode()) {
7385 // Avoid missing important xor optimizations.
7386 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007387 if (Tmp.getNode()) {
7388 if (Tmp.getNode() != TheXor) {
7389 DEBUG(dbgs() << "\nReplacing.8 ";
7390 TheXor->dump(&DAG);
7391 dbgs() << "\nWith: ";
7392 Tmp.getNode()->dump(&DAG);
7393 dbgs() << '\n');
7394 WorkListRemover DeadNodes(*this);
7395 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7396 removeFromWorkList(TheXor);
7397 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007398 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007399 MVT::Other, Chain, Tmp, N2);
7400 }
7401
Benjamin Kramer93354432013-03-30 21:28:18 +00007402 // visitXOR has changed XOR's operands or replaced the XOR completely,
7403 // bail out.
7404 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007405 }
7406 }
7407
7408 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7409 bool Equal = false;
7410 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7411 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7412 Op0.getOpcode() == ISD::XOR) {
7413 TheXor = Op0.getNode();
7414 Equal = true;
7415 }
7416
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007417 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007418 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007419 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007420 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007421 SetCCVT,
7422 Op0, Op1,
7423 Equal ? ISD::SETEQ : ISD::SETNE);
7424 // Replace the uses of XOR with SETCC
7425 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007426 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007427 removeFromWorkList(N1.getNode());
7428 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007429 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007430 MVT::Other, Chain, SetCC, N2);
7431 }
7432 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007433
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007434 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007435}
7436
Chris Lattnera49e16f2005-10-05 06:47:48 +00007437// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7438//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007439SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007440 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007441 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007442
Dan Gohman82e80012009-11-17 00:47:23 +00007443 // If N is a constant we could fold this into a fallthrough or unconditional
7444 // branch. However that doesn't happen very often in normal code, because
7445 // Instcombine/SimplifyCFG should have handled the available opportunities.
7446 // If we did this folding here, it would be necessary to update the
7447 // MachineBasicBlock CFG, which is awkward.
7448
Duncan Sands93b66092008-06-09 11:32:28 +00007449 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007450 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007451 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007452 false);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007453 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007454
Nate Begemanbd7df032005-10-05 21:43:42 +00007455 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007456 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007457 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007458 N->getOperand(0), Simp.getOperand(2),
7459 Simp.getOperand(0), Simp.getOperand(1),
7460 N->getOperand(4));
7461
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007462 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007463}
7464
Evan Chengfa832632012-01-13 01:37:24 +00007465/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7466/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007467/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007468static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7469 SelectionDAG &DAG,
7470 const TargetLowering &TLI) {
7471 EVT VT;
7472 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7473 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7474 return false;
7475 VT = Use->getValueType(0);
7476 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7477 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7478 return false;
7479 VT = ST->getValue().getValueType();
7480 } else
7481 return false;
7482
Chandler Carruth95f83e02013-01-07 15:14:13 +00007483 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007484 if (N->getOpcode() == ISD::ADD) {
7485 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7486 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007487 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007488 AM.BaseOffs = Offset->getSExtValue();
7489 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007490 // [reg +/- reg]
7491 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007492 } else if (N->getOpcode() == ISD::SUB) {
7493 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7494 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007495 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007496 AM.BaseOffs = -Offset->getSExtValue();
7497 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007498 // [reg +/- reg]
7499 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007500 } else
7501 return false;
7502
7503 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7504}
7505
Duncan Sands075293f2008-06-15 20:12:31 +00007506/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7507/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007508/// and it has other uses besides the load / store. After the
7509/// transformation, the new indexed load / store has effectively folded
7510/// the add / subtract in and all of its other uses are redirected to the
7511/// new load / store.
7512bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007513 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007514 return false;
7515
7516 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007517 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007518 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007519 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007520 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007521 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007522 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007523 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007524 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7525 return false;
7526 Ptr = LD->getBasePtr();
7527 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007528 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007529 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007530 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007531 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7532 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7533 return false;
7534 Ptr = ST->getBasePtr();
7535 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007536 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007537 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007538 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007539
Chris Lattnereabc15c2006-11-11 00:56:29 +00007540 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7541 // out. There is no reason to make this a preinc/predec.
7542 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007543 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007544 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007545
Chris Lattnereabc15c2006-11-11 00:56:29 +00007546 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007547 SDValue BasePtr;
7548 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007549 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7550 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7551 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007552
7553 // Backends without true r+i pre-indexed forms may need to pass a
7554 // constant base with a variable offset so that constant coercion
7555 // will work with the patterns in canonical form.
7556 bool Swapped = false;
7557 if (isa<ConstantSDNode>(BasePtr)) {
7558 std::swap(BasePtr, Offset);
7559 Swapped = true;
7560 }
7561
Evan Cheng044a0a82007-05-03 23:52:19 +00007562 // Don't create a indexed load / store with zero offset.
7563 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007564 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007565 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007566
Chris Lattnera0a80032006-11-11 01:00:15 +00007567 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007568 // 1) The new base ptr is a frame index.
7569 // 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 +00007570 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007571 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007572 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007573 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007574
Chris Lattnera0a80032006-11-11 01:00:15 +00007575 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7576 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007577 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007578 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007579
Chris Lattnera0a80032006-11-11 01:00:15 +00007580 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007581 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007582 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007583 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007584 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007585 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007586
Hal Finkel25819052013-02-08 21:35:47 +00007587 // If the offset is a constant, there may be other adds of constants that
7588 // can be folded with this one. We should do this to avoid having to keep
7589 // a copy of the original base pointer.
7590 SmallVector<SDNode *, 16> OtherUses;
7591 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007592 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007593 if (Use == Ptr.getNode())
7594 continue;
7595
7596 if (Use->isPredecessorOf(N))
7597 continue;
7598
7599 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7600 OtherUses.clear();
7601 break;
7602 }
7603
7604 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7605 if (Op1.getNode() == BasePtr.getNode())
7606 std::swap(Op0, Op1);
7607 assert(Op0.getNode() == BasePtr.getNode() &&
7608 "Use of ADD/SUB but not an operand");
7609
7610 if (!isa<ConstantSDNode>(Op1)) {
7611 OtherUses.clear();
7612 break;
7613 }
7614
7615 // FIXME: In some cases, we can be smarter about this.
7616 if (Op1.getValueType() != Offset.getValueType()) {
7617 OtherUses.clear();
7618 break;
7619 }
7620
7621 OtherUses.push_back(Use);
7622 }
7623
7624 if (Swapped)
7625 std::swap(BasePtr, Offset);
7626
Evan Chenga4d187b2007-05-24 02:35:39 +00007627 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007628 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007629
7630 // Caches for hasPredecessorHelper
7631 SmallPtrSet<const SDNode *, 32> Visited;
7632 SmallVector<const SDNode *, 16> Worklist;
7633
Jim Grosbache8160032014-04-11 01:13:13 +00007634 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007635 if (Use == N)
7636 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007637 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007638 return false;
7639
Evan Chengfa832632012-01-13 01:37:24 +00007640 // If Ptr may be folded in addressing mode of other use, then it's
7641 // not profitable to do this transformation.
7642 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007643 RealUse = true;
7644 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007645
Chris Lattnereabc15c2006-11-11 00:56:29 +00007646 if (!RealUse)
7647 return false;
7648
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007649 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007650 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007651 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007652 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007653 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007654 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007655 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007656 ++PreIndexedNodes;
7657 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007658 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007659 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007660 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007661 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007662 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007663 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007664 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007665 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7666 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007667 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007668 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007669 }
7670
Chris Lattnereabc15c2006-11-11 00:56:29 +00007671 // Finally, since the node is now dead, remove it from the graph.
7672 DAG.DeleteNode(N);
7673
Hal Finkel25819052013-02-08 21:35:47 +00007674 if (Swapped)
7675 std::swap(BasePtr, Offset);
7676
7677 // Replace other uses of BasePtr that can be updated to use Ptr
7678 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7679 unsigned OffsetIdx = 1;
7680 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7681 OffsetIdx = 0;
7682 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7683 BasePtr.getNode() && "Expected BasePtr operand");
7684
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007685 // We need to replace ptr0 in the following expression:
7686 // x0 * offset0 + y0 * ptr0 = t0
7687 // knowing that
7688 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007689 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007690 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7691 // indexed load/store and the expresion that needs to be re-written.
7692 //
7693 // Therefore, we have:
7694 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007695
7696 ConstantSDNode *CN =
7697 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007698 int X0, X1, Y0, Y1;
7699 APInt Offset0 = CN->getAPIntValue();
7700 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007701
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007702 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7703 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7704 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7705 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007706
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007707 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7708
7709 APInt CNV = Offset0;
7710 if (X0 < 0) CNV = -CNV;
7711 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7712 else CNV = CNV - Offset1;
7713
7714 // We can now generate the new expression.
7715 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7716 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7717
7718 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007719 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007720 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7721 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7722 removeFromWorkList(OtherUses[i]);
7723 DAG.DeleteNode(OtherUses[i]);
7724 }
7725
Chris Lattnereabc15c2006-11-11 00:56:29 +00007726 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007727 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007728 removeFromWorkList(Ptr.getNode());
7729 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007730
7731 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007732}
7733
Duncan Sands075293f2008-06-15 20:12:31 +00007734/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007735/// add / sub of the base pointer node into a post-indexed load / store.
7736/// The transformation folded the add / subtract into the new indexed
7737/// load / store effectively and all of its uses are redirected to the
7738/// new load / store.
7739bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007740 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007741 return false;
7742
7743 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007744 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007745 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007746 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007747 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007748 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007749 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007750 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7751 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7752 return false;
7753 Ptr = LD->getBasePtr();
7754 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007755 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007756 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007757 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007758 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7759 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7760 return false;
7761 Ptr = ST->getBasePtr();
7762 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007763 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007764 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007765 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007766
Gabor Greiff304a7a2008-08-28 21:40:38 +00007767 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007768 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007769
Jim Grosbache8160032014-04-11 01:13:13 +00007770 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007771 if (Op == N ||
7772 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7773 continue;
7774
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007775 SDValue BasePtr;
7776 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007777 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7778 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007779 // Don't create a indexed load / store with zero offset.
7780 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007781 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007782 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007783
Chris Lattnereabc15c2006-11-11 00:56:29 +00007784 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007785 // 1) All uses are load / store ops that use it as base ptr (and
7786 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007787 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7788 // nor a successor of N. Otherwise, if Op is folded that would
7789 // create a cycle.
7790
Evan Chengcfc05132009-05-06 18:25:01 +00007791 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7792 continue;
7793
Chris Lattnereabc15c2006-11-11 00:56:29 +00007794 // Check for #1.
7795 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007796 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007797 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007798 continue;
7799
Chris Lattnereabc15c2006-11-11 00:56:29 +00007800 // If all the uses are load / store addresses, then don't do the
7801 // transformation.
7802 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7803 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007804 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007805 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007806 RealUse = true;
7807 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007808
Chris Lattnereabc15c2006-11-11 00:56:29 +00007809 if (!RealUse) {
7810 TryNext = true;
7811 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007812 }
7813 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007814 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007815
Chris Lattnereabc15c2006-11-11 00:56:29 +00007816 if (TryNext)
7817 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007818
Chris Lattnereabc15c2006-11-11 00:56:29 +00007819 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007820 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007821 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007822 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007823 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007824 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007825 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007826 ++PostIndexedNodes;
7827 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007828 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007829 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007830 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007831 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007832 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007833 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007834 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007835 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7836 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007837 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007838 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007839 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007840
Chris Lattnereabc15c2006-11-11 00:56:29 +00007841 // Finally, since the node is now dead, remove it from the graph.
7842 DAG.DeleteNode(N);
7843
7844 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007845 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007846 Result.getValue(isLoad ? 1 : 0));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007847 removeFromWorkList(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007848 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007849 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007850 }
7851 }
7852 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007853
Chris Lattnerffad2162006-11-11 00:39:41 +00007854 return false;
7855}
7856
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007857SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007858 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007859 SDValue Chain = LD->getChain();
7860 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007861
Evan Chenga684cd22007-05-01 00:38:21 +00007862 // If load is not volatile and there are no uses of the loaded value (and
7863 // the updated indexed value in case of indexed loads), change uses of the
7864 // chain value into uses of the chain input (i.e. delete the dead load).
7865 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007866 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007867 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007868 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007869 // It's not safe to use the two value CombineTo variant here. e.g.
7870 // v1, chain2 = load chain1, loc
7871 // v2, chain3 = load chain2, loc
7872 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007873 // Now we replace use of chain2 with chain1. This makes the second load
7874 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007875 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007876 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007877 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007878 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007879 dbgs() << "\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007880 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007881 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007882
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007883 if (N->use_empty()) {
7884 removeFromWorkList(N);
7885 DAG.DeleteNode(N);
7886 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007887
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007888 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007889 }
Evan Chengb68343c2007-05-01 08:53:39 +00007890 } else {
7891 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007892 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel2c77fe52014-05-28 15:33:19 +00007893 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00007894 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00007895 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007896 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007897 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007898 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007899 dbgs() << " and 2 other values\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007900 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007901 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel2c77fe52014-05-28 15:33:19 +00007902 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7903 DAG.getUNDEF(N->getValueType(1)));
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007904 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng7be15282008-01-16 23:11:54 +00007905 removeFromWorkList(N);
Evan Cheng7be15282008-01-16 23:11:54 +00007906 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007907 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00007908 }
Evan Chenga684cd22007-05-01 00:38:21 +00007909 }
7910 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007911
Chris Lattnere260ed82005-10-10 22:04:48 +00007912 // If this load is directly stored, replace the load value with the stored
7913 // value.
7914 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007915 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00007916 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007917 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00007918 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7919 if (PrevST->getBasePtr() == Ptr &&
7920 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00007921 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00007922 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00007923 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007924
Evan Cheng43cd9e32010-04-01 06:04:33 +00007925 // Try to infer better alignment information than the load already has.
7926 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00007927 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00007928 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7929 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007930 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00007931 LD->getValueType(0),
7932 Chain, Ptr, LD->getPointerInfo(),
7933 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007934 LD->isVolatile(), LD->isNonTemporal(), Align,
7935 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00007936 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7937 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00007938 }
7939 }
7940
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00007941 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7942 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00007943#ifndef NDEBUG
7944 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7945 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7946 UseAA = false;
7947#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00007948 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00007949 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007950 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007951
Jim Laskey708d0db2006-10-04 16:53:27 +00007952 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00007953 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007954 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00007955
Jim Laskeyd07be232006-09-25 16:29:54 +00007956 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007957 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007958 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007959 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007960 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007961 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00007962 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007963 BetterChain, Ptr, LD->getMemoryVT(),
7964 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007965 }
Jim Laskeyd07be232006-09-25 16:29:54 +00007966
Jim Laskey708d0db2006-10-04 16:53:27 +00007967 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00007968 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00007969 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00007970
Nate Begeman879d8f12009-09-15 00:18:30 +00007971 // Make sure the new and old chains are cleaned up.
7972 AddToWorkList(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00007973
Jim Laskeydcf983c2006-10-13 23:32:28 +00007974 // Replace uses with load result and token factor. Don't add users
7975 // to work list.
7976 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00007977 }
7978 }
7979
Evan Cheng357017f2006-11-03 03:06:21 +00007980 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00007981 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007982 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00007983
Quentin Colombetde0e0622013-10-11 18:29:42 +00007984 // Try to slice up N to more direct loads if the slices are mapped to
7985 // different register banks or pairing can take place.
7986 if (SliceUpLoad(N))
7987 return SDValue(N, 0);
7988
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007989 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00007990}
7991
Quentin Colombetde0e0622013-10-11 18:29:42 +00007992namespace {
7993/// \brief Helper structure used to slice a load in smaller loads.
7994/// Basically a slice is obtained from the following sequence:
7995/// Origin = load Ty1, Base
7996/// Shift = srl Ty1 Origin, CstTy Amount
7997/// Inst = trunc Shift to Ty2
7998///
7999/// Then, it will be rewriten into:
8000/// Slice = load SliceTy, Base + SliceOffset
8001/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8002///
8003/// SliceTy is deduced from the number of bits that are actually used to
8004/// build Inst.
8005struct LoadedSlice {
8006 /// \brief Helper structure used to compute the cost of a slice.
8007 struct Cost {
8008 /// Are we optimizing for code size.
8009 bool ForCodeSize;
8010 /// Various cost.
8011 unsigned Loads;
8012 unsigned Truncates;
8013 unsigned CrossRegisterBanksCopies;
8014 unsigned ZExts;
8015 unsigned Shift;
8016
8017 Cost(bool ForCodeSize = false)
8018 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8019 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8020
8021 /// \brief Get the cost of one isolated slice.
8022 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8023 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8024 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8025 EVT TruncType = LS.Inst->getValueType(0);
8026 EVT LoadedType = LS.getLoadedType();
8027 if (TruncType != LoadedType &&
8028 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8029 ZExts = 1;
8030 }
8031
8032 /// \brief Account for slicing gain in the current cost.
8033 /// Slicing provide a few gains like removing a shift or a
8034 /// truncate. This method allows to grow the cost of the original
8035 /// load with the gain from this slice.
8036 void addSliceGain(const LoadedSlice &LS) {
8037 // Each slice saves a truncate.
8038 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8039 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8040 LS.Inst->getOperand(0).getValueType()))
8041 ++Truncates;
8042 // If there is a shift amount, this slice gets rid of it.
8043 if (LS.Shift)
8044 ++Shift;
8045 // If this slice can merge a cross register bank copy, account for it.
8046 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8047 ++CrossRegisterBanksCopies;
8048 }
8049
8050 Cost &operator+=(const Cost &RHS) {
8051 Loads += RHS.Loads;
8052 Truncates += RHS.Truncates;
8053 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8054 ZExts += RHS.ZExts;
8055 Shift += RHS.Shift;
8056 return *this;
8057 }
8058
8059 bool operator==(const Cost &RHS) const {
8060 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8061 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8062 ZExts == RHS.ZExts && Shift == RHS.Shift;
8063 }
8064
8065 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8066
8067 bool operator<(const Cost &RHS) const {
8068 // Assume cross register banks copies are as expensive as loads.
8069 // FIXME: Do we want some more target hooks?
8070 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8071 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8072 // Unless we are optimizing for code size, consider the
8073 // expensive operation first.
8074 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8075 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8076 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8077 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8078 }
8079
8080 bool operator>(const Cost &RHS) const { return RHS < *this; }
8081
8082 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8083
8084 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8085 };
8086 // The last instruction that represent the slice. This should be a
8087 // truncate instruction.
8088 SDNode *Inst;
8089 // The original load instruction.
8090 LoadSDNode *Origin;
8091 // The right shift amount in bits from the original load.
8092 unsigned Shift;
8093 // The DAG from which Origin came from.
8094 // This is used to get some contextual information about legal types, etc.
8095 SelectionDAG *DAG;
8096
Craig Topperc0196b12014-04-14 00:51:57 +00008097 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8098 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008099 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8100
8101 LoadedSlice(const LoadedSlice &LS)
8102 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8103
8104 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8105 /// \return Result is \p BitWidth and has used bits set to 1 and
8106 /// not used bits set to 0.
8107 APInt getUsedBits() const {
8108 // Reproduce the trunc(lshr) sequence:
8109 // - Start from the truncated value.
8110 // - Zero extend to the desired bit width.
8111 // - Shift left.
8112 assert(Origin && "No original load to compare against.");
8113 unsigned BitWidth = Origin->getValueSizeInBits(0);
8114 assert(Inst && "This slice is not bound to an instruction");
8115 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8116 "Extracted slice is bigger than the whole type!");
8117 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8118 UsedBits.setAllBits();
8119 UsedBits = UsedBits.zext(BitWidth);
8120 UsedBits <<= Shift;
8121 return UsedBits;
8122 }
8123
8124 /// \brief Get the size of the slice to be loaded in bytes.
8125 unsigned getLoadedSize() const {
8126 unsigned SliceSize = getUsedBits().countPopulation();
8127 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8128 return SliceSize / 8;
8129 }
8130
8131 /// \brief Get the type that will be loaded for this slice.
8132 /// Note: This may not be the final type for the slice.
8133 EVT getLoadedType() const {
8134 assert(DAG && "Missing context");
8135 LLVMContext &Ctxt = *DAG->getContext();
8136 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8137 }
8138
8139 /// \brief Get the alignment of the load used for this slice.
8140 unsigned getAlignment() const {
8141 unsigned Alignment = Origin->getAlignment();
8142 unsigned Offset = getOffsetFromBase();
8143 if (Offset != 0)
8144 Alignment = MinAlign(Alignment, Alignment + Offset);
8145 return Alignment;
8146 }
8147
8148 /// \brief Check if this slice can be rewritten with legal operations.
8149 bool isLegal() const {
8150 // An invalid slice is not legal.
8151 if (!Origin || !Inst || !DAG)
8152 return false;
8153
8154 // Offsets are for indexed load only, we do not handle that.
8155 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8156 return false;
8157
8158 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8159
8160 // Check that the type is legal.
8161 EVT SliceType = getLoadedType();
8162 if (!TLI.isTypeLegal(SliceType))
8163 return false;
8164
8165 // Check that the load is legal for this type.
8166 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8167 return false;
8168
8169 // Check that the offset can be computed.
8170 // 1. Check its type.
8171 EVT PtrType = Origin->getBasePtr().getValueType();
8172 if (PtrType == MVT::Untyped || PtrType.isExtended())
8173 return false;
8174
8175 // 2. Check that it fits in the immediate.
8176 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8177 return false;
8178
8179 // 3. Check that the computation is legal.
8180 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8181 return false;
8182
8183 // Check that the zext is legal if it needs one.
8184 EVT TruncateType = Inst->getValueType(0);
8185 if (TruncateType != SliceType &&
8186 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8187 return false;
8188
8189 return true;
8190 }
8191
8192 /// \brief Get the offset in bytes of this slice in the original chunk of
8193 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008194 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008195 uint64_t getOffsetFromBase() const {
8196 assert(DAG && "Missing context.");
8197 bool IsBigEndian =
8198 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8199 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8200 uint64_t Offset = Shift / 8;
8201 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8202 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8203 "The size of the original loaded type is not a multiple of a"
8204 " byte.");
8205 // If Offset is bigger than TySizeInBytes, it means we are loading all
8206 // zeros. This should have been optimized before in the process.
8207 assert(TySizeInBytes > Offset &&
8208 "Invalid shift amount for given loaded size");
8209 if (IsBigEndian)
8210 Offset = TySizeInBytes - Offset - getLoadedSize();
8211 return Offset;
8212 }
8213
8214 /// \brief Generate the sequence of instructions to load the slice
8215 /// represented by this object and redirect the uses of this slice to
8216 /// this new sequence of instructions.
8217 /// \pre this->Inst && this->Origin are valid Instructions and this
8218 /// object passed the legal check: LoadedSlice::isLegal returned true.
8219 /// \return The last instruction of the sequence used to load the slice.
8220 SDValue loadSlice() const {
8221 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8222 const SDValue &OldBaseAddr = Origin->getBasePtr();
8223 SDValue BaseAddr = OldBaseAddr;
8224 // Get the offset in that chunk of bytes w.r.t. the endianess.
8225 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8226 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8227 if (Offset) {
8228 // BaseAddr = BaseAddr + Offset.
8229 EVT ArithType = BaseAddr.getValueType();
8230 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8231 DAG->getConstant(Offset, ArithType));
8232 }
8233
8234 // Create the type of the loaded slice according to its size.
8235 EVT SliceType = getLoadedType();
8236
8237 // Create the load for the slice.
8238 SDValue LastInst = DAG->getLoad(
8239 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8240 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8241 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8242 // If the final type is not the same as the loaded type, this means that
8243 // we have to pad with zero. Create a zero extend for that.
8244 EVT FinalType = Inst->getValueType(0);
8245 if (SliceType != FinalType)
8246 LastInst =
8247 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8248 return LastInst;
8249 }
8250
8251 /// \brief Check if this slice can be merged with an expensive cross register
8252 /// bank copy. E.g.,
8253 /// i = load i32
8254 /// f = bitcast i32 i to float
8255 bool canMergeExpensiveCrossRegisterBankCopy() const {
8256 if (!Inst || !Inst->hasOneUse())
8257 return false;
8258 SDNode *Use = *Inst->use_begin();
8259 if (Use->getOpcode() != ISD::BITCAST)
8260 return false;
8261 assert(DAG && "Missing context");
8262 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8263 EVT ResVT = Use->getValueType(0);
8264 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8265 const TargetRegisterClass *ArgRC =
8266 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8267 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8268 return false;
8269
8270 // At this point, we know that we perform a cross-register-bank copy.
8271 // Check if it is expensive.
8272 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8273 // Assume bitcasts are cheap, unless both register classes do not
8274 // explicitly share a common sub class.
8275 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8276 return false;
8277
8278 // Check if it will be merged with the load.
8279 // 1. Check the alignment constraint.
8280 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8281 ResVT.getTypeForEVT(*DAG->getContext()));
8282
8283 if (RequiredAlignment > getAlignment())
8284 return false;
8285
8286 // 2. Check that the load is a legal operation for that type.
8287 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8288 return false;
8289
8290 // 3. Check that we do not have a zext in the way.
8291 if (Inst->getValueType(0) != getLoadedType())
8292 return false;
8293
8294 return true;
8295 }
8296};
8297}
8298
Quentin Colombetde0e0622013-10-11 18:29:42 +00008299/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8300/// \p UsedBits looks like 0..0 1..1 0..0.
8301static bool areUsedBitsDense(const APInt &UsedBits) {
8302 // If all the bits are one, this is dense!
8303 if (UsedBits.isAllOnesValue())
8304 return true;
8305
8306 // Get rid of the unused bits on the right.
8307 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8308 // Get rid of the unused bits on the left.
8309 if (NarrowedUsedBits.countLeadingZeros())
8310 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8311 // Check that the chunk of bits is completely used.
8312 return NarrowedUsedBits.isAllOnesValue();
8313}
8314
8315/// \brief Check whether or not \p First and \p Second are next to each other
8316/// in memory. This means that there is no hole between the bits loaded
8317/// by \p First and the bits loaded by \p Second.
8318static bool areSlicesNextToEachOther(const LoadedSlice &First,
8319 const LoadedSlice &Second) {
8320 assert(First.Origin == Second.Origin && First.Origin &&
8321 "Unable to match different memory origins.");
8322 APInt UsedBits = First.getUsedBits();
8323 assert((UsedBits & Second.getUsedBits()) == 0 &&
8324 "Slices are not supposed to overlap.");
8325 UsedBits |= Second.getUsedBits();
8326 return areUsedBitsDense(UsedBits);
8327}
8328
8329/// \brief Adjust the \p GlobalLSCost according to the target
8330/// paring capabilities and the layout of the slices.
8331/// \pre \p GlobalLSCost should account for at least as many loads as
8332/// there is in the slices in \p LoadedSlices.
8333static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8334 LoadedSlice::Cost &GlobalLSCost) {
8335 unsigned NumberOfSlices = LoadedSlices.size();
8336 // If there is less than 2 elements, no pairing is possible.
8337 if (NumberOfSlices < 2)
8338 return;
8339
8340 // Sort the slices so that elements that are likely to be next to each
8341 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008342 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8343 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8344 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8345 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8346 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008347 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8348 // First (resp. Second) is the first (resp. Second) potentially candidate
8349 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008350 const LoadedSlice *First = nullptr;
8351 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008352 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8353 // Set the beginning of the pair.
8354 First = Second) {
8355
8356 Second = &LoadedSlices[CurrSlice];
8357
8358 // If First is NULL, it means we start a new pair.
8359 // Get to the next slice.
8360 if (!First)
8361 continue;
8362
8363 EVT LoadedType = First->getLoadedType();
8364
8365 // If the types of the slices are different, we cannot pair them.
8366 if (LoadedType != Second->getLoadedType())
8367 continue;
8368
8369 // Check if the target supplies paired loads for this type.
8370 unsigned RequiredAlignment = 0;
8371 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8372 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008373 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008374 continue;
8375 }
8376 // Check if we meet the alignment requirement.
8377 if (RequiredAlignment > First->getAlignment())
8378 continue;
8379
8380 // Check that both loads are next to each other in memory.
8381 if (!areSlicesNextToEachOther(*First, *Second))
8382 continue;
8383
8384 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8385 --GlobalLSCost.Loads;
8386 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008387 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008388 }
8389}
8390
8391/// \brief Check the profitability of all involved LoadedSlice.
8392/// Currently, it is considered profitable if there is exactly two
8393/// involved slices (1) which are (2) next to each other in memory, and
8394/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8395///
8396/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8397/// the elements themselves.
8398///
8399/// FIXME: When the cost model will be mature enough, we can relax
8400/// constraints (1) and (2).
8401static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8402 const APInt &UsedBits, bool ForCodeSize) {
8403 unsigned NumberOfSlices = LoadedSlices.size();
8404 if (StressLoadSlicing)
8405 return NumberOfSlices > 1;
8406
8407 // Check (1).
8408 if (NumberOfSlices != 2)
8409 return false;
8410
8411 // Check (2).
8412 if (!areUsedBitsDense(UsedBits))
8413 return false;
8414
8415 // Check (3).
8416 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8417 // The original code has one big load.
8418 OrigCost.Loads = 1;
8419 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8420 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8421 // Accumulate the cost of all the slices.
8422 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8423 GlobalSlicingCost += SliceCost;
8424
8425 // Account as cost in the original configuration the gain obtained
8426 // with the current slices.
8427 OrigCost.addSliceGain(LS);
8428 }
8429
8430 // If the target supports paired load, adjust the cost accordingly.
8431 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8432 return OrigCost > GlobalSlicingCost;
8433}
8434
8435/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8436/// operations, split it in the various pieces being extracted.
8437///
8438/// This sort of thing is introduced by SROA.
8439/// This slicing takes care not to insert overlapping loads.
8440/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8441bool DAGCombiner::SliceUpLoad(SDNode *N) {
8442 if (Level < AfterLegalizeDAG)
8443 return false;
8444
8445 LoadSDNode *LD = cast<LoadSDNode>(N);
8446 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8447 !LD->getValueType(0).isInteger())
8448 return false;
8449
8450 // Keep track of already used bits to detect overlapping values.
8451 // In that case, we will just abort the transformation.
8452 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8453
8454 SmallVector<LoadedSlice, 4> LoadedSlices;
8455
8456 // Check if this load is used as several smaller chunks of bits.
8457 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8458 // of computation for each trunc.
8459 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8460 UI != UIEnd; ++UI) {
8461 // Skip the uses of the chain.
8462 if (UI.getUse().getResNo() != 0)
8463 continue;
8464
8465 SDNode *User = *UI;
8466 unsigned Shift = 0;
8467
8468 // Check if this is a trunc(lshr).
8469 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8470 isa<ConstantSDNode>(User->getOperand(1))) {
8471 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8472 User = *User->use_begin();
8473 }
8474
8475 // At this point, User is a Truncate, iff we encountered, trunc or
8476 // trunc(lshr).
8477 if (User->getOpcode() != ISD::TRUNCATE)
8478 return false;
8479
8480 // The width of the type must be a power of 2 and greater than 8-bits.
8481 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008482 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008483 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008484 unsigned Width = User->getValueSizeInBits(0);
8485 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8486 return 0;
8487
8488 // Build the slice for this chain of computations.
8489 LoadedSlice LS(User, LD, Shift, &DAG);
8490 APInt CurrentUsedBits = LS.getUsedBits();
8491
8492 // Check if this slice overlaps with another.
8493 if ((CurrentUsedBits & UsedBits) != 0)
8494 return false;
8495 // Update the bits used globally.
8496 UsedBits |= CurrentUsedBits;
8497
8498 // Check if the new slice would be legal.
8499 if (!LS.isLegal())
8500 return false;
8501
8502 // Record the slice.
8503 LoadedSlices.push_back(LS);
8504 }
8505
8506 // Abort slicing if it does not seem to be profitable.
8507 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8508 return false;
8509
8510 ++SlicedLoads;
8511
8512 // Rewrite each chain to use an independent load.
8513 // By construction, each chain can be represented by a unique load.
8514
8515 // Prepare the argument for the new token factor for all the slices.
8516 SmallVector<SDValue, 8> ArgChains;
8517 for (SmallVectorImpl<LoadedSlice>::const_iterator
8518 LSIt = LoadedSlices.begin(),
8519 LSItEnd = LoadedSlices.end();
8520 LSIt != LSItEnd; ++LSIt) {
8521 SDValue SliceInst = LSIt->loadSlice();
8522 CombineTo(LSIt->Inst, SliceInst, true);
8523 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8524 SliceInst = SliceInst.getOperand(0);
8525 assert(SliceInst->getOpcode() == ISD::LOAD &&
8526 "It takes more than a zext to get to the loaded slice!!");
8527 ArgChains.push_back(SliceInst.getValue(1));
8528 }
8529
8530 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00008531 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00008532 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8533 return true;
8534}
8535
Chris Lattner4041ab62010-04-15 04:48:01 +00008536/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8537/// load is having specific bytes cleared out. If so, return the byte size
8538/// being masked out and the shift amount.
8539static std::pair<unsigned, unsigned>
8540CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8541 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008542
Chris Lattner4041ab62010-04-15 04:48:01 +00008543 // Check for the structure we're looking for.
8544 if (V->getOpcode() != ISD::AND ||
8545 !isa<ConstantSDNode>(V->getOperand(1)) ||
8546 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8547 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008548
Chris Lattner3245afd2010-04-15 06:10:49 +00008549 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008550 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008551 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008552
Chris Lattner3245afd2010-04-15 06:10:49 +00008553 // The store should be chained directly to the load or be an operand of a
8554 // tokenfactor.
8555 if (LD == Chain.getNode())
8556 ; // ok.
8557 else if (Chain->getOpcode() != ISD::TokenFactor)
8558 return Result; // Fail.
8559 else {
8560 bool isOk = false;
8561 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8562 if (Chain->getOperand(i).getNode() == LD) {
8563 isOk = true;
8564 break;
8565 }
8566 if (!isOk) return Result;
8567 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008568
Chris Lattner4041ab62010-04-15 04:48:01 +00008569 // This only handles simple types.
8570 if (V.getValueType() != MVT::i16 &&
8571 V.getValueType() != MVT::i32 &&
8572 V.getValueType() != MVT::i64)
8573 return Result;
8574
8575 // Check the constant mask. Invert it so that the bits being masked out are
8576 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8577 // follow the sign bit for uniformity.
8578 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008579 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008580 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008581 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008582 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8583 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008584
Chris Lattner4041ab62010-04-15 04:48:01 +00008585 // See if we have a continuous run of bits. If so, we have 0*1+0*
8586 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8587 return Result;
8588
8589 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8590 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8591 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008592
Chris Lattner4041ab62010-04-15 04:48:01 +00008593 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8594 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008595 case 1:
8596 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008597 case 4: break;
8598 default: return Result; // All one mask, or 5-byte mask.
8599 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008600
Chris Lattner4041ab62010-04-15 04:48:01 +00008601 // Verify that the first bit starts at a multiple of mask so that the access
8602 // is aligned the same as the access width.
8603 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008604
Chris Lattner4041ab62010-04-15 04:48:01 +00008605 Result.first = MaskedBytes;
8606 Result.second = NotMaskTZ/8;
8607 return Result;
8608}
8609
8610
8611/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8612/// provides a value as specified by MaskInfo. If so, replace the specified
8613/// store with a narrower store of truncated IVal.
8614static SDNode *
8615ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8616 SDValue IVal, StoreSDNode *St,
8617 DAGCombiner *DC) {
8618 unsigned NumBytes = MaskInfo.first;
8619 unsigned ByteShift = MaskInfo.second;
8620 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008621
Chris Lattner4041ab62010-04-15 04:48:01 +00008622 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8623 // that uses this. If not, this is not a replacement.
8624 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8625 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008626 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008627
Chris Lattner4041ab62010-04-15 04:48:01 +00008628 // Check that it is legal on the target to do this. It is legal if the new
8629 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8630 // legalization.
8631 MVT VT = MVT::getIntegerVT(NumBytes*8);
8632 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008633 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008634
Chris Lattner4041ab62010-04-15 04:48:01 +00008635 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8636 // shifted by ByteShift and truncated down to NumBytes.
8637 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008638 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008639 DAG.getConstant(ByteShift*8,
8640 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008641
8642 // Figure out the offset for the store and the alignment of the access.
8643 unsigned StOffset;
8644 unsigned NewAlign = St->getAlignment();
8645
8646 if (DAG.getTargetLoweringInfo().isLittleEndian())
8647 StOffset = ByteShift;
8648 else
8649 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008650
Chris Lattner4041ab62010-04-15 04:48:01 +00008651 SDValue Ptr = St->getBasePtr();
8652 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008653 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008654 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8655 NewAlign = MinAlign(NewAlign, StOffset);
8656 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008657
Chris Lattner4041ab62010-04-15 04:48:01 +00008658 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008659 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008660
Chris Lattner4041ab62010-04-15 04:48:01 +00008661 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008662 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008663 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008664 false, false, NewAlign).getNode();
8665}
8666
Evan Chenga9cda8a2009-05-28 00:35:15 +00008667
8668/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8669/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8670/// of the loaded bits, try narrowing the load and store if it would end up
8671/// being a win for performance or code size.
8672SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8673 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008674 if (ST->isVolatile())
8675 return SDValue();
8676
Evan Chenga9cda8a2009-05-28 00:35:15 +00008677 SDValue Chain = ST->getChain();
8678 SDValue Value = ST->getValue();
8679 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008680 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008681
8682 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008683 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008684
8685 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008686
Chris Lattner4041ab62010-04-15 04:48:01 +00008687 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8688 // is a byte mask indicating a consecutive number of bytes, check to see if
8689 // Y is known to provide just those bytes. If so, we try to replace the
8690 // load + replace + store sequence with a single (narrower) store, which makes
8691 // the load dead.
8692 if (Opc == ISD::OR) {
8693 std::pair<unsigned, unsigned> MaskedLoad;
8694 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8695 if (MaskedLoad.first)
8696 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8697 Value.getOperand(1), ST,this))
8698 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008699
Chris Lattner4041ab62010-04-15 04:48:01 +00008700 // Or is commutative, so try swapping X and Y.
8701 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8702 if (MaskedLoad.first)
8703 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8704 Value.getOperand(0), ST,this))
8705 return SDValue(NewST, 0);
8706 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008707
Evan Chenga9cda8a2009-05-28 00:35:15 +00008708 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8709 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008710 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008711
8712 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008713 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8714 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008715 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008716 if (LD->getBasePtr() != Ptr ||
8717 LD->getPointerInfo().getAddrSpace() !=
8718 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008719 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008720
8721 // Find the type to narrow it the load / op / store to.
8722 SDValue N1 = Value.getOperand(1);
8723 unsigned BitWidth = N1.getValueSizeInBits();
8724 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8725 if (Opc == ISD::AND)
8726 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008727 if (Imm == 0 || Imm.isAllOnesValue())
8728 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008729 unsigned ShAmt = Imm.countTrailingZeros();
8730 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8731 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008732 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008733 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008734 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008735 TLI.isNarrowingProfitable(VT, NewVT))) {
8736 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008737 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008738 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008739 if (NewBW >= BitWidth)
8740 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008741
8742 // If the lsb changed does not start at the type bitwidth boundary,
8743 // start at the previous one.
8744 if (ShAmt % NewBW)
8745 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008746 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8747 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008748 if ((Imm & Mask) == Imm) {
8749 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8750 if (Opc == ISD::AND)
8751 NewImm ^= APInt::getAllOnesValue(NewBW);
8752 uint64_t PtrOff = ShAmt / 8;
8753 // For big endian targets, we need to adjust the offset to the pointer to
8754 // load the correct bytes.
8755 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008756 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008757
8758 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008759 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008760 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008761 return SDValue();
8762
Andrew Trickef9de2a2013-05-25 02:42:55 +00008763 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008764 Ptr.getValueType(), Ptr,
8765 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008766 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008767 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008768 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008769 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008770 LD->isInvariant(), NewAlign,
8771 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008772 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008773 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008774 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008775 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008776 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008777 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008778
8779 AddToWorkList(NewPtr.getNode());
8780 AddToWorkList(NewLD.getNode());
8781 AddToWorkList(NewVal.getNode());
8782 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008783 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008784 ++OpsNarrowed;
8785 return NewST;
8786 }
8787 }
8788
Evan Cheng6673ff02009-05-28 18:41:02 +00008789 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008790}
8791
Evan Chengd42641c2011-02-02 01:06:55 +00008792/// TransformFPLoadStorePair - For a given floating point load / store pair,
8793/// if the load value isn't used by any other operations, then consider
8794/// transforming the pair to integer load / store operations if the target
8795/// deems the transformation profitable.
8796SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8797 StoreSDNode *ST = cast<StoreSDNode>(N);
8798 SDValue Chain = ST->getChain();
8799 SDValue Value = ST->getValue();
8800 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8801 Value.hasOneUse() &&
8802 Chain == SDValue(Value.getNode(), 1)) {
8803 LoadSDNode *LD = cast<LoadSDNode>(Value);
8804 EVT VT = LD->getMemoryVT();
8805 if (!VT.isFloatingPoint() ||
8806 VT != ST->getMemoryVT() ||
8807 LD->isNonTemporal() ||
8808 ST->isNonTemporal() ||
8809 LD->getPointerInfo().getAddrSpace() != 0 ||
8810 ST->getPointerInfo().getAddrSpace() != 0)
8811 return SDValue();
8812
8813 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8814 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8815 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8816 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8817 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8818 return SDValue();
8819
8820 unsigned LDAlign = LD->getAlignment();
8821 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008822 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008823 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008824 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8825 return SDValue();
8826
Andrew Trickef9de2a2013-05-25 02:42:55 +00008827 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008828 LD->getChain(), LD->getBasePtr(),
8829 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008830 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008831
Andrew Trickef9de2a2013-05-25 02:42:55 +00008832 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008833 NewLD, ST->getBasePtr(),
8834 ST->getPointerInfo(),
8835 false, false, STAlign);
8836
8837 AddToWorkList(NewLD.getNode());
8838 AddToWorkList(NewST.getNode());
8839 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008840 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008841 ++LdStFP2Int;
8842 return NewST;
8843 }
8844
8845 return SDValue();
8846}
8847
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008848/// Helper struct to parse and store a memory address as base + index + offset.
8849/// We ignore sign extensions when it is safe to do so.
8850/// The following two expressions are not equivalent. To differentiate we need
8851/// to store whether there was a sign extension involved in the index
8852/// computation.
8853/// (load (i64 add (i64 copyfromreg %c)
8854/// (i64 signextend (add (i8 load %index)
8855/// (i8 1))))
8856/// vs
8857///
8858/// (load (i64 add (i64 copyfromreg %c)
8859/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8860/// (i32 1)))))
8861struct BaseIndexOffset {
8862 SDValue Base;
8863 SDValue Index;
8864 int64_t Offset;
8865 bool IsIndexSignExt;
8866
8867 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8868
8869 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8870 bool IsIndexSignExt) :
8871 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8872
8873 bool equalBaseIndex(const BaseIndexOffset &Other) {
8874 return Other.Base == Base && Other.Index == Index &&
8875 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008876 }
8877
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008878 /// Parses tree in Ptr for base, index, offset addresses.
8879 static BaseIndexOffset match(SDValue Ptr) {
8880 bool IsIndexSignExt = false;
8881
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008882 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8883 // instruction, then it could be just the BASE or everything else we don't
8884 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008885 if (Ptr->getOpcode() != ISD::ADD)
8886 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8887
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008888 // We know that we have at least an ADD instruction. Try to pattern match
8889 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008890 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8891 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8892 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8893 IsIndexSignExt);
8894 }
8895
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008896 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008897 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008898 // (i64 add (i64 %array_ptr)
8899 // (i64 mul (i64 %induction_var)
8900 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008901 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008902 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008903
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008904 // Look at Base + Index + Offset cases.
8905 SDValue Base = Ptr->getOperand(0);
8906 SDValue IndexOffset = Ptr->getOperand(1);
8907
8908 // Skip signextends.
8909 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8910 IndexOffset = IndexOffset->getOperand(0);
8911 IsIndexSignExt = true;
8912 }
8913
8914 // Either the case of Base + Index (no offset) or something else.
8915 if (IndexOffset->getOpcode() != ISD::ADD)
8916 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8917
8918 // Now we have the case of Base + Index + offset.
8919 SDValue Index = IndexOffset->getOperand(0);
8920 SDValue Offset = IndexOffset->getOperand(1);
8921
8922 if (!isa<ConstantSDNode>(Offset))
8923 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8924
8925 // Ignore signextends.
8926 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8927 Index = Index->getOperand(0);
8928 IsIndexSignExt = true;
8929 } else IsIndexSignExt = false;
8930
8931 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8932 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8933 }
8934};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008935
8936/// Holds a pointer to an LSBaseSDNode as well as information on where it
8937/// is located in a sequence of memory operations connected by a chain.
8938struct MemOpLink {
8939 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8940 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8941 // Ptr to the mem node.
8942 LSBaseSDNode *MemNode;
8943 // Offset from the base ptr.
8944 int64_t OffsetFromBase;
8945 // What is the sequence number of this mem node.
8946 // Lowest mem operand in the DAG starts at zero.
8947 unsigned SequenceNum;
8948};
8949
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008950bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8951 EVT MemVT = St->getMemoryVT();
8952 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00008953 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8954 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008955
8956 // Don't merge vectors into wider inputs.
8957 if (MemVT.isVector() || !MemVT.isSimple())
8958 return false;
8959
8960 // Perform an early exit check. Do not bother looking at stored values that
8961 // are not constants or loads.
8962 SDValue StoredVal = St->getValue();
8963 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8964 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8965 !IsLoadSrc)
8966 return false;
8967
8968 // Only look at ends of store sequences.
8969 SDValue Chain = SDValue(St, 1);
8970 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8971 return false;
8972
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008973 // This holds the base pointer, index, and the offset in bytes from the base
8974 // pointer.
8975 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008976
8977 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008978 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008979 return false;
8980
8981 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008982 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008983 return false;
8984
Nadav Rotem307d7672012-11-29 00:00:08 +00008985 // Save the LoadSDNodes that we find in the chain.
8986 // We need to make sure that these nodes do not interfere with
8987 // any of the store nodes.
8988 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8989
8990 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008991 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00008992
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008993 // Walk up the chain and look for nodes with offsets from the same
8994 // base pointer. Stop when reaching an instruction with a different kind
8995 // or instruction which has a different base pointer.
8996 unsigned Seq = 0;
8997 StoreSDNode *Index = St;
8998 while (Index) {
8999 // If the chain has more than one use, then we can't reorder the mem ops.
9000 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9001 break;
9002
9003 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009004 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009005
9006 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009007 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009008 break;
9009
9010 // Check that the alignment is the same.
9011 if (Index->getAlignment() != St->getAlignment())
9012 break;
9013
9014 // The memory operands must not be volatile.
9015 if (Index->isVolatile() || Index->isIndexed())
9016 break;
9017
9018 // No truncation.
9019 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9020 if (St->isTruncatingStore())
9021 break;
9022
9023 // The stored memory type must be the same.
9024 if (Index->getMemoryVT() != MemVT)
9025 break;
9026
9027 // We do not allow unaligned stores because we want to prevent overriding
9028 // stores.
9029 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9030 break;
9031
9032 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009033 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009034
Nadav Rotem307d7672012-11-29 00:00:08 +00009035 // Find the next memory operand in the chain. If the next operand in the
9036 // chain is a store then move up and continue the scan with the next
9037 // memory operand. If the next operand is a load save it and use alias
9038 // information to check if it interferes with anything.
9039 SDNode *NextInChain = Index->getChain().getNode();
9040 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009041 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009042 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009043 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009044 break;
9045 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009046 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009047 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009048 break;
9049 }
9050
Nadav Rotem307d7672012-11-29 00:00:08 +00009051 // Save the load node for later. Continue the scan.
9052 AliasLoadNodes.push_back(Ldn);
9053 NextInChain = Ldn->getChain().getNode();
9054 continue;
9055 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009056 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009057 break;
9058 }
9059 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009060 }
9061
9062 // Check if there is anything to merge.
9063 if (StoreNodes.size() < 2)
9064 return false;
9065
9066 // Sort the memory operands according to their distance from the base pointer.
9067 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009068 [](MemOpLink LHS, MemOpLink RHS) {
9069 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9070 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9071 LHS.SequenceNum > RHS.SequenceNum);
9072 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009073
9074 // Scan the memory operations on the chain and find the first non-consecutive
9075 // store memory address.
9076 unsigned LastConsecutiveStore = 0;
9077 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009078 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9079
9080 // Check that the addresses are consecutive starting from the second
9081 // element in the list of stores.
9082 if (i > 0) {
9083 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9084 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9085 break;
9086 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009087
Nadav Rotem307d7672012-11-29 00:00:08 +00009088 bool Alias = false;
9089 // Check if this store interferes with any of the loads that we found.
9090 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9091 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9092 Alias = true;
9093 break;
9094 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009095 // We found a load that alias with this store. Stop the sequence.
9096 if (Alias)
9097 break;
9098
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009099 // Mark this node as useful.
9100 LastConsecutiveStore = i;
9101 }
9102
9103 // The node with the lowest store address.
9104 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9105
9106 // Store the constants into memory as one consecutive store.
9107 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009108 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009109 unsigned LastLegalVectorType = 0;
9110 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009111 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9112 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9113 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009114
9115 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009116 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009117 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009118 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009119 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009120 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009121 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009122 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009123
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009124 // Find a legal type for the constant store.
9125 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9126 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9127 if (TLI.isTypeLegal(StoreTy))
9128 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009129 // Or check whether a truncstore is legal.
9130 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9131 TargetLowering::TypePromoteInteger) {
9132 EVT LegalizedStoredValueTy =
9133 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9134 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9135 LastLegalType = i+1;
9136 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009137
9138 // Find a legal type for the vector store.
9139 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9140 if (TLI.isTypeLegal(Ty))
9141 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009142 }
9143
Bob Wilson3365b802012-12-20 01:36:20 +00009144 // We only use vectors if the constant is known to be zero and the
9145 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009146 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009147 LastLegalVectorType = 0;
9148
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009149 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009150 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009151 return false;
9152
Nadav Rotem495b1a42013-02-14 18:28:52 +00009153 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009154 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9155
9156 // Make sure we have something to merge.
9157 if (NumElem < 2)
9158 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009159
9160 unsigned EarliestNodeUsed = 0;
9161 for (unsigned i=0; i < NumElem; ++i) {
9162 // Find a chain for the new wide-store operand. Notice that some
9163 // of the store nodes that we found may not be selected for inclusion
9164 // in the wide store. The chain we use needs to be the chain of the
9165 // earliest store node which is *used* and replaced by the wide store.
9166 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9167 EarliestNodeUsed = i;
9168 }
9169
9170 // The earliest Node in the DAG.
9171 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009172 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009173
Nadav Rotemb27777f2012-10-04 22:35:15 +00009174 SDValue StoredVal;
9175 if (UseVector) {
9176 // Find a legal type for the vector store.
9177 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9178 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9179 StoredVal = DAG.getConstant(0, Ty);
9180 } else {
9181 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9182 APInt StoreInt(StoreBW, 0);
9183
9184 // Construct a single integer constant which is made of the smaller
9185 // constant inputs.
9186 bool IsLE = TLI.isLittleEndian();
9187 for (unsigned i = 0; i < NumElem ; ++i) {
9188 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9189 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9190 SDValue Val = St->getValue();
9191 StoreInt<<=ElementSizeBytes*8;
9192 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9193 StoreInt|=C->getAPIntValue().zext(StoreBW);
9194 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9195 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9196 } else {
9197 assert(false && "Invalid constant element type");
9198 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009199 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009200
9201 // Create the new Load and Store operations.
9202 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9203 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009204 }
9205
Nadav Rotemb27777f2012-10-04 22:35:15 +00009206 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009207 FirstInChain->getBasePtr(),
9208 FirstInChain->getPointerInfo(),
9209 false, false,
9210 FirstInChain->getAlignment());
9211
9212 // Replace the first store with the new store
9213 CombineTo(EarliestOp, NewStore);
9214 // Erase all other stores.
9215 for (unsigned i = 0; i < NumElem ; ++i) {
9216 if (StoreNodes[i].MemNode == EarliestOp)
9217 continue;
9218 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009219 // ReplaceAllUsesWith will replace all uses that existed when it was
9220 // called, but graph optimizations may cause new ones to appear. For
9221 // example, the case in pr14333 looks like
9222 //
9223 // St's chain -> St -> another store -> X
9224 //
9225 // And the only difference from St to the other store is the chain.
9226 // When we change it's chain to be St's chain they become identical,
9227 // get CSEed and the net result is that X is now a use of St.
9228 // Since we know that St is redundant, just iterate.
9229 while (!St->use_empty())
9230 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009231 removeFromWorkList(St);
9232 DAG.DeleteNode(St);
9233 }
9234
9235 return true;
9236 }
9237
9238 // Below we handle the case of multiple consecutive stores that
9239 // come from multiple consecutive loads. We merge them into a single
9240 // wide load and a single wide store.
9241
9242 // Look for load nodes which are used by the stored values.
9243 SmallVector<MemOpLink, 8> LoadNodes;
9244
9245 // Find acceptable loads. Loads need to have the same chain (token factor),
9246 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009247 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009248 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9249 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9250 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9251 if (!Ld) break;
9252
9253 // Loads must only have one use.
9254 if (!Ld->hasNUsesOfValue(1, 0))
9255 break;
9256
9257 // Check that the alignment is the same as the stores.
9258 if (Ld->getAlignment() != St->getAlignment())
9259 break;
9260
9261 // The memory operands must not be volatile.
9262 if (Ld->isVolatile() || Ld->isIndexed())
9263 break;
9264
9265 // We do not accept ext loads.
9266 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9267 break;
9268
9269 // The stored memory type must be the same.
9270 if (Ld->getMemoryVT() != MemVT)
9271 break;
9272
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009273 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009274 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009275 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009276 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009277 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009278 break;
9279 } else {
9280 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009281 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009282 }
9283
9284 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009285 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009286 }
9287
9288 if (LoadNodes.size() < 2)
9289 return false;
9290
9291 // Scan the memory operations on the chain and find the first non-consecutive
9292 // load memory address. These variables hold the index in the store node
9293 // array.
9294 unsigned LastConsecutiveLoad = 0;
9295 // This variable refers to the size and not index in the array.
9296 unsigned LastLegalVectorType = 0;
9297 unsigned LastLegalIntegerType = 0;
9298 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009299 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9300 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9301 // All loads much share the same chain.
9302 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9303 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009304
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009305 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9306 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9307 break;
9308 LastConsecutiveLoad = i;
9309
9310 // Find a legal type for the vector store.
9311 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9312 if (TLI.isTypeLegal(StoreTy))
9313 LastLegalVectorType = i + 1;
9314
9315 // Find a legal type for the integer store.
9316 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9317 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9318 if (TLI.isTypeLegal(StoreTy))
9319 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009320 // Or check whether a truncstore and extload is legal.
9321 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9322 TargetLowering::TypePromoteInteger) {
9323 EVT LegalizedStoredValueTy =
9324 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9325 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9326 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9327 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9328 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9329 LastLegalIntegerType = i+1;
9330 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009331 }
9332
9333 // Only use vector types if the vector type is larger than the integer type.
9334 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009335 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009336 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9337
9338 // We add +1 here because the LastXXX variables refer to location while
9339 // the NumElem refers to array/index size.
9340 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9341 NumElem = std::min(LastLegalType, NumElem);
9342
9343 if (NumElem < 2)
9344 return false;
9345
9346 // The earliest Node in the DAG.
9347 unsigned EarliestNodeUsed = 0;
9348 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9349 for (unsigned i=1; i<NumElem; ++i) {
9350 // Find a chain for the new wide-store operand. Notice that some
9351 // of the store nodes that we found may not be selected for inclusion
9352 // in the wide store. The chain we use needs to be the chain of the
9353 // earliest store node which is *used* and replaced by the wide store.
9354 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9355 EarliestNodeUsed = i;
9356 }
9357
9358 // Find if it is better to use vectors or integers to load and store
9359 // to memory.
9360 EVT JointMemOpVT;
9361 if (UseVectorTy) {
9362 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9363 } else {
9364 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9365 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9366 }
9367
Andrew Trickef9de2a2013-05-25 02:42:55 +00009368 SDLoc LoadDL(LoadNodes[0].MemNode);
9369 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009370
9371 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9372 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9373 FirstLoad->getChain(),
9374 FirstLoad->getBasePtr(),
9375 FirstLoad->getPointerInfo(),
9376 false, false, false,
9377 FirstLoad->getAlignment());
9378
9379 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9380 FirstInChain->getBasePtr(),
9381 FirstInChain->getPointerInfo(), false, false,
9382 FirstInChain->getAlignment());
9383
Nadav Rotemac920662012-10-03 19:30:31 +00009384 // Replace one of the loads with the new load.
9385 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9386 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9387 SDValue(NewLoad.getNode(), 1));
9388
9389 // Remove the rest of the load chains.
9390 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009391 // Replace all chain users of the old load nodes with the chain of the new
9392 // load node.
9393 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009394 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9395 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009396
Nadav Rotemac920662012-10-03 19:30:31 +00009397 // Replace the first store with the new store.
9398 CombineTo(EarliestOp, NewStore);
9399 // Erase all other stores.
9400 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009401 // Remove all Store nodes.
9402 if (StoreNodes[i].MemNode == EarliestOp)
9403 continue;
9404 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9405 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9406 removeFromWorkList(St);
9407 DAG.DeleteNode(St);
9408 }
9409
9410 return true;
9411}
9412
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009413SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009414 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009415 SDValue Chain = ST->getChain();
9416 SDValue Value = ST->getValue();
9417 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009418
Evan Chenga4cf58a2007-05-07 21:27:48 +00009419 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009420 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009421 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009422 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009423 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009424 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009425 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009426 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009427 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009428 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009429 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009430 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009431 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009432 ST->isNonTemporal(), OrigAlign,
9433 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009434 }
Owen Andersona5192842011-04-14 17:30:49 +00009435
Chris Lattner41c80e82011-04-09 02:32:02 +00009436 // Turn 'store undef, Ptr' -> nothing.
9437 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9438 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009439
Nate Begeman8e20c762006-12-11 02:23:46 +00009440 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009441 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009442 // NOTE: If the original store is volatile, this transform must not increase
9443 // the number of stores. For example, on x86-32 an f64 can be stored in one
9444 // processor operation but an i64 (which is not legal) requires two. So the
9445 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009446 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009447 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009448 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009449 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009450 case MVT::f16: // We don't do this for these yet.
9451 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009452 case MVT::f128:
9453 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009454 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009455 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009456 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009457 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009458 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009459 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009460 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009461 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009462 }
9463 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009464 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009465 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009466 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009467 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009468 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009469 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009470 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009471 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009472 }
Owen Andersona5192842011-04-14 17:30:49 +00009473
Chris Lattner41c80e82011-04-09 02:32:02 +00009474 if (!ST->isVolatile() &&
9475 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009476 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009477 // argument passing. Since this is so common, custom legalize the
9478 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009479 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009480 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9481 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009482 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009483
Dan Gohman2af30632007-07-09 22:18:38 +00009484 unsigned Alignment = ST->getAlignment();
9485 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009486 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009487 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009488
Andrew Trickef9de2a2013-05-25 02:42:55 +00009489 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009490 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009491 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009492 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009493 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009494 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009495 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009496 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009497 Ptr, ST->getPointerInfo().getWithOffset(4),
9498 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009499 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009500 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009501 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009502 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009503
Chris Lattnerb7524b62006-12-12 04:16:14 +00009504 break;
Evan Cheng21836982006-12-11 17:25:19 +00009505 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009506 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009507 }
9508
Evan Cheng43cd9e32010-04-01 06:04:33 +00009509 // Try to infer better alignment information than the store already has.
9510 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009511 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9512 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009513 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009514 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009515 ST->isVolatile(), ST->isNonTemporal(), Align,
9516 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009517 }
9518 }
9519
Evan Chengd42641c2011-02-02 01:06:55 +00009520 // Try transforming a pair floating point load / store ops to integer
9521 // load / store ops.
9522 SDValue NewST = TransformFPLoadStorePair(N);
9523 if (NewST.getNode())
9524 return NewST;
9525
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009526 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9527 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009528#ifndef NDEBUG
9529 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9530 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9531 UseAA = false;
9532#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009533 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009534 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009535 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009536
Jim Laskey708d0db2006-10-04 16:53:27 +00009537 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009538 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009539 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009540
9541 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009542 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009543 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009544 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009545 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009546 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009547 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009548 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009549
Jim Laskeyd07be232006-09-25 16:29:54 +00009550 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009551 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009552 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009553
Nate Begeman879d8f12009-09-15 00:18:30 +00009554 // Make sure the new and old chains are cleaned up.
9555 AddToWorkList(Token.getNode());
9556
Jim Laskeydcf983c2006-10-13 23:32:28 +00009557 // Don't add users to work list.
9558 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009559 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009560 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009561
Evan Cheng33157702006-11-05 09:31:14 +00009562 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009563 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009564 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009565
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009566 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009567 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009568 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009569 // See if we can simplify the input to this truncstore with knowledge that
9570 // only the low bits are being used. For example:
9571 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009572 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009573 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009574 APInt::getLowBitsSet(
9575 Value.getValueType().getScalarType().getSizeInBits(),
9576 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00009577 AddToWorkList(Value.getNode());
9578 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009579 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009580 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009581
Chris Lattnerf47e3062007-10-13 06:58:48 +00009582 // Otherwise, see if we can simplify the operation with
9583 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009584 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009585 APInt::getLowBitsSet(
9586 Value.getValueType().getScalarType().getSizeInBits(),
9587 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009588 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009589 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009590
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009591 // If this is a load followed by a store to the same location, then the store
9592 // is dead/noop.
9593 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009594 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009595 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009596 // There can't be any side effects between the load and store, such as
9597 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009598 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009599 // The store is dead, remove it.
9600 return Chain;
9601 }
9602 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009603
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009604 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9605 // truncating store. We can do this even if this is already a truncstore.
9606 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009607 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009608 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009609 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009610 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009611 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009612 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009613
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009614 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009615 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009616 if (!LegalTypes) {
9617 bool EverChanged = false;
9618
9619 do {
9620 // There can be multiple store sequences on the same chain.
9621 // Keep trying to merge store sequences until we are unable to do so
9622 // or until we merge the last store on the chain.
9623 bool Changed = MergeConsecutiveStores(ST);
9624 EverChanged |= Changed;
9625 if (!Changed) break;
9626 } while (ST->getOpcode() != ISD::DELETED_NODE);
9627
9628 if (EverChanged)
9629 return SDValue(N, 0);
9630 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009631
Evan Chenga9cda8a2009-05-28 00:35:15 +00009632 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009633}
9634
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009635SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9636 SDValue InVec = N->getOperand(0);
9637 SDValue InVal = N->getOperand(1);
9638 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009639 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009640
Bob Wilson42603952010-05-19 23:42:58 +00009641 // If the inserted element is an UNDEF, just use the input vector.
9642 if (InVal.getOpcode() == ISD::UNDEF)
9643 return InVec;
9644
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009645 EVT VT = InVec.getValueType();
9646
Owen Andersonb2c80da2011-02-25 21:41:48 +00009647 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009648 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9649 return SDValue();
9650
Eli Friedmanb7910b72011-09-09 21:04:06 +00009651 // Check that we know which element is being inserted
9652 if (!isa<ConstantSDNode>(EltNo))
9653 return SDValue();
9654 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009655
Eli Friedmanb7910b72011-09-09 21:04:06 +00009656 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9657 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9658 // vector elements.
9659 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009660 // Do not combine these two vectors if the output vector will not replace
9661 // the input vector.
9662 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009663 Ops.append(InVec.getNode()->op_begin(),
9664 InVec.getNode()->op_end());
9665 } else if (InVec.getOpcode() == ISD::UNDEF) {
9666 unsigned NElts = VT.getVectorNumElements();
9667 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9668 } else {
9669 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009670 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009671
9672 // Insert the element
9673 if (Elt < Ops.size()) {
9674 // All the operands of BUILD_VECTOR must have the same type;
9675 // we enforce that here.
9676 EVT OpVT = Ops[0].getValueType();
9677 if (InVal.getValueType() != OpVT)
9678 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9679 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9680 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9681 Ops[Elt] = InVal;
9682 }
9683
9684 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +00009685 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +00009686}
9687
Michael J. Spencerf375d802014-05-29 01:42:45 +00009688SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9689 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9690 EVT ResultVT = EVE->getValueType(0);
9691 EVT VecEltVT = InVecVT.getVectorElementType();
9692 unsigned Align = OriginalLoad->getAlignment();
9693 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9694 VecEltVT.getTypeForEVT(*DAG.getContext()));
9695
9696 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9697 return SDValue();
9698
9699 Align = NewAlign;
9700
9701 SDValue NewPtr = OriginalLoad->getBasePtr();
9702 SDValue Offset;
9703 EVT PtrType = NewPtr.getValueType();
9704 MachinePointerInfo MPI;
9705 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9706 int Elt = ConstEltNo->getZExtValue();
9707 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9708 if (TLI.isBigEndian())
9709 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9710 Offset = DAG.getConstant(PtrOff, PtrType);
9711 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9712 } else {
9713 Offset = DAG.getNode(
9714 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9715 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9716 if (TLI.isBigEndian())
9717 Offset = DAG.getNode(
9718 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9719 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9720 MPI = OriginalLoad->getPointerInfo();
9721 }
9722 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9723
9724 // The replacement we need to do here is a little tricky: we need to
9725 // replace an extractelement of a load with a load.
9726 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9727 // Note that this replacement assumes that the extractvalue is the only
9728 // use of the load; that's okay because we don't want to perform this
9729 // transformation in other cases anyway.
9730 SDValue Load;
9731 SDValue Chain;
9732 if (ResultVT.bitsGT(VecEltVT)) {
9733 // If the result type of vextract is wider than the load, then issue an
9734 // extending load instead.
9735 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9736 ? ISD::ZEXTLOAD
9737 : ISD::EXTLOAD;
9738 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(),
9739 NewPtr, MPI, VecEltVT, OriginalLoad->isVolatile(),
9740 OriginalLoad->isNonTemporal(), Align,
9741 OriginalLoad->getTBAAInfo());
9742 Chain = Load.getValue(1);
9743 } else {
9744 Load = DAG.getLoad(
9745 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9746 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9747 OriginalLoad->isInvariant(), Align, OriginalLoad->getTBAAInfo());
9748 Chain = Load.getValue(1);
9749 if (ResultVT.bitsLT(VecEltVT))
9750 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9751 else
9752 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9753 }
9754 WorkListRemover DeadNodes(*this);
9755 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9756 SDValue To[] = { Load, Chain };
9757 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9758 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9759 // worklist explicitly as well.
9760 AddToWorkList(Load.getNode());
9761 AddUsersToWorkList(Load.getNode()); // Add users too
9762 // Make sure to revisit this node to clean it up; it will usually be dead.
9763 AddToWorkList(EVE);
9764 ++OpsNarrowed;
9765 return SDValue(EVE, 0);
9766}
9767
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009768SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009769 // (vextract (scalar_to_vector val, 0) -> val
9770 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009771 EVT VT = InVec.getValueType();
9772 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009773
Duncan Sands6be291a2011-05-09 08:03:33 +00009774 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9775 // Check if the result type doesn't match the inserted element type. A
9776 // SCALAR_TO_VECTOR may truncate the inserted element and the
9777 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9778 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009779 if (InOp.getValueType() != NVT) {
9780 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009781 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009782 }
9783 return InOp;
9784 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009785
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009786 SDValue EltNo = N->getOperand(1);
9787 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9788
9789 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9790 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009791 // we may introduce new vector instructions which are not backed by TD
9792 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +00009793 // without using extract_subvector. However, if we can find an underlying
9794 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009795 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +00009796 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009797 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9798 int NumElem = VT.getVectorNumElements();
9799 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9800 // Find the new index to extract from.
9801 int OrigElt = SVOp->getMaskElt(Elt);
9802
9803 // Extracting an undef index is undef.
9804 if (OrigElt == -1)
9805 return DAG.getUNDEF(NVT);
9806
9807 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +00009808 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009809 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +00009810 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009811 } else {
Hal Finkel02807592014-03-31 11:43:19 +00009812 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009813 OrigElt -= NumElem;
9814 }
9815
Hal Finkel02807592014-03-31 11:43:19 +00009816 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9817 SDValue InOp = SVInVec.getOperand(OrigElt);
9818 if (InOp.getValueType() != NVT) {
9819 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9820 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9821 }
9822
9823 return InOp;
9824 }
9825
9826 // FIXME: We should handle recursing on other vector shuffles and
9827 // scalar_to_vector here as well.
9828
9829 if (!LegalOperations) {
9830 EVT IndexTy = TLI.getVectorIdxTy();
9831 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9832 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9833 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009834 }
9835
Michael J. Spencerf375d802014-05-29 01:42:45 +00009836 bool BCNumEltsChanged = false;
9837 EVT ExtVT = VT.getVectorElementType();
9838 EVT LVT = ExtVT;
9839
9840 // If the result of load has to be truncated, then it's not necessarily
9841 // profitable.
9842 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9843 return SDValue();
9844
9845 if (InVec.getOpcode() == ISD::BITCAST) {
9846 // Don't duplicate a load with other uses.
9847 if (!InVec.hasOneUse())
9848 return SDValue();
9849
9850 EVT BCVT = InVec.getOperand(0).getValueType();
9851 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9852 return SDValue();
9853 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9854 BCNumEltsChanged = true;
9855 InVec = InVec.getOperand(0);
9856 ExtVT = BCVT.getVectorElementType();
9857 }
9858
9859 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
9860 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
9861 ISD::isNormalLoad(InVec.getNode())) {
9862 SDValue Index = N->getOperand(1);
9863 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
9864 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
9865 OrigLoad);
9866 }
9867
Evan Cheng1120279a2008-05-13 08:35:03 +00009868 // Perform only after legalization to ensure build_vector / vector_shuffle
9869 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009870 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009871
Mon P Wangca6d6de2009-01-17 00:07:25 +00009872 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9873 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9874 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009875
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009876 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009877 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009878
Craig Topperc0196b12014-04-14 00:51:57 +00009879 LoadSDNode *LN0 = nullptr;
9880 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009881 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009882 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009883 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009884 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009885 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009886 // Don't duplicate a load with other uses.
9887 if (!InVec.hasOneUse())
9888 return SDValue();
9889
Evan Cheng1120279a2008-05-13 08:35:03 +00009890 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009891 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009892 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9893 // =>
9894 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009895
Eli Friedmane96286c2011-12-26 22:49:32 +00009896 // Don't duplicate a load with other uses.
9897 if (!InVec.hasOneUse())
9898 return SDValue();
9899
Mon P Wangb5eb7202008-12-11 00:26:16 +00009900 // If the bit convert changed the number of elements, it is unsafe
9901 // to examine the mask.
9902 if (BCNumEltsChanged)
9903 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009904
9905 // Select the input vector, guarding against out of range extract vector.
9906 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009907 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009908 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9909
Eli Friedmane96286c2011-12-26 22:49:32 +00009910 if (InVec.getOpcode() == ISD::BITCAST) {
9911 // Don't duplicate a load with other uses.
9912 if (!InVec.hasOneUse())
9913 return SDValue();
9914
Evan Cheng1120279a2008-05-13 08:35:03 +00009915 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +00009916 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00009917 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009918 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +00009919 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencerf375d802014-05-29 01:42:45 +00009920 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +00009921 }
9922 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009923
Eli Friedmane96286c2011-12-26 22:49:32 +00009924 // Make sure we found a non-volatile load and the extractelement is
9925 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +00009926 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009927 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009928
Eric Christopherc6418b12010-11-03 20:44:42 +00009929 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9930 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +00009931 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +00009932
Michael J. Spencerf375d802014-05-29 01:42:45 +00009933 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +00009934 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009935
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009936 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009937}
Evan Cheng0de312d2007-10-06 08:19:55 +00009938
Michael Liao6d106b72012-10-23 23:06:52 +00009939// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9940SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9941 // We perform this optimization post type-legalization because
9942 // the type-legalizer often scalarizes integer-promoted vectors.
9943 // Performing this optimization before may create bit-casts which
9944 // will be type-legalized to complex code sequences.
9945 // We perform this optimization only before the operation legalizer because we
9946 // may introduce illegal operations.
9947 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9948 return SDValue();
9949
Dan Gohmana8665142007-06-25 16:23:39 +00009950 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009951 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009952 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +00009953
Nadav Rotembf6568b2011-10-29 21:23:04 +00009954 // Check to see if this is a BUILD_VECTOR of a bunch of values
9955 // which come from any_extend or zero_extend nodes. If so, we can create
9956 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +00009957 // optimizations. We do not handle sign-extend because we can't fill the sign
9958 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009959 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +00009960 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +00009961
Craig Topper02cb0fb2012-01-17 09:09:48 +00009962 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +00009963 SDValue In = N->getOperand(i);
9964 // Ignore undef inputs.
9965 if (In.getOpcode() == ISD::UNDEF) continue;
9966
9967 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9968 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9969
Nadav Rotemf3103612011-10-31 20:08:25 +00009970 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009971 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +00009972 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009973 break;
9974 }
9975
9976 // The input is a ZeroExt or AnyExt. Check the original type.
9977 EVT InTy = In.getOperand(0).getValueType();
9978
9979 // Check that all of the widened source types are the same.
9980 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +00009981 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009982 SourceType = InTy;
9983 else if (InTy != SourceType) {
9984 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +00009985 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009986 break;
9987 }
9988
9989 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +00009990 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009991 }
9992
Nadav Rotemf3103612011-10-31 20:08:25 +00009993 // In order to have valid types, all of the inputs must be extended from the
9994 // same source type and all of the inputs must be any or zero extend.
9995 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +00009996 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009997 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +00009998 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9999 isPowerOf2_32(SourceType.getSizeInBits());
10000
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010001 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10002 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010003 if (!ValidTypes)
10004 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010005
Michael Liao6d106b72012-10-23 23:06:52 +000010006 bool isLE = TLI.isLittleEndian();
10007 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10008 assert(ElemRatio > 1 && "Invalid element size ratio");
10009 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10010 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010011
Michael Liao6d106b72012-10-23 23:06:52 +000010012 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10013 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010014
Michael Liao6d106b72012-10-23 23:06:52 +000010015 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010016 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010017 SDValue Cast = N->getOperand(i);
10018 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10019 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10020 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10021 SDValue In;
10022 if (Cast.getOpcode() == ISD::UNDEF)
10023 In = DAG.getUNDEF(SourceType);
10024 else
10025 In = Cast->getOperand(0);
10026 unsigned Index = isLE ? (i * ElemRatio) :
10027 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010028
Michael Liao6d106b72012-10-23 23:06:52 +000010029 assert(Index < Ops.size() && "Invalid index");
10030 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010031 }
Chris Lattner5336a592006-03-19 01:27:56 +000010032
Michael Liao6d106b72012-10-23 23:06:52 +000010033 // The type of the new BUILD_VECTOR node.
10034 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10035 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10036 "Invalid vector size");
10037 // Check if the new vector type is legal.
10038 if (!isTypeLegal(VecVT)) return SDValue();
10039
10040 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010041 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010042
10043 // The new BUILD_VECTOR node has the potential to be further optimized.
10044 AddToWorkList(BV.getNode());
10045 // Bitcast to the desired type.
10046 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10047}
10048
Michael Liao59229792012-10-24 04:14:18 +000010049SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10050 EVT VT = N->getValueType(0);
10051
10052 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010053 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010054
10055 EVT SrcVT = MVT::Other;
10056 unsigned Opcode = ISD::DELETED_NODE;
10057 unsigned NumDefs = 0;
10058
10059 for (unsigned i = 0; i != NumInScalars; ++i) {
10060 SDValue In = N->getOperand(i);
10061 unsigned Opc = In.getOpcode();
10062
10063 if (Opc == ISD::UNDEF)
10064 continue;
10065
10066 // If all scalar values are floats and converted from integers.
10067 if (Opcode == ISD::DELETED_NODE &&
10068 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10069 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010070 }
Tom Stellard567f8862013-01-02 22:13:01 +000010071
Michael Liao59229792012-10-24 04:14:18 +000010072 if (Opc != Opcode)
10073 return SDValue();
10074
10075 EVT InVT = In.getOperand(0).getValueType();
10076
10077 // If all scalar values are typed differently, bail out. It's chosen to
10078 // simplify BUILD_VECTOR of integer types.
10079 if (SrcVT == MVT::Other)
10080 SrcVT = InVT;
10081 if (SrcVT != InVT)
10082 return SDValue();
10083 NumDefs++;
10084 }
10085
10086 // If the vector has just one element defined, it's not worth to fold it into
10087 // a vectorized one.
10088 if (NumDefs < 2)
10089 return SDValue();
10090
10091 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10092 && "Should only handle conversion from integer to float.");
10093 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10094
10095 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010096
10097 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10098 return SDValue();
10099
Michael Liao59229792012-10-24 04:14:18 +000010100 SmallVector<SDValue, 8> Opnds;
10101 for (unsigned i = 0; i != NumInScalars; ++i) {
10102 SDValue In = N->getOperand(i);
10103
10104 if (In.getOpcode() == ISD::UNDEF)
10105 Opnds.push_back(DAG.getUNDEF(SrcVT));
10106 else
10107 Opnds.push_back(In.getOperand(0));
10108 }
Craig Topper48d114b2014-04-26 18:35:24 +000010109 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Michael Liao59229792012-10-24 04:14:18 +000010110 AddToWorkList(BV.getNode());
10111
10112 return DAG.getNode(Opcode, dl, VT, BV);
10113}
10114
Michael Liao6d106b72012-10-23 23:06:52 +000010115SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10116 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010117 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010118 EVT VT = N->getValueType(0);
10119
10120 // A vector built entirely of undefs is undef.
10121 if (ISD::allOperandsUndef(N))
10122 return DAG.getUNDEF(VT);
10123
10124 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10125 if (V.getNode())
10126 return V;
10127
Michael Liao59229792012-10-24 04:14:18 +000010128 V = reduceBuildVecConvertToConvertBuildVec(N);
10129 if (V.getNode())
10130 return V;
10131
Dan Gohmana8665142007-06-25 16:23:39 +000010132 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10133 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10134 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010135
10136 // May only combine to shuffle after legalize if shuffle is legal.
10137 if (LegalOperations &&
10138 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10139 return SDValue();
10140
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010141 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010142 for (unsigned i = 0; i != NumInScalars; ++i) {
10143 // Ignore undef inputs.
10144 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010145
Dan Gohmana8665142007-06-25 16:23:39 +000010146 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010147 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010148 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010149 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010150 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010151 break;
10152 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010153
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010154 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010155 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010156 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10157 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010158
Craig Topperc0196b12014-04-14 00:51:57 +000010159 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010160 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010161 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010162 VecIn2 = ExtractedFromVec;
10163 } else {
10164 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010165 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010166 break;
10167 }
10168 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010169
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010170 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010171 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010172 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010173 for (unsigned i = 0; i != NumInScalars; ++i) {
10174 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010175 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010176 continue;
10177 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010178
Rafael Espindolab93db662009-04-24 12:40:33 +000010179 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010180 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010181 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010182 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010183 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10184 if (ExtIndex > VT.getVectorNumElements())
10185 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010186
Nate Begeman5f829d82009-04-29 05:20:52 +000010187 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010188 continue;
10189 }
10190
10191 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010192 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010193 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010194 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010195
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010196 // We can't generate a shuffle node with mismatched input and output types.
10197 // Attempt to transform a single input vector to the correct type.
10198 if ((VT != VecIn1.getValueType())) {
10199 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010200 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010201 return SDValue();
10202
10203 // We only support widening of vectors which are half the size of the
10204 // output registers. For example XMM->YMM widening on X86 with AVX.
10205 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10206 return SDValue();
10207
James Molloy1e5c6112012-09-10 14:01:21 +000010208 // If the input vector type has a different base type to the output
10209 // vector type, bail out.
10210 if (VecIn1.getValueType().getVectorElementType() !=
10211 VT.getVectorElementType())
10212 return SDValue();
10213
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010214 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010215 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010216 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010217 }
10218
10219 // If VecIn2 is unused then change it to undef.
10220 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10221
Nadav Rotem841c9a82012-09-20 08:53:31 +000010222 // Check that we were able to transform all incoming values to the same
10223 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010224 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10225 VecIn1.getValueType() != VT)
10226 return SDValue();
10227
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010228 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010229 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010230 return SDValue();
10231
Dan Gohmana8665142007-06-25 16:23:39 +000010232 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010233 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010234 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010235 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010236 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010237 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010238
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010239 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010240}
10241
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010242SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010243 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10244 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10245 // inputs come from at most two distinct vectors, turn this into a shuffle
10246 // node.
10247
10248 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010249 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010250 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010251
Nadav Rotem01892102012-07-14 21:30:27 +000010252 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010253 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010254 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010255 return DAG.getUNDEF(VT);
10256
10257 // Optimize concat_vectors where one of the vectors is undef.
10258 if (N->getNumOperands() == 2 &&
10259 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10260 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010261 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010262
10263 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10264 if (In->getOpcode() == ISD::BITCAST &&
10265 !In->getOperand(0)->getValueType(0).isVector()) {
10266 SDValue Scalar = In->getOperand(0);
10267 EVT SclTy = Scalar->getValueType(0);
10268
10269 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10270 return SDValue();
10271
10272 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10273 VT.getSizeInBits() / SclTy.getSizeInBits());
10274 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10275 return SDValue();
10276
10277 SDLoc dl = SDLoc(N);
10278 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10279 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10280 }
10281 }
Nadav Rotem01892102012-07-14 21:30:27 +000010282
Robert Lougher7d9084f2014-02-11 15:42:46 +000010283 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10284 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10285 if (N->getNumOperands() == 2 &&
10286 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10287 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10288 EVT VT = N->getValueType(0);
10289 SDValue N0 = N->getOperand(0);
10290 SDValue N1 = N->getOperand(1);
10291 SmallVector<SDValue, 8> Opnds;
10292 unsigned BuildVecNumElts = N0.getNumOperands();
10293
10294 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10295 Opnds.push_back(N0.getOperand(i));
10296 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10297 Opnds.push_back(N1.getOperand(i));
10298
Craig Topper48d114b2014-04-26 18:35:24 +000010299 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010300 }
10301
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010302 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10303 // nodes often generate nop CONCAT_VECTOR nodes.
10304 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10305 // place the incoming vectors at the exact same location.
10306 SDValue SingleSource = SDValue();
10307 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10308
10309 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10310 SDValue Op = N->getOperand(i);
10311
10312 if (Op.getOpcode() == ISD::UNDEF)
10313 continue;
10314
10315 // Check if this is the identity extract:
10316 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10317 return SDValue();
10318
10319 // Find the single incoming vector for the extract_subvector.
10320 if (SingleSource.getNode()) {
10321 if (Op.getOperand(0) != SingleSource)
10322 return SDValue();
10323 } else {
10324 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010325
10326 // Check the source type is the same as the type of the result.
10327 // If not, this concat may extend the vector, so we can not
10328 // optimize it away.
10329 if (SingleSource.getValueType() != N->getValueType(0))
10330 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010331 }
10332
10333 unsigned IdentityIndex = i * PartNumElem;
10334 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10335 // The extract index must be constant.
10336 if (!CS)
10337 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010338
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010339 // Check that we are reading from the identity index.
10340 if (CS->getZExtValue() != IdentityIndex)
10341 return SDValue();
10342 }
10343
10344 if (SingleSource.getNode())
10345 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010346
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010347 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010348}
10349
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010350SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10351 EVT NVT = N->getValueType(0);
10352 SDValue V = N->getOperand(0);
10353
Michael Liao7a442c802012-10-17 20:48:33 +000010354 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10355 // Combine:
10356 // (extract_subvec (concat V1, V2, ...), i)
10357 // Into:
10358 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010359 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10360 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010361 if (V->getOperand(0).getValueType() != NVT)
10362 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010363 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10364 unsigned NumElems = NVT.getVectorNumElements();
10365 assert((Idx % NumElems) == 0 &&
10366 "IDX in concat is not a multiple of the result vector length.");
10367 return V->getOperand(Idx / NumElems);
10368 }
10369
Michael Liaobb05a1d2013-03-25 23:47:35 +000010370 // Skip bitcasting
10371 if (V->getOpcode() == ISD::BITCAST)
10372 V = V.getOperand(0);
10373
10374 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010375 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010376 // Handle only simple case where vector being inserted and vector
10377 // being extracted are of same type, and are half size of larger vectors.
10378 EVT BigVT = V->getOperand(0).getValueType();
10379 EVT SmallVT = V->getOperand(1).getValueType();
10380 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10381 return SDValue();
10382
10383 // Only handle cases where both indexes are constants with the same type.
10384 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10385 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10386
10387 if (InsIdx && ExtIdx &&
10388 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10389 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10390 // Combine:
10391 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10392 // Into:
10393 // indices are equal or bit offsets are equal => V1
10394 // otherwise => (extract_subvec V1, ExtIdx)
10395 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10396 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10397 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10398 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10399 DAG.getNode(ISD::BITCAST, dl,
10400 N->getOperand(0).getValueType(),
10401 V->getOperand(0)), N->getOperand(1));
10402 }
10403 }
10404
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010405 return SDValue();
10406}
10407
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010408// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10409static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10410 EVT VT = N->getValueType(0);
10411 unsigned NumElts = VT.getVectorNumElements();
10412
10413 SDValue N0 = N->getOperand(0);
10414 SDValue N1 = N->getOperand(1);
10415 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10416
10417 SmallVector<SDValue, 4> Ops;
10418 EVT ConcatVT = N0.getOperand(0).getValueType();
10419 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10420 unsigned NumConcats = NumElts / NumElemsPerConcat;
10421
10422 // Look at every vector that's inserted. We're looking for exact
10423 // subvector-sized copies from a concatenated vector
10424 for (unsigned I = 0; I != NumConcats; ++I) {
10425 // Make sure we're dealing with a copy.
10426 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010427 bool AllUndef = true, NoUndef = true;
10428 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10429 if (SVN->getMaskElt(J) >= 0)
10430 AllUndef = false;
10431 else
10432 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010433 }
10434
Hao Liubc601962013-05-13 02:07:05 +000010435 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010436 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10437 return SDValue();
10438
10439 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10440 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10441 return SDValue();
10442
10443 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10444 if (FirstElt < N0.getNumOperands())
10445 Ops.push_back(N0.getOperand(FirstElt));
10446 else
10447 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10448
10449 } else if (AllUndef) {
10450 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10451 } else { // Mixed with general masks and undefs, can't do optimization.
10452 return SDValue();
10453 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010454 }
10455
Craig Topper48d114b2014-04-26 18:35:24 +000010456 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010457}
10458
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010459SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010460 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010461 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010462
Mon P Wang25f01062008-11-10 04:46:22 +000010463 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010464 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010465
Craig Topper5894fe42012-04-09 05:16:56 +000010466 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010467
Craig Topper279c77b2012-01-04 08:07:43 +000010468 // Canonicalize shuffle undef, undef -> undef
10469 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10470 return DAG.getUNDEF(VT);
10471
10472 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10473
10474 // Canonicalize shuffle v, v -> v, undef
10475 if (N0 == N1) {
10476 SmallVector<int, 8> NewMask;
10477 for (unsigned i = 0; i != NumElts; ++i) {
10478 int Idx = SVN->getMaskElt(i);
10479 if (Idx >= (int)NumElts) Idx -= NumElts;
10480 NewMask.push_back(Idx);
10481 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010482 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010483 &NewMask[0]);
10484 }
10485
10486 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10487 if (N0.getOpcode() == ISD::UNDEF) {
10488 SmallVector<int, 8> NewMask;
10489 for (unsigned i = 0; i != NumElts; ++i) {
10490 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010491 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010492 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010493 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010494 else
10495 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010496 }
10497 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010498 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010499 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010500 &NewMask[0]);
10501 }
10502
10503 // Remove references to rhs if it is undef
10504 if (N1.getOpcode() == ISD::UNDEF) {
10505 bool Changed = false;
10506 SmallVector<int, 8> NewMask;
10507 for (unsigned i = 0; i != NumElts; ++i) {
10508 int Idx = SVN->getMaskElt(i);
10509 if (Idx >= (int)NumElts) {
10510 Idx = -1;
10511 Changed = true;
10512 }
10513 NewMask.push_back(Idx);
10514 }
10515 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010516 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010517 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010518
Bob Wilsonf63da122010-10-28 17:06:14 +000010519 // If it is a splat, check if the argument vector is another splat or a
10520 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010521 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010522 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010523
Dan Gohmana8665142007-06-25 16:23:39 +000010524 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010525 // not the number of vector elements, look through it. Be careful not to
10526 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010527 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010528 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010529 if (ConvInput.getValueType().isVector() &&
10530 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010531 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010532 }
10533
Dan Gohmana8665142007-06-25 16:23:39 +000010534 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010535 assert(V->getNumOperands() == NumElts &&
10536 "BUILD_VECTOR has wrong number of operands");
10537 SDValue Base;
10538 bool AllSame = true;
10539 for (unsigned i = 0; i != NumElts; ++i) {
10540 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10541 Base = V->getOperand(i);
10542 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010543 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010544 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010545 // Splat of <u, u, u, u>, return <u, u, u, u>
10546 if (!Base.getNode())
10547 return N0;
10548 for (unsigned i = 0; i != NumElts; ++i) {
10549 if (V->getOperand(i) != Base) {
10550 AllSame = false;
10551 break;
10552 }
10553 }
10554 // Splat of <x, x, x, x>, return <x, x, x, x>
10555 if (AllSame)
10556 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010557 }
10558 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010559
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010560 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10561 Level < AfterLegalizeVectorOps &&
10562 (N1.getOpcode() == ISD::UNDEF ||
10563 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10564 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10565 SDValue V = partitionShuffleOfConcats(N, DAG);
10566
10567 if (V.getNode())
10568 return V;
10569 }
10570
Nadav Rotemb0783502012-04-01 19:31:22 +000010571 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010572 // and it reverses the swizzle of the previous shuffle then we can
10573 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotemb0783502012-04-01 19:31:22 +000010574 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10575 N1.getOpcode() == ISD::UNDEF) {
10576
Nadav Rotemb0783502012-04-01 19:31:22 +000010577 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10578
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010579 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10580 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10581 return SDValue();
10582
Craig Topper5894fe42012-04-09 05:16:56 +000010583 // The incoming shuffle must be of the same type as the result of the
10584 // current shuffle.
10585 assert(OtherSV->getOperand(0).getValueType() == VT &&
10586 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010587
10588 for (unsigned i = 0; i != NumElts; ++i) {
10589 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010590 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010591 // Next, this index comes from the first value, which is the incoming
10592 // shuffle. Adopt the incoming index.
10593 if (Idx >= 0)
10594 Idx = OtherSV->getMaskElt(Idx);
10595
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010596 // The combined shuffle must map each index to itself.
Craig Topper5894fe42012-04-09 05:16:56 +000010597 if (Idx >= 0 && (unsigned)Idx != i)
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010598 return SDValue();
Nadav Rotemb0783502012-04-01 19:31:22 +000010599 }
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010600
10601 return OtherSV->getOperand(0);
Nadav Rotemb0783502012-04-01 19:31:22 +000010602 }
10603
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010604 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010605}
10606
Manman Ren413a6cb2014-01-31 01:10:35 +000010607SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10608 SDValue N0 = N->getOperand(0);
10609 SDValue N2 = N->getOperand(2);
10610
10611 // If the input vector is a concatenation, and the insert replaces
10612 // one of the halves, we can optimize into a single concat_vectors.
10613 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10614 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10615 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10616 EVT VT = N->getValueType(0);
10617
10618 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10619 // (concat_vectors Z, Y)
10620 if (InsIdx == 0)
10621 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10622 N->getOperand(1), N0.getOperand(1));
10623
10624 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10625 // (concat_vectors X, Z)
10626 if (InsIdx == VT.getVectorNumElements()/2)
10627 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10628 N0.getOperand(0), N->getOperand(1));
10629 }
10630
10631 return SDValue();
10632}
10633
Evan Chenga320abc2006-04-20 08:56:16 +000010634/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010635/// an AND to a vector_shuffle with the destination vector and a zero vector.
10636/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010637/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010638SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010639 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010640 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010641 SDValue LHS = N->getOperand(0);
10642 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010643 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010644 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010645 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010646 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010647 SmallVector<int, 8> Indices;
10648 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010649 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010650 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010651 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010652 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010653
10654 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010655 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010656 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010657 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010658 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010659 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010660 }
10661
10662 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010663 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010664 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010665 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010666
Dan Gohmana8665142007-06-25 16:23:39 +000010667 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010668 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010669 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010670 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000010671 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000010672 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010673 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010674 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010675 }
10676 }
Bill Wendling31b50992009-01-30 23:59:18 +000010677
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010678 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010679}
10680
Dan Gohmana8665142007-06-25 16:23:39 +000010681/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010682SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010683 assert(N->getValueType(0).isVector() &&
10684 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010685
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010686 SDValue LHS = N->getOperand(0);
10687 SDValue RHS = N->getOperand(1);
10688 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010689 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010690
Dan Gohmana8665142007-06-25 16:23:39 +000010691 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010692 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010693 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010694 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010695 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010696 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10697 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010698 return SDValue();
10699
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010700 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010701 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010702 SDValue LHSOp = LHS.getOperand(i);
10703 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010704
Evan Cheng64d28462006-05-31 06:08:35 +000010705 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010706 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10707 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010708 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010709 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010710 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010711 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010712 break;
10713 }
Bill Wendling31b50992009-01-30 23:59:18 +000010714
Bob Wilson54081442010-12-17 23:06:49 +000010715 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010716 EVT RVT = RHSOp.getValueType();
10717 if (RVT != VT) {
10718 // Integer BUILD_VECTOR operands may have types larger than the element
10719 // size (e.g., when the element type is not legal). Prior to type
10720 // legalization, the types may not match between the two BUILD_VECTORS.
10721 // Truncate one of the operands to make them match.
10722 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010723 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010724 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010725 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010726 VT = RVT;
10727 }
10728 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010729 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010730 LHSOp, RHSOp);
10731 if (FoldOp.getOpcode() != ISD::UNDEF &&
10732 FoldOp.getOpcode() != ISD::Constant &&
10733 FoldOp.getOpcode() != ISD::ConstantFP)
10734 break;
10735 Ops.push_back(FoldOp);
10736 AddToWorkList(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010737 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010738
Bob Wilson54081442010-12-17 23:06:49 +000010739 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000010740 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000010741 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010742
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010743 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000010744}
10745
Craig Topper82384612012-09-11 01:45:21 +000010746/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10747SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000010748 assert(N->getValueType(0).isVector() &&
10749 "SimplifyVUnaryOp only works on vectors!");
10750
10751 SDValue N0 = N->getOperand(0);
10752
10753 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10754 return SDValue();
10755
10756 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10757 SmallVector<SDValue, 8> Ops;
10758 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10759 SDValue Op = N0.getOperand(i);
10760 if (Op.getOpcode() != ISD::UNDEF &&
10761 Op.getOpcode() != ISD::ConstantFP)
10762 break;
10763 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010764 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000010765 if (FoldOp.getOpcode() != ISD::UNDEF &&
10766 FoldOp.getOpcode() != ISD::ConstantFP)
10767 break;
10768 Ops.push_back(FoldOp);
10769 AddToWorkList(FoldOp.getNode());
10770 }
10771
10772 if (Ops.size() != N0.getNumOperands())
10773 return SDValue();
10774
Craig Topper48d114b2014-04-26 18:35:24 +000010775 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000010776}
10777
Andrew Trickef9de2a2013-05-25 02:42:55 +000010778SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000010779 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000010780 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000010781
Bill Wendling31b50992009-01-30 23:59:18 +000010782 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000010783 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000010784
Nate Begeman2042aa52005-10-08 00:29:44 +000010785 // If we got a simplified select_cc node back from SimplifySelectCC, then
10786 // break it down into a new SETCC node, and a new SELECT node, and then return
10787 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010788 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010789 // Check to see if we got a select_cc back (to turn into setcc/select).
10790 // Otherwise, just return whatever node we got back, like fabs.
10791 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010792 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010793 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000010794 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000010795 SCC.getOperand(4));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010796 AddToWorkList(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010797 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10798 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000010799 }
Bill Wendling31b50992009-01-30 23:59:18 +000010800
Nate Begeman2042aa52005-10-08 00:29:44 +000010801 return SCC;
10802 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010803 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000010804}
10805
Chris Lattner6c14c352005-10-18 06:04:22 +000010806/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10807/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000010808/// select. Callers of this should assume that TheSelect is deleted if this
10809/// returns true. As such, they should return the appropriate thing (e.g. the
10810/// node) back to the top-level of the DAG combiner loop to avoid it being
10811/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010812bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010813 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010814
Nadav Rotema49a02a2011-02-11 19:57:47 +000010815 // Cannot simplify select with vector condition
10816 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10817
Chris Lattner6c14c352005-10-18 06:04:22 +000010818 // If this is a select from two identical things, try to pull the operation
10819 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000010820 if (LHS.getOpcode() != RHS.getOpcode() ||
10821 !LHS.hasOneUse() || !RHS.hasOneUse())
10822 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010823
Chris Lattner254c4452010-09-21 15:46:59 +000010824 // If this is a load and the token chain is identical, replace the select
10825 // of two loads with a load through a select of the address to load from.
10826 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10827 // constants have been dropped into the constant pool.
10828 if (LHS.getOpcode() == ISD::LOAD) {
10829 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10830 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000010831
Chris Lattner254c4452010-09-21 15:46:59 +000010832 // Token chains must be identical.
10833 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000010834 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000010835 LLD->isVolatile() || RLD->isVolatile() ||
10836 // If this is an EXTLOAD, the VT's must match.
10837 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000010838 // If this is an EXTLOAD, the kind of extension must match.
10839 (LLD->getExtensionType() != RLD->getExtensionType() &&
10840 // The only exception is if one of the extensions is anyext.
10841 LLD->getExtensionType() != ISD::EXTLOAD &&
10842 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000010843 // FIXME: this discards src value information. This is
10844 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000010845 // both potential memory locations. Since we are discarding
10846 // src value info, don't do the transformation if the memory
10847 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000010848 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000010849 RLD->getPointerInfo().getAddrSpace() != 0 ||
10850 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10851 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000010852 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010853
Chris Lattnere3267522010-09-21 15:58:55 +000010854 // Check that the select condition doesn't reach either load. If so,
10855 // folding this will induce a cycle into the DAG. If not, this is safe to
10856 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000010857 SDValue Addr;
10858 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000010859 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10860 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10861 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10862 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000010863 // The loads must not depend on one another.
10864 if (LLD->isPredecessorOf(RLD) ||
10865 RLD->isPredecessorOf(LLD))
10866 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010867 Addr = DAG.getSelect(SDLoc(TheSelect),
10868 LLD->getBasePtr().getValueType(),
10869 TheSelect->getOperand(0), LLD->getBasePtr(),
10870 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000010871 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000010872 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10873 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10874
10875 if ((LLD->hasAnyUseOfValue(1) &&
10876 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000010877 (RLD->hasAnyUseOfValue(1) &&
10878 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000010879 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010880
Andrew Trickef9de2a2013-05-25 02:42:55 +000010881 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000010882 LLD->getBasePtr().getValueType(),
10883 TheSelect->getOperand(0),
10884 TheSelect->getOperand(1),
10885 LLD->getBasePtr(), RLD->getBasePtr(),
10886 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000010887 }
10888
Chris Lattnere3267522010-09-21 15:58:55 +000010889 SDValue Load;
10890 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10891 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010892 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010893 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010894 LLD->getChain(), Addr, MachinePointerInfo(),
10895 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010896 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000010897 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000010898 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10899 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010900 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000010901 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010902 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010903 LLD->getChain(), Addr, MachinePointerInfo(),
10904 LLD->getMemoryVT(), LLD->isVolatile(),
10905 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000010906 }
Chris Lattnere3267522010-09-21 15:58:55 +000010907
10908 // Users of the select now use the result of the load.
10909 CombineTo(TheSelect, Load);
10910
10911 // Users of the old loads now use the new load's chain. We know the
10912 // old-load value is dead now.
10913 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10914 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10915 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000010916 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010917
Chris Lattner6c14c352005-10-18 06:04:22 +000010918 return false;
10919}
10920
Chris Lattner43d63772009-03-11 05:08:08 +000010921/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10922/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010923SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010924 SDValue N2, SDValue N3,
10925 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000010926 // (x ? y : y) -> y.
10927 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000010928
Owen Anderson53aa7a92009-08-10 22:56:29 +000010929 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000010930 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10931 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10932 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010933
10934 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000010935 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000010936 N0, N1, CC, DL, false);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010937 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10938 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010939
10940 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000010941 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010942 return N2;
10943 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000010944 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010945 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010946
Nate Begeman2042aa52005-10-08 00:29:44 +000010947 // Check to see if we can simplify the select into an fabs node
10948 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10949 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000010950 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010951 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10952 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10953 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10954 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000010955 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010956
Nate Begeman2042aa52005-10-08 00:29:44 +000010957 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10958 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10959 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10960 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000010961 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000010962 }
10963 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010964
Chris Lattner43d63772009-03-11 05:08:08 +000010965 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10966 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10967 // in it. This is a win when the constant is not otherwise available because
10968 // it replaces two constant pool loads with one. We only do this if the FP
10969 // type is known to be legal, because if it isn't, then we are before legalize
10970 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000010971 // messing with soft float) and if the ConstantFP is not legal, because if
10972 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000010973 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10974 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10975 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000010976 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000010977 TargetLowering::Legal &&
10978 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10979 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000010980 // If both constants have multiple uses, then we won't need to do an
10981 // extra load, they are likely around in registers for other users.
10982 (TV->hasOneUse() || FV->hasOneUse())) {
10983 Constant *Elts[] = {
10984 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10985 const_cast<ConstantFP*>(TV->getConstantFPValue())
10986 };
Chris Lattner229907c2011-07-18 04:54:35 +000010987 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010988 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000010989
Chris Lattner43d63772009-03-11 05:08:08 +000010990 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000010991 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000010992 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10993 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000010994 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000010995
10996 // Get the offsets to the 0 and 1 element of the array so that we can
10997 // select between them.
10998 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000010999 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011000 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011001
Chris Lattner43d63772009-03-11 05:08:08 +000011002 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011003 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011004 N0, N1, CC);
Dan Gohmane83e1b22011-09-22 23:01:29 +000011005 AddToWorkList(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011006 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11007 Cond, One, Zero);
Dan Gohmane83e1b22011-09-22 23:01:29 +000011008 AddToWorkList(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011009 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011010 CstOffset);
Dan Gohmane83e1b22011-09-22 23:01:29 +000011011 AddToWorkList(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011012 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011013 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011014 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011015
11016 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011017 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011018
Nate Begeman2042aa52005-10-08 00:29:44 +000011019 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011020 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011021 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011022 (N1C->isNullValue() || // (a < 0) ? b : 0
11023 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011024 EVT XType = N0.getValueType();
11025 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011026 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011027 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011028 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011029 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11030 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011031 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011032 SDValue ShCt = DAG.getConstant(ShCtV,
11033 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011034 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011035 XType, N0, ShCt);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011036 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011037
Duncan Sands11dd4242008-06-08 20:54:56 +000011038 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011039 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011040 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011041 }
Bill Wendling31b50992009-01-30 23:59:18 +000011042
11043 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011044 }
Bill Wendling31b50992009-01-30 23:59:18 +000011045
Andrew Trickef9de2a2013-05-25 02:42:55 +000011046 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011047 XType, N0,
11048 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011049 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +000011050 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011051
Duncan Sands11dd4242008-06-08 20:54:56 +000011052 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011053 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011054 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011055 }
Bill Wendling31b50992009-01-30 23:59:18 +000011056
11057 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011058 }
11059 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011060
Owen Anderson3231d132010-09-22 22:58:22 +000011061 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11062 // where y is has a single bit set.
11063 // A plaintext description would be, we can turn the SELECT_CC into an AND
11064 // when the condition can be materialized as an all-ones register. Any
11065 // single bit-test can be materialized as an all-ones register with
11066 // shift-left and shift-right-arith.
11067 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11068 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011069 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011070 N2C && N2C->isNullValue()) {
11071 SDValue AndLHS = N0->getOperand(0);
11072 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11073 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11074 // Shift the tested bit over the sign bit.
11075 APInt AndMask = ConstAndRHS->getAPIntValue();
11076 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011077 DAG.getConstant(AndMask.countLeadingZeros(),
11078 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011079 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011080
Owen Anderson3231d132010-09-22 22:58:22 +000011081 // Now arithmetic right shift it all the way over, so the result is either
11082 // all-ones, or zero.
11083 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011084 DAG.getConstant(AndMask.getBitWidth()-1,
11085 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011086 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011087
Owen Anderson3231d132010-09-22 22:58:22 +000011088 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11089 }
11090 }
11091
Nate Begeman6828ed92005-10-10 21:26:48 +000011092 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011093 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sandsf2641e12011-09-06 19:07:46 +000011094 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11095 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011096
Chris Lattnera083ffc2007-04-11 06:50:51 +000011097 // If the caller doesn't want us to simplify this into a zext of a compare,
11098 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011099 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011100 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011101
Nate Begeman6828ed92005-10-10 21:26:48 +000011102 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011103 // NOTE: Don't create a SETCC if it's not legal on this target.
11104 if (!LegalOperations ||
11105 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011106 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011107 SDValue Temp, SCC;
11108 // cast from setcc result type to select result type
11109 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011110 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011111 N0, N1, CC);
11112 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011113 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011114 N2.getValueType());
11115 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011116 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011117 N2.getValueType(), SCC);
11118 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011119 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11120 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011121 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011122 }
11123
11124 AddToWorkList(SCC.getNode());
11125 AddToWorkList(Temp.getNode());
11126
11127 if (N2C->getAPIntValue() == 1)
11128 return Temp;
11129
11130 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011131 return DAG.getNode(
11132 ISD::SHL, DL, N2.getValueType(), Temp,
11133 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11134 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011135 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011136 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011137
Nate Begeman2042aa52005-10-08 00:29:44 +000011138 // Check to see if this is the equivalent of setcc
11139 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11140 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011141 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011142 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011143 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011144 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11145 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011146 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011147 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011148 return Res;
11149 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011150
Bill Wendling31b50992009-01-30 23:59:18 +000011151 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011152 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011153 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011154 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011155 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011156 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011157 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011158 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011159 }
Bill Wendling31b50992009-01-30 23:59:18 +000011160 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011161 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011162 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011163 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011164 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011165 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011166 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011167 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011168 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011169 }
Bill Wendling31b50992009-01-30 23:59:18 +000011170 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011171 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011172 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011173 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011174 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011175 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011176 }
11177 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011178
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011179 // Check to see if this is an integer abs.
11180 // select_cc setg[te] X, 0, X, -X ->
11181 // select_cc setgt X, -1, X, -X ->
11182 // select_cc setl[te] X, 0, -X, X ->
11183 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011184 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011185 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011186 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011187 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11188 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11189 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11190 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11191 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11192 (N1C->isOne() && CC == ISD::SETLT)) &&
11193 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11194 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11195
Owen Anderson53aa7a92009-08-10 22:56:29 +000011196 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011197 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011198 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011199 N0,
11200 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011201 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011202 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011203 XType, N0, Shift);
11204 AddToWorkList(Shift.getNode());
11205 AddToWorkList(Add.getNode());
11206 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011207 }
11208 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011209
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011210 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011211}
11212
Evan Cheng92658d52007-02-08 22:13:59 +000011213/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011214SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011215 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011216 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011217 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011218 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011219 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011220}
11221
Nate Begemanc6f067a2005-10-20 02:15:44 +000011222/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11223/// return a DAG expression to select that will generate the same value by
11224/// multiplying by a magic number. See:
11225/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011226SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011227 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11228 if (!C)
11229 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011230
11231 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011232 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011233 return SDValue();
11234
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011235 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011236 SDValue S =
11237 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011238
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011239 for (SDNode *N : Built)
11240 AddToWorkList(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011241 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011242}
11243
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011244/// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
Nate Begemanc6f067a2005-10-20 02:15:44 +000011245/// return a DAG expression to select that will generate the same value by
11246/// multiplying by a magic number. See:
11247/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011248SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011249 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11250 if (!C)
11251 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011252
11253 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011254 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011255 return SDValue();
11256
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011257 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011258 SDValue S =
11259 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011260
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011261 for (SDNode *N : Built)
11262 AddToWorkList(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011263 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011264}
11265
Nate Begeman18150d52009-09-25 06:05:26 +000011266/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011267// to alias with anything but itself. Provides base object and offset as
11268// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011269static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011270 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011271 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011272 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011273
Jim Laskey0463e082006-10-07 23:37:56 +000011274 // If it's an adding a simple constant then integrate the offset.
11275 if (Base.getOpcode() == ISD::ADD) {
11276 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11277 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011278 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011279 }
11280 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011281
Nate Begeman18150d52009-09-25 06:05:26 +000011282 // Return the underlying GlobalValue, and update the Offset. Return false
11283 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11284 // by multiple nodes with different offsets.
11285 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11286 GV = G->getGlobal();
11287 Offset += G->getOffset();
11288 return false;
11289 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011290
Nate Begeman18150d52009-09-25 06:05:26 +000011291 // Return the underlying Constant value, and update the Offset. Return false
11292 // for ConstantSDNodes since the same constant pool entry may be represented
11293 // by multiple nodes with different offsets.
11294 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011295 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11296 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011297 Offset += C->getOffset();
11298 return false;
11299 }
Jim Laskey0463e082006-10-07 23:37:56 +000011300 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011301 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011302}
11303
11304/// isAlias - Return true if there is any possibility that the two addresses
11305/// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011306bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011307 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011308 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011309
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011310 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011311 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011312
Jim Laskey0463e082006-10-07 23:37:56 +000011313 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011314 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011315 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011316 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011317 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011318 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11319 Base1, Offset1, GV1, CV1);
11320 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11321 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011322
Nate Begeman18150d52009-09-25 06:05:26 +000011323 // If they have a same base address then check to see if they overlap.
11324 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011325 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11326 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011327
Owen Anderson272ff942010-09-20 20:39:59 +000011328 // It is possible for different frame indices to alias each other, mostly
11329 // when tail call optimization reuses return address slots for arguments.
11330 // To catch this case, look up the actual index of frame indices to compute
11331 // the real alias relationship.
11332 if (isFrameIndex1 && isFrameIndex2) {
11333 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11334 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11335 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011336 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11337 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000011338 }
11339
Wesley Peck527da1b2010-11-23 03:31:01 +000011340 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011341 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011342 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11343 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011344
Nate Begeman879d8f12009-09-15 00:18:30 +000011345 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11346 // compared to the size and offset of the access, we may be able to prove they
11347 // do not alias. This check is conservative for now to catch cases created by
11348 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011349 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11350 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11351 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11352 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11353 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11354 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11355 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000011356
Nate Begeman879d8f12009-09-15 00:18:30 +000011357 // There is no overlap between these relatively aligned accesses of similar
11358 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011359 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11360 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000011361 return false;
11362 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011363
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011364 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11365 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011366#ifndef NDEBUG
11367 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11368 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11369 UseAA = false;
11370#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011371 if (UseAA &&
11372 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011373 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011374 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11375 Op1->getSrcValueOffset());
11376 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11377 Op0->getSrcValueOffset() - MinOffset;
11378 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11379 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011380 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011381 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11382 Overlap1,
11383 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11384 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11385 Overlap2,
11386 UseTBAA ? Op1->getTBAAInfo() : nullptr));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011387 if (AAResult == AliasAnalysis::NoAlias)
11388 return false;
11389 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011390
11391 // Otherwise we have to assume they alias.
11392 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011393}
11394
Jim Laskey708d0db2006-10-04 16:53:27 +000011395/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11396/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011397void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011398 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011399 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011400 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011401
Jim Laskeyd07be232006-09-25 16:29:54 +000011402 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011403 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000011404
Jim Laskey708d0db2006-10-04 16:53:27 +000011405 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011406 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011407 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011408
Jim Laskey6549d222006-10-05 15:07:25 +000011409 // Look at each chain and determine if it is an alias. If so, add it to the
11410 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011411 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011412 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011413 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011414 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011415
11416 // For TokenFactor nodes, look at each operand and only continue up the
11417 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011418 // find more and revert to original chain since the xform is unlikely to be
11419 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011420 //
11421 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011422 // chain we found before we hit a tokenfactor rather than the original
11423 // chain.
11424 if (Depth > 6 || Aliases.size() == 2) {
11425 Aliases.clear();
11426 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011427 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011428 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011429
Nate Begeman879d8f12009-09-15 00:18:30 +000011430 // Don't bother if we've been before.
11431 if (!Visited.insert(Chain.getNode()))
11432 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011433
Jim Laskey6549d222006-10-05 15:07:25 +000011434 switch (Chain.getOpcode()) {
11435 case ISD::EntryToken:
11436 // Entry token is ideal chain operand, but handled in FindBetterChain.
11437 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011438
Jim Laskey6549d222006-10-05 15:07:25 +000011439 case ISD::LOAD:
11440 case ISD::STORE: {
11441 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011442 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11443 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011444
Jim Laskey6549d222006-10-05 15:07:25 +000011445 // If chain is alias then stop here.
11446 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011447 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000011448 Aliases.push_back(Chain);
11449 } else {
11450 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011451 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011452 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011453 }
Jim Laskey6549d222006-10-05 15:07:25 +000011454 break;
11455 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011456
Jim Laskey6549d222006-10-05 15:07:25 +000011457 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011458 // We have to check each of the operands of the token factor for "small"
11459 // token factors, so we queue them up. Adding the operands to the queue
11460 // (stack) in reverse order maintains the original order and increases the
11461 // likelihood that getNode will find a matching token factor (CSE.)
11462 if (Chain.getNumOperands() > 16) {
11463 Aliases.push_back(Chain);
11464 break;
11465 }
Jim Laskey6549d222006-10-05 15:07:25 +000011466 for (unsigned n = Chain.getNumOperands(); n;)
11467 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011468 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011469 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011470
Jim Laskey6549d222006-10-05 15:07:25 +000011471 default:
11472 // For all other instructions we will just have to take what we can get.
11473 Aliases.push_back(Chain);
11474 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011475 }
11476 }
Hal Finkel51a98382014-01-24 20:12:02 +000011477
11478 // We need to be careful here to also search for aliases through the
11479 // value operand of a store, etc. Consider the following situation:
11480 // Token1 = ...
11481 // L1 = load Token1, %52
11482 // S1 = store Token1, L1, %51
11483 // L2 = load Token1, %52+8
11484 // S2 = store Token1, L2, %51+8
11485 // Token2 = Token(S1, S2)
11486 // L3 = load Token2, %53
11487 // S3 = store Token2, L3, %52
11488 // L4 = load Token2, %53+8
11489 // S4 = store Token2, L4, %52+8
11490 // If we search for aliases of S3 (which loads address %52), and we look
11491 // only through the chain, then we'll miss the trivial dependence on L1
11492 // (which also loads from %52). We then might change all loads and
11493 // stores to use Token1 as their chain operand, which could result in
11494 // copying %53 into %52 before copying %52 into %51 (which should
11495 // happen first).
11496 //
11497 // The problem is, however, that searching for such data dependencies
11498 // can become expensive, and the cost is not directly related to the
11499 // chain depth. Instead, we'll rule out such configurations here by
11500 // insisting that we've visited all chain users (except for users
11501 // of the original chain, which is not necessary). When doing this,
11502 // we need to look through nodes we don't care about (otherwise, things
11503 // like register copies will interfere with trivial cases).
11504
11505 SmallVector<const SDNode *, 16> Worklist;
11506 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11507 IE = Visited.end(); I != IE; ++I)
11508 if (*I != OriginalChain.getNode())
11509 Worklist.push_back(*I);
11510
11511 while (!Worklist.empty()) {
11512 const SDNode *M = Worklist.pop_back_val();
11513
11514 // We have already visited M, and want to make sure we've visited any uses
11515 // of M that we care about. For uses that we've not visisted, and don't
11516 // care about, queue them to the worklist.
11517
11518 for (SDNode::use_iterator UI = M->use_begin(),
11519 UIE = M->use_end(); UI != UIE; ++UI)
11520 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11521 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11522 // We've not visited this use, and we care about it (it could have an
11523 // ordering dependency with the original node).
11524 Aliases.clear();
11525 Aliases.push_back(OriginalChain);
11526 return;
11527 }
11528
11529 // We've not visited this use, but we don't care about it. Mark it as
11530 // visited and enqueue it to the worklist.
11531 Worklist.push_back(*UI);
11532 }
11533 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011534}
11535
11536/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11537/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011538SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11539 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011540
Jim Laskey708d0db2006-10-04 16:53:27 +000011541 // Accumulate all the aliases to this node.
11542 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011543
Dan Gohman4298df62011-05-17 22:20:36 +000011544 // If no operands then chain to entry token.
11545 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011546 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011547
11548 // If a single operand then chain to it. We don't need to revisit it.
11549 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011550 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011551
Jim Laskey708d0db2006-10-04 16:53:27 +000011552 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000011553 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000011554}
11555
Nate Begeman21158fc2005-09-01 00:19:25 +000011556// SelectionDAG::Combine - This is the entry point for the file.
11557//
Bill Wendling084669a2009-04-29 00:15:41 +000011558void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011559 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011560 /// run - This is the main entry point to this class.
11561 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011562 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011563}